diff --git a/CHANGELOG.md b/CHANGELOG.md index 16f70ba..2c1219d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,22 @@ Protocol axes (Tool v1, Analysis v2, Trace v2) are versioned separately. ## [Unreleased] +### Changed (RFC-VIEW-0002 PR-02) + +- Restructured the crate into the RFC-VIEW-0002 §5.3 layout: `src/protocol/ + {analysis_v2,trace_v2,tool_v1}.rs`, `src/reader/{source,markdown,model, + assemble,render,assets}.rs`, `src/config.rs`; `lib.rs` is the composition + root and `app.rs`/`project.rs`/`semantic.rs`/`trace.rs`/`document.rs`/ + `presentation.rs`/`source_map.rs`/`render.rs`/`assets.rs` are gone. +- Replaced `GET /api/document` with the read-only `GET /api/documents` + (documents list + current outline/function/analysis summary). +- Reading UI: removed variable/memory placeholder menu entries (one explicit + "unsupported capability" explanation remains), added a simple dark theme + toggle with a single token override layer and persisted preference. +- Reorganized tests into Cargo `[[test]]` suites: `tests/contract/` (CLI/Tool/ + Analysis/Trace/coupling/assets) and `tests/integration/` (Live HTTP/renderer/ + Unicode/export); `tests/fixtures`, `tests/golden`, `tests/browser` unchanged. + ### Changed (RFC-VIEW-0002 PR-01) - View product version is now `0.2.0` (`Cargo.toml`, `tool.json`, binary diff --git a/Cargo.toml b/Cargo.toml index c54ade4..292bfa1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,6 +14,14 @@ categories = ["command-line-utilities", "documentation"] name = "marqdo-view" path = "src/main.rs" +[[test]] +name = "contract" +path = "tests/contract/main.rs" + +[[test]] +name = "integration" +path = "tests/integration/main.rs" + [dependencies] clap = { version = "4.5", features = ["derive"] } serde = { version = "1", features = ["derive"] } diff --git a/README.md b/README.md index ae17769..7dc9c61 100644 --- a/README.md +++ b/README.md @@ -88,8 +88,8 @@ PublicCoreClient ─ MARQDO_BIN 子进程 + 公开 JSON(check --emit / run --t - Trace v2 与 Analysis 字节摘要严格绑定;`STALE/TRUNCATED/FAILED/UNSUPPORTED` 状态显式呈现,不猜测未公开值。 - Live/Export 内容同源;导出绝不执行、绝不覆盖项目源文件或无关目录。 -- 门禁:`tests/no_coupling.rs` 拒绝旧 crate/源码依赖、第二套渲染器/主题、shell 执行; - `tests/asset_integrity.rs` 锁定内嵌资产与唯一主题层。 +- 门禁:`tests/contract/no_coupling.rs` 拒绝旧 crate/源码依赖、第二套渲染器/主题、shell 执行; + `tests/contract/asset_integrity.rs` 锁定内嵌资产与唯一主题层。 ## 开发与验收 diff --git a/assets/reader.css b/assets/reader.css index f32b2df..ba27811 100644 --- a/assets/reader.css +++ b/assets/reader.css @@ -40,6 +40,28 @@ --mq-dock-h: 66px; --mq-note-width: 176px; } + + /* Simple dark theme (RFC-VIEW-0002 §1.2 MVP SMALL): one token override + * layer, no theme framework, no remote skin. */ + .mq-reader[data-theme="dark"] { + color-scheme: dark; + --mq-paper: #1e1b17; + --mq-surface: #26221d; + --mq-surface-2: #2e2923; + --mq-surface-3: #3a332b; + --mq-ink: #ece5da; + --mq-strong: #f7f2ea; + --mq-muted: #ab9c89; + --mq-line: #3d362d; + --mq-line-strong: #5b5041; + --mq-gold: #d0a55f; + --mq-gold-soft: #8a6a37; + --mq-olive: #a3b482; + --mq-ok: #a3b482; + --mq-warn: #d7a55a; + --mq-error: #e08072; + --mq-focus: #e2b877; + } } @layer reset { diff --git a/assets/reader.js b/assets/reader.js index a188553..ea79773 100644 --- a/assets/reader.js +++ b/assets/reader.js @@ -213,6 +213,22 @@ closeAllDialogs(); } + function applyTheme(theme, announce) { + var next = theme === "dark" ? "dark" : "light"; + reader.dataset.theme = next; + try { + window.localStorage.setItem("marqdo.view.theme", next); + } catch (error) { + /* storage is optional */ + } + if (announce) toast(next === "dark" ? "已切换到深色主题" : "已切换到暖纸主题"); + } + + function cycleTheme() { + applyTheme(reader.dataset.theme === "dark" ? "light" : "dark", true); + closeAllDialogs(); + } + function cycleTextSize() { var order = ["normal", "large", "small"]; var current = reader.dataset.size || "normal"; @@ -272,17 +288,15 @@ case "annotations": toggleAnnotationVisibility(); break; - case "variables": + case "unsupported": showUnsupported( - "变量快照", - "Trace v2 不提供逐语句赋值后的实际值;View 只能展示 Analysis 中的静态参数与赋值目标,绝不猜测运行时数据。" + "变量快照 / 内存检查 / 调试器 / 证明状态", + "Trace v2 不提供逐语句赋值后的实际值或内存快照,公开协议也没有断点/单步通道;" + + "知识证明属于独立 Prove 工具。View 绝不猜测这些运行事实,相应能力在具备公开、受版本约束的协议前不会出现。" ); break; - case "memory": - showUnsupported( - "内存快照", - "当前公开协议没有内存观测通道;该能力需等待未来独立、受权限审计的调试协议。" - ); + case "theme": + cycleTheme(); break; case "about": openDialog("mq-dialog-about"); @@ -451,6 +465,18 @@ } }, true); + // Restore reading preferences (theme only; never secrets/permissions). + try { + var storedTheme = window.localStorage.getItem("marqdo.view.theme"); + if (storedTheme === "dark" || storedTheme === "light") { + applyTheme(storedTheme, false); + } else if (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches) { + applyTheme("dark", false); + } + } catch (error) { + /* storage is optional */ + } + // Restore a URL-selected mode, then honour the persisted diagnostics state. try { var params = new URLSearchParams(window.location.search); diff --git a/docs/ACCEPTANCE.md b/docs/ACCEPTANCE.md index d533f62..33c8357 100644 --- a/docs/ACCEPTANCE.md +++ b/docs/ACCEPTANCE.md @@ -15,31 +15,31 @@ | ID | 结果 | 证据 | |---|---|---| -| A-01 无旧 crate 依赖 | PASS | `tests/no_coupling.rs` 依赖/Cargo.lock/源码扫描 | +| A-01 无旧 crate 依赖 | PASS | `tests/contract/no_coupling.rs` 依赖/Cargo.lock/源码扫描 | | A-02 独立新仓库 clean build | PASS | acceptance `build`;无 `marqdo`/`marqdo-cli` 源码依赖 | | A-03 Tool v1 安装/分发 | PASS | acceptance `archive_install`、`tool_list`、`view_help`;`scripts/install-smoke.sh` | | A-04 CLI SHA-256 前后相同 | PASS | acceptance `core_sha`;manifest 中 before==after=`062cb56e…` | | A-05 旧审计与截图基准 | PASS(静态) | `docs/audits/legacy-render-paths.md`(`LEGACY_RUNTIME_UNVERIFIED` 已声明) | -| A-06 单一 Renderer/CSS 入口 | PASS | `tests/no_coupling.rs`、`tests/asset_integrity.rs`、ADR-0001/0002 | -| S-01 Knowledge/Exec/继承 | PASS | `tests/rendering.rs`、`tests/unicode_spans.rs`、冻结 Analysis golden | -| S-02 Emph/Strong/Code 载体 | PASS | `tests/rendering.rs`(4 个 Exec 锚点)、`tests/unicode_spans.rs` | +| A-06 单一 Renderer/CSS 入口 | PASS | `tests/contract/no_coupling.rs`、`tests/contract/asset_integrity.rs`、ADR-0001/0002 | +| S-01 Knowledge/Exec/继承 | PASS | `tests/integration/rendering.rs`、`tests/integration/unicode_spans.rs`、冻结 Analysis golden | +| S-02 Emph/Strong/Code 载体 | PASS | `tests/integration/rendering.rs`(4 个 Exec 锚点)、`tests/integration/unicode_spans.rs` | | S-03 Knowledge 惰性 | PASS | `knowledge_emphasis_never_becomes_an_execution_anchor` | -| S-04 中文/emoji/CRLF/重复语句 | PASS | `examples/unicode-spans` + 冻结 golden + `tests/unicode_spans.rs` | -| S-05 check 失败可读 | PASS | `tests/presentation_states.rs`、浏览器 diagnostics 区 | -| S-06 未知 Analysis major 拒绝 | PASS | `tests/semantic` 单测、`tests/presentation_states.rs`、`verify` 负测 | -| S-07 digest/span 篡改 | PASS | `tests/trace_contract.rs`、`tests/presentation_states.rs` | -| R-01 刷新 10 次不运行 | PASS | `tests/http_live.rs::opening_and_refreshing_never_runs_the_document` | -| R-02 导出纯静态 | PASS | `tests/export.rs`(marker 假核心 + argv 无 run) | +| S-04 中文/emoji/CRLF/重复语句 | PASS | `examples/unicode-spans` + 冻结 golden + `tests/integration/unicode_spans.rs` | +| S-05 check 失败可读 | PASS | `tests/contract/presentation_states.rs`、浏览器 diagnostics 区 | +| S-06 未知 Analysis major 拒绝 | PASS | `tests/semantic` 单测、`tests/contract/presentation_states.rs`、`verify` 负测 | +| S-07 digest/span 篡改 | PASS | `tests/contract/trace_contract.rs`、`tests/contract/presentation_states.rs` | +| R-01 刷新 10 次不运行 | PASS | `tests/integration/http_live.rs::opening_and_refreshing_never_runs_the_document` | +| R-02 导出纯静态 | PASS | `tests/integration/export.rs`(marker 假核心 + argv 无 run) | | R-03 用户确认后真实运行 | PASS | acceptance `real_run`(安装态、CSRF、真实 Trace) | -| R-04 trace 不匹配 → STALE | PASS | `tests/trace_contract.rs`、`tests/http_live.rs` | +| R-04 trace 不匹配 → STALE | PASS | `tests/contract/trace_contract.rs`、`tests/integration/http_live.rs` | | R-05 截断/运行错误 | PASS | 真实 truncated/arity golden + 页面状态 | | R-06 不猜未公开值 | PASS | Trace 模型无这些字段;UI `UNSUPPORTED`(`docs/design/state-matrix.md`) | -| X-01 恶意 Markdown | PASS | `tests/rendering.rs`、`tests/fixtures/security-project` 浏览器 | -| X-02 路径穿越/symlink | PASS | `tests/http_live.rs`、`SafeRelativePath` 单测 | -| X-03 跨站 POST run | PASS | `tests/http_live.rs`(token/Origin/confirm/mode) | +| X-01 恶意 Markdown | PASS | `tests/integration/rendering.rs`、`tests/fixtures/security-project` 浏览器 | +| X-02 路径穿越/symlink | PASS | `tests/integration/http_live.rs`、`SafeRelativePath` 单测 | +| X-03 跨站 POST run | PASS | `tests/integration/http_live.rs`(token/Origin/confirm/mode) | | X-04 无 JS/禁网/file:// | PASS | 浏览器 no-JS/外部请求检查;`scripts/test-export.sh` file:// Chromium | -| X-05 stdout 注入转义 | PASS | `tests/http_live.rs::program_stdout_is_escaped...` | -| X-06 超时/子进程清理 | PASS | `tests/core_contract.rs::timeout_kills_the_process_group...` | +| X-05 stdout 注入转义 | PASS | `tests/integration/http_live.rs::program_stdout_is_escaped...` | +| X-06 超时/子进程清理 | PASS | `tests/contract/core_contract.rs::timeout_kills_the_process_group...` | | P-01 文档可复现 | PASS | README / RFC / STATUS / COMPATIBILITY / ADR / 审计 / 证据 | | P-02 archive clean install | PASS | acceptance 从 `.tar.gz` 解包到临时目录安装并运行 | | P-03 协议审计 | PASS | `docs/audits/protocol-conformance.md` | @@ -52,8 +52,8 @@ | U-02 多宽度 | PASS | 390/600/900/1280/1664/1920/2560 真实 Chromium:无横向溢出、Dock 在视口内 | | U-03 键盘/焦点/屏幕阅读器 | PASS(基础) | Tab 可达命名控件、Esc 关闭、Ctrl/Cmd+K 搜索;完整 screen-reader 手工走查未做 | | U-04 动态曲线侧注 | **PARTIAL** | 运行事件使用**内联 keyed chip**(无 JS/移动/打印均可读);SVG 曲线侧注未实现,不画错线 | -| U-05 Welcome 仅显式配置 | PASS | `view.json` 驱动;`tests/rendering.rs`、浏览器 | -| U-06 Live/Export 内容对照 | PASS | `tests/rendering.rs` 同模型对照;导出复用同一 renderer | +| U-05 Welcome 仅显式配置 | PASS | `view.json` 驱动;`tests/integration/rendering.rs`、浏览器 | +| U-06 Live/Export 内容对照 | PASS | `tests/integration/rendering.rs` 同模型对照;导出复用同一 renderer | ## 复现 diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index e534294..914a1c6 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -11,10 +11,10 @@ | # | 条款 | 状态 | 实现位置 / 证据 | |---|---|---|---| -| M1 | 独立构建/测试/打包/安装;不改/不重编译 CLI;无私有 crate/Git/path 依赖 | PASS(0001 基线) | `Cargo.toml`、`tests/no_coupling.rs`、`scripts/acceptance.sh`(SHA 前后一致) | +| M1 | 独立构建/测试/打包/安装;不改/不重编译 CLI;无私有 crate/Git/path 依赖 | PASS(0001 基线) | `Cargo.toml`、`tests/contract/no_coupling.rs`、`scripts/acceptance.sh`(SHA 前后一致) | | M2 | 语言真相=Analysis v2;运行真相=`run/call --json`+Trace v2;原文=`.mq.md`;Markdown 不判语义 | PARTIAL | 已实现 Analysis 严格校验与 Trace 绑定;`call` 入口与请求合同待 PR-03/04 | -| M3 | 打开/刷新/搜索/切换/导出/预览/目录/诊断绝不运行 | PASS(0001 证据,待 0002 复核) | `tests/http_live.rs`、`tests/export.rs`、浏览器证据 | -| M4 | 单一 Read Model / HTML 组件 / CSS / JS;Live=Export | PASS(0001 证据) | `src/render.rs`、`src/assets.rs`、`tests/no_coupling.rs`、`tests/asset_integrity.rs` | +| M3 | 打开/刷新/搜索/切换/导出/预览/目录/诊断绝不运行 | PASS(0001 证据,待 0002 复核) | `tests/integration/http_live.rs`、`tests/integration/export.rs`、浏览器证据 | +| M4 | 单一 Read Model / HTML 组件 / CSS / JS;Live=Export | PASS(0001 证据) | `src/render.rs`、`src/assets.rs`、`tests/contract/no_coupling.rs`、`tests/contract/asset_integrity.rs` | | M5 | 原生执行只经 `MARQDO_BIN run/call` 子进程;无第二运行时 | PARTIAL | 子进程已有;`call` 与取消/状态机待 PR-03/04 | | M6 | Tool 是普通进程;不得宣称 OS 沙箱 | PARTIAL | 文档已声明;UI 文案待 PR-04/06 复核 | | M7 | 不开发 lint/knowledge/prove;无硬依赖 | N/A(合规) | 无相关目录/依赖 | @@ -25,8 +25,8 @@ | 功能 | 状态 | 计划/证据 | |---|---|---| | Markdown/GFM 阅读 | PASS | `src/document.rs`、`src/render.rs`、浏览器证据 | -| `@exec`/`@knowledge` 轻量标识(依 Analysis) | PASS | `src/semantic.rs`、`tests/rendering.rs` | -| 源码态 | PASS | `src/render.rs`、`tests/unicode_spans.rs` | +| `@exec`/`@knowledge` 轻量标识(依 Analysis) | PASS | `src/semantic.rs`、`tests/integration/rendering.rs` | +| 源码态 | PASS | `src/render.rs`、`tests/integration/unicode_spans.rs` | | 函数清单/导航 | PASS | `src/presentation.rs`、`src/render.rs` | | 单函数参数填写 + 调用 | **PENDING** | PR-03 请求合同 + PR-04 前端表单 | | 文档入口 `main` 执行 | PARTIAL | 同步 pure 已存在;需改为 SSE 异步任务(PR-04) | @@ -50,9 +50,9 @@ |---|---|---| | 唯一 Reader+Controller+CLI;无 DocumentService→Execution 隐式调用 | PARTIAL | 现同步架构无隐式执行;SSE 后复核 | | 层间数据结构(SourceDocument/AnalysisArtifact/SemanticAnchor/ExecutionRecord/PresentationModel) | PARTIAL | 现有类型可映射;PR-02/03 重整 | -| §5.3 目标目录(protocol/reader/execution/server/scripts/tests 树) | **PENDING** | PR-01/02/04 迁移 | +| §5.3 目标目录(protocol/reader/execution/server/scripts/tests 树) | PARTIAL | protocol/reader/config/scripts/tests(contract,integration) 已迁移;execution/server 拆分与 security 套件待 PR-03/04 | | §5.4 单一渲染流水线;Export 类型边界不可执行 | PASS(0001) | `src/export.rs` 不依赖执行层;PR-06 复核 | -| 无第二 Markdown AST/解释器/主题/JS 入口 | PASS | `tests/no_coupling.rs`、`tests/asset_integrity.rs` | +| 无第二 Markdown AST/解释器/主题/JS 入口 | PASS | `tests/contract/no_coupling.rs`、`tests/contract/asset_integrity.rs` | ## 4. §6 HTTP / SSE / 执行合同 @@ -77,7 +77,7 @@ |---|---|---| | PR-00 取证/基线 | **完成** | 待提交(本提交) | | PR-01 Tool/打包/scripts/CI/0.2.0 | **完成** | `scripts/package.sh`、`scripts/install-smoke.sh`、`scripts/verify-frozen-cli.sh`、`.github/workflows/ci.yml` | -| PR-02 Reader/Analysis 结构与只读路由 | PENDING | — | +| PR-02 Reader/Analysis 结构与只读路由 | **完成** | `src/protocol/*`、`src/reader/*`、`src/config.rs`、`/api/documents`、`tests/{contract,integration}`;`docs/evidence/PR-02/` | | PR-03 执行层/请求/进程/控制器 | PENDING | — | | PR-04 SSE/路由/会话/前端闭环 | PENDING | — | | PR-05 Trace 绑定/标注/浏览器回归 | PENDING | — | @@ -88,9 +88,9 @@ | 组 | 状态 | 说明 | |---|---|---| | E01 Tool 安装/卸载/分发 | PASS(0001 证据;PR-01 重跑) | `scripts/acceptance.sh` | -| E02 打开 knowledge+exec 文件不运行 | PASS | `tests/http_live.rs` | +| E02 打开 knowledge+exec 文件不运行 | PASS | `tests/integration/http_live.rs` | | E03 Source/Document 切换 | PASS | 浏览器证据 | -| E04 中文/Emoji/表格/公式 span | PASS | `tests/unicode_spans.rs`、golden | +| E04 中文/Emoji/表格/公式 span | PASS | `tests/integration/unicode_spans.rs`、golden | | E05 main 运行 run --json --trace-file | PARTIAL | 同步路径有;SSE 终态待 PR-04 | | E06 H2 Exec n=5 call | **PENDING** | PR-03/04 | | E07 文本/列表常量参数 | **PENDING** | PR-03/04 | @@ -101,7 +101,7 @@ | E12 长任务心跳/GET 不重启 | **PENDING** | PR-04 | | E13 取消终止进程树 | **PENDING** | PR-03/04 | | E14 静态导出零联网/相对链接 | PARTIAL | 已实现;PR-06 复核 | -| E15 刷新/重开不自动执行 | PASS | `tests/http_live.rs` | +| E15 刷新/重开不自动执行 | PASS | `tests/integration/http_live.rs` | | E16 运行后改源码 → stale 无高亮 | PARTIAL | 现有 stale;PR-05 复核 | | N01–N22 | PARTIAL | 0001 已覆盖部分(路径/XSS/跨站/digest/超时/打包完整性);SSE/去重/取消/会话项待 PR-04 补齐,逐项记录在 PR-05/06 证据 | diff --git a/docs/STATUS.md b/docs/STATUS.md index 2c658d8..4b5ccd2 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -22,7 +22,7 @@ |---|---|---| | PR-00 基线、旧 View 取证、冻结 CLI 合同 | **完成** | `docs/audits/legacy-view.md`、`docs/audits/protocol-contract-0002.md`、`docs/decisions/0007` | | PR-01 Tool v1 打包/安装/调度、0.2.0、scripts/、CI | **完成** | `scripts/package.sh`、`scripts/install-smoke.sh`、`scripts/verify-frozen-cli.sh`、`.github/workflows/ci.yml`;冻结 CLI `tool install`/`view --help`/篡改拒绝实测 | -| PR-02 Reader/Analysis 只读面与目标目录结构 | 待开始(现有 0001 实现可迁移) | `src/document.rs`、`src/semantic.rs`、`src/render.rs`、`src/server.rs` | +| PR-02 Reader/Analysis 只读面与目标目录结构 | **完成** | `src/protocol/*`、`src/reader/*`、`src/config.rs`、`tests/{contract,integration}/`、`/api/documents`;证据 `docs/evidence/PR-02/` | | PR-03 执行层:request/process/controller、pure + project grants | 待开始(现有同步 `pure` 执行可迁移) | `src/core_client.rs`、`src/app.rs` | | PR-04 SSE 任务生命周期、取消、7 路由、会话 Cookie/CSRF | **未实现(MVP 阻塞项)** | — | | PR-05 Trace 绑定/原文标注/浏览器回归 | 待开始(现有 Trace 校验可迁移) | `src/trace.rs` | @@ -36,7 +36,7 @@ |---|---| | 原始 Markdown/GFM 阅读、源码态、搜索/设置/打印 | 已实现(单一 `assets/reader.css`/`assets/reader.js`) | | Analysis v2 严格校验、函数/Unit/签名/诊断/导入/引用/资源投影 | 已实现(无效 span 降级) | -| 单一 `ReaderRenderer`,Live/Export 共用 | 已实现(门禁测试) | +| 单一 `ReaderRenderer`,Live/Export 共用 | 已实现(`src/reader/render.rs`,门禁测试) | | 显式确认后同步运行 `pure` + Trace v2 校验与展示 | 已实现,但**不是 0002 的异步 SSE 闭环** | | 静态离线导出(无执行、manifest/哈希、原子发布) | 已实现,待按 0002 重新验收 | | Tool v1 打包/安装/分发、冻结 CLI SHA 前后一致 | 已实现,待迁移至 `scripts/` 与 0.2.0 | @@ -63,10 +63,11 @@ 7. **执行预算未按 0002**:默认 30s(最大 120s)、`--fuel 1000000`、 `--max-output 1048576`、`--trace-max-events 10000`、`--trace-max-bytes 4194304`、 JSON/Trace/日志 4 MiB 有界读取与 `view.output_limit` 未实现。 -8. **目录/测试/脚本/示例未按 0002 §5.3**:缺 `src/protocol`、`src/reader`、 - `src/execution`、`src/server`、`tests/{contract,integration,security,browser, - fixtures,golden}`、`scripts/`、`examples/{welcome,branch-loop,function-params, - knowledge-only,unsafe-side-effect}.mq.md`、`.github/workflows/ci.yml`。 +8. **目录/测试/示例仍有缺口**:`src/protocol`/`src/reader`/`src/config.rs`/ + `tests/{contract,integration}`/`scripts/`/`.github/workflows/ci.yml` 已就位; + 仍缺 `src/execution/*`、`src/server/{mod,routes,security,sse}.rs`、 + `tests/security/` 套件、`examples/{welcome,branch-loop,function-params, + knowledge-only,unsafe-side-effect}.mq.md`、`docs/design` 0002 宽度截图矩阵。 9. **文档口径**:README/COMPATIBILITY/ACCEPTANCE 仍含 0001 时期表述,需在 PR-06 前全部更新为 0002 口径。 10. **视觉回归矩阵**:0002 要求 2048×1133 源参考与 1664×920/1440×900/1024×768/ diff --git a/docs/audits/legacy-view.md b/docs/audits/legacy-view.md index f04aa2f..dbf4722 100644 --- a/docs/audits/legacy-view.md +++ b/docs/audits/legacy-view.md @@ -5,7 +5,7 @@ - 日期:2026-11-22 - 旧产品来源:`cflmy/marqdo`,`main@1c55baabd570e18b9da8f9057cef2f848e176690` (本机只读 checkout `/root/work/marqdo`;新仓库**没有**任何 Git/path/Cargo 依赖) -- 新仓库:`marqdo-view`(独立 crate,见 `Cargo.toml` / `tests/no_coupling.rs`) +- 新仓库:`marqdo-view`(独立 crate,见 `Cargo.toml` / `tests/contract/no_coupling.rs`) - 结论适用范围:只作为**视觉与历史取证**。旧 `view` 的运行结果、旧 AST、旧 `RunCapture` 都**不是** 3.0 语言语义真值;语言真值只来自冻结 CLI 的 Analysis v2 / Trace v2(见 `docs/audits/protocol-contract-0002.md`)。 diff --git a/docs/audits/protocol-conformance.md b/docs/audits/protocol-conformance.md index a9d00fc..01709ec 100644 --- a/docs/audits/protocol-conformance.md +++ b/docs/audits/protocol-conformance.md @@ -17,12 +17,12 @@ | 条款 | 实现 | 测试/证据 | |---|---|---| -| `tool.json` schema/字段/SemVer/command/entrypoint | `tool.json`、`scripts/package.sh` | `tests/no_coupling.rs`;`scripts/install-smoke.sh` | +| `tool.json` schema/字段/SemVer/command/entrypoint | `tool.json`、`scripts/package.sh` | `tests/contract/no_coupling.rs`;`scripts/install-smoke.sh` | | 冻结核心安装、整包摘要、启动校验 | `scripts/install-smoke.sh`、`scripts/acceptance.sh` | acceptance `archive_install` PASS;手工篡改字节验证 README(PR-01 证据) | -| 环境变量 `MARQDO_BIN`/协议协商 | `src/core_client.rs`、`src/version.rs` | `tests/core_contract.rs`、`tests/http_live.rs` | -| argv 数组、无 shell、保留退出码/stdio | `src/core_client.rs` | `tests/core_contract.rs`(argv、timeout、fake core) | -| 不链接/不重编译/不读 CLI 源码 | 依赖图 | `tests/no_coupling.rs`、`docs/ADR/0001` | -| 篡改/缺文件/协议不兼容拒绝 | CLI 自身 + View 侧协商 | `tests/core_contract.rs`、`scripts/install-smoke.sh` | +| 环境变量 `MARQDO_BIN`/协议协商 | `src/core_client.rs`、`src/version.rs` | `tests/contract/core_contract.rs`、`tests/integration/http_live.rs` | +| argv 数组、无 shell、保留退出码/stdio | `src/core_client.rs` | `tests/contract/core_contract.rs`(argv、timeout、fake core) | +| 不链接/不重编译/不读 CLI 源码 | 依赖图 | `tests/contract/no_coupling.rs`、`docs/ADR/0001` | +| 篡改/缺文件/协议不兼容拒绝 | CLI 自身 + View 侧协商 | `tests/contract/core_contract.rs`、`scripts/install-smoke.sh` | ## 3. Analysis v2 @@ -32,7 +32,7 @@ | `schema/schema_version=2`、未知 major 拒绝 | `src/semantic.rs`、`src/app.rs`、`verify` | | `producer.markdown_profile=marqdo.md.v1` | `src/semantic.rs` | | `project.root_id/identity_kind/lock_digest/stdlib` | `SemanticProjection` 字段 + `verify --json` | -| `source_digest` 精确字节校验 | `src/semantic.rs`、`tests/unicode_spans.rs`(CRLF) | +| `source_digest` 精确字节校验 | `src/semantic.rs`、`tests/integration/unicode_spans.rs`(CRLF) | | modules/units/functions/signature/body kind/span | `src/semantic.rs`(typed projection) | | `resources[]` formula/code + `display`/language | `StaticResource`,渲染为惰性资源 | | `imports[]`/`references[]`/`calls[]` | 标签与引用状态;不重新解析优先级 | @@ -44,7 +44,7 @@ | 条款 | 实现 | |---|---| | `schema/schema_version=2` | `src/trace.rs` | -| `sha256(analysis bytes)==source.analysis_digest` | `verify_trace`;`tests/trace_contract.rs` | +| `sha256(analysis bytes)==source.analysis_digest` | `verify_trace`;`tests/contract/trace_contract.rs` | | `source.root_id==project.root_id` | `verify_trace` | | 事件 `module_id` ∈ Analysis modules | `verify_trace` | | `seq` 严格递增 | `verify_trace` | @@ -62,28 +62,28 @@ | 原始 Markdown 是阅读主体 | `DocumentModel` + `ReaderRenderer` | | 不重新决定可执行性 | 只有 `semantic.rs` 的 Analysis 事实创建锚点 | | `@exec/@knowledge` 显示前缀仅显示层剥离 | `docs/ADR/0003` | -| 知识区强调/行内代码不执行 | `tests/unicode_spans.rs::knowledge_emphasis_never_becomes_an_execution_anchor` | -| GFM 表/任务列表/围栏/数学可读且惰性 | `tests/rendering.rs`、`tests/export.rs` | +| 知识区强调/行内代码不执行 | `tests/integration/unicode_spans.rs::knowledge_emphasis_never_becomes_an_execution_anchor` | +| GFM 表/任务列表/围栏/数学可读且惰性 | `tests/integration/rendering.rs`、`tests/integration/export.rs` | | 原始 HTML 默认忽略、URL scheme 净化 | `src/render.rs`、浏览器安全 fixture | ## 6. Security 边界(View 自身) | 条款 | 实现 | 测试 | |---|---|---| -| loopback-only + Host 校验 | `src/server.rs` | `tests/http_live.rs` | -| CSRF/Origin/确认 | `POST /api/run` | `tests/http_live.rs` | -| 路径边界/单次解码/无遍历 | `SafeRelativePath`、`percent_decode` | `tests/http_live.rs`、`tests/project` 单测 | -| 导出纯只读、无执行 | `src/export.rs` | `tests/export.rs`(marker 假核心) | +| loopback-only + Host 校验 | `src/server.rs` | `tests/integration/http_live.rs` | +| CSRF/Origin/确认 | `POST /api/run` | `tests/integration/http_live.rs` | +| 路径边界/单次解码/无遍历 | `SafeRelativePath`、`percent_decode` | `tests/integration/http_live.rs`、`tests/project` 单测 | +| 导出纯只读、无执行 | `src/export.rs` | `tests/integration/export.rs`(marker 假核心) | | 离线文件:// | 内嵌资产 + 相对链接 | `scripts/test-export.sh` Chromium file:// | -| 输出/错误不泄露绝对路径 | `ViewError::public_message`、manifest 相对路径 | `tests/http_live.rs`、`tests/export.rs` | -| 无第二渲染器/第二主题 | 代码门禁 | `tests/no_coupling.rs`、`tests/asset_integrity.rs` | +| 输出/错误不泄露绝对路径 | `ViewError::public_message`、manifest 相对路径 | `tests/integration/http_live.rs`、`tests/integration/export.rs` | +| 无第二渲染器/第二主题 | 代码门禁 | `tests/contract/no_coupling.rs`、`tests/contract/asset_integrity.rs` | ## 7. 明确 UNSUPPORTED / 非目标 - 逐语句赋值实际值、参数实际值、变量历史、Memory 全状态:Trace v2 不提供,UI 只显示静态分析目标并明确说明。 - 知识“已证明”/Prove/Lint/Knowledge 引擎:不实现,等独立版本化协议。 - 调试器/断点/单步、Notebook/旧 2.x 语法兼容、SSE 流式运行、多运行历史:非首版目标。 -- `inspect --ir` / 私有 IR / 旧 `ViewExecutionReport`:没有作为依赖;`tests/no_coupling.rs` 门禁。 +- `inspect --ir` / 私有 IR / 旧 `ViewExecutionReport`:没有作为依赖;`tests/contract/no_coupling.rs` 门禁。 - 严格模式/项目 grants:首版运行仅 `pure`;`project`/`strict` 需要未来独立授权界面。 ## 8. 复核命令 diff --git a/docs/decisions/0003-heading-prefix-and-anchor-identity.md b/docs/decisions/0003-heading-prefix-and-anchor-identity.md index 341d7a1..4884ef2 100644 --- a/docs/decisions/0003-heading-prefix-and-anchor-identity.md +++ b/docs/decisions/0003-heading-prefix-and-anchor-identity.md @@ -22,6 +22,6 @@ ## 后果 -- 同页多个 H2/H3 永远得到不同 id;`tests/rendering.rs::semantic_annotations_come_from_analysis_and_are_unique` 断言唯一性。 +- 同页多个 H2/H3 永远得到不同 id;`tests/integration/rendering.rs::semantic_annotations_come_from_analysis_and_are_unique` 断言唯一性。 - Setext 标题没有合法前缀声明,会被原样显示并沿用自身 span 锚点;如果未来需要更精确的继承模式标注,必须通过新的公开协议字段实现,不能在 JS/CSS 里猜。 - 标题显示与源码态自动保持一致;无需额外“复制原文”逻辑。 diff --git a/docs/decisions/0004-explicit-run-csrf-and-cache.md b/docs/decisions/0004-explicit-run-csrf-and-cache.md index a040f53..3600f29 100644 --- a/docs/decisions/0004-explicit-run-csrf-and-cache.md +++ b/docs/decisions/0004-explicit-run-csrf-and-cache.md @@ -22,4 +22,4 @@ - 正面:运行路径可被 HTTP 层测试完整覆盖(拒绝路径不产生 `run` 进程;页面加载 10 次为 0 次运行);Live 与 Export 继续共用唯一的 Reader 渲染字节。 - 负面:运行完成后整页重载(保留阅读位置);首版无流式输出/取消/多运行历史;这些属于后续 PR,不得伪造。 -- 门禁:`tests/http_live.rs` 覆盖 token/Origin/confirm/mode/单活动/清缓存/源码变化 stale;`tests/trace_contract.rs` 覆盖 digest、module、seq、truncated、failed。 +- 门禁:`tests/integration/http_live.rs` 覆盖 token/Origin/confirm/mode/单活动/清缓存/源码变化 stale;`tests/contract/trace_contract.rs` 覆盖 digest、module、seq、truncated、failed。 diff --git a/docs/evidence/PR-01/README.md b/docs/evidence/PR-01/README.md index 294e764..71b6621 100644 --- a/docs/evidence/PR-01/README.md +++ b/docs/evidence/PR-01/README.md @@ -38,7 +38,7 @@ MARQDO_BIN="$MARQDO_BIN" scripts/package.sh | 冻结 CLI SHA | 全流程前后 | 均为 `062cb56e…`,**未变化**;未构建/修改 CLI | `cargo build --release --locked` 的依赖图不含 `marqdo-cli`/旧 `marqdo` 私有 crate -(`tests/no_coupling.rs` 门禁)。 +(`tests/contract/no_coupling.rs` 门禁)。 ## 备注 diff --git a/docs/evidence/PR-02/README.md b/docs/evidence/PR-02/README.md new file mode 100644 index 0000000..a0685ea --- /dev/null +++ b/docs/evidence/PR-02/README.md @@ -0,0 +1,80 @@ +# PR-02 证据:Reader/Analysis 结构与只读面(RFC-VIEW-0002) + +- 日期:2026-11-22 +- 范围:`src/protocol/*`、`src/reader/*`、`src/config.rs`、只读路由与阅读 UI 收敛 +- 冻结 CLI:`marqdo 3.0.0-beta.1`(`062cb56e…`),本 PR 不改/不重编译 +- 证据来源:本仓库 `cargo test`、`cargo clippy`、冻结 Analysis/Trace golden、 + 真实 Chromium 证据(0001 时期,PR-05 重新跑 0002 宽度矩阵) + +## 1. 目标目录结构(§5.3 的 Reader 部分) + +``` +src/ + main.rs # 唯一 composition root(解析参数后调用 lib::run) + lib.rs # 模块声明 + 用例分派(browse/verify/export),无第二管线 + cli.rs # View 自有参数解析 + config.rs # view.json 站点配置(不定义语言语义、不授权) + core_client.rs # 唯一 MARQDO_BIN 调用入口(check/negotiate/verify) + error.rs # 稳定错误码 + export.rs # 静态导出(只依赖 Reader,不依赖执行) + protocol/ + analysis_v2.rs # 公共 Analysis v2 解析/校验/投影 + trace_v2.rs # 公共 Trace v2 解析/校验/绑定 + tool_v1.rs # Tool v1 环境协商与版本轴 + reader/ + source.rs # 受控项目根、路径 containment、UTF-8 byte span、source digest + markdown.rs # 唯一 GFM 渲染器(无语义执行判断) + model.rs # PresentationModel / SourceStatus / Navigation / Outline + assemble.rs # 静态+运行产物合并、stale 判定、DocumentService + render.rs # 唯一 HTML 渲染入口(Live/Export 共用) + assets.rs # 构建期内嵌唯一 CSS/JS/图片 + server.rs # 过渡文件:只读路由;PR-04 拆为 server/{mod,routes,security,sse} +``` + +`app.rs`/`project.rs`/`semantic.rs`/`trace.rs`/`document.rs`/`presentation.rs`/ +`source_map.rs`/`render.rs`/`assets.rs` 旧路径已删除;`git mv` 保留历史。 +没有对旧 `marqdo` 或 `marqdo-cli` 的 crate/Git/path 依赖(`tests/contract/no_coupling.rs`)。 + +## 2. 只读 API 收敛(本 PR 部分) + +| 路由 | 状态 | +|---|---| +| `GET /` | 只读页面(不执行) | +| `GET /file?path=...` | 受控单文件页面(不执行) | +| `GET /assets/...` | 固定打包资产 | +| `GET /api/documents` | **新增**:文档列表 + 当前文档 outline/functions/analysis 摘要;只读 | +| `GET /api/document` | **删除**(旧单数路由,返回 404) | +| `GET /api/health`、`POST /api/run`、`/api/clear-run` | 过渡保留,PR-04 替换为 7 条合同路由(SSE) | + +`GET /api/documents` 测试:`tests/integration/http_live.rs::documents_api_is_a_read_only_structure_and_old_route_is_gone`。 + +## 3. 阅读 UI 收敛(§4.2/§4.5) + +- 页面只保留 `文档 / 函数 / 运行` 三项;`源码` 仍为“更多/局部切换”,无编辑器。 +- “更多”菜单删除“变量信息/内存快照”占位项,改为一个“未提供的能力”说明项 + (变量/内存/调试/证明均明确 UNSUPPORTED,不伪造)。 +- 新增简单深色主题开关(`data-theme` + 单一 token 覆盖层 + localStorage 偏好), + 无主题框架/远程皮肤;设置里可切字号/标注/主题/打印。 +- `tests/integration/rendering.rs::reader_exposes_simple_theme_toggle_and_no_variable_or_memory_tabs` + 断言页面不再出现 variables/memory 动作,且存在 theme/unsupported 动作。 + +## 4. 测试执行(实际) + +```bash +cargo fmt --all -- --check +cargo clippy --all-targets --offline -- -D warnings +cargo test --locked --offline +``` + +结果:unit 41 + contract 41 + integration 33 = **115 passed / 0 failed**。 +`cargo test` 的输出中每个 `[[test]]` 目标: +`contract`(CLI/Tool/Analysis/Trace/coupling/assets)、 +`integration`(Live HTTP/renderer/unicode/export)。 + +## 5. 未完成/后续 + +- `server.rs` 仍是单文件过渡实现;PR-04 拆分为 `server/{mod,routes,security,sse}.rs` + 并落实 7 路由、会话 Cookie、SSE、取消。 +- `GET /api/health`/`/api/run`/`/api/clear-run` 是 PR-03/PR-04 前的过渡路由, + 最终必须删除;当前不把“同步运行后整页重载”当作 0002 交付。 +- `tests/security/` 套件与 `docs/design` 的 0002 宽度截图矩阵在 PR-04/PR-05 补齐。 diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..db4e484 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,89 @@ +//! View-only site configuration (`view.json`). +//! +//! This is **not** a Marqdo language protocol and cannot grant execution. Only +//! welcome/site_title/theme are read, and the welcome path is subject to the +//! same project-root boundary (RFC-VIEW-0002 §4.2/§5.3). + +use crate::error::{ViewError, ViewResult}; +use crate::reader::source::SafeRelativePath; +use std::path::Path; + +/// Optional View-only site configuration (`view.json`). +/// +/// This is **not** a Marqdo language protocol and cannot grant execution: only +/// the fields below are read, and the welcome path is still subject to the same +/// project-root boundary (RFC-VIEW-0001 §9.4). +#[derive(Debug, Clone, Default)] +pub struct ViewConfig { + pub welcome: Option, + pub site_title: Option, + pub theme: Option, +} + +impl ViewConfig { + pub fn load(root: &Path) -> ViewResult { + let path = root.join("view.json"); + let metadata = match std::fs::metadata(&path) { + Ok(metadata) => metadata, + Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Self::default()), + Err(err) => return Err(ViewError::io(&format!("stat {}", path.display()), err)), + }; + if !metadata.is_file() || metadata.len() > 64 * 1024 { + return Err(ViewError::PathForbidden { + detail: "view.json must be a regular file under 64 KiB".to_string(), + }); + } + let bytes = std::fs::read(&path) + .map_err(|err| ViewError::io(&format!("read {}", path.display()), err))?; + #[derive(serde::Deserialize)] + struct RawConfig { + #[serde(default)] + schema: String, + #[serde(default)] + schema_version: u32, + #[serde(default)] + welcome: Option, + #[serde(default)] + site_title: Option, + #[serde(default)] + theme: Option, + } + let raw: RawConfig = serde_json::from_slice(&bytes).map_err(|err| ViewError::Io { + detail: format!("view.json is not valid JSON: {err}"), + })?; + if raw.schema != "marqdo.view-config" || raw.schema_version != 1 { + return Err(ViewError::ProtocolIncompatible { + detail: format!( + "unsupported view.json schema {:?} version {}; expected marqdo.view-config v1", + raw.schema, raw.schema_version + ), + }); + } + let welcome = match raw.welcome { + Some(path) => Some(SafeRelativePath::parse(&path)?), + None => None, + }; + if let Some(welcome) = &welcome { + if !root.join(welcome.to_path()).is_file() { + return Err(ViewError::PathForbidden { + detail: format!( + "view.json welcome file {welcome} does not exist under the project root" + ), + }); + } + } + let site_title = raw + .site_title + .map(|title| title.trim().to_string()) + .filter(|title| !title.is_empty() && title.chars().count() <= 80); + let theme = raw + .theme + .map(|theme| theme.trim().to_string()) + .filter(|theme| theme == "botanical" || theme == "paper"); + Ok(Self { + welcome, + site_title, + theme, + }) + } +} diff --git a/src/core_client.rs b/src/core_client.rs index 127ab4f..822a867 100644 --- a/src/core_client.rs +++ b/src/core_client.rs @@ -10,9 +10,9 @@ //! drop. use crate::error::{ViewError, ViewResult}; -use crate::project::{Project, SafeRelativePath}; -use crate::source_map::{sha256_hex, sha256_prefixed}; -use crate::version::{self, CoreVersion}; +use crate::protocol::tool_v1::{self, CoreVersion}; +use crate::reader::source::{sha256_hex, sha256_prefixed}; +use crate::reader::source::{Project, SafeRelativePath}; use serde::{Deserialize, Serialize}; use std::ffi::OsString; use std::io::Read; @@ -240,9 +240,9 @@ impl CoreClient { Ok(Self { bin, protocol_env: ProtocolEnv { - tool: std::env::var(version::ENV_TOOL_PROTOCOL).ok(), - analysis: std::env::var(version::ENV_PROTOCOL_ANALYSIS).ok(), - trace: std::env::var(version::ENV_PROTOCOL_TRACE).ok(), + tool: std::env::var(tool_v1::ENV_TOOL_PROTOCOL).ok(), + analysis: std::env::var(tool_v1::ENV_PROTOCOL_ANALYSIS).ok(), + trace: std::env::var(tool_v1::ENV_PROTOCOL_TRACE).ok(), }, }) } @@ -265,7 +265,7 @@ impl CoreClient { /// environment variables. A missing Development-mode env is allowed; an /// unknown major is a hard error. pub fn negotiate(&self) -> ViewResult { - version::negotiate_protocol_env( + tool_v1::negotiate_protocol_env( self.protocol_env.tool.as_deref(), self.protocol_env.analysis.as_deref(), self.protocol_env.trace.as_deref(), @@ -285,13 +285,13 @@ impl CoreClient { ), }); } - let version = version::parse_version_output(&output.stdout)?; - if !version::product_is_compatible(&version.version) { + let version = tool_v1::parse_version_output(&output.stdout)?; + if !tool_v1::product_is_compatible(&version.version) { return Err(ViewError::ProtocolIncompatible { detail: format!( "core {} is outside the supported range {}", version.version, - version::PRODUCT_RANGE + tool_v1::PRODUCT_RANGE ), }); } @@ -655,6 +655,145 @@ fn summarize_stderr(stderr: &str) -> String { } } +// --------------------------------------------------------------------------- +// `marqdo view verify`: static Analysis/source binding check. Never executes. +// --------------------------------------------------------------------------- + +use crate::cli::{RuntimeOpts, VerifyArgs}; +use crate::protocol::analysis_v2; + +pub fn verify_command(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult { + let path = args + .path + .clone() + .or_else(|| opts.path.clone()) + .unwrap_or_else(|| std::path::PathBuf::from(".")); + let project = Project::open(&path)?; + let entry = project.entry().relative.clone(); + let source_bytes = project.read_source(&entry)?; + let source = String::from_utf8(source_bytes).map_err(|err| ViewError::Io { + detail: format!("{entry} is not valid UTF-8: {err}"), + })?; + let source_index = crate::reader::source::SourceIndex::new(&source); + + let client = CoreClient::from_env(opts.marqdo_bin.as_deref())?; + let core_version = client.negotiate()?; + let response = client.check( + &project, + &entry, + &CheckOptions { + refs: args.refs, + timeout: None, + }, + )?; + let check = match response { + CheckResponse { + success: false, + diagnostics, + exit_code, + .. + } => { + let first = diagnostics + .first() + .map(|diagnostic| { + format!( + "{}: {}", + if diagnostic.code.is_empty() { + "diagnostic" + } else { + &diagnostic.code + }, + diagnostic.message + ) + }) + .unwrap_or_else(|| "no diagnostic detail".to_string()); + return Err(ViewError::AnalysisFailed { + detail: format!( + "`marqdo check` failed with exit code {exit_code} ({} diagnostic(s)); first: {first}", + diagnostics.len() + ), + }); + } + CheckResponse { + analysis: Some(check), + .. + } => check, + CheckResponse { analysis: None, .. } => { + return Err(ViewError::AnalysisFailed { + detail: "`marqdo check` succeeded but emitted no Analysis".to_string(), + }) + } + }; + let verified = analysis_v2::verify_analysis( + &check.analysis_bytes, + &source, + &source_index, + entry.as_str(), + )?; + let projection = &verified.projection; + + if args.json { + let doc = serde_json::json!({ + "schema": "marqdo.view-verify", + "schema_version": 1, + "ok": true, + "core": { + "version": core_version.version.to_string(), + "supported_range": tool_v1::PRODUCT_RANGE, + }, + "analysis": { + "schema": "marqdo.analysis", + "schema_version": tool_v1::ANALYSIS_PROTOCOL, + "digest": projection.analysis_digest, + "producer_version": projection.producer_version, + "markdown_profile": projection.markdown_profile, + "functions": projection.functions.len(), + "units": projection.units.len(), + "diagnostics": projection.diagnostics.len(), + }, + "project": { + "root_id": projection.project_root_id, + "identity_kind": projection.identity_kind, + "lock_digest": projection.lock_digest, + "stdlib_version": projection.stdlib_version, + }, + "document": { + "relative_path": entry.as_str(), + "module_id": projection.module_id, + "source_digest": projection.source_digest, + "source_digest_matches": true, + }, + "result": "PASS", + "executed": false, + "note": "Static verification only; the document was not executed.", + }); + println!( + "{}", + serde_json::to_string_pretty(&doc).unwrap_or_else(|_| "{}".to_string()) + ); + } else { + println!( + "core: marqdo {} (supported {})", + core_version.version, + tool_v1::PRODUCT_RANGE + ); + println!( + "project: {} ({})", + projection.project_root_id, projection.identity_kind + ); + println!("document: {entry}"); + println!( + "analysis: schema=marqdo.analysis v2 modules={} functions={} digest={}", + projection.modules.len(), + projection.functions.len(), + projection.analysis_digest + ); + println!("source digest: match"); + println!("result: PASS (static only; document not executed)"); + } + Ok(0) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/export.rs b/src/export.rs index 0fa59b6..30eb2e0 100644 --- a/src/export.rs +++ b/src/export.rs @@ -1,15 +1,15 @@ //! Pure static site export. //! -//! Export uses the same `AppContext::load` (static `check` only) and the same +//! Export uses the same `DocumentService::load` (static `check` only) and the same //! `ReaderRenderer` as Live; it never calls `run`, never starts a provider and //! never writes into the source project (RFC-VIEW-0001 §11.3). -use crate::app::AppContext; -use crate::assets::AssetBundle; use crate::error::{ViewError, ViewResult}; -use crate::project::SafeRelativePath; -use crate::render::ReaderRenderer; -use crate::source_map::sha256_hex; +use crate::reader::assemble::DocumentService; +use crate::reader::assets::AssetBundle; +use crate::reader::render::ReaderRenderer; +use crate::reader::source::sha256_hex; +use crate::reader::source::SafeRelativePath; use std::path::{Path, PathBuf}; const MANIFEST_SCHEMA: &str = "marqdo.view-export"; @@ -28,7 +28,7 @@ pub struct ExportSummary { pub manifest_sha256: String, } -pub fn export(context: &AppContext, options: &ExportOptions) -> ViewResult { +pub fn export(context: &DocumentService, options: &ExportOptions) -> ViewResult { let bundle = AssetBundle::get(); let renderer = ReaderRenderer::new(); let root = context.project().root().to_path_buf(); @@ -89,7 +89,7 @@ pub fn export(context: &AppContext, options: &ExportOptions) -> ViewResult ViewResult ViewResult ViewResult { let opts = cli.runtime(); cli::validate_bind(&opts.host, opts.unsafe_expose) .map_err(|detail| ViewError::BindDenied { detail })?; match cli.command { - Some(cli::Command::Verify(args)) => app::verify(&opts, &args), - Some(cli::Command::Export(args)) => app::export(&opts, &args), - None => app::browse(&opts), + Some(cli::Command::Verify(args)) => core_client::verify_command(&opts, &args), + Some(cli::Command::Export(args)) => export_command(&opts, &args), + None => browse_command(&opts), } } + +/// `marqdo view [PATH]`: open the read-only Live reader. Never executes. +fn browse_command(opts: &RuntimeOpts) -> ViewResult { + let path = opts + .path + .clone() + .unwrap_or_else(|| std::path::PathBuf::from(".")); + let service = DocumentService::open(&path, opts.marqdo_bin.as_deref())?; + crate::server::serve(service, opts) +} + +/// `marqdo view export PATH --out DIR`: static export through the same Reader +/// model. The export path has no execution capability by type (RFC §5.4). +fn export_command(opts: &RuntimeOpts, args: &ExportArgs) -> ViewResult { + let path = args + .path + .clone() + .or_else(|| opts.path.clone()) + .unwrap_or_else(|| std::path::PathBuf::from(".")); + let service = DocumentService::open(&path, opts.marqdo_bin.as_deref())?; + let summary = export::export( + &service, + &ExportOptions { + out: args.out.clone(), + no_annotations: args.no_annotations, + }, + )?; + println!( + "marqdo view export: {} page(s), {} file(s) → {}", + summary.pages, + summary.files, + summary.out.display() + ); + println!("manifest: sha256:{}", summary.manifest_sha256); + println!("executed: false (纯静态导出,未运行任何文档)"); + Ok(0) +} diff --git a/src/semantic.rs b/src/protocol/analysis_v2.rs similarity index 99% rename from src/semantic.rs rename to src/protocol/analysis_v2.rs index 0cc05e9..e4f7f58 100644 --- a/src/semantic.rs +++ b/src/protocol/analysis_v2.rs @@ -7,8 +7,7 @@ //! instead of being pointed at nearby text (RFC-VIEW-0001 §4.3, §8.2). use crate::error::{ViewError, ViewResult}; -use crate::source_map::{sha256_hex, sha256_prefixed, SourceIndex, SourceSpan}; -use crate::version; +use crate::reader::source::{sha256_hex, sha256_prefixed, SourceIndex, SourceSpan}; use serde::Deserialize; use serde_json::Value; @@ -549,12 +548,12 @@ pub fn verify_analysis( detail: format!("unexpected Analysis schema {:?}", raw.schema), }); } - if raw.schema_version != version::ANALYSIS_PROTOCOL { + if raw.schema_version != crate::protocol::tool_v1::ANALYSIS_PROTOCOL { return Err(ViewError::ProtocolIncompatible { detail: format!( "Analysis schema_version {} is not supported (View implements v{})", raw.schema_version, - version::ANALYSIS_PROTOCOL + crate::protocol::tool_v1::ANALYSIS_PROTOCOL ), }); } diff --git a/src/protocol/mod.rs b/src/protocol/mod.rs new file mode 100644 index 0000000..0c932d7 --- /dev/null +++ b/src/protocol/mod.rs @@ -0,0 +1,8 @@ +//! Public protocol adapters consumed by View. +//! +//! These modules are a **consumer** of the published CLI formats, never a +//! second publisher or implementation of them (RFC-VIEW-0002 §5.3). + +pub mod analysis_v2; +pub mod tool_v1; +pub mod trace_v2; diff --git a/src/version.rs b/src/protocol/tool_v1.rs similarity index 100% rename from src/version.rs rename to src/protocol/tool_v1.rs diff --git a/src/trace.rs b/src/protocol/trace_v2.rs similarity index 98% rename from src/trace.rs rename to src/protocol/trace_v2.rs index c176594..d690eeb 100644 --- a/src/trace.rs +++ b/src/protocol/trace_v2.rs @@ -7,8 +7,8 @@ //! states, never invented (RFC-VIEW-0001 §4.4, §12). use crate::error::{ViewError, ViewResult}; -use crate::semantic::{ModuleSummary, SemanticProjection}; -use crate::source_map::{sha256_hex, sha256_prefixed, SourceIndex, SourceSpan}; +use crate::protocol::analysis_v2::{ModuleSummary, SemanticProjection}; +use crate::reader::source::{sha256_hex, sha256_prefixed, SourceIndex, SourceSpan}; use serde::Deserialize; use serde_json::Value; @@ -343,12 +343,12 @@ pub fn verify_trace(input: TraceVerificationInput<'_>) -> ViewResult { + pub document: DocumentModel, + pub analysis: Option<&'a crate::protocol::analysis_v2::VerifiedAnalysis>, + pub status: SourceStatus, + pub status_note: Option, + pub diagnostics: Vec, + pub navigation: Navigation, + pub core_version: Option, + pub run: Option<&'a crate::protocol::trace_v2::VerifiedRun>, +} + +pub fn build(input: BuildInput<'_>) -> PresentationModel { + let BuildInput { + mut document, + analysis, + status, + status_note, + mut diagnostics, + navigation, + core_version, + run, + } = input; + + let semantic = analysis.map(|verified| verified.projection.clone()); + if let Some(projection) = &semantic { + document.identity = DocumentIdentity { + project_root_id: projection.project_root_id.clone(), + module_id: projection.module_id.clone(), + relative_path: projection.relative_path.clone(), + source_sha256: projection.source_digest.clone(), + }; + for diagnostic in &projection.diagnostics { + if !diagnostics.iter().any(|existing| { + existing.code == diagnostic.code + && existing.message == diagnostic.message + && existing.span == diagnostic.span + }) { + diagnostics.push(diagnostic.clone()); + } + } + } + let warnings = semantic + .as_ref() + .map(|projection| projection.warnings.clone()) + .unwrap_or_default(); + let outline = semantic.as_ref().map(build_outline).unwrap_or_default(); + + PresentationModel { + version: PRESENTATION_VERSION, + title: document.title(), + document, + semantic, + source_status: status, + status_note, + diagnostics, + warnings, + navigation, + outline, + core_version, + run: run.map(|verified| verified.projection.clone()), + } +} + +fn build_outline(projection: &SemanticProjection) -> Vec { + let mut entries = Vec::new(); + for function in &projection.functions { + let params = if function.signature.params.is_empty() { + String::new() + } else { + function + .signature + .params + .iter() + .map(|param| { + if param.ty.is_empty() { + param.name.clone() + } else { + format!("{}: {}", param.name, param.ty) + } + }) + .collect::>() + .join(", ") + }; + let detail = if params.is_empty() { + "无参数".to_string() + } else { + format!("params({params})") + }; + entries.push(OutlineEntry { + label: function.local_name.clone(), + anchor: anchor_for_span(function.heading_span.start, function.heading_span.end), + detail, + kind: OutlineKind::Function, + }); + } + for unit in &projection.units { + let kind = match unit.kind { + crate::protocol::analysis_v2::UnitKind::Knowledge if unit.level >= 2 => { + OutlineKind::Knowledge + } + crate::protocol::analysis_v2::UnitKind::Section => OutlineKind::Section, + _ => continue, + }; + if unit.name.is_empty() { + continue; + } + entries.push(OutlineEntry { + label: unit.name.clone(), + anchor: anchor_for_span(unit.span.start, unit.span.end), + detail: if unit.level == 2 { + "知识单元".to_string() + } else { + "章节".to_string() + }, + kind, + }); + } + entries +} + +pub struct DocumentService { project: Project, config: ViewConfig, core: Option, @@ -27,7 +150,7 @@ pub struct AppContext { core_note: Option, } -impl AppContext { +impl DocumentService { pub fn open(path: &std::path::Path, marqdo_bin: Option<&std::path::Path>) -> ViewResult { let project = Project::open(path)?; let config = ViewConfig::load(project.root())?; @@ -126,7 +249,7 @@ impl AppContext { success: true, analysis: Some(check), .. - } => match semantic::verify_analysis( + } => match analysis_v2::verify_analysis( &check.analysis_bytes, &document.source, &document.source_index, @@ -172,7 +295,7 @@ impl AppContext { }) } else { Some(VerifiedRun { - projection: trace::stale_projection( + projection: trace_v2::stale_projection( &run.projection.analysis_digest, &document.source_index, ), @@ -180,7 +303,7 @@ impl AppContext { } } (Some(run), None) => Some(VerifiedRun { - projection: trace::stale_projection( + projection: trace_v2::stale_projection( &run.projection.analysis_digest, &document.source_index, ), @@ -188,7 +311,7 @@ impl AppContext { (None, _) => None, }; - Ok(presentation::build(BuildInput { + Ok(build(BuildInput { document, analysis: verified.as_ref(), status, @@ -208,11 +331,11 @@ impl AppContext { detail: "没有可用的冻结核心(MARQDO_BIN),运行被拒绝".to_string(), })?; let source_bytes = self.project.read_source(relative)?; - let source_digest = crate::source_map::sha256_hex(&source_bytes); + let source_digest = crate::reader::source::sha256_hex(&source_bytes); let source = String::from_utf8(source_bytes).map_err(|err| ViewError::Io { detail: format!("{relative} is not valid UTF-8: {err}"), })?; - let source_index = crate::source_map::SourceIndex::new(&source); + let source_index = crate::reader::source::SourceIndex::new(&source); let run = client.run( &self.project, @@ -237,13 +360,13 @@ impl AppContext { let check = response.analysis.ok_or_else(|| ViewError::AnalysisFailed { detail: "运行后的静态检查失败,无法绑定 Trace".to_string(), })?; - let verified = semantic::verify_analysis( + let verified = analysis_v2::verify_analysis( &check.analysis_bytes, &source, &source_index, relative.as_str(), )?; - let verified_run = trace::verify_trace(TraceVerificationInput { + let verified_run = trace_v2::verify_trace(TraceVerificationInput { trace_bytes: &trace_bytes, analysis_bytes: &check.analysis_bytes, semantic: &verified.projection, @@ -267,172 +390,6 @@ pub struct ExecutedRun { pub analysis_digest: String, } -pub fn verify(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult { - let path = args - .path - .clone() - .or_else(|| opts.path.clone()) - .unwrap_or_else(|| std::path::PathBuf::from(".")); - let project = Project::open(&path)?; - let entry = project.entry().relative.clone(); - let source_bytes = project.read_source(&entry)?; - let source = String::from_utf8(source_bytes).map_err(|err| ViewError::Io { - detail: format!("{entry} is not valid UTF-8: {err}"), - })?; - let source_index = crate::source_map::SourceIndex::new(&source); - - let client = CoreClient::from_env(opts.marqdo_bin.as_deref())?; - let core_version = client.negotiate()?; - let response = client.check( - &project, - &entry, - &CheckOptions { - refs: args.refs, - timeout: None, - }, - )?; - let check = match response { - CheckResponse { - success: false, - diagnostics, - exit_code, - .. - } => { - let first = diagnostics - .first() - .map(|diagnostic| { - format!( - "{}: {}", - if diagnostic.code.is_empty() { - "diagnostic" - } else { - &diagnostic.code - }, - diagnostic.message - ) - }) - .unwrap_or_else(|| "no diagnostic detail".to_string()); - return Err(ViewError::AnalysisFailed { - detail: format!( - "`marqdo check` failed with exit code {exit_code} ({} diagnostic(s)); first: {first}", - diagnostics.len() - ), - }); - } - CheckResponse { - analysis: Some(check), - .. - } => check, - CheckResponse { analysis: None, .. } => { - return Err(ViewError::AnalysisFailed { - detail: "`marqdo check` succeeded but emitted no Analysis".to_string(), - }) - } - }; - let verified = semantic::verify_analysis( - &check.analysis_bytes, - &source, - &source_index, - entry.as_str(), - )?; - let projection = &verified.projection; - - if args.json { - let doc = serde_json::json!({ - "schema": "marqdo.view-verify", - "schema_version": 1, - "ok": true, - "core": { - "version": core_version.version.to_string(), - "supported_range": version::PRODUCT_RANGE, - }, - "analysis": { - "schema": "marqdo.analysis", - "schema_version": version::ANALYSIS_PROTOCOL, - "digest": projection.analysis_digest, - "producer_version": projection.producer_version, - "markdown_profile": projection.markdown_profile, - "functions": projection.functions.len(), - "units": projection.units.len(), - "diagnostics": projection.diagnostics.len(), - }, - "project": { - "root_id": projection.project_root_id, - "identity_kind": projection.identity_kind, - "lock_digest": projection.lock_digest, - "stdlib_version": projection.stdlib_version, - }, - "document": { - "relative_path": entry.as_str(), - "module_id": projection.module_id, - "source_digest": projection.source_digest, - "source_digest_matches": true, - }, - "result": "PASS", - "executed": false, - "note": "Static verification only; the document was not executed.", - }); - println!( - "{}", - serde_json::to_string_pretty(&doc).unwrap_or_else(|_| "{}".to_string()) - ); - } else { - println!( - "core: marqdo {} (supported {})", - core_version.version, - version::PRODUCT_RANGE - ); - println!( - "project: {} ({})", - projection.project_root_id, projection.identity_kind - ); - println!("document: {entry}"); - println!( - "analysis: schema=marqdo.analysis v2 modules={} functions={} digest={}", - projection.modules.len(), - projection.functions.len(), - projection.analysis_digest - ); - println!("source digest: match"); - println!("result: PASS (static only; document not executed)"); - } - Ok(0) -} - -pub fn browse(opts: &RuntimeOpts) -> ViewResult { - let path = opts - .path - .clone() - .unwrap_or_else(|| std::path::PathBuf::from(".")); - let context = AppContext::open(&path, opts.marqdo_bin.as_deref())?; - crate::server::serve(context, opts) -} - -pub fn export(opts: &RuntimeOpts, args: &ExportArgs) -> ViewResult { - let path = args - .path - .clone() - .or_else(|| opts.path.clone()) - .unwrap_or_else(|| std::path::PathBuf::from(".")); - let context = AppContext::open(&path, opts.marqdo_bin.as_deref())?; - let summary = run_export( - &context, - &ExportOptions { - out: args.out.clone(), - no_annotations: args.no_annotations, - }, - )?; - println!( - "marqdo view export: {} page(s), {} file(s) → {}", - summary.pages, - summary.files, - summary.out.display() - ); - println!("manifest: sha256:{}", summary.manifest_sha256); - println!("executed: false (纯静态导出,未运行任何文档)"); - Ok(0) -} - fn generic_core_note(err: &ViewError) -> String { match err.code() { "view.core_missing" => { diff --git a/src/assets.rs b/src/reader/assets.rs similarity index 92% rename from src/assets.rs rename to src/reader/assets.rs index 3a912f6..13fced4 100644 --- a/src/assets.rs +++ b/src/reader/assets.rs @@ -4,7 +4,7 @@ //! asset carries its SHA-256; browser URLs use a hash prefix so a changed asset //! can never be confused with a cached older one. -use crate::source_map::sha256_hex; +use crate::reader::source::sha256_hex; use std::collections::HashMap; use std::sync::OnceLock; @@ -45,31 +45,31 @@ impl AssetBundle { "reader", "css", "text/css; charset=utf-8", - include_bytes!("../assets/reader.css"), + include_bytes!("../../assets/reader.css"), ), asset( "reader", "js", "text/javascript; charset=utf-8", - include_bytes!("../assets/reader.js"), + include_bytes!("../../assets/reader.js"), ), asset( "logo", "svg", "image/svg+xml", - include_bytes!("../assets/logo.svg"), + include_bytes!("../../assets/logo.svg"), ), asset( "blossom", "webp", "image/webp", - include_bytes!("../assets/blossom.webp"), + include_bytes!("../../assets/blossom.webp"), ), asset( "feather", "webp", "image/webp", - include_bytes!("../assets/feather.webp"), + include_bytes!("../../assets/feather.webp"), ), ]; let mut by_hashed_name = HashMap::new(); @@ -183,15 +183,15 @@ mod tests { let bundle = AssetBundle::get(); assert_eq!( bundle.css().sha256, - sha256_hex(include_bytes!("../assets/reader.css")) + sha256_hex(include_bytes!("../../assets/reader.css")) ); assert_eq!( bundle.js().sha256, - sha256_hex(include_bytes!("../assets/reader.js")) + sha256_hex(include_bytes!("../../assets/reader.js")) ); assert_eq!( bundle.logo().sha256, - sha256_hex(include_bytes!("../assets/logo.svg")) + sha256_hex(include_bytes!("../../assets/logo.svg")) ); assert_eq!(bundle.assets[3].sha256.len(), 64); assert!(bundle.by_path(&bundle.logo().hashed_name()).is_some()); diff --git a/src/document.rs b/src/reader/markdown.rs similarity index 99% rename from src/document.rs rename to src/reader/markdown.rs index d380e81..a9eea2f 100644 --- a/src/document.rs +++ b/src/reader/markdown.rs @@ -6,8 +6,8 @@ //! No semantic decision (which node is executable) is taken here — that comes //! exclusively from validated Analysis v2 (`semantic.rs`). -use crate::project::SafeRelativePath; -use crate::source_map::{sha256_hex, SourceIndex, SourceSpan}; +use crate::reader::source::SafeRelativePath; +use crate::reader::source::{sha256_hex, SourceIndex, SourceSpan}; use comrak::nodes::{ListType, NodeValue, Sourcepos, TableAlignment}; use comrak::{parse_document, Arena, Options}; diff --git a/src/reader/mod.rs b/src/reader/mod.rs new file mode 100644 index 0000000..5070736 --- /dev/null +++ b/src/reader/mod.rs @@ -0,0 +1,12 @@ +//! Reader layer: controlled source access, Markdown rendering, the one +//! presentation model, assembly from public protocols, and the one renderer. +//! +//! Live and Export share every type here; only link policy and interaction +//! availability differ (RFC-VIEW-0002 §4.3/§5.4). + +pub mod assemble; +pub mod assets; +pub mod markdown; +pub mod model; +pub mod render; +pub mod source; diff --git a/src/presentation.rs b/src/reader/model.rs similarity index 58% rename from src/presentation.rs rename to src/reader/model.rs index 8a67751..0605fc1 100644 --- a/src/presentation.rs +++ b/src/reader/model.rs @@ -1,13 +1,14 @@ //! Presentation model: the one intermediate form between verified domain data -//! and the one `ReaderRenderer`. +//! and the one `ReaderRenderer` (RFC-VIEW-0002 §5.2). //! -//! Nothing here spawns processes, builds HTML or parses Markdown semantics. It -//! only composes already-verified pieces (RFC-VIEW-0001 §6.3, §14.2). +//! Nothing here spawns processes, builds HTML or parses Markdown semantics. +//! Assembly from Analysis/Trace happens in `reader::assemble`. -use crate::document::{DocumentIdentity, DocumentModel}; -use crate::project::{Project, SafeRelativePath, ViewConfig}; -use crate::semantic::{CoreDiagnostic, SemanticProjection, ViewWarning}; -use crate::trace::{RunDisplayState, RunProjection}; +use crate::config::ViewConfig; +use crate::protocol::analysis_v2::{CoreDiagnostic, SemanticProjection, ViewWarning}; +use crate::protocol::trace_v2::{RunDisplayState, RunProjection}; +use crate::reader::markdown::DocumentModel; +use crate::reader::source::{Project, SafeRelativePath}; /// Private View presentation-model version. Not a public protocol. pub const PRESENTATION_VERSION: u32 = 1; @@ -158,125 +159,6 @@ impl PresentationModel { } } -/// Input to the one builder. `analysis` is already protocol/byte verified. -pub struct BuildInput<'a> { - pub document: DocumentModel, - pub analysis: Option<&'a crate::semantic::VerifiedAnalysis>, - pub status: SourceStatus, - pub status_note: Option, - pub diagnostics: Vec, - pub navigation: Navigation, - pub core_version: Option, - pub run: Option<&'a crate::trace::VerifiedRun>, -} - -pub fn build(input: BuildInput<'_>) -> PresentationModel { - let BuildInput { - mut document, - analysis, - status, - status_note, - mut diagnostics, - navigation, - core_version, - run, - } = input; - - let semantic = analysis.map(|verified| verified.projection.clone()); - if let Some(projection) = &semantic { - document.identity = DocumentIdentity { - project_root_id: projection.project_root_id.clone(), - module_id: projection.module_id.clone(), - relative_path: projection.relative_path.clone(), - source_sha256: projection.source_digest.clone(), - }; - for diagnostic in &projection.diagnostics { - if !diagnostics.iter().any(|existing| { - existing.code == diagnostic.code - && existing.message == diagnostic.message - && existing.span == diagnostic.span - }) { - diagnostics.push(diagnostic.clone()); - } - } - } - let warnings = semantic - .as_ref() - .map(|projection| projection.warnings.clone()) - .unwrap_or_default(); - let outline = semantic.as_ref().map(build_outline).unwrap_or_default(); - - PresentationModel { - version: PRESENTATION_VERSION, - title: document.title(), - document, - semantic, - source_status: status, - status_note, - diagnostics, - warnings, - navigation, - outline, - core_version, - run: run.map(|verified| verified.projection.clone()), - } -} - -fn build_outline(projection: &SemanticProjection) -> Vec { - let mut entries = Vec::new(); - for function in &projection.functions { - let params = if function.signature.params.is_empty() { - String::new() - } else { - function - .signature - .params - .iter() - .map(|param| { - if param.ty.is_empty() { - param.name.clone() - } else { - format!("{}: {}", param.name, param.ty) - } - }) - .collect::>() - .join(", ") - }; - let detail = if params.is_empty() { - "无参数".to_string() - } else { - format!("params({params})") - }; - entries.push(OutlineEntry { - label: function.local_name.clone(), - anchor: anchor_for_span(function.heading_span.start, function.heading_span.end), - detail, - kind: OutlineKind::Function, - }); - } - for unit in &projection.units { - let kind = match unit.kind { - crate::semantic::UnitKind::Knowledge if unit.level >= 2 => OutlineKind::Knowledge, - crate::semantic::UnitKind::Section => OutlineKind::Section, - _ => continue, - }; - if unit.name.is_empty() { - continue; - } - entries.push(OutlineEntry { - label: unit.name.clone(), - anchor: anchor_for_span(unit.span.start, unit.span.end), - detail: if unit.level == 2 { - "知识单元".to_string() - } else { - "章节".to_string() - }, - kind, - }); - } - entries -} - /// Deterministic heading anchor derived from the heading byte span. It never /// depends on rendered text, so duplicate headings cannot collide. pub fn anchor_for_span(start: u64, end: u64) -> String { diff --git a/src/render.rs b/src/reader/render.rs similarity index 98% rename from src/render.rs rename to src/reader/render.rs index 120a4ad..df77291 100644 --- a/src/render.rs +++ b/src/reader/render.rs @@ -10,12 +10,12 @@ //! Markdown is serialized here from the View-owned `DocBlock` tree, with raw //! HTML omitted by default and every URL scheme sanitized. -use crate::assets::AssetBundle; -use crate::document::{DocBlock, Inline, TableAlign}; -use crate::presentation::{anchor_for_span, PresentationModel}; -use crate::project::SafeRelativePath; -use crate::semantic::{source_id, UnitKind}; -use crate::source_map::SourceSpan; +use crate::protocol::analysis_v2::{source_id, UnitKind}; +use crate::reader::assets::AssetBundle; +use crate::reader::markdown::{DocBlock, Inline, TableAlign}; +use crate::reader::model::{anchor_for_span, PresentationModel}; +use crate::reader::source::SafeRelativePath; +use crate::reader::source::SourceSpan; use std::fmt::Write as _; /// How links to other documents are resolved. This is the only Live/Export @@ -156,7 +156,7 @@ impl ReaderRenderer { - + 跳到正文 "##, presentation_version = model.version, @@ -205,7 +205,7 @@ impl ReaderRenderer { html: &mut String, model: &PresentationModel, _ctx: &RenderContext, - navigation: &crate::presentation::Navigation, + navigation: &crate::reader::model::Navigation, ) { let active = model .navigation @@ -254,7 +254,7 @@ impl ReaderRenderer { ); } - fn render_welcome(&self, html: &mut String, navigation: &crate::presentation::Navigation) { + fn render_welcome(&self, html: &mut String, navigation: &crate::reader::model::Navigation) { let _ = write!( html, r##"
@@ -509,6 +509,7 @@ impl ReaderRenderer {

阅读设置

  • +
@@ -519,8 +520,7 @@ impl ReaderRenderer {
  • -
  • -
  • +
  • @@ -918,7 +918,7 @@ fn resolve_heading_unit( model: &PresentationModel, heading_span: SourceSpan, level: u8, -) -> Option<&crate::semantic::SemanticUnit> { +) -> Option<&crate::protocol::analysis_v2::SemanticUnit> { let projection = model.semantic.as_ref()?; // A function heading maps to its function unit exactly; never borrow the // ancestor function for H3/H4 sections (that would duplicate DOM ids). @@ -945,7 +945,7 @@ fn resolve_heading_unit( fn display_heading_content( content: &[Inline], - unit: Option<&crate::semantic::SemanticUnit>, + unit: Option<&crate::protocol::analysis_v2::SemanticUnit>, ) -> (Option<(&'static str, &'static str)>, Vec) { let Some(unit) = unit else { return (None, content.to_vec()); diff --git a/src/project.rs b/src/reader/source.rs similarity index 59% rename from src/project.rs rename to src/reader/source.rs index f0db180..05851e9 100644 --- a/src/project.rs +++ b/src/reader/source.rs @@ -1,10 +1,293 @@ -//! Project-root and path boundary enforcement. +//! Exact UTF-8 byte ↔ line/column ↔ JavaScript UTF-16 offset mapping. //! -//! Production, HTTP, Export and tests all use these functions; there is no -//! second path validator (RFC-VIEW-0001 §14.4). +//! Core Analysis/Trace spans are half-open UTF-8 **byte** offsets into the +//! original file bytes. Browsers count UTF-16 code units. This module is the +//! only place that converts between them (RFC-VIEW-0001 §8.2). + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +/// Half-open byte span `[start, end)` into one module's exact source bytes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] +pub struct SourceSpan { + pub start: u64, + pub end: u64, +} + +impl SourceSpan { + pub fn new(start: u64, end: u64) -> Self { + Self { start, end } + } + + pub fn is_empty(&self) -> bool { + self.start == self.end + } + + pub fn len(&self) -> u64 { + self.end.saturating_sub(self.start) + } + + pub fn contains(&self, other: SourceSpan) -> bool { + self.start <= other.start && other.end <= self.end + } + + pub fn intersects(&self, other: SourceSpan) -> bool { + self.start < other.end && other.start < self.end + } + + pub fn as_usize_range(&self) -> Option> { + let start = usize::try_from(self.start).ok()?; + let end = usize::try_from(self.end).ok()?; + if start > end { + return None; + } + Some(start..end) + } +} + +/// Compute lowercase hex SHA-256 of exact bytes (no normalization). +pub fn sha256_hex(bytes: &[u8]) -> String { + let mut hasher = Sha256::new(); + hasher.update(bytes); + let digest = hasher.finalize(); + let mut out = String::with_capacity(64); + for byte in digest { + use std::fmt::Write as _; + let _ = write!(out, "{byte:02x}"); + } + out +} + +/// SHA-256 with the `sha256:` prefix used by Analysis/Trace identity fields. +pub fn sha256_prefixed(bytes: &[u8]) -> String { + format!("sha256:{}", sha256_hex(bytes)) +} + +/// Immutable source index built from the exact original bytes. +#[derive(Debug, Clone)] +pub struct SourceIndex { + /// Byte length of the source. + len: usize, + /// Byte offset of the start of every line (0-based line number). + line_starts: Vec, + /// Number of leading UTF-8 BOM bytes tolerated before the first content + /// byte. Spans in Analysis are relative to the file bytes, so the BOM + /// stays part of the index. + bom_len: usize, +} + +impl SourceIndex { + pub fn new(source: &str) -> Self { + let bytes = source.as_bytes(); + let bom_len = if source.starts_with('\u{feff}') { 3 } else { 0 }; + let mut line_starts = vec![0usize]; + let mut index = bom_len; + while index < bytes.len() { + if bytes[index] == b'\n' { + line_starts.push(index + 1); + } + index += 1; + } + Self { + len: bytes.len(), + line_starts, + bom_len, + } + } + + pub fn len(&self) -> usize { + self.len + } + + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + pub fn bom_len(&self) -> usize { + self.bom_len + } + + pub fn source_text<'a>(&self, source: &'a str, span: SourceSpan) -> Option<&'a str> { + if !self.validate_span_bytes(source.as_bytes(), span) { + return None; + } + let range = span.as_usize_range()?; + source.get(range) + } + + /// True when the span is in range and both ends are UTF-8 code-point + /// boundaries of the supplied original bytes. + pub fn validate_span_bytes(&self, bytes: &[u8], span: SourceSpan) -> bool { + let (Ok(start), Ok(end)) = (usize::try_from(span.start), usize::try_from(span.end)) else { + return false; + }; + if start > end || end > bytes.len() { + return false; + } + is_char_boundary(bytes, start) && is_char_boundary(bytes, end) + } + + /// Byte offset of the start of a 1-based line. + pub fn line_start(&self, line: usize) -> Option { + if line == 0 { + return None; + } + self.line_starts.get(line - 1).copied() + } + + /// Number of lines in the source. + pub fn line_count(&self) -> usize { + self.line_starts.len() + } + + /// Text of a 1-based line without its trailing newline. + pub fn line_text<'a>(&self, source: &'a str, line: usize) -> Option<&'a str> { + let start = self.line_start(line)?; + let end = self.line_starts.get(line).copied().unwrap_or(self.len); + let bytes = source.as_bytes(); + let mut end = end.min(bytes.len()); + if end > start && bytes.get(end - 1) == Some(&b'\n') { + end -= 1; + if end > start && bytes.get(end - 1) == Some(&b'\r') { + end -= 1; + } + } + source.get(start..end) + } + + /// 1-based line and 1-based byte column for a byte offset, clamped to the + /// file length. Column counts bytes, matching Core's presentation fields. + pub fn line_col(&self, byte: usize) -> (usize, usize) { + let byte = byte.min(self.len); + let line_index = match self.line_starts.binary_search(&byte) { + Ok(found) => found, + Err(insert) => insert.saturating_sub(1), + }; + let line_start = self.line_starts[line_index]; + (line_index + 1, byte - line_start + 1) + } + + /// Byte offset → number of UTF-16 code units before it (JS string index). + pub fn utf16_offset(&self, source: &str, byte: usize) -> Option { + if byte > source.len() || !is_char_boundary(source.as_bytes(), byte) { + return None; + } + Some(source[..byte].encode_utf16().count()) + } + + /// Byte offset for a UTF-16 offset, only when it lands on a boundary. + pub fn byte_for_utf16(&self, source: &str, utf16: usize) -> Option { + let mut units = 0usize; + for (byte, ch) in source.char_indices() { + if units == utf16 { + return Some(byte); + } + if units > utf16 { + return None; + } + units += ch.len_utf16(); + } + if units == utf16 { + Some(source.len()) + } else { + None + } + } + + /// True when an arbitrary `(line, column)` from a Core diagnostic is inside + /// the source index; line/column are presentation hints, spans are primary. + pub fn line_col_in_range(&self, line: u64, column: u64) -> bool { + let Ok(line) = usize::try_from(line) else { + return false; + }; + let Ok(column) = usize::try_from(column) else { + return false; + }; + if line == 0 || column == 0 || line > self.line_starts.len() { + return false; + } + let start = self.line_starts[line - 1]; + let end = self.line_starts.get(line).copied().unwrap_or(self.len); + start + column - 1 <= end + } +} + +fn is_char_boundary(bytes: &[u8], offset: usize) -> bool { + if offset == 0 || offset >= bytes.len() { + return offset <= bytes.len(); + } + // UTF-8 continuation bytes start with 0b10. + bytes[offset] & 0b1100_0000 != 0b1000_0000 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn maps_multibyte_and_emoji_offsets() { + let source = "中文\nemoji🙂x\r\nlast"; + let index = SourceIndex::new(source); + let emoji_byte = source.find('🙂').unwrap(); + assert_eq!(index.line_col(emoji_byte), (2, 6)); + let utf16 = index.utf16_offset(source, emoji_byte).unwrap(); + assert_eq!(index.byte_for_utf16(source, utf16), Some(emoji_byte)); + // Inside the emoji is not a char boundary. + assert!(index.utf16_offset(source, emoji_byte + 1).is_none()); + let span = SourceSpan::new(emoji_byte as u64, (emoji_byte + 4) as u64); + assert_eq!(index.source_text(source, span), Some("🙂")); + } + + #[test] + fn rejects_out_of_range_and_misaligned_spans() { + let source = "# 数学"; + let index = SourceIndex::new(source); + assert!( + index.validate_span_bytes(source.as_bytes(), SourceSpan::new(0, source.len() as u64)) + ); + assert!(!index.validate_span_bytes( + source.as_bytes(), + SourceSpan::new(0, source.len() as u64 + 1) + )); + assert!(!index.validate_span_bytes(source.as_bytes(), SourceSpan::new(2, 1))); + // 2 is the middle of the 3-byte 字/数? Either way it is not a boundary + // for the CJK character starting at 2..5; check the interior byte 3. + assert!(!index.validate_span_bytes(source.as_bytes(), SourceSpan::new(3, 5))); + } + + #[test] + fn digest_is_exact_bytes() { + assert_eq!( + sha256_hex(b""), + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + ); + assert_eq!( + sha256_prefixed(b"a"), + "sha256:ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb" + ); + } + + #[test] + fn bom_is_still_indexed() { + let source = "\u{feff}# hi"; + let index = SourceIndex::new(source); + assert_eq!(index.bom_len(), 3); + assert_eq!(index.line_col(3), (1, 4)); + assert_eq!( + index.source_text(source, SourceSpan::new(0, 3)), + Some("\u{feff}") + ); + } +} + +// --------------------------------------------------------------------------- +// Controlled project root, path boundary and document source access. +// +// All production/HTTP/Export/tests use these functions; there is no second +// path validator (RFC-VIEW-0002 §5.2/§6.8). +// --------------------------------------------------------------------------- use crate::error::{ViewError, ViewResult}; -use crate::source_map::sha256_hex; use std::path::{Path, PathBuf}; /// Hard cap on one source document, matching the Core read limit family. @@ -306,86 +589,6 @@ impl Project { } } -/// Optional View-only site configuration (`view.json`). -/// -/// This is **not** a Marqdo language protocol and cannot grant execution: only -/// the fields below are read, and the welcome path is still subject to the same -/// project-root boundary (RFC-VIEW-0001 §9.4). -#[derive(Debug, Clone, Default)] -pub struct ViewConfig { - pub welcome: Option, - pub site_title: Option, - pub theme: Option, -} - -impl ViewConfig { - pub fn load(root: &Path) -> ViewResult { - let path = root.join("view.json"); - let metadata = match std::fs::metadata(&path) { - Ok(metadata) => metadata, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Self::default()), - Err(err) => return Err(ViewError::io(&format!("stat {}", path.display()), err)), - }; - if !metadata.is_file() || metadata.len() > 64 * 1024 { - return Err(ViewError::PathForbidden { - detail: "view.json must be a regular file under 64 KiB".to_string(), - }); - } - let bytes = std::fs::read(&path) - .map_err(|err| ViewError::io(&format!("read {}", path.display()), err))?; - #[derive(serde::Deserialize)] - struct RawConfig { - #[serde(default)] - schema: String, - #[serde(default)] - schema_version: u32, - #[serde(default)] - welcome: Option, - #[serde(default)] - site_title: Option, - #[serde(default)] - theme: Option, - } - let raw: RawConfig = serde_json::from_slice(&bytes).map_err(|err| ViewError::Io { - detail: format!("view.json is not valid JSON: {err}"), - })?; - if raw.schema != "marqdo.view-config" || raw.schema_version != 1 { - return Err(ViewError::ProtocolIncompatible { - detail: format!( - "unsupported view.json schema {:?} version {}; expected marqdo.view-config v1", - raw.schema, raw.schema_version - ), - }); - } - let welcome = match raw.welcome { - Some(path) => Some(SafeRelativePath::parse(&path)?), - None => None, - }; - if let Some(welcome) = &welcome { - if !root.join(welcome.to_path()).is_file() { - return Err(ViewError::PathForbidden { - detail: format!( - "view.json welcome file {welcome} does not exist under the project root" - ), - }); - } - } - let site_title = raw - .site_title - .map(|title| title.trim().to_string()) - .filter(|title| !title.is_empty() && title.chars().count() <= 80); - let theme = raw - .theme - .map(|theme| theme.trim().to_string()) - .filter(|theme| theme == "botanical" || theme == "paper"); - Ok(Self { - welcome, - site_title, - theme, - }) - } -} - /// Discover the project root for a source file: nearest ancestor with /// `marqdo.yaml`, else the file's directory. The file itself is canonical. pub fn discover_project_root(file: &Path) -> PathBuf { @@ -434,7 +637,7 @@ fn canonicalize(path: &Path, what: &str) -> ViewResult { } #[cfg(test)] -mod tests { +mod path_tests { use super::*; #[test] diff --git a/src/server.rs b/src/server.rs index 42b5f22..3351bd7 100644 --- a/src/server.rs +++ b/src/server.rs @@ -4,15 +4,15 @@ //! exposed until the explicit-run flow lands; every response carries a strict //! CSP and the Host header is validated to blunt DNS-rebinding. -use crate::app::AppContext; -use crate::assets::AssetBundle; use crate::cli::RuntimeOpts; use crate::error::{ViewError, ViewResult}; -use crate::presentation::PresentationModel; -use crate::project::SafeRelativePath; -use crate::render::{ReaderRenderer, RenderContext}; -use crate::source_map::sha256_hex; -use crate::trace::VerifiedRun; +use crate::protocol::trace_v2::VerifiedRun; +use crate::reader::assemble::DocumentService; +use crate::reader::assets::AssetBundle; +use crate::reader::model::PresentationModel; +use crate::reader::render::{ReaderRenderer, RenderContext}; +use crate::reader::source::sha256_hex; +use crate::reader::source::SafeRelativePath; use std::collections::HashMap; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; @@ -22,7 +22,7 @@ const MAX_URL_BYTES: usize = 2048; const MAX_QUERY_BYTES: usize = 4096; const MAX_BODY_BYTES: usize = 16 * 1024; -pub fn serve(ctx: AppContext, opts: &RuntimeOpts) -> ViewResult { +pub fn serve(ctx: DocumentService, opts: &RuntimeOpts) -> ViewResult { let address = format!("{}:{}", opts.host, opts.port); let server = Server::http(&address).map_err(|err| ViewError::Io { detail: format!("listen on {address}: {err}"), @@ -89,7 +89,7 @@ pub fn serve(ctx: AppContext, opts: &RuntimeOpts) -> ViewResult { } struct ServerState { - ctx: AppContext, + ctx: DocumentService, csrf_token: String, renderer: ReaderRenderer, cache: Mutex>, @@ -291,7 +291,7 @@ fn handle(state: &ServerState, request: Request) -> ViewResult<()> { Err(err) => serve_error_page(request, &err, is_head), } } - "/api/document" => { + "/api/documents" => { let relative = match query_param(query, "path") .and_then(|raw| percent_decode(&raw)) .map(|decoded| SafeRelativePath::parse(&decoded)) @@ -303,7 +303,7 @@ fn handle(state: &ServerState, request: Request) -> ViewResult<()> { None => state.ctx.project().entry().relative.clone(), }; match state.load_for_page(&relative, query_param(query, "run").as_deref()) { - Ok(model) => serve_document_json(request, &model), + Ok(model) => serve_documents_json(state, request, &relative, &model), Err(err) => respond_json_error(request, StatusCode(500), &err), } } @@ -326,9 +326,9 @@ fn handle(state: &ServerState, request: Request) -> ViewResult<()> { "version": state.ctx.core_version(), }, "protocols": { - "tool": crate::version::TOOL_PROTOCOL, - "analysis": crate::version::ANALYSIS_PROTOCOL, - "trace": crate::version::TRACE_PROTOCOL, + "tool": crate::protocol::tool_v1::TOOL_PROTOCOL, + "analysis": crate::protocol::tool_v1::ANALYSIS_PROTOCOL, + "trace": crate::protocol::tool_v1::TRACE_PROTOCOL, }, "documents": documents, "run_api": true, @@ -684,7 +684,7 @@ fn serve_page( is_head: bool, ) -> ViewResult<()> { let ctx = RenderContext { - links: crate::render::LinkPolicy::LocalServer, + links: crate::reader::render::LinkPolicy::LocalServer, live: true, csrf_token: Some(state.csrf_token.clone()), run_available: state.ctx.core().is_some() && model.can_offer_run(), @@ -703,55 +703,84 @@ fn serve_error_page(request: Request, err: &ViewError, is_head: bool) -> ViewRes respond_html(request, html.into_bytes(), is_head) } -fn serve_document_json(request: Request, model: &PresentationModel) -> ViewResult<()> { +fn serve_documents_json( + state: &ServerState, + request: Request, + relative: &SafeRelativePath, + model: &PresentationModel, +) -> ViewResult<()> { let semantic = model.semantic.as_ref(); + let documents = state + .ctx + .project() + .list_documents() + .unwrap_or_default() + .into_iter() + .map(|path| { + serde_json::json!({ + "path": path.as_str(), + "active": path == *relative, + }) + }) + .collect::>(); + let functions = model + .outline + .iter() + .filter(|entry| entry.kind == crate::reader::model::OutlineKind::Function) + .map(|entry| { + serde_json::json!({ + "label": entry.label, + "anchor": entry.anchor, + "detail": entry.detail, + }) + }) + .collect::>(); let doc = serde_json::json!({ - "schema": "marqdo.view-document", + "schema": "marqdo.view-documents", "schema_version": 1, - "title": model.title, - "document": { + "entry": state.ctx.project().entry().relative.as_str(), + "documents": documents, + "current": { "relative_path": model.document.identity.relative_path, "module_id": model.document.identity.module_id, + "title": model.title, "source_sha256": sha256_hex(model.document.source.as_bytes()), + "source_status": model.source_status.data_value(), + "semantics_usable": model.source_status.semantics_usable(), + "analysis": semantic.map(|projection| serde_json::json!({ + "digest": projection.analysis_digest, + "schema_version": crate::protocol::tool_v1::ANALYSIS_PROTOCOL, + "producer_version": projection.producer_version, + "project_root_id": projection.project_root_id, + "functions": projection.functions.len(), + "units": projection.units.len(), + "diagnostics": projection.diagnostics.len(), + })), + "outline": model.outline.iter().map(|entry| serde_json::json!({ + "label": entry.label, + "anchor": entry.anchor, + "detail": entry.detail, + "kind": match entry.kind { + crate::reader::model::OutlineKind::Function => "function", + crate::reader::model::OutlineKind::Knowledge => "knowledge", + crate::reader::model::OutlineKind::Section => "section", + }, + })).collect::>(), + "functions": functions, + "run": model.run.as_ref().map(|run| serde_json::json!({ + "state": run.state.data_value(), + "label": run.state.label(), + "run_id": run.run_id, + "run_status": run.run_status, + "exit_code": run.exit_code, + "event_count": run.counts.total(), + "entry_event_count": run.entry_event_count, + "truncated": run.truncated.as_ref().map(|truncated| truncated.label()), + "has_result_value": run.result_value.is_some(), + })), + "can_offer_run": model.can_offer_run(), }, - "source_status": model.source_status.data_value(), - "semantics_usable": model.source_status.semantics_usable(), - "analysis": semantic.map(|projection| serde_json::json!({ - "digest": projection.analysis_digest, - "schema_version": crate::version::ANALYSIS_PROTOCOL, - "producer_version": projection.producer_version, - "project_root_id": projection.project_root_id, - "functions": projection.functions.len(), - "units": projection.units.len(), - "diagnostics": projection.diagnostics.len(), - })), - "outline": model.outline.iter().map(|entry| serde_json::json!({ - "label": entry.label, - "anchor": entry.anchor, - "detail": entry.detail, - "kind": match entry.kind { - crate::presentation::OutlineKind::Function => "function", - crate::presentation::OutlineKind::Knowledge => "knowledge", - crate::presentation::OutlineKind::Section => "section", - }, - })).collect::>(), - "navigation": { - "documents": model.navigation.documents.iter().map(|doc| doc.as_str()).collect::>(), - "welcome": model.navigation.welcome, - }, - "run": model.run.as_ref().map(|run| serde_json::json!({ - "state": run.state.data_value(), - "label": run.state.label(), - "run_id": run.run_id, - "run_status": run.run_status, - "exit_code": run.exit_code, - "event_count": run.counts.total(), - "entry_event_count": run.entry_event_count, - "truncated": run.truncated.as_ref().map(|truncated| truncated.label()), - "has_result_value": run.result_value.is_some(), - })), - "can_offer_run": model.can_offer_run(), - "note": "Read-only PresentationModel summary; this page load never executes the document.", + "note": "Read-only document structure; this request never executes the document.", }); respond_json(request, StatusCode(200), &doc) } diff --git a/src/source_map.rs b/src/source_map.rs deleted file mode 100644 index 34c14ba..0000000 --- a/src/source_map.rs +++ /dev/null @@ -1,281 +0,0 @@ -//! Exact UTF-8 byte ↔ line/column ↔ JavaScript UTF-16 offset mapping. -//! -//! Core Analysis/Trace spans are half-open UTF-8 **byte** offsets into the -//! original file bytes. Browsers count UTF-16 code units. This module is the -//! only place that converts between them (RFC-VIEW-0001 §8.2). - -use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; - -/// Half-open byte span `[start, end)` into one module's exact source bytes. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] -pub struct SourceSpan { - pub start: u64, - pub end: u64, -} - -impl SourceSpan { - pub fn new(start: u64, end: u64) -> Self { - Self { start, end } - } - - pub fn is_empty(&self) -> bool { - self.start == self.end - } - - pub fn len(&self) -> u64 { - self.end.saturating_sub(self.start) - } - - pub fn contains(&self, other: SourceSpan) -> bool { - self.start <= other.start && other.end <= self.end - } - - pub fn intersects(&self, other: SourceSpan) -> bool { - self.start < other.end && other.start < self.end - } - - pub fn as_usize_range(&self) -> Option> { - let start = usize::try_from(self.start).ok()?; - let end = usize::try_from(self.end).ok()?; - if start > end { - return None; - } - Some(start..end) - } -} - -/// Compute lowercase hex SHA-256 of exact bytes (no normalization). -pub fn sha256_hex(bytes: &[u8]) -> String { - let mut hasher = Sha256::new(); - hasher.update(bytes); - let digest = hasher.finalize(); - let mut out = String::with_capacity(64); - for byte in digest { - use std::fmt::Write as _; - let _ = write!(out, "{byte:02x}"); - } - out -} - -/// SHA-256 with the `sha256:` prefix used by Analysis/Trace identity fields. -pub fn sha256_prefixed(bytes: &[u8]) -> String { - format!("sha256:{}", sha256_hex(bytes)) -} - -/// Immutable source index built from the exact original bytes. -#[derive(Debug, Clone)] -pub struct SourceIndex { - /// Byte length of the source. - len: usize, - /// Byte offset of the start of every line (0-based line number). - line_starts: Vec, - /// Number of leading UTF-8 BOM bytes tolerated before the first content - /// byte. Spans in Analysis are relative to the file bytes, so the BOM - /// stays part of the index. - bom_len: usize, -} - -impl SourceIndex { - pub fn new(source: &str) -> Self { - let bytes = source.as_bytes(); - let bom_len = if source.starts_with('\u{feff}') { 3 } else { 0 }; - let mut line_starts = vec![0usize]; - let mut index = bom_len; - while index < bytes.len() { - if bytes[index] == b'\n' { - line_starts.push(index + 1); - } - index += 1; - } - Self { - len: bytes.len(), - line_starts, - bom_len, - } - } - - pub fn len(&self) -> usize { - self.len - } - - pub fn is_empty(&self) -> bool { - self.len == 0 - } - - pub fn bom_len(&self) -> usize { - self.bom_len - } - - pub fn source_text<'a>(&self, source: &'a str, span: SourceSpan) -> Option<&'a str> { - if !self.validate_span_bytes(source.as_bytes(), span) { - return None; - } - let range = span.as_usize_range()?; - source.get(range) - } - - /// True when the span is in range and both ends are UTF-8 code-point - /// boundaries of the supplied original bytes. - pub fn validate_span_bytes(&self, bytes: &[u8], span: SourceSpan) -> bool { - let (Ok(start), Ok(end)) = (usize::try_from(span.start), usize::try_from(span.end)) else { - return false; - }; - if start > end || end > bytes.len() { - return false; - } - is_char_boundary(bytes, start) && is_char_boundary(bytes, end) - } - - /// Byte offset of the start of a 1-based line. - pub fn line_start(&self, line: usize) -> Option { - if line == 0 { - return None; - } - self.line_starts.get(line - 1).copied() - } - - /// Number of lines in the source. - pub fn line_count(&self) -> usize { - self.line_starts.len() - } - - /// Text of a 1-based line without its trailing newline. - pub fn line_text<'a>(&self, source: &'a str, line: usize) -> Option<&'a str> { - let start = self.line_start(line)?; - let end = self.line_starts.get(line).copied().unwrap_or(self.len); - let bytes = source.as_bytes(); - let mut end = end.min(bytes.len()); - if end > start && bytes.get(end - 1) == Some(&b'\n') { - end -= 1; - if end > start && bytes.get(end - 1) == Some(&b'\r') { - end -= 1; - } - } - source.get(start..end) - } - - /// 1-based line and 1-based byte column for a byte offset, clamped to the - /// file length. Column counts bytes, matching Core's presentation fields. - pub fn line_col(&self, byte: usize) -> (usize, usize) { - let byte = byte.min(self.len); - let line_index = match self.line_starts.binary_search(&byte) { - Ok(found) => found, - Err(insert) => insert.saturating_sub(1), - }; - let line_start = self.line_starts[line_index]; - (line_index + 1, byte - line_start + 1) - } - - /// Byte offset → number of UTF-16 code units before it (JS string index). - pub fn utf16_offset(&self, source: &str, byte: usize) -> Option { - if byte > source.len() || !is_char_boundary(source.as_bytes(), byte) { - return None; - } - Some(source[..byte].encode_utf16().count()) - } - - /// Byte offset for a UTF-16 offset, only when it lands on a boundary. - pub fn byte_for_utf16(&self, source: &str, utf16: usize) -> Option { - let mut units = 0usize; - for (byte, ch) in source.char_indices() { - if units == utf16 { - return Some(byte); - } - if units > utf16 { - return None; - } - units += ch.len_utf16(); - } - if units == utf16 { - Some(source.len()) - } else { - None - } - } - - /// True when an arbitrary `(line, column)` from a Core diagnostic is inside - /// the source index; line/column are presentation hints, spans are primary. - pub fn line_col_in_range(&self, line: u64, column: u64) -> bool { - let Ok(line) = usize::try_from(line) else { - return false; - }; - let Ok(column) = usize::try_from(column) else { - return false; - }; - if line == 0 || column == 0 || line > self.line_starts.len() { - return false; - } - let start = self.line_starts[line - 1]; - let end = self.line_starts.get(line).copied().unwrap_or(self.len); - start + column - 1 <= end - } -} - -fn is_char_boundary(bytes: &[u8], offset: usize) -> bool { - if offset == 0 || offset >= bytes.len() { - return offset <= bytes.len(); - } - // UTF-8 continuation bytes start with 0b10. - bytes[offset] & 0b1100_0000 != 0b1000_0000 -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn maps_multibyte_and_emoji_offsets() { - let source = "中文\nemoji🙂x\r\nlast"; - let index = SourceIndex::new(source); - let emoji_byte = source.find('🙂').unwrap(); - assert_eq!(index.line_col(emoji_byte), (2, 6)); - let utf16 = index.utf16_offset(source, emoji_byte).unwrap(); - assert_eq!(index.byte_for_utf16(source, utf16), Some(emoji_byte)); - // Inside the emoji is not a char boundary. - assert!(index.utf16_offset(source, emoji_byte + 1).is_none()); - let span = SourceSpan::new(emoji_byte as u64, (emoji_byte + 4) as u64); - assert_eq!(index.source_text(source, span), Some("🙂")); - } - - #[test] - fn rejects_out_of_range_and_misaligned_spans() { - let source = "# 数学"; - let index = SourceIndex::new(source); - assert!( - index.validate_span_bytes(source.as_bytes(), SourceSpan::new(0, source.len() as u64)) - ); - assert!(!index.validate_span_bytes( - source.as_bytes(), - SourceSpan::new(0, source.len() as u64 + 1) - )); - assert!(!index.validate_span_bytes(source.as_bytes(), SourceSpan::new(2, 1))); - // 2 is the middle of the 3-byte 字/数? Either way it is not a boundary - // for the CJK character starting at 2..5; check the interior byte 3. - assert!(!index.validate_span_bytes(source.as_bytes(), SourceSpan::new(3, 5))); - } - - #[test] - fn digest_is_exact_bytes() { - assert_eq!( - sha256_hex(b""), - "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" - ); - assert_eq!( - sha256_prefixed(b"a"), - "sha256:ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb" - ); - } - - #[test] - fn bom_is_still_indexed() { - let source = "\u{feff}# hi"; - let index = SourceIndex::new(source); - assert_eq!(index.bom_len(), 3); - assert_eq!(index.line_col(3), (1, 4)); - assert_eq!( - index.source_text(source, SourceSpan::new(0, 3)), - Some("\u{feff}") - ); - } -} diff --git a/tests/asset_integrity.rs b/tests/contract/asset_integrity.rs similarity index 97% rename from tests/asset_integrity.rs rename to tests/contract/asset_integrity.rs index 6ecdc4b..6d15158 100644 --- a/tests/asset_integrity.rs +++ b/tests/contract/asset_integrity.rs @@ -49,7 +49,7 @@ fn reused_assets_match_their_recorded_hashes() { #[test] fn embedded_asset_bundle_matches_disk_and_has_one_theme() { - let bundle = marqdo_view::assets::AssetBundle::get(); + let bundle = marqdo_view::reader::assets::AssetBundle::get(); let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); let css = std::fs::read(root.join("assets/reader.css")).unwrap(); assert_eq!(sha256_hex(&css), bundle.css().sha256); diff --git a/tests/cli_surface.rs b/tests/contract/cli_surface.rs similarity index 97% rename from tests/cli_surface.rs rename to tests/contract/cli_surface.rs index 21f8e37..3ce6c6e 100644 --- a/tests/cli_surface.rs +++ b/tests/contract/cli_surface.rs @@ -1,7 +1,7 @@ //! CLI surface tests: this program owns its own help/subcommands and refuses //! unsafe defaults. Exit codes follow RFC-VIEW-0001 §10.2. -mod common; +use crate::common; use common::run_view; @@ -76,7 +76,7 @@ fn degradation_without_core_keeps_prose_readable() { project.marqdo_project("# @knowledge 标题\n\n正文 **加粗**。\n"); // Explicitly point at a missing core so the test is independent of the // caller environment (acceptance scripts export MARQDO_BIN). - let context = marqdo_view::app::AppContext::open( + let context = marqdo_view::reader::assemble::DocumentService::open( &project.dir, Some(std::path::Path::new("/definitely/missing/marqdo-frozen")), ) diff --git a/tests/core_contract.rs b/tests/contract/core_contract.rs similarity index 99% rename from tests/core_contract.rs rename to tests/contract/core_contract.rs index 23da80e..da42b04 100644 --- a/tests/core_contract.rs +++ b/tests/contract/core_contract.rs @@ -4,11 +4,11 @@ //! The fake core is a shell script, not a mocked Rust trait, so everything at //! the process boundary is exercised for real. -mod common; +use crate::common; use common::{minimal_analysis, sha256_hex, FakeCore, TempProject}; use marqdo_view::core_client::{CheckOptions, CheckResponse, CoreClient, RunOptions}; -use marqdo_view::project::Project; +use marqdo_view::reader::source::Project; fn fixture(name: &str) -> (TempProject, FakeCore) { let project = TempProject::new(name); diff --git a/tests/contract/main.rs b/tests/contract/main.rs new file mode 100644 index 0000000..6355ef1 --- /dev/null +++ b/tests/contract/main.rs @@ -0,0 +1,12 @@ +//! Contract suite: the frozen CLI black-box process contract, Analysis v2 / +//! Trace v2 validation, the View CLI surface, and architecture/asset gates. + +#[path = "../common/mod.rs"] +mod common; + +mod asset_integrity; +mod cli_surface; +mod core_contract; +mod no_coupling; +mod presentation_states; +mod trace_contract; diff --git a/tests/no_coupling.rs b/tests/contract/no_coupling.rs similarity index 100% rename from tests/no_coupling.rs rename to tests/contract/no_coupling.rs diff --git a/tests/presentation_states.rs b/tests/contract/presentation_states.rs similarity index 82% rename from tests/presentation_states.rs rename to tests/contract/presentation_states.rs index c34f90b..7479158 100644 --- a/tests/presentation_states.rs +++ b/tests/contract/presentation_states.rs @@ -1,11 +1,11 @@ //! Degradation/state matrix contract (RFC-VIEW-0001 S-05..S-07, §12.3): //! prose stays readable while semantics become explicitly unusable. -mod common; +use crate::common; use common::{minimal_analysis, sha256_hex, FakeCore, TempProject}; -use marqdo_view::app::AppContext; -use marqdo_view::presentation::SourceStatus; +use marqdo_view::reader::assemble::DocumentService; +use marqdo_view::reader::model::SourceStatus; fn project(name: &str) -> (TempProject, FakeCore) { let project = TempProject::new(name); @@ -24,7 +24,7 @@ fn failed_check_keeps_prose_and_shows_core_diagnostics() { core.set_check_json( r#"{"command":"check","success":false,"errors":1,"diagnostics":[{"code":"sem.unclosed_control","column":1,"file":"/home/secret/index.mq.md","line":3,"message":"`if` is not closed by `end`","module":"root:fixture@0.1.0::index.mq.md","severity":"error"}]}"#, ); - let context = AppContext::open(&project.dir, Some(&core.script)).unwrap(); + let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap(); let relative = context.project().entry().relative.clone(); let model = context.load(&relative).unwrap(); assert_eq!(model.source_status, SourceStatus::CoreError); @@ -46,7 +46,7 @@ fn failed_check_keeps_prose_and_shows_core_diagnostics() { fn source_digest_mismatch_degrades_instead_of_misbinding() { let (project, core) = project("state-source-mismatch"); core.set_analysis(&minimal_analysis("index.mq.md", &"0".repeat(64), 2)); - let context = AppContext::open(&project.dir, Some(&core.script)).unwrap(); + let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap(); let relative = context.project().entry().relative.clone(); let model = context.load(&relative).unwrap(); assert_eq!(model.source_status, SourceStatus::SourceMismatch); @@ -59,7 +59,7 @@ fn unknown_analysis_schema_is_a_hard_protocol_error() { let (project, core) = project("state-protocol"); let source = std::fs::read(project.path("index.mq.md")).unwrap(); core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 3)); - let context = AppContext::open(&project.dir, Some(&core.script)).unwrap(); + let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap(); let relative = context.project().entry().relative.clone(); let err = context.load(&relative).unwrap_err(); assert_eq!(err.code(), "view.protocol_incompatible"); @@ -78,7 +78,7 @@ fn invalid_core_span_is_dropped_with_an_explicit_warning() { "span": {"start": 0, "end": 999_999} }]); core.set_analysis(&serde_json::to_string(&analysis).unwrap()); - let context = AppContext::open(&project.dir, Some(&core.script)).unwrap(); + let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap(); let relative = context.project().entry().relative.clone(); let model = context.load(&relative).unwrap(); assert_eq!(model.source_status, SourceStatus::StaticOk); @@ -105,30 +105,36 @@ fn run_attached_to_changed_source_becomes_stale() { let analysis = std::fs::read(repo_root.join("tests/golden/analysis-v2/control-flow.json")).unwrap(); core.set_analysis(std::str::from_utf8(&analysis).unwrap()); - let context = AppContext::open(&project.dir, Some(&core.script)).unwrap(); + let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap(); let relative = context.project().entry().relative.clone(); // Build a verified run directly from the golden trace + golden analysis. - let source_index = marqdo_view::source_map::SourceIndex::new(&source); - let verified_analysis = - marqdo_view::semantic::verify_analysis(&analysis, &source, &source_index, "index.mq.md") - .unwrap(); + let source_index = marqdo_view::reader::source::SourceIndex::new(&source); + let verified_analysis = marqdo_view::protocol::analysis_v2::verify_analysis( + &analysis, + &source, + &source_index, + "index.mq.md", + ) + .unwrap(); let trace = std::fs::read(repo_root.join("tests/golden/trace-v2/control-flow.trace.json")).unwrap(); let run_json: serde_json::Value = serde_json::from_slice( &std::fs::read(repo_root.join("tests/golden/trace-v2/control-flow.run.json")).unwrap(), ) .unwrap(); - let run = marqdo_view::trace::verify_trace(marqdo_view::trace::TraceVerificationInput { - trace_bytes: &trace, - analysis_bytes: &analysis, - semantic: &verified_analysis.projection, - modules: &verified_analysis.projection.modules, - source: &source, - source_index: &source_index, - run_json: &run_json, - exit_code: 0, - }) + let run = marqdo_view::protocol::trace_v2::verify_trace( + marqdo_view::protocol::trace_v2::TraceVerificationInput { + trace_bytes: &trace, + analysis_bytes: &analysis, + semantic: &verified_analysis.projection, + modules: &verified_analysis.projection.modules, + source: &source, + source_index: &source_index, + run_json: &run_json, + exit_code: 0, + }, + ) .unwrap(); let attached = context.load_with_run(&relative, Some(&run)).unwrap(); assert_eq!(attached.run_state().data_value(), "succeeded"); diff --git a/tests/trace_contract.rs b/tests/contract/trace_contract.rs similarity index 97% rename from tests/trace_contract.rs rename to tests/contract/trace_contract.rs index a672f58..ce2d7aa 100644 --- a/tests/trace_contract.rs +++ b/tests/contract/trace_contract.rs @@ -2,9 +2,9 @@ //! goldens bind to the committed Analysis v2 bytes by digest, so a changed //! source cannot silently reuse an old trace. -use marqdo_view::semantic; -use marqdo_view::source_map::{sha256_prefixed, SourceIndex}; -use marqdo_view::trace::{verify_trace, RunDisplayState, TraceVerificationInput}; +use marqdo_view::protocol::analysis_v2 as semantic; +use marqdo_view::protocol::trace_v2::{verify_trace, RunDisplayState, TraceVerificationInput}; +use marqdo_view::reader::source::{sha256_prefixed, SourceIndex}; use serde_json::Value; struct Fixture { @@ -43,7 +43,7 @@ fn verify( trace_golden: &str, run_golden: &str, exit_code: i32, -) -> marqdo_view::trace::VerifiedRun { +) -> marqdo_view::protocol::trace_v2::VerifiedRun { let trace = golden_bytes(trace_golden); let run_json = golden_json(run_golden); verify_trace(TraceVerificationInput { diff --git a/tests/export.rs b/tests/integration/export.rs similarity index 99% rename from tests/export.rs rename to tests/integration/export.rs index cae30bd..cf00e9f 100644 --- a/tests/export.rs +++ b/tests/integration/export.rs @@ -1,7 +1,7 @@ //! Static export contract tests: pure read-only, same renderer, offline assets, //! safe output paths and no execution (RFC-VIEW-0001 §11.3, R-02, X-04). -mod common; +use crate::common; use common::{run_view, sha256_hex, FakeCore, TempProject}; use std::path::{Path, PathBuf}; @@ -124,7 +124,7 @@ fn exports_offline_site_with_shared_renderer_and_relative_links() { assert_eq!(sha256_hex(&bytes), entry["sha256"].as_str().unwrap()); } // Assets are exactly the embedded bundle bytes. - let bundle = marqdo_view::assets::AssetBundle::get(); + let bundle = marqdo_view::reader::assets::AssetBundle::get(); let css = std::fs::read(out.join("assets").join(bundle.hashed_css_name())).unwrap(); assert_eq!(css, bundle.css_bytes()); diff --git a/tests/http_live.rs b/tests/integration/http_live.rs similarity index 95% rename from tests/http_live.rs rename to tests/integration/http_live.rs index ea2a9dd..81e4069 100644 --- a/tests/http_live.rs +++ b/tests/integration/http_live.rs @@ -2,7 +2,7 @@ //! The server is a real child process so startup, URL output, routing, security //! headers, CSRF and the explicit-run flow are exercised end to end. -mod common; +use crate::common; use common::{run_view, FakeCore}; use std::io::{BufRead, BufReader, Read, Write}; @@ -567,3 +567,23 @@ fn cli_verify_output_contract_still_holds_for_installed_style_invocation() { assert_eq!(json["executed"], false); assert_eq!(json["analysis"]["schema_version"], 2); } + +#[test] +fn documents_api_is_a_read_only_structure_and_old_route_is_gone() { + let server = start_server(); + let response = http_get(server.port, None, "/api/documents"); + assert_eq!(response.status, 200); + let body = json_body(&response.body); + assert_eq!(body["schema"], "marqdo.view-documents"); + assert_eq!(body["schema_version"], 1); + assert!(body["documents"].is_array()); + assert!(body["documents"].as_array().unwrap().len() >= 2); + assert!(body["current"]["relative_path"].is_string()); + assert!(body["current"]["outline"].is_array()); + assert!(body["current"]["note"].is_null() || body["current"]["note"].is_string()); + assert!(body["note"].as_str().unwrap().contains("never executes")); + + // The old singular route is not part of the target API surface. + let old = http_get(server.port, None, "/api/document?path=index.mq.md"); + assert_eq!(old.status, 404); +} diff --git a/tests/integration/main.rs b/tests/integration/main.rs new file mode 100644 index 0000000..271dc80 --- /dev/null +++ b/tests/integration/main.rs @@ -0,0 +1,10 @@ +//! Integration suite: the Live HTTP surface, the one renderer, Unicode span +//! mapping and the static export path. + +#[path = "../common/mod.rs"] +mod common; + +mod export; +mod http_live; +mod rendering; +mod unicode_spans; diff --git a/tests/rendering.rs b/tests/integration/rendering.rs similarity index 87% rename from tests/rendering.rs rename to tests/integration/rendering.rs index cac6c27..f1c9af6 100644 --- a/tests/rendering.rs +++ b/tests/integration/rendering.rs @@ -1,15 +1,15 @@ //! Rendering contract tests: one renderer, safe Markdown, exact source view, //! verified semantic annotations and Live/Export link differences. -mod common; +use marqdo_view::config::ViewConfig; +use marqdo_view::protocol::analysis_v2 as semantic; +use marqdo_view::reader::assemble::{self as assemble, BuildInput}; +use marqdo_view::reader::markdown::{DocumentIdentity, DocumentModel}; +use marqdo_view::reader::model::{Navigation, SourceStatus}; +use marqdo_view::reader::render::{ReaderRenderer, RenderContext}; +use marqdo_view::reader::source::{Project, SafeRelativePath}; -use marqdo_view::document::{DocumentIdentity, DocumentModel}; -use marqdo_view::presentation::{self, BuildInput, Navigation, SourceStatus}; -use marqdo_view::project::{Project, SafeRelativePath, ViewConfig}; -use marqdo_view::render::{ReaderRenderer, RenderContext}; -use marqdo_view::semantic; - -fn example(name: &str) -> (marqdo_view::presentation::PresentationModel, String) { +fn example(name: &str) -> (marqdo_view::reader::model::PresentationModel, String) { let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("examples") .join(name); @@ -29,7 +29,7 @@ fn example(name: &str) -> (marqdo_view::presentation::PresentationModel, String) .unwrap_or_else(|err| panic!("golden does not verify for {name}: {err}")); let config = ViewConfig::load(project.root()).unwrap_or_default(); let navigation = Navigation::from_project(&project, &config, &entry); - let model = presentation::build(BuildInput { + let model = assemble::build(BuildInput { document, analysis: Some(&verified), status: SourceStatus::StaticOk, @@ -42,13 +42,13 @@ fn example(name: &str) -> (marqdo_view::presentation::PresentationModel, String) (model, source) } -fn render_live(model: &marqdo_view::presentation::PresentationModel) -> String { +fn render_live(model: &marqdo_view::reader::model::PresentationModel) -> String { ReaderRenderer::new() .render(model, &RenderContext::live()) .html } -fn render_static(model: &marqdo_view::presentation::PresentationModel, depth: usize) -> String { +fn render_static(model: &marqdo_view::reader::model::PresentationModel, depth: usize) -> String { ReaderRenderer::new() .render(model, &RenderContext::static_site(depth)) .html @@ -203,7 +203,7 @@ fn malicious_markdown_cannot_inject_markup_or_scripts() { &config, &SafeRelativePath::parse("index.mq.md").unwrap(), ); - let model = presentation::build(BuildInput { + let model = assemble::build(BuildInput { document, analysis: None, status: SourceStatus::CoreUnavailable, @@ -250,3 +250,14 @@ fn run_controls_are_explicitly_unavailable_before_pr04() { assert!(!html.contains("data-run-state=\"running\"")); assert!(!html.contains("data-run-state=\"succeeded\"")); } + +#[test] +fn reader_exposes_simple_theme_toggle_and_no_variable_or_memory_tabs() { + let (model, _source) = example("welcome"); + let html = render_live(&model); + assert!(html.contains("data-theme=\"light\"")); + assert!(html.contains("data-action=\"theme\"")); + assert!(!html.contains("data-action=\"variables\"")); + assert!(!html.contains("data-action=\"memory\"")); + assert!(html.contains("data-action=\"unsupported\"")); +} diff --git a/tests/unicode_spans.rs b/tests/integration/unicode_spans.rs similarity index 88% rename from tests/unicode_spans.rs rename to tests/integration/unicode_spans.rs index 5ded0e4..3d78246 100644 --- a/tests/unicode_spans.rs +++ b/tests/integration/unicode_spans.rs @@ -1,12 +1,14 @@ //! Unicode/CRLF/duplicate-text span contract (RFC-VIEW-0001 S-04). //! Goldens are emitted by the frozen CLI from the exact fixture bytes. -use marqdo_view::document::{DocumentIdentity, DocumentModel}; -use marqdo_view::presentation::{self, BuildInput, Navigation, SourceStatus}; -use marqdo_view::project::{Project, SafeRelativePath, ViewConfig}; -use marqdo_view::render::{ReaderRenderer, RenderContext}; -use marqdo_view::semantic; -use marqdo_view::source_map::sha256_hex; +use marqdo_view::config::ViewConfig; +use marqdo_view::protocol::analysis_v2 as semantic; +use marqdo_view::reader::assemble::{self as assemble, BuildInput}; +use marqdo_view::reader::markdown::{DocumentIdentity, DocumentModel}; +use marqdo_view::reader::model::{Navigation, SourceStatus}; +use marqdo_view::reader::render::{ReaderRenderer, RenderContext}; +use marqdo_view::reader::source::sha256_hex; +use marqdo_view::reader::source::{Project, SafeRelativePath}; fn repo_root() -> std::path::PathBuf { std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) @@ -15,7 +17,7 @@ fn repo_root() -> std::path::PathBuf { fn load(path: &str, golden: &str) -> (String, Vec, semantic::VerifiedAnalysis) { let root = repo_root(); let source = std::fs::read_to_string(root.join(path)).unwrap(); - let index = marqdo_view::source_map::SourceIndex::new(&source); + let index = marqdo_view::reader::source::SourceIndex::new(&source); let analysis = std::fs::read(root.join(golden)).unwrap(); let relative = std::path::Path::new(path) .file_name() @@ -32,7 +34,7 @@ fn render(verified: &semantic::VerifiedAnalysis, source: &str, relative: &str) - let entry = SafeRelativePath::parse(relative).unwrap(); let document = DocumentModel::parse(source.to_string(), DocumentIdentity::placeholder(&entry)); let navigation = Navigation::from_project(&project, &ViewConfig::default(), &entry); - let model = presentation::build(BuildInput { + let model = assemble::build(BuildInput { document, analysis: Some(verified), status: SourceStatus::StaticOk, @@ -67,7 +69,7 @@ fn unicode_spans_are_exact_and_duplicate_returns_get_distinct_anchors() { let first = returns[0].span; let second = returns[1].span; assert_ne!(first, second); - let index = marqdo_view::source_map::SourceIndex::new(&source); + let index = marqdo_view::reader::source::SourceIndex::new(&source); // Core statement spans cover the whole carrier node (including markers). assert_eq!(index.source_text(&source, first), Some("`return 1`")); assert_eq!(index.source_text(&source, second), Some("`return 1`")); @@ -106,7 +108,7 @@ fn crlf_source_keeps_exact_digest_and_line_mapping() { verified.projection.source_digest, sha256_hex(source.as_bytes()) ); - let index = marqdo_view::source_map::SourceIndex::new(&source); + let index = marqdo_view::reader::source::SourceIndex::new(&source); let function = &verified.projection.functions[0]; for (_, statement) in verified .projection @@ -137,7 +139,7 @@ fn knowledge_emphasis_never_becomes_an_execution_anchor() { let project = Project::open(&root.join("examples/mixed-modes")).unwrap(); let entry = project.entry().relative.clone(); let source = project.read_source_text(&entry).unwrap(); - let index = marqdo_view::source_map::SourceIndex::new(&source); + let index = marqdo_view::reader::source::SourceIndex::new(&source); let analysis = std::fs::read(root.join("tests/golden/analysis-v2/mixed-modes.json")).unwrap(); let verified = semantic::verify_analysis(&analysis, &source, &index, entry.as_str()).unwrap(); assert_eq!( @@ -146,7 +148,7 @@ fn knowledge_emphasis_never_becomes_an_execution_anchor() { ); let document = DocumentModel::parse(source.clone(), DocumentIdentity::placeholder(&entry)); let navigation = Navigation::from_project(&project, &ViewConfig::default(), &entry); - let model = presentation::build(BuildInput { + let model = assemble::build(BuildInput { document, analysis: Some(&verified), status: SourceStatus::StaticOk,