diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 621c256..9a2582c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,7 +20,7 @@ jobs: - name: Fail on retired Analysis/Trace/flags/Tool negotiation shell: bash run: scripts/check-no-legacy.sh - - name: Current docs describe the rc.4 baseline + - name: Current docs describe the rc.6 baseline shell: bash run: scripts/check-docs.sh @@ -46,7 +46,7 @@ jobs: run: cargo test --locked frozen-acceptance: - name: frozen rc.4 acceptance (install / Observation / SSE / export / browser) + name: frozen rc.6 acceptance (install / Observation / SSE / export / browser) runs-on: ubuntu-24.04 needs: [no-legacy, quality] env: @@ -65,7 +65,7 @@ jobs: - uses: actions/setup-node@v4 with: node-version: "22" - - name: Fetch the official frozen rc.4 CLI and verify its identity + - name: Fetch the official frozen rc.6 CLI and verify its identity shell: bash run: | set -euo pipefail @@ -76,13 +76,12 @@ jobs: (cd tests/browser && npm ci --no-audit --no-fund) (cd tests/browser && npx playwright install --with-deps chromium) - name: Run one-command acceptance (G01-G12) - run: scripts/acceptance.sh + run: VIEW_EVIDENCE_OUT="$RUNNER_TEMP/view-evidence/manifest.json" scripts/acceptance.sh - name: Upload acceptance evidence uses: actions/upload-artifact@v4 with: name: view-evidence-${{ github.sha }} path: | - docs/evidence/452e9a32bd9e40dba427d4180691c58bab74449e/manifest.json dist/acceptance/manifest.json dist/acceptance/logs/ dist/marqdo-view-*.tar.gz diff --git a/.woodpecker/ci.yml b/.woodpecker/ci.yml index f29a062..50c6255 100644 --- a/.woodpecker/ci.yml +++ b/.woodpecker/ci.yml @@ -14,7 +14,11 @@ steps: - cargo clippy --all-targets --locked -- -D warnings - cargo test --locked - cargo build --release --locked - - SKIP_BROWSER=1 scripts/acceptance.sh + - | + set -eu + MARQDO_BIN="$(scripts/frozen-beta.sh fetch "$(mktemp -d)")" + export MARQDO_BIN + SKIP_BROWSER=1 VIEW_EVIDENCE_OUT="$PWD/dist/view-evidence/manifest.json" scripts/acceptance.sh browser: depends_on: [build-acceptance] @@ -25,10 +29,7 @@ steps: - (cd tests/browser && npm ci --no-audit --no-fund) - | set -eu - curl -fsSL --retry 3 -o /tmp/marqdo.tar.gz "https://git.cflmy.cn/cflmy/marqdo-cli/releases/download/v3.0.0-rc.5/marqdo-3.0.0-rc.5-x86_64-unknown-linux-gnu.tar.gz" - echo "fd7a313e0ddaf38a9b1901ff2a9aa7b9a0a153e65522a9c0c60f01e2549f583b /tmp/marqdo.tar.gz" | sha256sum -c - - mkdir -p /opt/marqdo - tar -xzf /tmp/marqdo.tar.gz -C /opt/marqdo - export MARQDO_BIN=/opt/marqdo/marqdo-3.0.0-rc.5-x86_64-unknown-linux-gnu/marqdo - "$MARQDO_BIN" --version + MARQDO_BIN="$(scripts/frozen-beta.sh fetch "$(mktemp -d)")" + export MARQDO_BIN ./scripts/test-browser.sh + ./scripts/test-export.sh diff --git a/CHANGELOG.md b/CHANGELOG.md index b24e18d..9fe6c0d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,13 @@ revision 1 (`api_revision` 1), Analysis revision 3 and Observation revision 1. `marqdo 3.0.0-rc.4`. There is no compatibility layer for the retired formats: old code paths, fixtures and documents were replaced, not branched. +## [Unreleased] + +- Freeze component acceptance on the published RC.6 CLI and verify the Worker and Stdlib manifest. +- Export an explicitly selected, completed Observation with its source and run identity. Add a script-free, single-document export for hosts using the reader's existing theme and media policy. +- Place function inputs, confirmation, results and audit details in the reader. Preserve exact integers and share bounded ValueWire rendering with offline snapshots. +- Verify result attribution against the observed top-level function and current static inputs. Use Analysis heading IDs for verified cross-document navigation. + ## [0.3.0] - 2026-11-25 ### Added diff --git a/COMPATIBILITY.md b/COMPATIBILITY.md index f7dc974..d0634ae 100644 --- a/COMPATIBILITY.md +++ b/COMPATIBILITY.md @@ -5,7 +5,7 @@ | 轴 | 本 View 值 | 说明 | |---|---|---| | View 产品版本 | `0.3.0` | 独立 SemVer,与 CLI 不共用 | -| `marqdo` 产品范围 | `>=3.0.0-rc.3,<4.0.0` | 预发布契约只在 rc.3 起有意义;验收固定 `3.0.0-rc.5` | +| `marqdo` 产品范围 | `>=3.0.0-rc.3,<4.0.0` | 预发布契约只在 rc.3 起有意义;验收固定 `3.0.0-rc.6` | | CLI Tool revision | `1` | `tool.json`:`requires.api_revision = 1`,无 `compatibility` 字段 | | Analysis revision | `3` | `marqdo.analysis`,ADR-0069 公共边界(含 source/document/anchors/references/heading_span) | | Observation revision | `1` | `marqdo.observation`,单一事件序列(JSONL 流 / 原子快照) | @@ -16,9 +16,9 @@ `3.0.0-rc.3,<4.0.0` 是当前预发布范围;`>=3.0.0,<4.0.0` 不匹配任何 rc 预发布版。 验收与证据只认绑定 CLI 源码 SHA / 归档 SHA / 二进制 SHA 的结果: -`marqdo 3.0.0-rc.5`,源码 `c44b0f943875d563bb7c170f8ccd3fd56a82360f`, -归档 `fd7a313e0ddaf38a9b1901ff2a9aa7b9a0a153e65522a9c0c60f01e2549f583b`, -二进制 `a19049ee111f41512a69c5ed748aaa4968eb3a3f5abd585ccdcf9bbb201bd7ee`。 +`marqdo 3.0.0-rc.6`,源码 `63776735e924ade279cdf59d5c733dc24bfdabbb`, +归档 `8dc0b006302e03c23451b8ea9f8a0fcdae8bf67c80c546bee2434bf69755bfe3`, +二进制 `4f12e6b8a2edb327c0d9ab6165f74e8e88a01b05350527e3aade6f52d4f7a06c`。 ## 契约替换(0.3.0 一次性完成) diff --git a/Cargo.toml b/Cargo.toml index 93dacee..a57f34b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,7 +33,7 @@ pulldown-latex = "=0.8.0" roxmltree = "0.21" clap = { version = "4.5", features = ["derive"] } serde = { version = "1", features = ["derive"] } -serde_json = "1" +serde_json = { version = "1", features = ["float_roundtrip"] } sha2 = "0.10" comrak = { version = "=1.0.0", default-features = false } semver = "1" diff --git a/README.md b/README.md index dbd953d..741be89 100644 --- a/README.md +++ b/README.md @@ -13,8 +13,8 @@ Observation revision 1——附着回原文,而不是把文档翻译成另一 - 冻结 CLI 合同审计:[`docs/audits/protocol-contract-0002.md`](docs/audits/protocol-contract-0002.md) - 兼容性:[`COMPATIBILITY.md`](COMPATIBILITY.md) / 变更:[`CHANGELOG.md`](CHANGELOG.md) -> 0.3.0 只支持当前预发布契约:`marqdo 3.0.0-rc.5`(产品范围 -> `>=3.0.0-rc.3,<4.0.0`;验收固定 rc.5)。静态语义只有一个来源 +> 0.3.0 只支持当前预发布契约:`marqdo 3.0.0-rc.6`(产品范围 +> `>=3.0.0-rc.3,<4.0.0`;验收固定 rc.6)。静态语义只有一个来源 > `check --emit`(Analysis revision 3,含精确 source、Markdown AST、heading 作用域、 > anchors 与状态化 references);运行事实只有一条 Observation revision 1 事件序列 > (`run`/`call --output jsonl`,原子快照 `--observation-file`)。旧格式显式拒绝, @@ -22,7 +22,7 @@ Observation revision 1——附着回原文,而不是把文档翻译成另一 ## 能力(0.3.0 实现范围) -> 下表的“实现”表示当前代码路径按 rc.5 契约实现;`PASS/FAIL/UNVERIFIED` 的机器 +> 下表的“实现”表示当前代码路径按 rc.6 契约实现;`PASS/FAIL/UNVERIFIED` 的机器 > 验收结论只以 [`docs/evidence/`](docs/evidence/README.md) 中绑定 CLI 源码 SHA 的 > manifest 为准。new manifest 生成前,全部发布门禁在 STATUS 中保持 `UNVERIFIED`。 @@ -34,9 +34,9 @@ Observation revision 1——附着回原文,而不是把文档翻译成另一 | 引用状态 resolved / not_loaded / missing / ambiguous / external / outside_scope / invalid | 实现;`not_loaded` 显示“未核验”,不是断链 | | 本机 Live 阅读(默认 `127.0.0.1`,只读 API + 显式执行端点) | 实现 | | 显式确认后单次运行/调用;Observation v1 事件经 View SSE 转发/摘要 | 实现(单任务、取消、断线重放) | -| 只读静态导出(离线 `file://`、媒体/字体/哈希);普通导出与单次结果 ZIP | 实现 | -| 单函数参数表单 + 受控 `project` fs grants | 参数来自 Analysis 签名;project 需显式 glob 二次确认 | -| 变量/参数值观测 | 协议支持 `--observe-variable`/`--observe-parameter`(Text 需 `--observe-text-values`);**View 默认不请求任何值**,绝不伪造变量值/内存状态 | +| 只读静态导出、宿主嵌入、已有运行快照 | 同一渲染器和主题,支持 `file://` 离线阅读 | +| 原位函数调用与审计 | 参数来自 Analysis 签名。CLI 处理声明默认值。`project` 文件 glob 需二次确认 | +| ValueWire 返回值与观察 | 展示精确整数、有界容器和惰性代码、公式。View 默认不请求变量或实际参数值 | | 知识“已证明” / Prove / Lint / 调试器 | 非目标/等待独立协议 | 不变量: @@ -50,9 +50,9 @@ Observation revision 1——附着回原文,而不是把文档翻译成另一 ## 安装 ```bash -# 1) 取得官方冻结 CLI 发布包(验收固定 3.0.0-rc.5) -MARQDO_BIN=/absolute/path/to/marqdo-3.0.0-rc.5-x86_64-unknown-linux-gnu/marqdo -"$MARQDO_BIN" --version # marqdo 3.0.0-rc.5 +# 1) 取得官方冻结 CLI 发布包(验收固定 3.0.0-rc.6) +MARQDO_BIN=/absolute/path/to/marqdo-3.0.0-rc.6-x86_64-unknown-linux-gnu/marqdo +"$MARQDO_BIN" --version # marqdo 3.0.0-rc.6 # 2) 构建并制作 CLI Tool revision 1 bundle ./scripts/package.sh @@ -79,6 +79,7 @@ marqdo view verify examples/mixed-modes --refs --json # 显式触发(只有页面确认后才 POST /api/runs) marqdo view examples/function-params.mq.md --no-open +marqdo view examples/circle-area.mq.md --no-open marqdo view examples/unsafe-side-effect.mq.md --no-open # 纯只读静态导出(永不执行;导出后可用 file:// 离线打开) @@ -92,6 +93,14 @@ Live 页面点击 Dock “运行”(执行 `main`)或函数标题旁的“ CLI 子进程;状态与结果通过 SSE 推送,可取消,断线可重放。页面刷新/打开/搜索/ 切换/导出都不会运行,也没有状态轮询。 +函数标题旁的参数表单按签名顺序显示字段。`Int` 使用十进制文本,`Float` 使用有限的 CLI 浮点常量, +`Text` 输入原文本,列表和映射使用 CLI 常量表达式。需要提交空文本时可勾选对应字段的“提交空文本”。 +声明的默认值由 CLI 处理。内存、资源和句柄需要在文稿中组织调用。 + +运行结束后可在函数位置查看返回值和审计信息。审计区列出提交的参数表达式、确认的调用计划和真实 Observation 标识。 +更改草稿会标记上次结果待更新,重新计算仍需确认。可从同页的函数表单重新查看最近的结果。View 只保留有界临时记录, +刷新页面后不会恢复旧运行。源码及依赖身份变化后,须重新确认,旧结果不能作为当前源码的证据。 + ## 架构(强制约束) ```text @@ -119,11 +128,48 @@ ExecutionController ─ 单任务、取消、SSE 事件(仅 POST /api/runs 可 - 单一 Rust package、单一渲染入口、单一主题文件;没有第二个 Markdown→语义管线。 - 协议模块之外没有 `schema_version` 判断;协议模块内只有当前 revision 一个分支。 - JSONL 流与原子快照共用同一解码器与领域类型;生产不“双读合并”,一致性只在测试中断言。 +- Live、ZIP 和外部快照共用有界的 ValueWire 呈现。浏览器仅挂载允许的文本与呈现元素,公式沿用阅读层 MathML。 - Live/Export 内容同源;导出绝不执行、绝不覆盖项目源文件或无关目录。 - 门禁:`tests/contract/no_coupling.rs` 拒绝旧 crate/源码依赖、第二套渲染器/主题、shell 执行; `tests/contract/asset_integrity.rs` 锁定内嵌资产与唯一主题层; `tests/security/` 覆盖 CSRF/Origin/Cookie/路径/symlink/XSS/跨会话 SSE。 +### 导出已完成的运行 + +使用 CLI 保存的 Observation 1 快照和调用方选定的 `run.id`。以下示例先在 CLI 明确执行一次。 + +```bash +marqdo call examples/function-params.mq.md double --arg n=3 --mode pure --output json > run.json +run_id="$(python3 -c 'import json; print(json.load(open("run.json"))["run"]["id"])')" +marqdo view export examples/function-params.mq.md --out /tmp/view-result \ + --observation run.json --run-id "$run_id" +``` + +导出时只执行静态 `check`,核对项目、Analysis 的精确字节摘要、生产者版本、实际顶层调用和完整成功终态。 +用 `file://` 打开 `index.html` 可查看函数附近的结果。`manifest.json` 记录快照的 SHA-256、已有的运行 ID 和文稿身份。 +快照应由调用方从可信 CLI 获取并保管。View 验证内容和绑定;Observation 1 没有签名,文件自身无法证明作者身份。 +默认输出数值、布尔等标量及事件计数。`--include-sensitive-result` 允许输出文本或容器返回值。 +标准输出、标准错误、参数值和完整事件流均不会写入此导出。终态没有记录结束时刻时,该字段为 `null`。 +错误运行 ID、已改动文稿、截断和未完成快照均拒绝导出。普通 `export --out DIR` 可继续用于无运行结果的文稿。 + +### 在宿主中嵌入只读正文 + +```bash +source_sha="$(sha256sum article.mq.md | cut -d' ' -f1)" +marqdo view export article.mq.md --out /tmp/view-reader --embed \ + --theme dark --anchor introduction --expect-source-sha256 "$source_sha" +``` + +`--embed` 接受选定的 `.mq.md` 或普通 `.md` 文件。普通 Markdown 直接阅读,状态为 `markdown-only`。 +主题选择为 `light`(默认)或 `dark`。`manifest.json` 的 `entry.heading_ids` 列出可跳转的标题 ID。 +省略 `--anchor` 可从文稿开头读取。若调用方指定了不存在的标题或不匹配的源码摘要,命令会返回诊断并停止导出。 + +宿主从本地包加载 `manifest.entry.href`。请核对 `mode=embedded`、`requires`、`producers.view.binary_sha256`、 +`pages[0].source_sha256` 和包文件的摘要。保留 `index.html`、`assets/` 与 `media/` 的相对位置, +在本地隔离浏览上下文中打开。使用 iframe 时可设置 `sandbox="allow-same-origin"` 而不开放脚本或顶层导航。 +正文使用独立 View 的同一主题、标题、公式、表格和媒体规则。只有本文稿内存在的标题链接可跳转, +外部及跨文稿链接保留为文字。有效媒体限于项目内的已验证静态图片。宿主管理选中文稿、导航和运行授权。 + ## 开发与验收 ```bash @@ -135,15 +181,15 @@ scripts/check-no-legacy.sh # G01:当前树 0 条旧契约残留(cmd 可单 scripts/check-docs.sh # G12:当前文档不把旧格式写成当前能力 ``` -全链路验收使用 Rust 1.89 或更新版本,以及能运行官方 rc.5 的 Linux x86_64 +全链路验收使用 Rust 1.89 或更新版本,以及能运行官方 rc.6 的 Linux x86_64 环境(glibc 2.39 起)。浏览器、显式运行和离线导出通过已安装的 Tool 执行。 ```bash (cd tests/browser && npm ci && PLAYWRIGHT_BROWSERS_PATH="$PWD/../.cache/pw-browsers" npx playwright install chromium) MARQDO_BIN="$(./scripts/frozen-beta.sh fetch "$(mktemp -d)")" export MARQDO_BIN -./scripts/acceptance.sh # G01–G12,写 docs/evidence/452e9a32…/manifest.json -cat docs/evidence/c44b0f943875d563bb7c170f8ccd3fd56a82360f/manifest.json +./scripts/acceptance.sh # G01–G12,写 docs/evidence/63776735…/manifest.json +cat docs/evidence/63776735e924ade279cdf59d5c733dc24bfdabbb/manifest.json ``` 验收会核对 CLI 源码 SHA、归档 SHA-256 与二进制 SHA-256,并在前后两次记录 CLI 摘要。 @@ -158,6 +204,7 @@ MARQDO_BIN=... ./scripts/test-contract.sh # code + Tool revision 1 + verify MARQDO_BIN=... ./scripts/test-export.sh # 纯只读导出 + file:// Chromium ./scripts/test-security.sh # HTTP/路径/XSS/导出对抗 MARQDO_BIN=... ./scripts/test-browser.sh # 真实 Chromium 视觉/交互/响应式/运行 +MARQDO_BIN=... VIEW_BIN=... python3 scripts/test-complete-reader.py ``` 协议 golden 由冻结 CLI 生成,见 `tests/golden/README.md` 与 `scripts/gen-golden.sh` diff --git a/assets/reader.css b/assets/reader.css index 8a0c8e6..10f3e88 100644 --- a/assets/reader.css +++ b/assets/reader.css @@ -242,6 +242,10 @@ margin: 0 auto; padding: clamp(28px, 5vh, 56px) 0 calc(var(--mq-dock-h) + 72px); } + .mq-reader[data-embedded="true"] .mq-main { + --mq-gutter: clamp(12px, 4vw, 32px); + padding: clamp(12px, 3vw, 28px) 0; + } .mq-docmeta { display: flex; @@ -1318,7 +1322,9 @@ font: 12px/1.5 var(--mq-sans); color: var(--mq-muted); } - .mq-run-param input { + .mq-run-param input, + .mq-run-param select, + .mq-run-param textarea { padding: 7px 10px; border: 1px solid var(--mq-line-strong); border-radius: 8px; @@ -1381,6 +1387,10 @@ .mq-document-image { max-inline-size: 100%; block-size: auto; } .mq-heading-anchor { display: block; } .mq-document math { font-family: "Noto Sans Math", math; } + .mq-result-value { overflow-wrap: anywhere; } + .mq-result-value .mq-result-text { white-space: pre-wrap; } + .mq-result-value math { font-family: "Noto Sans Math", math; } + .mq-result-value pre { overflow: auto; } } @layer semantics { @@ -1398,6 +1408,24 @@ background: var(--mq-surface); margin-block: 1.25rem 1.75rem; } + .mq-function-interaction { + margin: 0.75em 0 1.5em; + padding: clamp(12px, 3vw, 20px); + border: 1px solid var(--mq-line); + border-radius: var(--mq-radius); + background: var(--mq-surface); + } + .mq-function-actions { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; + margin-top: 0.75rem; + } + .mq-run-param :is(input, select, textarea) { box-sizing: border-box; width: 100%; } + .mq-empty-text { display: inline-block; margin-top: 0.25rem; } + .mq-empty-text[hidden], .mq-function-interaction[hidden], .mq-function-actions button[hidden] { display: none; } + #mq-run-audit-items dd { margin: 0 0 0.65em; white-space: pre-wrap; overflow-wrap: anywhere; } + body[data-mode="source"] .mq-function-interaction { display: none; } .mq-run-panel > summary { cursor: pointer; diff --git a/assets/reader.js b/assets/reader.js index ce37554..3acbf22 100644 --- a/assets/reader.js +++ b/assets/reader.js @@ -317,20 +317,13 @@ downloadSnapshot(); break; case "call-function": - if (trigger) { - var params = []; - try { - params = JSON.parse(trigger.dataset.params || "[]"); - } catch (error) { - params = []; - } - openRunForm({ - kind: "function", - functionId: trigger.dataset.functionId, - label: trigger.dataset.functionLabel, - params: params - }); - } + if (trigger) openFunctionForm(trigger); + break; + case "prepare-function": + prepareFunction(trigger.closest(".mq-function-interaction")); + break; + case "show-function-result": + showFunctionResult(trigger.closest(".mq-function-interaction")); break; case "clear-run": case "clear": @@ -341,13 +334,10 @@ } } - function csrfToken() { - var meta = document.querySelector('meta[name="mq-csrf-token"]'); - return meta ? meta.getAttribute("content") : ""; - } - var activeRun = null; var pendingRun = null; + var runBusy = false; + var functionRuns = new Map(); function randomId() { var bytes = new Uint8Array(16); @@ -402,6 +392,7 @@ } function setRunBusy(busy) { + runBusy = busy; var button = document.querySelector('.mq-dock-btn[data-action="run"]'); if (button) { if (busy) { @@ -415,7 +406,8 @@ button.disabled = false; } } - $$(".mq-fn-call[data-action=call-function]").forEach(function (call) { call.disabled = busy; }); + $$("[data-action=call-function], [data-action=prepare-function], [data-action=show-function-result]") + .forEach(function (call) { call.disabled = busy; }); var cancel = $("#mq-run-actions"); if (cancel) cancel.hidden = !busy; } @@ -429,10 +421,12 @@ } function clearRunOutput() { - ["#mq-run-summary", "#mq-run-stdout", "#mq-run-stderr", "#mq-run-events"].forEach(function (selector) { + ["#mq-run-summary", "#mq-run-stdout", "#mq-run-stderr", "#mq-run-events", "#mq-run-audit-items"].forEach(function (selector) { var node = $(selector); if (node) node.textContent = ""; }); + var audit = $("#mq-run-audit"); + if (audit) { audit.hidden = true; audit.open = false; } var stdout = $("#mq-run-stdout"); if (stdout) stdout.hidden = true; var stderr = $("#mq-run-stderr"); @@ -473,117 +467,219 @@ .filter(function (line) { return line.length > 0; }); } - function rawParams() { - var out = []; - $$("#mq-run-params [data-param-name]").forEach(function (input) { - out.push({ name: input.dataset.paramName, expression: input.value, required: input.dataset.required === "true" }); + function functionPanel(functionId) { + return $$(".mq-function-interaction").find(function (panel) { + return panel.dataset.functionFor === functionId; }); - return out; + } + + function collectParameters(panel) { + var parameters = []; + $$("[data-param-name]", panel).forEach(function (input) { + var type = input.dataset.paramType; + var name = input.dataset.paramName; + var expression = type === "text" ? input.value : input.value.trim(); + var supplied = expression !== ""; + if (type === "text") { + supplied = supplied || $("[data-text-present]", input.parentElement.parentElement).checked; + if (supplied) expression = JSON.stringify(expression); + } + if (!supplied) { + if (input.dataset.required === "true") throw new Error("缺少必填参数:" + name); + return; + } + if (type === "int" && !/^-?\d+$/.test(expression)) throw new Error(name + " 需要十进制整数"); + if (type === "float") { + if (/^-?\d+$/.test(expression)) expression += ".0"; + if (!/^-?\d+\.\d+(?:[eE][+-]?\d+)?$/.test(expression) || !Number.isFinite(Number(expression))) { + throw new Error(name + " 需要有限浮点数,例如 3.0 或 1.0e3"); + } + } + if (Array.from(expression).length > 4096) throw new Error(name + " 超过参数长度上限"); + parameters.push({ name: name, expression: expression }); + }); + return parameters; } function updateRunPreview() { var preview = $("#mq-run-command"); if (!preview || !pendingRun) return; var mode = selectedMode(); - var args = ["--mode", mode, "--output", "jsonl", "--observation-file", "<临时文件>"]; - var parts = []; - if (pendingRun.kind === "entry") { - parts = ["marqdo", "run", reader.dataset.document].concat(args); - } else { - parts = ["marqdo", "call", reader.dataset.document, "<函数 " + pendingRun.label + ">"].concat(args); - rawParams().forEach(function (param) { - if (!param.required && param.expression.trim() === "") return; - parts.push("--arg"); - parts.push(param.name + "=" + (param.expression || "<常量表达式>")); - }); - } + var parts = pendingRun.kind === "entry" + ? ["marqdo", "run", reader.dataset.document] + : ["marqdo", "call", reader.dataset.document, pendingRun.cliName]; + parts.push("--mode", mode, "--output", "jsonl"); + pendingRun.parameters.forEach(function (param) { parts.push("--arg", param.name + "=" + param.expression); }); if (mode === "project") { - grantList("mq-grant-read").forEach(function (glob) { parts.push("--allow-read"); parts.push(glob); }); - grantList("mq-grant-write").forEach(function (glob) { parts.push("--allow-write"); parts.push(glob); }); + grantList("mq-grant-read").forEach(function (glob) { parts.push("--allow-read", glob); }); + grantList("mq-grant-write").forEach(function (glob) { parts.push("--allow-write", glob); }); + } + preview.textContent = parts.map(function (part) { return /[\s"\\]/.test(part) ? JSON.stringify(part) : part; }).join(" "); + $("#mq-run-target-mode").textContent = mode; + var previous = functionRuns.get(pendingRun.functionId); + var grants = mode === "project" ? { read: grantList("mq-grant-read"), write: grantList("mq-grant-write") } : { read: [], write: [] }; + if (pendingRun.panel) updateApplicability(pendingRun.panel); + if (previous && (previous.mode !== mode || JSON.stringify(previous.grants) !== JSON.stringify(grants))) { + setApplicability(pendingRun.panel, "运行模式或授权已修改,上次结果属于历史。"); } - preview.textContent = parts.join(" "); - var modeLabel = $("#mq-run-target-mode"); - if (modeLabel) modeLabel.textContent = mode; } - function renderRunParams(params) { - var container = $("#mq-run-params"); - if (!container) return; - container.textContent = ""; + function renderRunParams(params, panel) { + var container = $(".mq-run-params", panel); if (!params.length) { - appendLine(container, "p", "mq-colophon", "该目标没有参数。"); + appendLine(container, "p", "mq-colophon", "该函数无需参数。"); return; } params.forEach(function (param) { + var type = (param.type || "").toLowerCase(); var label = document.createElement("label"); label.className = "mq-run-param"; var title = document.createElement("span"); - var type = param.type ? ": " + param.type : ""; - var required = param.required ? "(必填)" : "(可选)"; - title.textContent = param.name + type + " " + required; - var input = document.createElement("input"); - input.type = "text"; - input.dataset.paramName = param.name; - input.dataset.required = param.required ? "true" : "false"; - input.spellcheck = false; - input.placeholder = param.default ? "默认常量:" + param.default : "常量表达式,例如 5 或 \"text\""; - if (param.required) input.setAttribute("aria-required", "true"); - input.addEventListener("input", updateRunPreview); + title.textContent = param.name + ": " + (param.type || "未声明类型") + (param.required ? "(必填)" : "(可选)"); label.appendChild(title); + var wrapper = document.createElement("div"); + wrapper.appendChild(label); + container.appendChild(wrapper); + if (["resource", "memory", "pluginhandle", "functionref"].includes(type)) { + appendLine(label, "small", "mq-colophon", "此类型不能从阅读器传入。"); + if (param.required) panel.dataset.unsupported = param.name; + return; + } + var input = document.createElement(type === "bool" ? "select" : type === "text" ? "textarea" : "input"); + if (type === "bool") { + input.add(new Option(param.required ? "请选择" : "使用声明默认值", "")); + input.add(new Option("真 (true)", "true")); + input.add(new Option("假 (false)", "false")); + } else { + input.maxLength = 4096; + input.spellcheck = false; + input.placeholder = param.default !== null && param.default !== undefined + ? "默认:" + JSON.stringify(param.default).slice(0, 120) + : ({ int: "十进制整数", float: "例如 3.0", text: "输入原文本", list: "例如 [1, 2]", map: '例如 {"key": 1}' }[type] || "CLI 常量表达式"); + if (type === "int") input.inputMode = "numeric"; + if (type === "float") input.inputMode = "decimal"; + if (type === "text") input.rows = 2; + } + input.dataset.paramName = param.name; + input.dataset.paramType = type; + input.dataset.required = String(param.required); + if (param.required) input.setAttribute("aria-required", "true"); label.appendChild(input); - container.appendChild(label); + if (type === "text") { + var emptyLabel = document.createElement("label"); + emptyLabel.className = "mq-colophon mq-empty-text"; + var empty = document.createElement("input"); + empty.type = "checkbox"; + empty.dataset.textPresent = "true"; + emptyLabel.append(empty, " 提交空文本"); + wrapper.appendChild(emptyLabel); + } }); } + function openFunctionForm(trigger) { + var panel = functionPanel(trigger.dataset.functionId); + if (!panel || runBusy) return; + closeAllDialogs(); + setMode("document"); + if (panel.hidden) { + renderRunParams(JSON.parse(panel.dataset.params), panel); + panel.hidden = false; + $$("[data-action=call-function]").filter(function (button) { + return button.dataset.functionId === panel.dataset.functionFor; + }).forEach(function (button) { button.setAttribute("aria-expanded", "true"); }); + } + updateApplicability(panel); + var field = $("[data-param-name]", panel) || $("[data-action=prepare-function]", panel); + if (field) field.focus(); + } + + function setApplicability(panel, text) { + if (!panel) return; + var notice = $("[data-function-applicability]", panel); + notice.textContent = text; + notice.hidden = !text; + } + + function updateApplicability(panel) { + var previous = functionRuns.get(panel.dataset.functionFor); + $("[data-action=show-function-result]", panel).hidden = !previous; + if (!previous) { setApplicability(panel, ""); return; } + var same = false; + try { same = JSON.stringify(collectParameters(panel)) === JSON.stringify(previous.parameters); } + catch (error) { /* The draft no longer matches the accepted arguments. */ } + setApplicability(panel, same ? "" : "参数已修改,待重新调用。上次结果与原参数仍可查看。"); + } + + function prepareFunction(panel) { + if (!panel || runBusy) return; + var feedback = $("[data-function-feedback]", panel); + try { + if (panel.dataset.unsupported) throw new Error(panel.dataset.unsupported + " 无法直接传入,请在文稿中组织调用"); + var parameters = collectParameters(panel); + feedback.hidden = true; + openRunForm({ + kind: "function", + functionId: panel.dataset.functionFor, + label: panel.dataset.functionLabel, + cliName: panel.dataset.cliName, + effects: panel.dataset.effects, + parameters: parameters, + panel: panel + }); + } catch (error) { + feedback.textContent = error.message; + feedback.hidden = false; + } + } + function openRunForm(target) { var dialog = $("#mq-dialog-run"); - if (!dialog) { - toast("当前页面没有可用的运行表单;请确认已安装冻结核心"); - return; - } - pendingRun = { - kind: target.kind, - functionId: target.functionId || "", - label: target.label || "入口 main", - clientRequestId: randomId(), - params: target.params || [] - }; - var label = $("#mq-run-target-label"); - if (label) label.textContent = target.kind === "entry" ? "入口 main" : "函数 " + (target.label || ""); - renderRunParams(pendingRun.params); - var mode = document.querySelector('input[name="mq-mode"][value="pure"]'); - if (mode) mode.checked = true; - var grants = $("#mq-run-grants"); - if (grants) grants.hidden = true; + if (!dialog || runBusy) return; + pendingRun = Object.assign({ parameters: [], clientRequestId: randomId() }, target); + $("#mq-run-target-label").textContent = target.kind === "entry" ? "入口 main" : "函数 " + target.label; + $("#mq-run-identity").textContent = reader.dataset.document + " · Analysis " + reader.dataset.analysisDigest + + (target.effects ? " · 静态效果 " + target.effects : " · 静态效果未标注"); + $('input[name="mq-mode"][value="pure"]').checked = true; + $("#mq-grant-read").value = ""; + $("#mq-grant-write").value = ""; + $("#mq-run-grants").hidden = true; updateRunPreview(); openDialog("mq-dialog-run"); } function openRunForMain() { if (reader.dataset.coreAvailable !== "true") { - showUnsupported( - "运行文档", - "当前页面没有可用的冻结核心(MARQDO_BIN),无法通过 CLI 执行;打开、刷新与导出仍然零副作用。" - ); + showUnsupported("运行文档", "当前页面没有可用的冻结核心(MARQDO_BIN)。"); return; } if (reader.dataset.hasMain !== "true") { - toast("本文档没有可执行的 main;请从函数面板选择一个 H2 Exec 函数"); + toast("本文档没有可执行的 main;请从函数面板选择函数"); showFunctions(); return; } - openRunForm({ kind: "entry", label: "入口 main" }); + var functionId = reader.dataset.entryFunction; + if (reader.dataset.entryNeedsParameters === "true") { + var trigger = $$(".mq-document [data-action=call-function]").find(function (button) { + return button.dataset.functionId === functionId; + }); + if (trigger) openFunctionForm(trigger); + return; + } + openRunForm({ kind: "entry", label: "入口 main", functionId: functionId }); + } + + function placeRunPanel(functionId) { + var panel = runPanel(); + var slot = $$(".mq-result-slot").find(function (item) { return item.dataset.resultFor === functionId; }); + if (slot && panel) slot.appendChild(panel); + else if (panel) $("#mq-document").after(panel); + if (panel) panel.open = true; } function submitRun() { - if (!pendingRun) return; - var params = rawParams(); - for (var i = 0; i < params.length; i += 1) { - if (params[i].required && params[i].expression.trim() === "") { - toast("缺少必填参数:" + params[i].name); - return; - } - } + if (!pendingRun || runBusy) return; + var selection = pendingRun; var mode = selectedMode(); var grants = mode === "project" ? { read: grantList("mq-grant-read"), write: grantList("mq-grant-write") } @@ -598,29 +694,19 @@ } var payload = { document: reader.dataset.document, - target: pendingRun.kind === "entry" + target: selection.kind === "entry" ? { kind: "entry" } - : { kind: "function", function_id: pendingRun.functionId }, - parameters: params.filter(function (param) { - return param.required || param.expression.trim() !== ""; - }).map(function (param) { - return { name: param.name, expression: param.expression }; - }), + : { kind: "function", function_id: selection.functionId }, + parameters: selection.parameters, analysis_digest: reader.dataset.analysisDigest, mode: mode, grants: grants, - client_request_id: pendingRun.clientRequestId + client_request_id: selection.clientRequestId }; + pendingRun = null; closeAllDialogs(); clearRunOutput(); - var panel = runPanel(); - var slot = $$(".mq-result-slot").find(function (element) { - return element.dataset.resultFor === payload.target.function_id || - (payload.target.kind === "entry" && element.dataset.resultFor.split(".").pop().split("::").pop() === "main"); - }); - if (slot && panel) slot.appendChild(panel); - else if (panel) $("#mq-document").after(panel); - if (panel) panel.open = true; + placeRunPanel(selection.functionId); showRunPanel(); setRunBusy(true); setRunStatus("正在提交运行请求…"); @@ -643,10 +729,15 @@ setRunBusy(false); var reason = result.data && result.data.message ? result.data.message : "运行请求被拒绝"; setRunStatus("运行未启动(" + result.status + "):" + reason); + if (result.status === 409 && result.data && result.data.code === "view.observation_stale") { + placeRunPanel(""); + functionRuns.forEach(function (previous) { previous.sourceStale = true; }); + setApplicability(selection.panel, "文稿或依赖已变化。请刷新后重新确认,旧结果属于历史。"); + } toast("运行未启动:" + reason); return; } - subscribeRun(result.data, pendingRun ? pendingRun.label : "运行", payload.parameters); + subscribeRun(result.data, selection, payload); }) .catch(function (error) { setRunBusy(false); @@ -655,7 +746,7 @@ }); } - function subscribeRun(job, targetLabel, parameters) { + function subscribeRun(job, selection, payload) { closeActiveObserver(); activeRun = { runId: job.run_id, @@ -663,8 +754,11 @@ cancelUrl: job.cancel_url, source: null, lastSeq: -1, - targetLabel: targetLabel || "运行", - parameters: parameters, + targetLabel: selection.label, + functionId: selection.functionId, + parameters: payload.parameters, + mode: payload.mode, + grants: payload.grants, terminal: false }; clearRunOutput(); @@ -732,23 +826,53 @@ } } - function updateRunView(data) { + function showFunctionResult(panel) { + var previous = panel && functionRuns.get(panel.dataset.functionFor); + if (!previous || runBusy) return; + activeRun = previous; + clearRunOutput(); + placeRunPanel(previous.sourceStale ? "" : previous.functionId); + updateRunView(previous.terminalEvent, true); + } + + function updateRunView(data, historical) { var panel = runPanel(); if (panel) { panel.hidden = false; panel.dataset.runState = data.state; } reader.dataset.runState = data.state; - setRunStatus("状态:" + stateLabel(data.state) + (data.at ? " · " + data.at : "")); + var partial = data.state === "succeeded" && data.result && data.result.output_complete === false; + var rejected = data.result && data.result.core_run_status === "rejected"; + var label = rejected ? "运行前拒绝" : partial ? "已结束,观察或输出不完整" : stateLabel(data.state); + setRunStatus((historical ? "历史运行:" : "状态:") + label + + (data.at ? " · " + data.at : "")); if (!isTerminalState(data.state)) { setRunBusy(true); return; } if (activeRun) { activeRun.terminal = true; + activeRun.terminalEvent = data; activeRun.exportData = data.result && data.result.export_preview ? data : null; var exportButton = $("#mq-export-result"); if (exportButton) exportButton.hidden = !activeRun.exportData; + if (data.result && data.result.stale) { + placeRunPanel(""); + functionRuns.forEach(function (previous) { previous.sourceStale = true; }); + setApplicability(functionPanel(activeRun.functionId), "文稿或依赖已变化,当前结果无法绑定。请刷新后重新确认。"); + } else if (activeRun.functionId && !historical) { + functionRuns.delete(activeRun.functionId); + functionRuns.set(activeRun.functionId, activeRun); + if (functionRuns.size > 8) { + var retired = functionRuns.keys().next().value; + functionRuns.delete(retired); + var retiredPanel = functionPanel(retired); + if (retiredPanel) updateApplicability(retiredPanel); + } + var targetPanel = functionPanel(activeRun.functionId); + if (targetPanel) updateApplicability(targetPanel); + } } closeActiveObserver(); setRunBusy(false); @@ -757,11 +881,38 @@ if (data.observation_summary) { var traceTitle = $("#mq-run-observation-title"); if (traceTitle && data.observation_summary.status === "verified") traceTitle.textContent = "已验证的 Observation v1 事件"; - renderTrace(data.observation_summary); + renderTrace(data.observation_summary, historical); } else if (data.result && data.result.observation_status) renderTraceStatus(data.result.observation_status); - if (data.state === "succeeded") toast("运行完成"); - else toast("运行" + stateLabel(data.state)); + renderRunAudit(data); + if (!historical) toast(data.state === "succeeded" && !partial ? "运行完成" : label); + } + + function renderRunAudit(data) { + var audit = $("#mq-run-audit"); + var items = $("#mq-run-audit-items"); + if (!audit || !items || !activeRun) return; + var result = data.result || {}; + var submitted = activeRun.parameters.map(function (param) { return param.name + " = " + param.expression; }); + var grants = activeRun.grants; + var rows = [ + ["函数身份(Analysis)", result.function_id || activeRun.functionId], + ["提交的参数表达式", submitted.join("\n") || "无;声明默认值由 CLI 处理"], + ["调用计划", activeRun.mode + " · 读 " + (grants.read.join(", ") || "无") + " · 写 " + (grants.write.join(", ") || "无")], + ["文稿身份(Analysis)", result.analysis_digest || reader.dataset.analysisDigest], + ["Stdlib / lock 摘要", (result.stdlib_digest || "未知") + " / " + (result.lock_digest || "未锁定")], + ["CLI 生产者 / Observation run_id", (result.core_version || "未取得") + " / " + (result.core_run_id || "未取得")], + ["CLI 开始时刻(Unix 毫秒)", result.started_unix_ms === null || result.started_unix_ms === undefined ? "未取得" : String(result.started_unix_ms)], + ["View 终态时间", data.at || "未取得"], + ["观测值", "未请求实际参数值和变量值"], + ["适用范围", "可核验静态身份见上。文件内容、时间或外部环境可能变化,仍需独立核验。"] + ]; + items.textContent = ""; + rows.forEach(function (row) { + appendLine(items, "dt", "", row[0]); + appendLine(items, "dd", "", row[1]); + }); + audit.hidden = false; } function previewBytes(text, count) { @@ -886,6 +1037,43 @@ } } + // Rust supplies one inert fragment for both snapshots and Live. Parse as + // XML, then recreate only presentation nodes and their safe attributes. + function mountResultValue(container, markup) { + if (!markup) return false; + var htmlTags = new Set("div span small p details summary ol li dl dt dd table thead tr th tbody td pre code a".split(" ")); + var mathTags = new Set("math mrow mi mo mn mtext mfrac msqrt mroot msub msup msubsup munder mover munderover mtable mtr mtd mspace mpadded mstyle menclose mphantom mmultiscripts mprescripts none".split(" ")); + var mathAttributes = new Set("display mathvariant mathsize mathcolor displaystyle scriptlevel stretchy symmetric movablelimits form fence separator lspace rspace minsize maxsize accent accentunder linethickness width height depth columnalign rowalign rowspacing columnspacing notation".split(" ")); + var mathNS = "http://www.w3.org/1998/Math/MathML"; + var root = new DOMParser().parseFromString(markup, "application/xml").documentElement; + if (root.namespaceURI !== null || root.localName !== "div" || root.getAttribute("class") !== "mq-result-value") return false; + function copy(node) { + if (node.nodeType === Node.TEXT_NODE) return document.createTextNode(node.data); + if (node.nodeType !== Node.ELEMENT_NODE) return null; + var isMath = node.namespaceURI === mathNS; + var name = node.localName; + if (!(isMath ? mathTags.has(name) : node.namespaceURI === null && htmlTags.has(name))) return null; + var result = isMath ? document.createElementNS(mathNS, name) : document.createElement(name); + Array.from(node.attributes).forEach(function (attr) { + var safeMathAttribute = isMath && attr.namespaceURI === null && mathAttributes.has(attr.name); + var safeHtmlAttribute = !isMath && ( + (attr.name === "class" && /^mq-[a-z-]+$/.test(attr.value)) || + (attr.name === "open" && name === "details") || + (attr.name === "href" && name === "a" && /^#mq-h-[0-9a-f]+-[0-9a-f]+$/.test(attr.value)) || + (attr.name === "tabindex" && attr.value === "0") + ); + if (safeMathAttribute || safeHtmlAttribute) result.setAttribute(attr.name, attr.value); + }); + node.childNodes.forEach(function (child) { + var element = copy(child); + if (element) result.appendChild(element); + }); + return result; + } + container.appendChild(copy(root)); + return true; + } + function renderRunResult(result, state, error) { var summary = $("#mq-run-summary"); if (!summary) return; @@ -897,7 +1085,7 @@ (typeof result.duration_ms === "number" ? " · " + result.duration_ms + " ms" : "") + (result.exit_code === null || typeof result.exit_code === "undefined" ? "" : " · 退出码 " + result.exit_code)); } - if (result.value_text) { + if (!mountResultValue(summary, result.value_markup) && result.value_text && result.source_verified) { appendLine(summary, "p", "mq-run-result", "返回值:" + result.value_text); } var observationState = result.observation_status; @@ -947,22 +1135,22 @@ if (error && (error.code || error.message)) { appendLine(summary, "p", "mq-run-error", (error.code || "error") + ":" + (error.message || "运行失败")); } - if (state === "cancelled") { - appendLine(summary, "p", "mq-run-warning", "运行已按请求取消;进程组已终止。"); - } + if (state === "cancelled") appendLine(summary, "p", "mq-run-warning", "View 已结束本次运行;详情见实际终态。"); } function renderTraceStatus(status) { if (!status || status === "verified") return; var summary = $("#mq-run-summary"); if (!summary) return; - var message = status === "invalid" + var message = status === "rejected" + ? "CLI 在开始运行前拒绝了本次调用,未建立源码观察绑定。" + : status === "invalid" ? "Observation 与本次 Analysis 不匹配或格式无效:不绘制执行标注,也不声称观察到完整过程。" : "本次运行没有可用的 Observation v1(unavailable):只展示 CLI 返回值与输出。"; appendLine(summary, "p", "mq-run-warning", message); } - function renderTrace(trace) { + function renderTrace(trace, historical) { var summary = $("#mq-run-summary"); var wrap = $("#mq-run-observation-wrap"); var list = $("#mq-run-events"); @@ -993,7 +1181,7 @@ if (entryEvents.length > 200) { appendLine(list, "li", "mq-colophon", "仅显示前 200 条(共 " + entryEvents.length + " 条)。"); } - if (!trace.stale) { + if (!trace.stale && !historical) { var bySource = {}; $$("[data-source-id]").forEach(function (element) { bySource[element.dataset.sourceId] = element; @@ -1052,9 +1240,12 @@ } function clearRun() { + if (runBusy) { toast("请先取消运行或等待终态。"); return; } closeAllDialogs(); closeActiveObserver(); activeRun = null; + functionRuns.clear(); + $$(".mq-function-interaction").filter(function (panel) { return !panel.hidden; }).forEach(updateApplicability); var panel = runPanel(); if (panel) { panel.hidden = true; @@ -1092,9 +1283,11 @@ if (event.target && event.target.id === "mq-search-input") { renderSearch(event.target.value); } - if (event.target && (event.target.id === "mq-grant-read" || event.target.id === "mq-grant-write" || event.target.dataset.paramName)) { + if (event.target && (event.target.id === "mq-grant-read" || event.target.id === "mq-grant-write")) { updateRunPreview(); } + var panel = event.target.closest ? event.target.closest(".mq-function-interaction") : null; + if (panel) updateApplicability(panel); }); document.addEventListener("change", function (event) { if (event.target && (event.target.id === "mq-export-confirm" || event.target.id === "mq-export-partial")) { diff --git a/docs/ACCEPTANCE.md b/docs/ACCEPTANCE.md index e1e9d78..d5df354 100644 --- a/docs/ACCEPTANCE.md +++ b/docs/ACCEPTANCE.md @@ -1,4 +1,4 @@ -# 验收状态(marqdo-view 0.3.0 / rc.5 契约) +# 验收状态(marqdo-view 0.3.0 / rc.6 契约) > 本文件定义**当前**验收基线,不代替机器证据。`PASS/FAIL/UNVERIFIED` 只以 > `docs/evidence//manifest.json` 为准;manifest 生成前,全部 @@ -12,10 +12,10 @@ | View 源码提交 | manifest 生成时的 `git rev-parse HEAD` | | View release 二进制 SHA-256 | `dist/marqdo-view/bin/marqdo-view`,`sha256:` 前缀 | | View Tool 包摘要 | bundle 内规范化 `SHA256SUMS` 字节的 SHA-256,`sha256:` 前缀 | -| 冻结 CLI 版本 | `3.0.0-rc.5` | -| 冻结 CLI 源码 SHA | `c44b0f943875d563bb7c170f8ccd3fd56a82360f` | -| 冻结 CLI 归档 SHA-256 | `sha256:fd7a313e0ddaf38a9b1901ff2a9aa7b9a0a153e65522a9c0c60f01e2549f583b` | -| 冻结 CLI 二进制 SHA-256 | `sha256:a19049ee111f41512a69c5ed748aaa4968eb3a3f5abd585ccdcf9bbb201bd7ee` | +| 冻结 CLI 版本 | `3.0.0-rc.6` | +| 冻结 CLI 源码 SHA | `63776735e924ade279cdf59d5c733dc24bfdabbb` | +| 冻结 CLI 归档 SHA-256 | `sha256:8dc0b006302e03c23451b8ea9f8a0fcdae8bf67c80c546bee2434bf69755bfe3` | +| 冻结 CLI 二进制 SHA-256 | `sha256:4f12e6b8a2edb327c0d9ab6165f74e8e88a01b05350527e3aade6f52d4f7a06c` | | 平台 | `linux-x86_64-glibc2.39` | | Markdown profile | `marqdo.md.v1` | | 生成时间 | UTC ISO-8601 | @@ -25,17 +25,17 @@ manifest schema:`marqdo.view.acceptance`,`schema_version: 1`。结构见 [`docs/evidence/README.md`](evidence/README.md)。生成命令: ```bash -export MARQDO_BIN=/abs/unpacked/marqdo-3.0.0-rc.5-x86_64-unknown-linux-gnu/marqdo +export MARQDO_BIN=/abs/unpacked/marqdo-3.0.0-rc.6-x86_64-unknown-linux-gnu/marqdo scripts/check-no-legacy.sh scripts/check-docs.sh -scripts/acceptance.sh # 生成 docs/evidence/452e9a32…/manifest.json + dist/acceptance/manifest.json +scripts/acceptance.sh # 生成 docs/evidence/63776735…/manifest.json + dist/acceptance/manifest.json ``` ## 1. P0 发布门禁(G01–G12) -当前状态:**G01–G12 全部 `PASS`**(manifest `docs/evidence/c44b0f943875d563bb7c170f8ccd3fd56a82360f/manifest.json`,`result: PASS`;View 源码提交 `340ecb035fbde0a825c1e5edf1d28b41342d1002`;远端 Woodpecker pipeline #10 对同一 SHA 成功)。 +历史记录(RC.5):**G01–G12 全部 `PASS`**(manifest `docs/evidence/c44b0f943875d563bb7c170f8ccd3fd56a82360f/manifest.json`,`result: PASS`;View 源码提交 `340ecb035fbde0a825c1e5edf1d28b41342d1002`;远端 Woodpecker pipeline #10 对同一 SHA 成功)。 -| # | 门禁 | 命令 / 方式 | 通过判据 | 当前 | +| # | 门禁 | 命令 / 方式 | 通过判据 | 历史记录 | |---|---|---|---|---| | G01 | 协议层无旧契约残留 | `scripts/check-no-legacy.sh` | 0 命中 | `PASS` | | G02 | 构建与静态检查 | `cargo fmt --all -- --check && cargo clippy --locked --all-targets -- -D warnings && cargo test --locked && cargo build --release --locked` | 全部 exit 0,记录测试数 | `PASS` | @@ -50,11 +50,11 @@ scripts/acceptance.sh # 生成 docs/evidence/452e9a32…/manifest.json + | G11 | 证据与 CI | manifest + CI 完整门禁 | CI 红不发布;manifest 与 CI 同 SHA | `PASS`(Woodpecker #10 对 `340ecb0…` 成功,见 manifest `gates.G11_evidence_ci`) | | G12 | 文档事实一致 | `scripts/check-docs.sh` + 人工 | 当前文档不把旧格式写成当前能力 | `PASS` | -任一 P0 门禁 `FAIL` 或 `UNVERIFIED` → 不发布 0.3.0。 +RC.6 候选须重新执行 G01–G12。任一 P0 门禁为 `FAIL` 或 `UNVERIFIED` 时,候选缺少发布证据。 ## 2. 正向用例(功能契约) -| ID | 场景 | 期望 | 当前 | +| ID | 场景 | 期望 | 历史记录 | |---|---|---|---| | E01 | Tool 安装/分发/卸载(rc.5 归档) | 安装成功;分发 `view`;退出码透传;卸载后分发失败 | `PASS` | | E02 | 打开含 `@knowledge` 的文档 | 不执行;无 run 调用 | `PASS` | @@ -77,7 +77,7 @@ scripts/acceptance.sh # 生成 docs/evidence/452e9a32…/manifest.json + ## 3. 负向与失败关闭用例 -| ID | 注入 | 期望 | 当前 | +| ID | 注入 | 期望 | 历史记录 | |---|---|---|---| | N01 | Analysis `schema_version: 2` | `view.protocol_incompatible`;不尝试旧解码 | `PASS` | | N02 | Analysis 未知 revision / 错误 `schema` | 拒绝;不猜测 | `PASS` | @@ -111,14 +111,15 @@ scripts/acceptance.sh # 生成 docs/evidence/452e9a32…/manifest.json + ## 5. 复现 ```bash -export MARQDO_BIN=/abs/unpacked/marqdo-3.0.0-rc.5-x86_64-unknown-linux-gnu/marqdo -sha256sum "$MARQDO_BIN" # a19049ee111f41512a69c5ed748aaa4968eb3a3f5abd585ccdcf9bbb201bd7ee +export MARQDO_BIN=/abs/unpacked/marqdo-3.0.0-rc.6-x86_64-unknown-linux-gnu/marqdo +export MARQDO_WOODPECKER_URL=https://ci.cflmy.cn # 核验本次 View SHA 已结束的远端 CI +sha256sum "$MARQDO_BIN" # 4f12e6b8a2edb327c0d9ab6165f74e8e88a01b05350527e3aade6f52d4f7a06c scripts/frozen-beta.sh verify "$MARQDO_BIN" scripts/check-no-legacy.sh scripts/check-docs.sh cargo fmt --all -- --check && cargo clippy --locked --all-targets -- -D warnings && cargo test --locked scripts/acceptance.sh -cat docs/evidence/c44b0f943875d563bb7c170f8ccd3fd56a82360f/manifest.json +cat docs/evidence/63776735e924ade279cdf59d5c733dc24bfdabbb/manifest.json ``` 单项: @@ -131,8 +132,15 @@ python3 scripts/check-observation.py fail-closed MARQDO_BIN=... scripts/test-no-exec.sh MARQDO_BIN=... scripts/test-export.sh MARQDO_BIN=... scripts/test-browser.sh +MARQDO_BIN=... VIEW_BIN=... python3 scripts/test-complete-reader.py +MARQDO_BIN=... VIEW_BIN=... PLAYWRIGHT_BROWSERS_PATH=... node tests/browser/complete-reader.browser.cjs ``` +`scripts/check-examples.sh` 以 RC.6 检查圆面积的真实调用,与浏览器渲染的同类型返回值交叉核验。 +浏览器检查草稿变化、单次确认、大整数、Unicode、浮点特殊返回值和审计身份。`scripts/test-export.sh` 用真实 CLI 和 +断网 Chromium 检查外部运行导出及单文稿嵌入。完整阅读器套件额外检查失败 ZIP 的确认、取消和超时拒绝、并发会话隔离、 +已核验跨页锚点、同名函数、复合返回值、可定位函数引用,以及脚本禁用后的离线快照。消费者候选复验与公开发行资产单独取证。 + ## 6. 诚实限制 - 运行仅 `pure`(默认)与受控 `project` fs read/write;`strict` 不提供 SSE 目的地, @@ -147,4 +155,4 @@ MARQDO_BIN=... scripts/test-browser.sh `0.2.0`(2026-11-22)按旧预发布契约完成过阅读/执行/导出验收,证据保留在 `docs/evidence/2c7c4f31…/`、`docs/evidence/issue-2/`、`docs/evidence/issue-3/`、 -`docs/evidence/PR-01..PR-06/`。这些结果只记录历史,**不能**替代 rc.5 门禁。 +`docs/evidence/PR-01..PR-06/`。这些结果只记录历史,**不能**替代 rc.6 门禁。 diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 52346ff..6415e98 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -1,13 +1,12 @@ -# 合规矩阵(CONFORMANCE)— marqdo-view 0.3.0 / rc.4 +# 合规矩阵(CONFORMANCE)— marqdo-view 0.3.0 / rc.6 > 活文档。状态值: -> `PASS`(已由绑定 SHA 的机器证据证明)、`FAIL`、`PASS`(尚未证明, +> `PASS`(已由绑定 SHA 的机器证据证明)、`FAIL`、`UNVERIFIED`(尚未证明, > 不得写成 PASS)、`N/A`(明确非目标)。 > 本矩阵不代替 [`docs/ACCEPTANCE.md`](ACCEPTANCE.md) 与 -> `docs/evidence//manifest.json`。当前 rc.4 证据已生成且 -> G01–G12 全部 `PASS`;0.2.0 的旧证据只作历史记录。 +> `docs/evidence//manifest.json`。表中已验收项描述历史门禁覆盖。RC.6 候选按本仓最新提交重新取证。 -最后更新:2026-11-25。 +最后更新:2026-11-29。 ## 1. 当前契约不变量 @@ -41,6 +40,8 @@ | 显式确认后才 `POST /api/runs` 启动一次 run/call | 实现(已验收) | `src/server/*`、`assets/reader.js` | | Observation v1 序列经 View SSE 转发/摘要,不重编号/重排/合成 | 实现(已验收) | `src/execution/*`、`src/server/sse.rs` | | 源绑定:analysis_digest + root_id + module_id + UTF-8 半开 span + source_digest | 实现(已验收) | `src/execution/controller.rs`;`scripts/check-observation.py binding` | +| 原位函数确认、精确参数与审计、同一调用计划 | 实现 | `tests/browser/reader.browser.cjs`、`tests/integration/execution.rs` | +| 返回值类型和展示预算 | 实现 | `src/protocol/value_wire_v1.rs`、`src/reader/result_value.rs` | | stale 不显示成功、不错误高亮 | 实现(已验收) | `src/execution/*`;View 回归路径待测试负责人声明 | | `observation.truncated`/capture.truncated → TRUNCATED;EOF 无终态 → 未完成 | 实现(已验收) | `src/protocol/observation_v1.rs`、`src/execution/events.rs` | | 值默认不请求、不展示;协议支持显式 `--observe-*`(Text 需二次同意) | 实现(已验收) | `src/execution/*` | @@ -53,13 +54,15 @@ |---|---|---| | 普通导出零执行、零联网、离线 file:// 可读 | 实现(已验收) | `scripts/test-export.sh` | | 显式单次结果导出:来源匹配终态、隐私预览、只读 ZIP | 实现(已验收) | `src/server/*`、`scripts/test-complete-reader.py` | +| 外部既有 Observation 导出 | 实现 | `scripts/test-export.sh` 核验 run.id、源摘要、完整性与副作用计数 | +| 共享主题的嵌入正文 | 实现 | `tests/browser/embedded.browser.cjs` 断网验证主题、锚点、媒体及键盘滚动 | | Live/Export 同一 HTML/CSS/JS 与渲染器 | 实现(已验收) | `tests/contract/no_coupling.rs`、`asset_integrity.rs` | | 打开/刷新/搜索/切换/导出零副作用 | 实现(已验收) | `scripts/test-no-exec.sh` | | CSRF/Origin/Cookie/Host/路径/symlink/XSS/跨会话 SSE | 实现(已验收) | `tests/security/`、`scripts/test-security.sh` | | 快照/错误无绝对主机路径;错误只用 relative_path | 实现(已验收) | `src/protocol/observation_v1.rs`、renderer | | Tool 安装/分发/卸载/篡改拒绝;CLI SHA 前后一致 | 实现(已验收) | `scripts/install-smoke.sh`、acceptance G03 | -## 5. 门禁与证据 +## 5. 历史门禁与证据 | 门禁 | 状态 | 证据 | |---|---|---| @@ -73,7 +76,7 @@ | G08 负例 | `PASS` | `scripts/check-observation.py fail-closed` + 测试套件 | | G09 安全基线 | `PASS` | `scripts/test-security.sh`、`test-no-exec.sh`、浏览器 | | G10 导出 | `PASS` | `scripts/test-export.sh` | -| G11 证据与 CI | `PASS` | 远端 CI 未在本环境运行 | +| G11 证据与 CI | `PASS` | 历史同 SHA Woodpecker #10 | | G12 文档一致 | `PASS` | `scripts/check-docs.sh` | ## 6. 明确非目标(N/A) @@ -84,4 +87,4 @@ | 变量/内存/句柄默认可视化 | N/A(协议支持显式选择;View 0.3.0 默认不请求) | | net/process/env/plugin/provider/kernel 授权 UI | N/A(拒绝并引导终端 CLI) | | Windows/macOS 发行 | N/A(不声明) | -| 像素级人工视觉比对、完整 screen-reader 走查 | `PASS`(人工项) | +| 像素级人工视觉比对、完整 screen-reader 走查 | `UNVERIFIED`(人工项) | diff --git a/docs/STATUS.md b/docs/STATUS.md index 1553365..d3c41c6 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -1,7 +1,7 @@ # marqdo-view 现状(STATUS) -> 最后更新:2026-11-25。当前目标:`marqdo-view 0.3.0`,只支持 -> `marqdo 3.0.0-rc.5` 的公开契约(adaptation #4,验收 #5,公共 Analysis 边界 #6)。 +> 最后更新:2026-11-29。当前目标:`marqdo-view 0.3.0`,只支持 +> `marqdo 3.0.0-rc.6` 的公开契约(adaptation #4,验收 #5,公共 Analysis 边界 #6)。 > 机器证据只认绑定 CLI 源码 SHA 的 manifest;未生成的证据一律 `UNVERIFIED`。 ## 版本与基线 @@ -9,38 +9,42 @@ | 项 | 值 | |---|---| | View 产品版本 | `0.3.0` | -| 产品范围 | `>=3.0.0-rc.3,<4.0.0`;验收固定 `3.0.0-rc.5` | +| 产品范围 | `>=3.0.0-rc.3,<4.0.0`;验收固定 `3.0.0-rc.6` | | CLI Tool | revision 1:`requires {api_revision: 1, analysis: 3, observation: 1}`,无 `compatibility` | | 静态语义 | Analysis revision 3(`marqdo.analysis`,ADR-0069 公共边界) | | 运行事实 | Observation revision 1(`marqdo.observation`,单一事件序列) | | Markdown profile | `marqdo.md.v1` | -| 冻结 CLI 版本 | `marqdo 3.0.0-rc.5` | -| CLI 源码 SHA | `c44b0f943875d563bb7c170f8ccd3fd56a82360f` | -| CLI 归档 SHA-256 | `fd7a313e0ddaf38a9b1901ff2a9aa7b9a0a153e65522a9c0c60f01e2549f583b` | -| CLI 二进制 SHA-256 | `a19049ee111f41512a69c5ed748aaa4968eb3a3f5abd585ccdcf9bbb201bd7ee` | -| 平台 | Linux x86_64 / glibc 2.39(唯一正式验证) | +| 冻结 CLI 版本 | `marqdo 3.0.0-rc.6` | +| CLI 源码 SHA | `63776735e924ade279cdf59d5c733dc24bfdabbb` | +| CLI 归档 SHA-256 | `8dc0b006302e03c23451b8ea9f8a0fcdae8bf67c80c546bee2434bf69755bfe3` | +| CLI 二进制 SHA-256 | `4f12e6b8a2edb327c0d9ab6165f74e8e88a01b05350527e3aade6f52d4f7a06c` | +| 目标平台 | Linux x86_64 / glibc 2.39 起。执行环境由候选 manifest 记录 | | 视觉基准 | `docs/design/reference-old-view-reader.png`(**2048×1133**) | -| 验收 manifest | `docs/evidence/c44b0f943875d563bb7c170f8ccd3fd56a82360f/manifest.json`(**result: PASS,G01–G12 全部 PASS**) | +| 验收 manifest | `scripts/acceptance.sh` 按当前 View 和 CLI SHA 生成。RC.5 目录保留历史记录 | ## 0.3.0 适配交付(实现状态) | 交付 | 状态 | 位置 | |---|---|---| | CLI Tool revision 1 清单、无 `compatibility` | 实现 | `tool.json`、`scripts/package.sh` | -| Analysis revision 3 单一静态源(source/document/anchors/heading_span/references) | 实现(待验收) | `src/protocol/analysis_v3.rs`、`src/reader/*` | -| Observation revision 1 流/快照单一解码器 | 实现(待验收) | `src/protocol/observation_v1.rs`、`src/core_client.rs` | -| 绑定校验(analysis_digest/root_id/module_id/UTF-8 半开 span) | 实现(待验收) | `src/execution/*` | -| 引用状态渲染(`not_loaded` = 未核验) | 实现(待验收) | `src/reader/render.rs`、`assets/reader.js` | +| Analysis revision 3 单一静态源(source/document/anchors/heading_span/references) | 实现 | `src/protocol/analysis_v3.rs`、`src/reader/*` | +| Observation revision 1 流、快照单一解码器 | 实现 | `src/protocol/observation_v1.rs`、`src/core_client.rs` | +| 绑定校验(Analysis、入口、执行目标和 UTF-8 半开 span) | 实现 | `src/execution/*` | +| 引用状态及已核验标题 ID | 实现 | `src/reader/links.rs`、`src/reader/render.rs` | | 值默认不请求、不伪造 | 实现 | `src/execution/*`、`assets/reader.js` | | G01 无旧契约静态检查 | 通过 | `scripts/check-no-legacy.sh` | | G12 文档事实一致 | 通过 | `scripts/check-docs.sh` | -| 验收 manifest G01–G12 + `unverified` | 已生成 `result: PASS` | `scripts/acceptance.sh` | -| CI 钉 rc.5 + 独立 no-legacy job | 远端 Woodpecker pipeline #10 对 `340ecb0` 成功 | `.github/workflows/ci.yml`、`.woodpecker.yml` | +| RC.6 验收 manifest G01–G12 | 记录实际命令、CLI 身份和远端同 SHA 的完成状态 | `scripts/acceptance.sh` | +| 独立运行结果导出和单文稿嵌入 | 实现 | `export --observation ... --run-id ...` 和 `export --embed` | +| 函数原位输入、显式确认、ValueWire 和临时审计 | 实现 | `src/execution/`、`src/reader/result_value.rs`、`assets/reader.js` | -## 发布门禁 G01–G12(issue #5) +对应工单的当前候选和 CI 记录在组件 PR。Harness 消费者组合、发布与父级晋升各需独立证据。 +[marqdo-view #18](https://git.cflmy.cn/cflmy/marqdo-view/pulls/18) + +## 历史发布门禁 G01–G12(issue #5) > 证据规则:`PASS/FAIL/UNVERIFIED` 只能由 `scripts/acceptance.sh` 生成并写入 -> `docs/evidence//manifest.json`。当前 manifest 对 View 源码提交 +> `docs/evidence//manifest.json`。以下结果仅适用于历史 View 源码提交 > `340ecb035fbde0a825c1e5edf1d28b41342d1002` 的 `result` 为 `PASS`(G11 引用 > Woodpecker #10);`UNVERIFIED`、`PARTIAL`、`WARN` 一律不得写成 `PASS`。 @@ -59,7 +63,7 @@ | G11 | manifest 与 CI 同 SHA;CI 红不发布 | `PASS` | | G12 | 文档事实一致(`scripts/check-docs.sh`) | `PASS` | -任一 P0 门禁 `FAIL` 或 `UNVERIFIED` → 不发布 0.3.0。 +RC.6 候选须重新执行 G01–G12。任一 P0 门禁为 `FAIL` 或 `UNVERIFIED` 时,候选缺少发布证据。 ## 能力基线 @@ -73,11 +77,11 @@ | 固定 Live 路由;打开/刷新/搜索/切换/导出零执行 | 实现并测试 | | 显式单任务执行(run main / call function),纯 + 受控 project fs grants | 实现(两阶段确认、命令预览、二次确认) | | Observation v1 经 View SSE 转发/摘要;状态/终态、取消、心跳、Last-Event-ID 重放、无轮询 | 实现(单任务、有界摘要、2 连接上限) | -| 运行结果(Wire Value/stdout/stderr/错误/诊断)安全文本展示 | 实现(无 innerHTML 服务端数据) | +| 运行结果(ValueWire、stdout、stderr、诊断) | 有界类型化返回值与惰性文本,Live 和静态结果共用组件 | | 引用/调用/分支/循环/副作用标注 + stale 降级 | 实现(分组 chip、来源标注、截断/无效显式) | | Tool revision 1 独立安装/分发、冻结 CLI SHA 前后一致 | 实现(0.3.0 包,篡改拒绝) | | 静态离线导出(无执行、无联网、manifest/哈希、不可变发布) | 实现 | -| 固定 examples(welcome/branch-loop/function-params/knowledge-only/unsafe-side-effect) | 实现,rc.5 check/call/run 实测脚本 | +| 固定 examples(含 circle-area) | RC.6 静态检查、运行、调用及浏览器用例 | | 逐语句变量值 / 参数实际值 / 内存快照 | **默认不请求、不展示**(协议支持显式选择;View 0.3.0 不请求,绝不伪造) | | 知识“已证明” / Prove / Lint | **UNSUPPORTED**(等待独立版本化报告协议) | | 调试器/断点/单步/调用栈、Notebook/持久内核、Session/journal | **不实现**(明确非目标) | @@ -97,7 +101,7 @@ | 内容 | 路径 | |---|---| -| 一键验收 + manifest(G01–G12) | `scripts/acceptance.sh`;`docs/evidence/452e9a32…/manifest.json`(**result: PASS**,G01–G12 全 PASS) | +| 一键验收 + manifest(G01–G12) | `scripts/acceptance.sh`;`docs/evidence//manifest.json` | | 证据目录说明与 manifest schema | `docs/evidence/README.md` | | 验收标准 | `docs/ACCEPTANCE.md` | | 合规矩阵 | `docs/CONFORMANCE.md` | @@ -117,7 +121,7 @@ - SSE 只推送 View 生命周期与 Observation 摘要,不承诺逐字 stdout/Token 流。 - 观测侧注采用内联分组 chip,而非 SVG 曲线。 - 像素级人工视觉比对与完整 screen-reader 走查仍为 `UNVERIFIED`。 -- 远端 CI 配置已提供但本环境未执行;未运行门禁保持 `UNVERIFIED`。 +- 最终 CI 状态来自同 SHA 完成的 Woodpecker 流水线,尚未取得对应证据的门禁保持 `UNVERIFIED`。 - 平台:Linux x86_64 glibc 正式验证;其他平台不声明支持。 ## 历史 diff --git a/docs/architecture/observation-v1-and-analysis-v3.md b/docs/architecture/observation-v1-and-analysis-v3.md index fce2aaa..32f8be1 100644 --- a/docs/architecture/observation-v1-and-analysis-v3.md +++ b/docs/architecture/observation-v1-and-analysis-v3.md @@ -1,6 +1,6 @@ # Observation v1 与 Analysis revision 3:当前分层 -> 适用范围:`marqdo-view 0.3.0`,冻结 `marqdo 3.0.0-rc.4`。 +> 适用范围:`marqdo-view 0.3.0`,冻结 `marqdo 3.0.0-rc.6`。 > 本文是当前实现的架构基线;0.2.0 时期的 RFC 只保留为历史记录 > (`docs/architecture/RFC-VIEW-0001*.md`、`docs/architecture/RFC-VIEW-0002.md`)。 @@ -41,8 +41,8 @@ protocol 解码 + 结构校验(src/protocol/{analysis_v3,observation_v1,tool_v 1. 协议模块之外没有 `schema_version` 判断;协议模块内只有当前 revision 一个分支。 2. 依赖单向:`core_client → protocol → model`;`reader/execution/server → model`。 模型不反向依赖 CLI/协议;reader 不依赖 core_client 细节。 -3. JSONL 流与原子快照共用同一解码器与同一领域类型;生产代码只消费一种来源 - (Live 用流),两者一致性只在测试中断言,不做“双读合并”。 +3. JSONL 流与原子快照共用同一个解码器。Live 只消费本次流,CLI 静态导出可独立读取选定的既有快照。 + 流与快照的合并不属于任何生产入口。 4. 每个拒绝都有稳定 `view.*` 错误码与可执行提示;不使用 `unwrap`/`expect` 处理协议数据。 5. 事件顺序、`run_id` 一致性、连续 `seq`、唯一终态、`truncated` 语义由解码器集中校验; @@ -58,6 +58,7 @@ protocol 解码 + 结构校验(src/protocol/{analysis_v3,observation_v1,tool_v 不从 `relative_path` 重读文件重建 span。 - 标题 UI/目录/锚点使用 `heading_span`;内容高亮/section 切片/标注归属使用完整 `span`(到下一个同级或更高层标题或 EOF)。 +- 已核验文稿用 Analysis 的锚点映射关联标题。普通 Markdown 保留阅读层的稳定标题 ID。 - `units[].path` 是结构化数组;`parent_id`/`mode`/`mode_origin`/`mode_source_unit_id` 直接使用;不 split display id。`anchors` 是导航名称,不是身份。 - `calls[]` 的 `state/target_kind/target_owner/reason` 用于执行标记; @@ -131,7 +132,17 @@ protocol 解码 + 结构校验(src/protocol/{analysis_v3,observation_v1,tool_v | 领域/绑定 | `src/execution/{request,controller,events}.rs` | | 阅读/渲染 | `src/reader/*`、`assets/reader.css`、`assets/reader.js` | | 服务/SSE | `src/server/{mod,routes,security,sse}.rs` | -| 导出 | `src/export*.rs`(同一 ReaderRenderer) | +| 导出 | `src/export*.rs`(普通站点、隔离嵌入和选定结果共用 ReaderRenderer) | + +### 函数交互和证据归属 + +函数表单消费当前入口 Analysis 的精确函数 ID、标题跨度、签名和静态效果。浏览器只将字段编码为现有请求的参数表达式。 +请求通过 `execution/request` 核对允许的目标、参数名称、必填字段和授权。`core_client` 与 `execution/controller` 仍是唯一执行路径。 +CLI 产生的顶层函数、生产者、执行模式及 Analysis 摘要用于验证此次运行。运行后再次检查静态身份,以判定结果能否附回当前源码。 + +`reader/result_value` 把校验后的 ValueWire 投影为有预算的呈现。Live 和静态页面消费同一返回值组件。 +审计保留已确认的表达式与实际 Observation 事件的区别,时间和环境字段仅在来源可核验时提供。 +只有用户选择结果后,静态打包才写入经批准字段。嵌入入口为单文稿正文,使用同一主题和媒体校验。 | 门禁 | `tests/contract/no_coupling.rs`、`scripts/check-no-legacy.sh`、`scripts/check-docs.sh`、`scripts/check-observation.py` | ## 8. 验证入口 diff --git a/docs/decisions/0011-explicit-result-export.md b/docs/decisions/0011-explicit-result-export.md index 7587d75..8fbfa6a 100644 --- a/docs/decisions/0011-explicit-result-export.md +++ b/docs/decisions/0011-explicit-result-export.md @@ -5,3 +5,7 @@ - 本决策更新 ADR-0005 的可导出内容。普通导出及 Live 结果导出共用文档模型、渲染器和打包核心。 唯一执行入口仍为 `POST /api/runs`。用户可在当前会话的终态 Job 有效期内选择一次结果,明确确认后由 `POST /api/exports` 返回静态 ZIP。该路由验证当前来源、会话和字段选择,将有界不可变的数据交给渲染器。结果随 Job 过期,下载完成的文件由用户保管。 + +外部调用方可使用 `export --observation FILE --run-id ID` 导出一次已完成的可信快照。它通过同一 decoder 验证快照, +并与当前文稿的 Analysis、顶层函数和生产者绑定。这个入口只读取已有运行,默认省略可能敏感的非标量返回值。 +Live ZIP 继续使用已有会话和确认机制。两条导出入口的返回值呈现和静态打包共用实现。 diff --git a/docs/evidence/README.md b/docs/evidence/README.md index 765ff10..bef1b39 100644 --- a/docs/evidence/README.md +++ b/docs/evidence/README.md @@ -1,18 +1,17 @@ # 验收证据 本目录只保存**由真实命令生成**的机器证据。当前基线: -`marqdo 3.0.0-rc.4`(源码 `452e9a32bd9e40dba427d4180691c58bab74449e`)。 +`marqdo 3.0.0-rc.6`。冻结源码和制品身份由 `scripts/frozen-beta.sh metadata` 提供。 `PASS/FAIL/UNVERIFIED` 一律以 manifest 为准;`UNVERIFIED`、`PARTIAL`、`WARN` 不得写成 `PASS`。缺证据即视为未完成,任一 P0 门禁失败/未证明 → 不发布 0.3.0。 ## 目录布局 -- `docs/evidence//manifest.json`:当前契约的机器验收清单 - (当前目录名固定为 `452e9a32bd9e40dba427d4180691c58bab74449e`); +- `docs/evidence//manifest.json`:该次验收的机器清单,由生成器按 CLI 源码 SHA 定位。 - `docs/evidence//README.md`:该次证据的说明/附件索引; - 历史目录(`2c7c4f31e7a388d3fcfa717a77067e696ed13854/`、`issue-2/`、 `issue-3/`、`PR-01..PR-06/`、`0001-pr03/`):0.2.0 旧预发布契约时代的证据, - **仅作历史记录,不能替代 rc.4 门禁**; + 仅作历史记录。RC.4 和 RC.5 的清单也适用同一证据边界。 - 分 PR 的人工/截图/日志不是协议证据,只在对应 README 中说明。 ## manifest schema:`marqdo.view.acceptance` / `schema_version: 1` @@ -26,10 +25,10 @@ "view_commit": "<40 hex>", "view_binary_sha256": "sha256:<64 hex>", "view_tool_bundle_digest": "sha256:<64 hex>", - "cli_source_sha": "452e9a32bd9e40dba427d4180691c58bab74449e", - "cli_archive_sha256": "sha256:9c3f166b5e5b8840d39d10019074e4e1c42432fc23e26c69670e64fdcf4e15d8", - "cli_binary_sha256": "sha256:a7306962689c635445a59043971ea2eb09298e01feeee81f0ba07b1f3e10306e", - "platform": "linux-x86_64-glibc2.39", + "cli_source_sha": "<40 hex>", + "cli_archive_sha256": "sha256:<64 hex>", + "cli_binary_sha256": "sha256:<64 hex>", + "platform": "", "generated_utc": "", "gates": { "G01_no_legacy": {"state": "UNVERIFIED", "command": "...", "exit_code": null, "log": ""} @@ -63,16 +62,17 @@ G01–G12 的判定命令与通过判据见 [`docs/ACCEPTANCE.md`](../ACCEPTANCE manifest 的 gate id 固定为:`G01_no_legacy`、`G02_build`、`G03_install`、 `G04_static`、`G05_run`、`G06_stream_snapshot`、`G07_binding_stale`、 `G08_negative`、`G09_security`、`G10_export`、`G11_evidence_ci`、`G12_docs`。 -G11(证据与 CI)只在其实际运行的 CI 环境中可为 PASS;本地 manifest 中保持 +G11(证据与 CI)须查询同一 View 提交已经结束的 Woodpecker 流水线。如果没有查询到结果,manifest 中保持 `UNVERIFIED`,不能证明远端 CI 通过。 ## 生成方式(不要手写/篡改) ```bash -export MARQDO_BIN=/abs/unpacked/marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu/marqdo +export MARQDO_BIN=/abs/unpacked/marqdo-3.0.0-rc.6-x86_64-unknown-linux-gnu/marqdo +export MARQDO_WOODPECKER_URL=https://ci.cflmy.cn scripts/frozen-beta.sh verify "$MARQDO_BIN" scripts/acceptance.sh -# → docs/evidence/452e9a32bd9e40dba427d4180691c58bab74449e/manifest.json +# → docs/evidence//manifest.json # → dist/acceptance/manifest.json(同一内容) ``` diff --git a/examples/circle-area.mq.md b/examples/circle-area.mq.md new file mode 100644 index 0000000..7731674 --- /dev/null +++ b/examples/circle-area.mq.md @@ -0,0 +1,11 @@ +# @knowledge 圆的面积 + +半径为 $r$ 的圆,其面积为 $S=\pi r^2$。半径应当非负,面积单位是长度单位的平方。 + +## @exec circle_area + +`params(r: Float)` + +输入浮点半径 r。函数使用固定的圆周率近似值,因此返回的是数值近似。 + +`return 3.141592653589793 * r * r` diff --git a/examples/complete-reader/index.mq.md b/examples/complete-reader/index.mq.md index 1ad2c63..1294683 100644 --- a/examples/complete-reader/index.mq.md +++ b/examples/complete-reader/index.mq.md @@ -21,7 +21,7 @@ $$ - [x] 记录样本 - [ ] 审查结果 -[误差说明](docs/explanation.mq.md#误差-1) · [本页公式](#计算均值) +[误差说明](docs/explanation.mq.md#误差-2) · [本页公式](#计算均值) # @exec 计算 diff --git a/scripts/acceptance.sh b/scripts/acceptance.sh index 6a413e9..e39c90c 100755 --- a/scripts/acceptance.sh +++ b/scripts/acceptance.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# marqdo-view 0.3.0 one-command acceptance for the rc.4 contract baseline +# marqdo-view 0.3.0 one-command acceptance for the rc.6 contract baseline # (adaptation issue #4, acceptance gates G01-G12 from issue #5, public Analysis # boundary issue #6). # @@ -131,8 +131,11 @@ finish() { "$cli_archive_sha" "$bundle_sha" "$sums_sha" "$result" "$test_count" \ "$browser_state" <<'PY_MANIFEST' import datetime +import hashlib import json +import os import pathlib +import platform import subprocess import sys @@ -140,6 +143,10 @@ import sys cli_source_sha, cli_binary_sha, cli_archive_sha, view_binary_sha, bundle_sha, result, test_count, browser_state) = sys.argv[1:] repo = pathlib.Path.cwd() +cli_install = pathlib.Path(os.environ["MARQDO_BIN"]).parent +evidence = pathlib.Path(evidence_path) +libc, libc_version = platform.libc_ver() +host = f"{platform.system().lower()}-{platform.machine()}-{libc}{libc_version}" gates = {} for line in pathlib.Path(gates_path).read_text().splitlines(): gate_id, state, exit_code, command, log, note = line.split("\t") @@ -147,7 +154,7 @@ for line in pathlib.Path(gates_path).read_text().splitlines(): if log: prefix = "dist/acceptance/logs/" if log.startswith(prefix): - log = f"docs/evidence/{cli_source_sha}/logs/{log[len(prefix):]}" + log = f"logs/{log[len(prefix):]}" entry["log"] = log if note: entry["note"] = note @@ -170,10 +177,12 @@ manifest = { "cli_source_sha": cli_source_sha, "cli_archive_sha256": "sha256:" + cli_archive_sha, "cli_binary_sha256": "sha256:" + cli_binary_sha, + "cli_worker_sha256": "sha256:" + hashlib.sha256((cli_install / "marqdo-provider-worker").read_bytes()).hexdigest(), + "cli_stdlib": json.loads((cli_install / "stdlib/stdlib.json").read_text()), "contracts": {"api_revision": 1, "analysis": 3, "observation": 1}, "markdown_profile": "marqdo.md.v1", "product_range": ">=3.0.0-rc.3,<4.0.0", - "platform": "linux-x86_64-glibc2.39", + "platform": host, "generated_utc": datetime.datetime.now(datetime.timezone.utc).isoformat(), "result": result, "gates": gates, @@ -185,7 +194,7 @@ manifest = { }, } text = json.dumps(manifest, indent=2, sort_keys=True) + "\n" -pathlib.Path(evidence_path).write_text(text) +evidence.write_text(text) pathlib.Path(dist_path).write_text(text) print("evidence manifest:", evidence_path) PY_MANIFEST @@ -238,7 +247,7 @@ fi # ---------------------------------------------------------------- gates ---- gate_run G01_no_legacy "no retired contracts in src/tool.json/current docs" "./scripts/check-no-legacy.sh" -gate_run G12_docs "current docs describe the rc.4 baseline" "./scripts/check-docs.sh" +gate_run G12_docs "current docs describe the rc.6 baseline" "./scripts/check-docs.sh" gate_run G02_build "fmt, clippy, tests and release build" \ "cargo fmt --all -- --check && cargo clippy --locked --all-targets -- -D warnings && cargo test --locked && cargo build --release --locked" @@ -397,62 +406,57 @@ else fi gate_run G10_export "static export zero-execution + single renderer contract" \ - "env MARQDO_BIN=\"$MARQDO_BIN\" ./scripts/test-export.sh && cargo test --locked --test contract" + "env MARQDO_BIN=\"$MARQDO_BIN\" ./scripts/test-export.sh && env VIEW_BIN=\"$bundle/bin/marqdo-view\" python3 scripts/test-complete-reader.py && cargo test --locked --test contract" + +# Running inside CI does not attest a finished workflow: the browser stage +# may still fail. Only a finished remote pipeline on these exact source bytes +# can satisfy G11. The URL is optional for offline/local acceptance. +ci_state="UNVERIFIED" +ci_note="no finished remote CI pipeline was verified for this commit" +ci_cmd="remote CI run" +if [[ -n "${MARQDO_WOODPECKER_URL:-}" ]]; then + ci_commit="$(git rev-parse HEAD)" + ci_url="${MARQDO_WOODPECKER_URL%/}" + ci_cmd="$ci_url cflmy/marqdo-view pipelines (commit $ci_commit)" + ci_headers=() + if [[ -n "${MARQDO_WOODPECKER_TOKEN:-}" ]]; then + ci_headers=(-H "Authorization: Bearer $MARQDO_WOODPECKER_TOKEN") + fi + ci_json="$(curl -fsS --max-time 20 "${ci_headers[@]}" \ + "$ci_url/api/repos/2/pipelines?limit=20" 2>/dev/null || true)" + ci_result="$(CI_JSON="$ci_json" CI_COMMIT="$ci_commit" CI_URL="$ci_url" python3 - <<'PY_CI' +import json +import os -if [[ "${CI:-}" == "true" || "${CI:-}" == "woodpecker" || -n "${WOODPECKER:-}" || -n "${GITHUB_ACTIONS:-}" ]]; then - gate_state[G11_evidence_ci]=PASS - gate_cmd[G11_evidence_ci]="this acceptance ran inside the unified CI job" - gate_exit[G11_evidence_ci]=0 - gate_log[G11_evidence_ci]="" - gate_note[G11_evidence_ci]="manifest generated in the same CI invocation that produced the artifacts (GitHub Actions or Woodpecker sets CI=true)" -else - # A local manifest can still cite a real remote CI run, but only when the - # Woodpecker API confirms a successful pipeline for this exact commit SHA. - ci_state="UNVERIFIED" - ci_note="remote CI was not executed in this environment; this local manifest cannot attest CI. CI red => no release." - ci_cmd="remote CI run" - if [[ -n "${MARQDO_WOODPECKER_TOKEN:-}" && -n "${MARQDO_WOODPECKER_URL:-}" ]]; then - ci_commit="$(git rev-parse HEAD)" - ci_json="$(curl -fsS -H "Authorization: Bearer $MARQDO_WOODPECKER_TOKEN" \ - "$MARQDO_WOODPECKER_URL/api/repos/2/pipelines?limit=20" 2>/dev/null || true)" - ci_result="$(CI_JSON="$ci_json" CI_COMMIT="$ci_commit" python3 - <<'PY_CI' -import json, os -text = os.environ.get("CI_JSON", "") -commit = os.environ.get("CI_COMMIT", "") -if not text: - print("UNVERIFIED\tno API response") - raise SystemExit(0) try: - pipelines = json.loads(text) -except Exception as err: - print(f"UNVERIFIED\tAPI response is not JSON: {err}") - raise SystemExit(0) -for pipeline in pipelines: - if pipeline.get("commit") != commit: - continue - state = pipeline.get("status") - number = pipeline.get("number") - if state == "success": - print(f"PASS\tWoodpecker pipeline #{number} succeeded for {commit}") + pipelines = json.loads(os.environ["CI_JSON"]) +except ValueError: + pipelines = None +if not isinstance(pipelines, list): + print("UNVERIFIED\tWoodpecker did not return a pipeline list") +else: + commit = os.environ["CI_COMMIT"] + pipeline = next((p for p in pipelines if p.get("commit") == commit), None) + if pipeline is None: + print(f"UNVERIFIED\tno Woodpecker pipeline for {commit}") else: - print(f"FAIL\tWoodpecker pipeline #{number} is {state} for {commit}") - raise SystemExit(0) -print(f"UNVERIFIED\tno Woodpecker pipeline for {commit}") + state = pipeline.get("status") + number = pipeline.get("number") + verdict = {"success": "PASS", "failure": "FAIL", "error": "FAIL"}.get(state, "UNVERIFIED") + print(f"{verdict}\t{os.environ['CI_URL']}/repos/2/pipeline/{number} is {state} for {commit}") PY_CI )" - ci_state="${ci_result%%$'\t'*}" - ci_note="${ci_result#*$'\t'}" - if [[ "$ci_state" == "PASS" || "$ci_state" == "FAIL" ]]; then - gate_state[G11_evidence_ci]="$ci_state" - gate_cmd[G11_evidence_ci]="$MARQDO_WOODPECKER_URL cflmy/marqdo-view pipelines (commit $ci_commit)" - gate_exit[G11_evidence_ci]=$([[ "$ci_state" == "PASS" ]] && echo 0 || echo 1) - gate_log[G11_evidence_ci]="" - gate_note[G11_evidence_ci]="$ci_note" - fi - fi - if [[ -z "${gate_state[G11_evidence_ci]:-}" ]]; then - gate_unverified G11_evidence_ci "$ci_cmd" "$ci_note" - fi + ci_state="${ci_result%%$'\t'*}" + ci_note="${ci_result#*$'\t'}" +fi +if [[ "$ci_state" == "UNVERIFIED" ]]; then + gate_unverified G11_evidence_ci "$ci_cmd" "$ci_note" +else + gate_state[G11_evidence_ci]="$ci_state" + gate_cmd[G11_evidence_ci]="$ci_cmd" + gate_exit[G11_evidence_ci]=$([[ "$ci_state" == "PASS" ]] && echo 0 || echo 1) + gate_log[G11_evidence_ci]="" + gate_note[G11_evidence_ci]="$ci_note" fi # Leave the isolated tool home clean. diff --git a/scripts/check-docs.sh b/scripts/check-docs.sh index 7c9bb91..9c86466 100755 --- a/scripts/check-docs.sh +++ b/scripts/check-docs.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# G12 (issue #5): current documentation must describe the rc.5 contracts as the +# G12 (issue #5): current documentation must describe the rc.6 contracts as the # only current capability. Historical CHANGELOG entries may name retired # interfaces only under an explicit `## History` heading. # @@ -7,7 +7,7 @@ # README.md, COMPATIBILITY.md, CHANGELOG.md, docs/STATUS.md, docs/ACCEPTANCE.md # # The script never rewrites files and never claims a gate is PASS: it only -# reports fact drift between the current docs and the rc.5 contract baseline. +# reports fact drift between the current docs and the rc.6 contract baseline. # # Usage: scripts/check-docs.sh set -euo pipefail @@ -73,17 +73,17 @@ if [[ "$fail" -ne 0 ]]; then cat >&2 <<'EOF' check-docs: FAIL - Update the current docs to the rc.5 baseline: + Update the current docs to the rc.6 baseline: * one static source: `check --emit` Analysis revision 3 (ADR-0069); * one runtime sequence: Observation revision 1 (`--output jsonl` / `--observation-file`), no retired trace file or event stream; * CLI Tool revision 1 with exact `requires` (api_revision 1, analysis 3, observation 1), no `compatibility` field; - * product range >=3.0.0-rc.3,<4.0.0, acceptance pinned to rc.5. + * product range >=3.0.0-rc.3,<4.0.0, acceptance pinned to rc.6. Old release notes belong under CHANGELOG's explicit `## History` heading. Do not claim PASS/UNVERIFIED results that have no generated evidence. EOF exit 1 fi -echo "check-docs: PASS (README/COMPATIBILITY/CHANGELOG/STATUS/ACCEPTANCE describe the rc.5 baseline; CHANGELOG history is explicit)" +echo "check-docs: PASS (README/COMPATIBILITY/CHANGELOG/STATUS/ACCEPTANCE describe the rc.6 baseline; CHANGELOG history is explicit)" diff --git a/scripts/check-examples.sh b/scripts/check-examples.sh index 698b029..b6a96e1 100755 --- a/scripts/check-examples.sh +++ b/scripts/check-examples.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Prove the five 3.0 example documents against the frozen released CLI using +# Verify the example documents against the frozen released CLI using # the current public contracts: one `check --emit` Analysis v3 source and one # Observation v1 sequence per `run`/`call`. Never rebuilds the Core; runs in a # copied temp project so the repository examples are never modified. @@ -18,13 +18,13 @@ work="$repo_root/dist/examples-check" rm -rf "$work" mkdir -p "$work" cp examples/welcome.mq.md examples/branch-loop.mq.md examples/function-params.mq.md \ - examples/knowledge-only.mq.md examples/unsafe-side-effect.mq.md "$work/" + examples/knowledge-only.mq.md examples/unsafe-side-effect.mq.md examples/circle-area.mq.md "$work/" cp examples/view.json "$work/" cd "$work" -echo "==> check all five example documents (one static source: check --emit)" -for file in welcome.mq.md branch-loop.mq.md function-params.mq.md knowledge-only.mq.md unsafe-side-effect.mq.md; do +echo "==> check example documents (one static source: check --emit)" +for file in welcome.mq.md branch-loop.mq.md function-params.mq.md knowledge-only.mq.md unsafe-side-effect.mq.md circle-area.mq.md; do if ! "$core" check "$file" --emit "analysis-$file.json" --json > "check-$file.json"; then echo "error: frozen CLI refused $file" >&2 cat "check-$file.json" >&2 @@ -34,7 +34,7 @@ for file in welcome.mq.md branch-loop.mq.md function-params.mq.md knowledge-only done python3 - <<'PY' import json -for name in ("welcome", "branch-loop", "function-params", "knowledge-only", "unsafe-side-effect"): +for name in ("welcome", "branch-loop", "function-params", "knowledge-only", "unsafe-side-effect", "circle-area"): artifact = json.load(open(f"analysis-{name}.mq.md.json")) assert artifact["schema"] == "marqdo.analysis", artifact["schema"] assert artifact["schema_version"] == 3, artifact["schema_version"] @@ -57,6 +57,26 @@ assert terminal["payload"]["value"] == {"type": "int", "decimal": "10"}, termina print("call double(5): PASS (Observation v1, Int 10)") PY +echo "==> call circle_area with real Float inputs and independent run IDs" +python3 - "$core" <<'PY' +import json +import subprocess +import sys + +core = sys.argv[1] +ids = set() +for radius, expected in [('3.0', 28.274333882308138), ('4.0', 50.26548245743669), ('0.0', 0.0)]: + run = json.loads(subprocess.check_output([core, 'call', 'circle-area.mq.md', 'circle_area', + '--arg', f'r={radius}', '--mode', 'pure', '--output', 'json'])) + terminal = run['events'][-1] + assert terminal['kind'] == 'run.completed' + value = terminal['payload']['value'] + assert value['type'] == 'float' and abs(value['value'] - expected) < 1e-9, value + ids.add(run['run']['id']) +assert len(ids) == 3 +print('circle_area: PASS (3 verified inputs, one run_id per invocation)') +PY + echo "==> run branch-loop main -> Int 0 with loop/return events" "$core" run branch-loop.mq.md --mode pure --output json > run.json python3 - <<'PY' diff --git a/scripts/check-no-legacy.sh b/scripts/check-no-legacy.sh index 8496ba5..a660f44 100755 --- a/scripts/check-no-legacy.sh +++ b/scripts/check-no-legacy.sh @@ -157,13 +157,13 @@ check-no-legacy: FAIL Remove the retired reference from the current tree (delete the code path, rewrite the doc claim, or move history into CHANGELOG.md under its explicit `## History` heading). Do not add a compatibility branch, fallback decoder or - migration shim: the rc.4 baseline has exactly one current contract per + migration shim: the rc.6 baseline has exactly one current contract per boundary. Historical evidence under docs/evidence/** and historical ADRs are exempt and untouched. - Current baseline: marqdo 3.0.0-rc.4, Analysis revision 3 (ADR-0069), + Current baseline: marqdo 3.0.0-rc.6, Analysis revision 3 (ADR-0069), Observation revision 1, CLI Tool revision 1. EOF exit 1 fi -echo "check-no-legacy: PASS (0 retired references in src/, tool.json and current docs; rc.4 baseline)" +echo "check-no-legacy: PASS (0 retired references in src/, tool.json and current docs; rc.6 baseline)" diff --git a/scripts/frozen-beta.sh b/scripts/frozen-beta.sh index ba396df..f6da090 100755 --- a/scripts/frozen-beta.sh +++ b/scripts/frozen-beta.sh @@ -2,15 +2,17 @@ # Identity of the released CLI used by the marqdo-view 0.3.0 acceptance gate. # # The pinned release is the current public-contract baseline: -# marqdo 3.0.0-rc.5 (Analysis v3 / ADR-0069, Observation v1, CLI Tool revision 1) +# marqdo 3.0.0-rc.6 (Analysis v3 / ADR-0069, Observation v1, CLI Tool revision 1) # The script only downloads, unpacks and verifies the official archive; it never # rebuilds or modifies the CLI. set -euo pipefail -version=3.0.0-rc.5 -source_sha=c44b0f943875d563bb7c170f8ccd3fd56a82360f -binary_sha=a19049ee111f41512a69c5ed748aaa4968eb3a3f5abd585ccdcf9bbb201bd7ee -archive_sha=fd7a313e0ddaf38a9b1901ff2a9aa7b9a0a153e65522a9c0c60f01e2549f583b +version=3.0.0-rc.6 +source_sha=63776735e924ade279cdf59d5c733dc24bfdabbb +binary_sha=4f12e6b8a2edb327c0d9ab6165f74e8e88a01b05350527e3aade6f52d4f7a06c +archive_sha=8dc0b006302e03c23451b8ea9f8a0fcdae8bf67c80c546bee2434bf69755bfe3 +worker_sha=aa9cbc0082674f3d21d6e6cd1ad3def41e08c07a147bbd24dd87f3d8a58b50fe +stdlib_manifest_sha=b7783cb5f32de7d7a1725354e8ae19f12a734bbd2992cf9ca084e6928b923305 artifact="marqdo-$version-x86_64-unknown-linux-gnu" root="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" @@ -27,6 +29,12 @@ verify() { echo "error: frozen marqdo version does not match $version" >&2 return 1 fi + ( + cd "$install" + printf '%s %s\n' \ + "$worker_sha" marqdo-provider-worker \ + "$stdlib_manifest_sha" stdlib/stdlib.json | sha256sum --strict -c - >&2 + ) } if [[ "${1:-}" == "metadata" && $# -eq 1 ]]; then diff --git a/scripts/test-browser.sh b/scripts/test-browser.sh index c79cc0c..239e29a 100755 --- a/scripts/test-browser.sh +++ b/scripts/test-browser.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash # Browser acceptance for the Live reader: real Chromium, real frozen core -# pinned to marqdo 3.0.0-rc.4 (Analysis revision 3, Observation revision 1). +# pinned to marqdo 3.0.0-rc.6 (Analysis revision 3, Observation revision 1). # # Usage: # MARQDO_BIN=/abs/path/marqdo scripts/test-browser.sh @@ -84,7 +84,9 @@ mkdir -p "$repo_root/tests/.cache" "$MQ_SCREENSHOT_DIR" run_suite examples/welcome run_suite examples/control-flow run_suite examples/function-params.mq.md +run_suite examples/circle-area.mq.md run_suite tests/fixtures/security-project +VIEW_BIN="$repo_root/target/release/marqdo-view" node tests/browser/complete-reader.browser.cjs core_after="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)" if [[ "$core_before" != "$core_after" ]]; then diff --git a/scripts/test-complete-reader.py b/scripts/test-complete-reader.py index d02acfd..780da02 100755 --- a/scripts/test-complete-reader.py +++ b/scripts/test-complete-reader.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""HTTP and ZIP acceptance against the frozen rc.4 release binary. +"""HTTP and ZIP acceptance against the frozen release binary. The View consumes Observation v1 (`--output jsonl` / `--observation-file`); there is no trace file or legacy JSON run envelope. @@ -78,7 +78,7 @@ def verify_zip(payload, destination, expected_digest): assert not any(name.endswith(".js") for name in names) html = archive.read("index.html").decode() assert "4" in html and "参数未包含" in html assert html.count('class="mq-snapshot"') == 1 other = archive.read("pages/docs/explanation.mq.md.html").decode() assert 'class="mq-snapshot"' not in other and '" not in html and "<script>bad()" in html - assert json.loads(archive.read("manifest.json"))["execution"]["observation_status"] == "unavailable" + assert json.loads(archive.read("manifest.json"))["execution"]["observation_status"] == "verified" first, headers = post(browser, base, "/api/exports", token, selection) verify_zip(first, None, headers["X-Marqdo-Manifest-SHA256"]) - print("active/cancelled export denied, verified failure gated, stdout escaped, missing Observation separate") + print("active/cancelled export denied, verified failure gated, stdout escaped, Live uses its verified stream alone") print("selected IDs remain isolated, tampering detected, oversized request denied, failed and aborted packages cleaned") calls = count.read_text().splitlines() assert calls == ["call"] * 4, calls diff --git a/scripts/test-export.sh b/scripts/test-export.sh index 48b2000..d2937ac 100755 --- a/scripts/test-export.sh +++ b/scripts/test-export.sh @@ -49,10 +49,129 @@ for pattern in (" + +| 文字 | 列 | +| --- | --- | +| {wide} | 示例 | + +```text +{wide} +``` + +## Detail + +> 一段引用。 +''' +(project / 'index.mq.md').write_text('# @knowledge 阅读\n' + body) +(project / 'plain.md').write_text('# 阅读\n' + body) +(project / 'other.mq.md').write_text('# @knowledge 不应打包\n') +def chunk(name, data): + return struct.pack('>I', len(data)) + name + data + struct.pack('>I', zlib.crc32(name + data)) +image = (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 1, 1, 8, 2, 0, 0, 0)) + + chunk(b'IDAT', zlib.compress(b'\x00\xA0\x00\x50')) + chunk(b'IEND', b'')) +(project / 'image.png').write_bytes(image) +(work / 'outside.png').write_bytes(image) +(project / 'escape.png').symlink_to('../outside.png') +PY +for source in index.mq.md plain.md; do + document="$embed_work/project/$source" + document_sha="$(sha256sum "$document" | cut -d' ' -f1)" + "${view[@]}" export "$document" --out "$embed_work/$source" --embed \ + --theme dark --anchor detail --expect-source-sha256 "$document_sha" +done +for option in --anchor --expect-source-sha256; do + if "${view[@]}" export "$document" --out "$embed_work/invalid" --embed \ + "$option" missing > "$embed_work/rejection.log" 2>&1; then + echo "error: embedded export accepted invalid $option" >&2 + exit 1 + fi + grep -Eq 'view\.export_(invalid|source_changed)' "$embed_work/rejection.log" + test ! -e "$embed_work/invalid" +done + # X-04: open the exported site from file:// in a real browser (offline). if [[ -d "$repo_root/tests/browser/node_modules/playwright" ]]; then PLAYWRIGHT_BROWSERS_PATH="${PLAYWRIGHT_BROWSERS_PATH:-$repo_root/tests/.cache/pw-browsers}" \ - MQ_FILE="$site/index.html" node - "$repo_root/tests/browser" <<'JS' + MQ_FILE="$site/index.html" MQ_RESULT="$result_work/site/index.html" MQ_RUN_ID="$run_id" \ + node - "$repo_root/tests/browser" <<'JS' const path = require("path"); const { chromium } = require(path.join(process.argv[2], "node_modules/playwright")); (async () => { @@ -75,13 +194,22 @@ const { chromium } = require(path.join(process.argv[2], "node_modules/playwright if (external.length) throw new Error("offline page requested " + external.join(",")); if (errors.length) throw new Error("offline console errors: " + errors.join(" | ")); if ((await page.locator("link[rel=stylesheet]").count()) !== 1) throw new Error("stylesheet missing"); + await page.context().setOffline(true); + await page.goto("file://" + process.env.MQ_RESULT, { waitUntil: "load" }); + await page.reload(); + const result = await page.locator(".mq-snapshot").innerText(); + if (!result.includes(process.env.MQ_RUN_ID) || !result.includes("成功")) throw new Error("selected result missing"); + if (external.length || errors.length) throw new Error("offline snapshot requested external resources or reported browser errors"); console.log("file:// offline browser check: PASS"); await browser.close(); })().catch((error) => { console.error(error.message); process.exit(1); }); JS + PLAYWRIGHT_BROWSERS_PATH="${PLAYWRIGHT_BROWSERS_PATH:-$repo_root/tests/.cache/pw-browsers}" \ + node tests/browser/embedded.browser.cjs "$embed_work" "${view[@]}" else echo "note: Playwright not installed; skipped file:// browser check" fi +test ! -e "$result_work/project/out/view-sentinel.txt" core_after="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)" [[ "$core_before" == "$core_after" ]] || { echo "error: frozen core changed" >&2; exit 1; } diff --git a/src/cli.rs b/src/cli.rs index f61ae33..39581ee 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -80,6 +80,39 @@ pub struct ExportArgs { /// Disable semantic annotations but keep the prose readable. #[arg(long)] pub no_annotations: bool, + + /// Import a trusted, already completed CLI Observation snapshot. + #[arg( + long, + value_name = "FILE", + requires = "run_id", + conflicts_with = "embed" + )] + pub observation: Option, + + /// Exact Observation run.id selected for export. + #[arg(long, value_name = "ID", requires = "observation")] + pub run_id: Option, + + /// Include a potentially sensitive, non-scalar return value from the snapshot. + #[arg(long, requires = "observation")] + pub include_sensitive_result: bool, + + /// Export one document as a script-free, embeddable reader package. + #[arg(long)] + pub embed: bool, + + /// Select the embedded reader theme (default: light). + #[arg(long, value_parser = ["light", "dark"], requires = "embed")] + pub theme: Option, + + /// Publish an entry link to this exact heading ID in the embedded document. + #[arg(long, value_name = "ID", requires = "embed")] + pub anchor: Option, + + /// Require this raw, lowercase SHA-256 of the selected document's bytes. + #[arg(long, value_name = "HEX", requires = "embed")] + pub expect_source_sha256: Option, } #[derive(Debug, Args)] diff --git a/src/execution/controller.rs b/src/execution/controller.rs index d9d3a27..9654394 100644 --- a/src/execution/controller.rs +++ b/src/execution/controller.rs @@ -27,6 +27,7 @@ use crate::protocol::observation_v1::{ }; use crate::protocol::tool_v1; use crate::reader::assemble::{DocumentService, StaticDocument}; +use crate::reader::result_value::render_result_value; use crate::reader::source::{sha256_hex, sha256_prefixed}; use std::collections::{HashMap, VecDeque}; use std::ffi::OsString; @@ -279,7 +280,7 @@ impl ExecutionController { // concurrent submissions cannot both pass the single-job gate. let static_doc = self.service.static_document(&validated.document)?; if static_doc.analysis_digest != validated.analysis_digest { - return Err(ViewError::RunInvalid { + return Err(ViewError::ObservationStale { detail: "页面携带的 analysis_digest 与当前源码的 check --emit 不一致(页面已过期);请刷新后重试" .to_string(), }); @@ -402,6 +403,11 @@ impl ExecutionController { .ok_or_else(|| ViewError::RunDenied { detail: "没有可用的冻结核心(MARQDO_BIN),运行被拒绝".to_string(), })?; + if self.service.project().source_digest(&plan.document)? != static_doc.source_sha256 { + return Err(ViewError::ObservationStale { + detail: "the document changed after confirmation, before CLI spawn".into(), + }); + } let entry = self.service.project().absolute_for(&plan.document)?; let scratch = ScratchDir::create("run")?; let observation_path = scratch.file("observation.json"); @@ -462,14 +468,6 @@ impl ExecutionController { hooks, )?; - // Exit code 2 is the frozen CLI rejecting the explicit argument/option - // combination before the run started (for example - // `strict.unsupported_grant`). View never strips a flag and retries. - classify_exit_code( - outcome.exit_code.unwrap_or(-1), - &outcome.stderr.text_lossy(), - )?; - Ok(CoreRun { process: outcome, decoder: receive_decoder.try_recv().ok(), @@ -547,7 +545,56 @@ impl ExecutionController { let stale = sha256_hex(¤t_source) != static_doc.source_sha256; let process_stderr = outcome.stderr.text_lossy(); let exit_code = outcome.exit_code.unwrap_or(-1); - match decoder.finish(exit_code, &process_stderr, stale) { + let decoded = decoder.finish(exit_code, &process_stderr, stale); + let decoded = match decoded { + Err(err @ ViewError::ObservationInvalid { .. }) if exit_code == 2 => { + // Preserve a valid CLI rejection when the stream contains one. + // Only an option failure without a usable terminal needs the + // process-status diagnostic. There is no retry. + Err(classify_exit_code(exit_code, &process_stderr) + .err() + .unwrap_or(err)) + } + decoded => decoded, + }; + let binding = decoded.and_then(|projection| { + if projection.is_success() && exit_code != 0 { + return Err(ViewError::ObservationInvalid { + detail: "Observation success disagrees with the CLI exit status".into(), + }); + } + if projection.source_verified && projection.mode.as_deref() != Some(plan.mode.as_str()) + { + return Err(ViewError::ObservationInvalid { + detail: "Observation run mode disagrees with the confirmed request".into(), + }); + } + if (projection.is_success() || projection.root_function_id.is_some()) + && !projection.matches_target(&static_doc.verified.projection, &plan.function_id) + { + return Err(ViewError::ObservationStale { + detail: "Observation target or producer disagrees with the confirmed function" + .into(), + }); + } + if projection.is_success() + && !self + .service + .static_document(&plan.document) + .is_ok_and(|current| { + current.analysis_digest == static_doc.analysis_digest + && current.media_digests == static_doc.media_digests + }) + { + return Err(ViewError::ObservationStale { + detail: + "document, dependencies or media changed before the result could be bound" + .into(), + }); + } + Ok(projection) + }); + match binding { Ok(projection) => terminal_from_projection(plan, static_doc, duration_ms, projection), Err(err) => error_terminal(plan, static_doc, duration_ms, &err), } @@ -767,6 +814,11 @@ fn base_result( "analysis_digest": static_doc.analysis_digest, "source_digest": sha256_prefixed(static_doc.source.as_bytes()), "duration_ms": duration_ms, + "project_root_id": static_doc.verified.projection.project_root_id, + "entry_module_id": static_doc.verified.projection.entry_module_id, + "lock_digest": static_doc.verified.projection.lock_digest, + "manifest_digest": static_doc.verified.projection.manifest_digest, + "stdlib_digest": static_doc.verified.projection.stdlib_digest, "stale": false, }) } @@ -932,7 +984,9 @@ fn terminal_state_for(state: RunDisplayState) -> RunState { /// Observation binding status exposed to the browser. A failed *run* can still /// have a fully verified observation stream; truncation is called out first. fn observation_status_for(projection: &RunProjection) -> &'static str { - if projection.truncated.is_some() { + if projection.run_status == "rejected" { + "rejected" + } else if projection.truncated.is_some() { "truncated" } else { match projection.state { @@ -962,7 +1016,9 @@ fn terminal_from_projection( &projection, observation_status, ); - let summary = observation_v1::summary_json(&projection, &static_doc.verified.projection, false); + let summary = projection + .source_verified + .then(|| observation_v1::summary_json(&projection, &static_doc.verified.projection, false)); let (error_code, error_message) = match state { RunState::Failed => ( Some( @@ -987,7 +1043,7 @@ fn terminal_from_projection( TerminalOutcome { state, result, - observation_summary: Some(summary), + observation_summary: summary, observation: Some(projection), error_code, error_message, @@ -1017,6 +1073,12 @@ fn observation_result( result["value"] = value; result["value_type"] = serde_json::json!(value_type); result["value_text"] = serde_json::json!(value_text); + result["value_markup"] = serde_json::json!(projection + .result_value + .as_ref() + .map(|value| render_result_value(value, Some(&static_doc.verified.projection))) + .as_ref() + .map(|value| value.as_html())); result["stdout"] = serde_json::json!(projection.stdout); result["stderr"] = serde_json::json!(projection.stderr); result["stdout_bytes"] = serde_json::json!(projection.stdout.len()); @@ -1033,6 +1095,9 @@ fn observation_result( _ => serde_json::Value::Null, }; result["core_run_id"] = serde_json::json!(projection.run_id); + result["core_run_status"] = serde_json::json!(projection.run_status); + result["core_version"] = serde_json::json!(projection.producer_version); + result["started_unix_ms"] = serde_json::json!(projection.started_unix_ms); result["capture_level"] = serde_json::json!(projection.capture_level); result["observation_status"] = serde_json::json!(observation_status); result["observation_protocol"] = serde_json::json!(tool_v1::OBSERVATION_REVISION); @@ -1120,6 +1185,10 @@ mod tests { RunProjection { run_id: "core-run".to_string(), entry: None, + root_function_id: None, + producer_version: String::new(), + mode: None, + started_unix_ms: None, run_status: "ok".to_string(), state, error_code: None, diff --git a/src/execution/export_candidate.rs b/src/execution/export_candidate.rs index ae53420..215d69c 100644 --- a/src/execution/export_candidate.rs +++ b/src/execution/export_candidate.rs @@ -8,6 +8,7 @@ use crate::execution::events::RunState; use crate::execution::request::ExecutionPlan; use crate::protocol::observation_v1::{EventCounts, RunProjection}; use crate::reader::assemble::StaticDocument; +use crate::reader::result_value::{render_result_value, ResultMarkup}; use serde_json::{json, Value}; use std::collections::BTreeMap; @@ -33,6 +34,7 @@ pub struct TerminalExportCandidate { pub terminal_at: String, pub state: RunState, pub value: Option, + pub value_markup: Option, pub value_is_public_scalar: bool, pub stdout: String, pub stderr: String, @@ -73,17 +75,24 @@ impl TerminalExportCandidate { .find(|function| function.id == plan.function_id)?; let (stdout, stdout_complete) = bounded_text(result["stdout"].as_str()); let (stderr, stderr_complete) = bounded_text(result["stderr"].as_str()); - // Only a public scalar result value is exportable without an extra - // sensitive-output confirmation; container/text values stay omitted. + // Scalar values may be preselected. Other values require the user's + // explicit sensitive-output confirmation. let (value, value_complete, value_is_public_scalar) = match observation.result_value.as_ref() { - Some(run) if public_scalar_type(&run.ty) => { + Some(run) => { let (text, complete) = bounded_text(Some(run.display.as_str())); - (Some(text), complete, true) + (Some(text), complete, public_scalar_type(&run.ty)) } - Some(_) => (None, false, false), None => (None, true, false), }; + let value_markup = observation + .result_value + .as_ref() + .map(|value| render_result_value(value, Some(projection))); + let result_complete = state == RunState::Succeeded + && observation.truncated.is_none() + && value_complete + && value_markup.as_ref().is_none_or(|markup| !markup.clipped); let observation_truncated = observation.truncated.is_some(); let observation_counts = Some(counts_map(&observation.counts)); Some(Self { @@ -103,6 +112,7 @@ impl TerminalExportCandidate { terminal_at: crate::execution::events::utc_now(), state, value, + value_markup, value_is_public_scalar, stdout, stderr, @@ -113,9 +123,7 @@ impl TerminalExportCandidate { output_complete: result["output_complete"].as_bool() == Some(true) && stdout_complete && stderr_complete, - result_complete: state == RunState::Succeeded - && !observation_truncated - && value_complete, + result_complete, observation_truncated, }) } @@ -139,14 +147,14 @@ impl TerminalExportCandidate { } } -fn public_scalar_type(ty: &str) -> bool { +pub(crate) fn public_scalar_type(ty: &str) -> bool { matches!( ty.to_ascii_lowercase().as_str(), "int" | "float" | "bool" | "unit" | "none" ) } -fn counts_map(counts: &EventCounts) -> BTreeMap { +pub(crate) fn counts_map(counts: &EventCounts) -> BTreeMap { [ ("total", counts.total()), ("call_enter", counts.call_enter), diff --git a/src/execution/request.rs b/src/execution/request.rs index 1649122..f92e81f 100644 --- a/src/execution/request.rs +++ b/src/execution/request.rs @@ -125,7 +125,7 @@ impl ValidatedRequest { pub fn plan_against(self, projection: &SemanticProjection) -> ViewResult { let (target, function_id) = match &self.target { RunTarget::Entry => { - let Some(function) = resolve_main(projection) else { + let Some(function) = projection.entry_main() else { return Err(ViewError::NoEntryFunction { detail: format!( "{} 没有可调用的 main;请从函数面板选择一个 H2 Exec 函数", @@ -133,6 +133,14 @@ impl ValidatedRequest { ), }); }; + if !self.parameters.is_empty() + || function.signature.params.iter().any(|param| param.required) + { + return Err(ViewError::RunInvalid { + detail: "run main 不提交参数;请从调用面板明确选择 main 并填写该函数参数" + .into(), + }); + } (ExecutionTarget::Entry, function.id.clone()) } RunTarget::Function { function_id } => { @@ -145,14 +153,8 @@ impl ValidatedRequest { "function_id {function_id:?} 不在当前入口模块可调用函数中;依赖模块函数不能作为 call 目标" ), })?; - let canonical = canonical_name(&function.id, &projection.module_id); - let cli_name = if unique_local_name(projection, &function.local_name, &function.id) - { - function.local_name.clone() - } else { - canonical.clone() - }; - let label = canonical; + let cli_name = projection.call_name(function).to_owned(); + let label = projection.canonical_function_name(function).to_owned(); validate_parameters(&self.parameters, projection, &function.id)?; ( ExecutionTarget::Function { cli_name, label }, @@ -367,40 +369,6 @@ fn validate_glob(glob: &str) -> ViewResult<()> { Ok(()) } -/// Resolve `main` exactly like the frozen CLI does for `run`: canonical name -/// first, then a unique local name. No fallback to any other function. -fn resolve_main( - projection: &SemanticProjection, -) -> Option<&crate::protocol::analysis_v3::SemanticFunction> { - projection - .functions - .iter() - .find(|function| canonical_name(&function.id, &projection.module_id) == "main") - .or_else(|| { - let mut candidates = projection - .functions - .iter() - .filter(|function| function.local_name == "main"); - let first = candidates.next()?; - candidates.next().is_none().then_some(first) - }) -} - -fn unique_local_name(projection: &SemanticProjection, local_name: &str, id: &str) -> bool { - let matches = projection - .functions - .iter() - .filter(|function| function.local_name == local_name) - .count(); - if matches == 1 { - return true; - } - // If several namespaces define the same local name, only the canonical - // qualified name is unambiguous; the CLI resolver has the same rule. - let canonical = canonical_name(id, &projection.module_id); - canonical == local_name -} - /// Analysis v3 function ids are `::`. pub fn canonical_name(function_id: &str, module_id: &str) -> String { function_id @@ -442,6 +410,16 @@ fn validate_parameters( }); } } + if let Some(missing) = function + .signature + .params + .iter() + .find(|param| param.required && !seen.contains(¶m.name)) + { + return Err(ViewError::RunInvalid { + detail: format!("缺少必填参数 {:?}", missing.name), + }); + } Ok(()) } diff --git a/src/export.rs b/src/export.rs index 568e774..39753b3 100644 --- a/src/export.rs +++ b/src/export.rs @@ -5,9 +5,10 @@ //! never writes into the source project (RFC-VIEW-0001 §11.3). use crate::error::{ViewError, ViewResult}; +use crate::export_result::ObservationImport; use crate::reader::assemble::DocumentService; use crate::reader::assets::AssetBundle; -use crate::reader::render::ReaderRenderer; +use crate::reader::render::{fragment_href, ReaderRenderer}; use crate::reader::snapshot::ExportResultOverlay; use crate::reader::source::sha256_hex; use crate::reader::source::SafeRelativePath; @@ -31,7 +32,22 @@ pub struct ExportSummary { pub manifest_sha256: String, } +pub(crate) struct EmbedOptions<'a> { + pub dark_theme: bool, + pub anchor: Option<&'a str>, + pub expected_sha256: Option<&'a str>, +} + pub fn export(context: &DocumentService, options: &ExportOptions) -> ViewResult { + write_export(context, options, None, None) +} + +pub(crate) fn write_export( + context: &DocumentService, + options: &ExportOptions, + observation: Option>, + embed: Option<&EmbedOptions<'_>>, +) -> ViewResult { let root = context.project().root().to_path_buf(); let out = absolute_export_target(&options.out)?; if out.starts_with(&root) { @@ -45,10 +61,39 @@ pub fn export(context: &DocumentService, options: &ExportOptions) -> ViewResult< } validate_existing_target(&out)?; + let entry = context.load(&context.project().entry().relative)?; + if let Some(embed) = embed { + if embed + .expected_sha256 + .is_some_and(|expected| expected != sha256_hex(entry.document.source.as_bytes())) + { + return Err(ViewError::ExportSourceChanged { + detail: "embedded document does not match --expect-source-sha256".into(), + }); + } + if embed + .anchor + .is_some_and(|anchor| !entry.has_heading_anchor(anchor)) + { + return Err(ViewError::ExportInvalid { + detail: "requested heading anchor does not exist in the embedded document".into(), + }); + } + } + let overlay = observation + .map(|input| input.prepare(&entry)) + .transpose()? + .map(Arc::new); let staging = staging_dir(&out)?; let result = (|| { - let entry = context.load(&context.project().entry().relative)?; - let site = build_site(context, &entry, &staging, !options.no_annotations, None)?; + let site = build_site( + context, + &entry, + &staging, + !options.no_annotations, + overlay, + embed, + )?; publish(&staging, &out)?; Ok(ExportSummary { out, @@ -117,9 +162,14 @@ fn build_site( staging: &Path, annotations: bool, overlay: Option>, + embed: Option<&EmbedOptions<'_>>, ) -> ViewResult { - let documents = context.project().list_documents()?; let entry = SafeRelativePath::parse(&entry_model.document.identity.relative_path)?; + let documents = if embed.is_some() { + vec![entry.clone()] + } else { + context.project().list_documents()? + }; if !documents.contains(&entry) { return Err(ViewError::ExportFailed { detail: "entry document is missing".into(), @@ -134,7 +184,7 @@ fn build_site( let renderer = ReaderRenderer::new(); let mut assets = Vec::new(); for asset in bundle.all() { - if overlay.is_some() && asset.extension == "js" { + if (overlay.is_some() || embed.is_some()) && asset.extension == "js" { continue; } let (name, bytes) = if asset.name == "reader" && asset.extension == "css" { @@ -164,16 +214,26 @@ fn build_site( entry.insert(record); } } - let depth = relative.as_str().split('/').count(); + let depth = if embed.is_some() { + 0 + } else { + relative.as_str().split('/').count() + }; let mut settings = crate::reader::render::RenderContext::static_export(depth, annotations); settings.snapshot_package = overlay.is_some(); + settings.embedded = embed.is_some(); + settings.dark_theme = embed.is_some_and(|embed| embed.dark_theme); settings.overlay = if *relative == entry { overlay.clone() } else { None }; let page = renderer.render(model, &settings); - let path = format!("pages/{}.html", relative.as_str()); + let path = if embed.is_some() { + "index.html".to_string() + } else { + format!("pages/{}.html", relative.as_str()) + }; let file = writer.write(&path, page.html.as_bytes())?; pages.push(serde_json::json!({ "relative_path": relative.as_str(), @@ -187,15 +247,19 @@ fn build_site( })); files.push(file); } + let index_sha = if embed.is_some() { + pages[0]["sha256"].clone() + } else { + let mut index_context = crate::reader::render::RenderContext::static_export(0, annotations); + index_context.snapshot_package = overlay.is_some(); + index_context.overlay = overlay.clone(); + let index_page = renderer.render(entry_model, &index_context); + let index_file = writer.write("index.html", index_page.html.as_bytes())?; + let sha = index_file["sha256"].clone(); + files.push(index_file); + sha + }; files.extend(media_files.values().cloned()); - - let mut index_context = crate::reader::render::RenderContext::static_export(0, annotations); - index_context.snapshot_package = overlay.is_some(); - index_context.overlay = overlay.clone(); - let index_page = renderer.render(entry_model, &index_context); - let index_file = writer.write("index.html", index_page.html.as_bytes())?; - let index_sha = index_file["sha256"].clone(); - files.push(index_file); files.sort_by(|a, b| a["path"].as_str().cmp(&b["path"].as_str())); let mut manifest = serde_json::json!({ "schema": MANIFEST_SCHEMA, @@ -245,6 +309,22 @@ fn build_site( fields.remove("note"); } } + if let Some(embed) = embed { + let mut anchors: Vec<_> = entry_model.heading_slugs.iter().collect(); + anchors.sort_by_key(|(span, _)| (span.start, span.end)); + let href = match embed.anchor { + Some(anchor) => format!("index.html{}", fragment_href(anchor)), + None => "index.html".to_string(), + }; + manifest["mode"] = serde_json::json!("embedded"); + manifest["theme"] = serde_json::json!(if embed.dark_theme { "dark" } else { "light" }); + manifest["entry"]["href"] = serde_json::json!(href); + manifest["entry"]["anchor"] = serde_json::json!(embed.anchor); + manifest["entry"]["heading_ids"] = serde_json::json!(anchors + .into_iter() + .map(|(_, slug)| slug) + .collect::>()); + } let manifest_bytes = serde_json::to_vec_pretty(&manifest).map_err(|err| ViewError::ExportFailed { detail: format!("serialize export manifest: {err}"), @@ -297,7 +377,14 @@ pub fn snapshot( let staging = scratch.file("site"); std::fs::create_dir(&staging) .map_err(|err| ViewError::io("create private snapshot site", err))?; - let site = build_site(context, model, &staging, true, Some(Arc::new(overlay)))?; + let site = build_site( + context, + model, + &staging, + true, + Some(Arc::new(overlay)), + None, + )?; let path = scratch.file("snapshot.zip"); let archive = std::fs::File::create(&path).map_err(|err| ViewError::io("create snapshot ZIP", err))?; diff --git a/src/export_result.rs b/src/export_result.rs index a2f8455..75bd8e9 100644 --- a/src/export_result.rs +++ b/src/export_result.rs @@ -2,18 +2,27 @@ //! The output is an owned reader projection, independent of the job. use crate::{ - execution::{events::RunState, export_candidate::TerminalExportCandidate}, - protocol::tool_v1, + execution::{ + events::RunState, + export_candidate::{counts_map, public_scalar_type, TerminalExportCandidate}, + }, + protocol::{ + observation_v1::{decode_snapshot, RunDisplayState, MAX_SNAPSHOT_BYTES}, + tool_v1, + }, reader::{ assemble::DocumentService, media, model::PresentationModel, + result_value::render_result_value, snapshot::{ExportResultOverlay, SnapshotContracts, SnapshotExecution, SnapshotSource}, source::{sha256_hex, SafeRelativePath}, }, ViewError, ViewResult, }; use serde::Deserialize; +use std::io::Read; +use std::path::Path; pub const MAX_EXPORT_REQUEST: usize = 8 * 1024; @@ -152,7 +161,8 @@ impl ExportSelection { target: candidate.function_id.clone(), core_version: candidate.core_version.clone(), status: candidate.state.data_value(), - terminal_at: candidate.terminal_at.clone(), + terminal_at: Some(candidate.terminal_at.clone()), + observation_sha256: None, source_verified: true, observation_status: candidate.observation_status.clone(), capture_level: candidate.capture_level.clone(), @@ -175,7 +185,7 @@ impl ExportSelection { value: self .include .result_value - .then(|| candidate.value.clone()) + .then(|| candidate.value_markup.clone()) .flatten(), stdout: self.include.stdout.then(|| candidate.stdout.clone()), stderr: self.include.stderr.then(|| candidate.stderr.clone()), @@ -189,3 +199,109 @@ impl ExportSelection { Ok((model, overlay)) } } + +pub(crate) struct ObservationImport<'a> { + pub path: &'a Path, + pub run_id: &'a str, + pub include_sensitive_result: bool, +} + +impl ObservationImport<'_> { + pub(crate) fn prepare(&self, model: &PresentationModel) -> ViewResult { + let invalid = |detail: &str| ViewError::ExportInvalid { + detail: detail.into(), + }; + let analysis = model + .semantic + .as_ref() + .ok_or_else(|| ViewError::ExportSourceChanged { + detail: "Observation export requires verified Analysis for the selected document" + .into(), + })?; + let metadata = std::fs::metadata(self.path) + .map_err(|err| ViewError::io("read Observation snapshot metadata", err))?; + if !metadata.is_file() || metadata.len() > MAX_SNAPSHOT_BYTES as u64 { + return Err(invalid( + "Observation snapshot must be a regular file of at most 16 MiB", + )); + } + let mut bytes = Vec::new(); + std::fs::File::open(self.path) + .and_then(|file| { + file.take(MAX_SNAPSHOT_BYTES as u64 + 1) + .read_to_end(&mut bytes) + }) + .map_err(|err| ViewError::io("read Observation snapshot", err))?; + let run = decode_snapshot(&bytes, analysis)?; + if run.run_id != self.run_id { + return Err(invalid( + "Observation run.id does not match the selected --run-id", + )); + } + if !run.source_verified || run.state != RunDisplayState::Succeeded || !run.output_complete { + return Err(invalid( + "Observation export requires a complete, successful, untruncated run", + )); + } + let function = analysis + .functions + .iter() + .find(|function| Some(function.id.as_str()) == run.root_function_id.as_deref()) + .ok_or_else(|| { + invalid("Observation has no verifiable top-level function in this document") + })?; + if !run.matches_target(analysis, &function.id) { + return Err(invalid( + "Observation entry does not match its verified top-level function", + )); + } + let mode = run + .mode + .ok_or_else(|| invalid("Observation has no execution mode"))?; + let value = run + .result_value + .as_ref() + .filter(|value| public_scalar_type(&value.ty) || self.include_sensitive_result) + .map(|value| render_result_value(value, Some(analysis))); + let result_complete = value.as_ref().is_none_or(|value| !value.clipped); + Ok(ExportResultOverlay { + source: SnapshotSource { + project_root_id: analysis.project_root_id.clone(), + document: analysis.relative_path.clone(), + module_id: analysis.module_id.clone(), + source_sha256: sha256_hex(model.document.source.as_bytes()), + analysis_digest: analysis.analysis_digest.clone(), + lock_digest: (!analysis.lock_digest.is_empty()) + .then(|| analysis.lock_digest.clone()), + }, + execution: SnapshotExecution { + included: true, + core_run_id: run.run_id.clone(), + core_version: run.producer_version, + target: function.id.clone(), + status: RunState::Succeeded.data_value(), + terminal_at: None, + observation_sha256: Some(sha256_hex(&bytes)), + source_verified: true, + observation_status: "verified".into(), + capture_level: run.capture_level.clone(), + result_complete, + output_complete: true, + observation_truncated: false, + parameters: "omitted", + mode, + contracts: SnapshotContracts { + api_revision: tool_v1::API_REVISION, + analysis: analysis.schema_version, + observation: tool_v1::OBSERVATION_REVISION, + }, + }, + label: function.local_name.clone(), + value, + stdout: None, + stderr: None, + observation_counts: Some(counts_map(&run.counts)), + arguments: None, + }) + } +} diff --git a/src/lib.rs b/src/lib.rs index 0781f17..2f5263c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -56,12 +56,32 @@ fn export_command(opts: &RuntimeOpts, args: &ExportArgs) -> ViewResult { .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( + let observation = match (args.observation.as_deref(), args.run_id.as_deref()) { + (Some(path), Some(run_id)) => Some(export_result::ObservationImport { + path, + run_id, + include_sensitive_result: args.include_sensitive_result, + }), + (None, None) if !args.include_sensitive_result => None, + _ => { + return Err(ViewError::ExportInvalid { + detail: "--observation and --run-id must be provided together".into(), + }) + } + }; + let embed = args.embed.then(|| export::EmbedOptions { + dark_theme: args.theme.as_deref() == Some("dark"), + anchor: args.anchor.as_deref(), + expected_sha256: args.expect_source_sha256.as_deref(), + }); + let summary = export::write_export( &service, &ExportOptions { out: args.out.clone(), no_annotations: args.no_annotations, }, + observation, + embed.as_ref(), )?; println!( "marqdo view export: {} page(s), {} file(s) → {}", diff --git a/src/protocol/analysis_v3.rs b/src/protocol/analysis_v3.rs index fe83df5..0b1ff11 100644 --- a/src/protocol/analysis_v3.rs +++ b/src/protocol/analysis_v3.rs @@ -453,6 +453,42 @@ pub struct SemanticProjection { } impl SemanticProjection { + /// The CLI resolves canonical `main` first, followed by a unique local `main`. + pub(crate) fn entry_main(&self) -> Option<&SemanticFunction> { + self.functions + .iter() + .find(|function| self.canonical_function_name(function) == "main") + .or_else(|| { + let mut candidates = self + .functions + .iter() + .filter(|function| function.local_name == "main"); + let first = candidates.next()?; + candidates.next().is_none().then_some(first) + }) + } + + pub(crate) fn canonical_function_name<'a>(&self, function: &'a SemanticFunction) -> &'a str { + function + .id + .strip_prefix(&format!("{}::", self.module_id)) + .unwrap_or(&function.id) + } + + pub(crate) fn call_name<'a>(&self, function: &'a SemanticFunction) -> &'a str { + if self + .functions + .iter() + .filter(|item| item.local_name == function.local_name) + .count() + == 1 + { + &function.local_name + } else { + self.canonical_function_name(function) + } + } + pub fn module(&self, id: &str) -> Option<&ModuleSummary> { self.modules.iter().find(|module| module.id == id) } diff --git a/src/protocol/observation_v1.rs b/src/protocol/observation_v1.rs index dd4003d..177f788 100644 --- a/src/protocol/observation_v1.rs +++ b/src/protocol/observation_v1.rs @@ -7,8 +7,7 @@ //! event, `observation.truncated`, source binding (`analysis_digest`/`root_id`), //! module identity, UTF-8 half-open spans, value-consent and byte chunks. //! -//! Production consumes the live JSONL stream only; the atomic snapshot is -//! used by tests to assert stream/snapshot equivalence. No second decoder or +//! Live consumes JSONL; offline export can import one atomic snapshot. No second decoder or //! double-read merge exists. use crate::error::{ViewError, ViewResult}; @@ -24,6 +23,7 @@ pub const SCHEMA: &str = "marqdo.observation"; pub const SCHEMA_VERSION: u32 = 1; const MAX_LINE: usize = 4 * 1024 * 1024; const MAX_TRANSPORT: usize = 16 * 1024 * 1024; +pub(crate) const MAX_SNAPSHOT_BYTES: usize = MAX_TRANSPORT; const MAX_DISPLAY_BYTES: usize = 64 * 1024; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -229,9 +229,10 @@ impl Truncation { pub struct RunValue { pub ty: String, pub display: String, + pub wire: Option, } -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Capture { pub level: String, pub values: bool, @@ -244,6 +245,10 @@ pub struct Capture { pub struct RunProjection { pub run_id: String, pub entry: Option, + pub root_function_id: Option, + pub producer_version: String, + pub mode: Option, + pub started_unix_ms: Option, /// Raw Core terminal status (`ok`, `error`, `rejected` or empty/incomplete). pub run_status: String, pub state: RunDisplayState, @@ -265,6 +270,30 @@ pub struct RunProjection { } impl RunProjection { + pub(crate) fn matches_target(&self, analysis: &SemanticProjection, function_id: &str) -> bool { + let Some(function) = analysis + .functions + .iter() + .find(|function| function.id == function_id) + else { + return false; + }; + if !self.source_verified + || analysis.module_id != analysis.entry_module_id + || self.producer_version != analysis.producer_version + || self.root_function_id.as_deref() != Some(function_id) + { + return false; + } + let prefix = format!("{}::", analysis.module_id); + self.entry + .as_deref() + .and_then(|entry| entry.strip_prefix(&prefix)) + .is_some_and(|name| { + name == function.local_name || function_id.strip_prefix(&prefix) == Some(name) + }) + } + pub fn state_label(&self) -> &'static str { self.state.label() } @@ -375,6 +404,8 @@ struct Terminal { struct BindingSource { root_id: String, analysis_digest: String, + mode: String, + started_unix_ms: Option, } /// Incremental JSONL decoder shared by the live stream. Each complete line is @@ -388,6 +419,9 @@ pub struct ObservationDecoder { capture: Option, started: Option, entry: Option, + producer_version: String, + root_function_id: Option, + root_frame_count: usize, terminal: Option, truncated: Option, counts: EventCounts, @@ -419,6 +453,9 @@ impl ObservationDecoder { capture: None, started: None, entry: None, + producer_version: String::new(), + root_function_id: None, + root_frame_count: 0, terminal: None, truncated: None, counts: EventCounts::default(), @@ -570,13 +607,12 @@ impl ObservationDecoder { if producer.get("name").and_then(Value::as_str) != Some("marqdo") { return Err("stream.opened producer.name is not `marqdo`".to_string()); } - if producer + self.producer_version = producer .get("version") .and_then(Value::as_str) - .is_none_or(str::is_empty) - { - return Err("stream.opened producer.version is missing".to_string()); - } + .filter(|version| !version.is_empty()) + .ok_or_else(|| "stream.opened producer.version is missing".to_string())? + .to_owned(); let observation = payload .get("observation") .and_then(Value::as_object) @@ -666,6 +702,8 @@ impl ObservationDecoder { self.started = Some(BindingSource { root_id: root_id.to_string(), analysis_digest: analysis_digest.to_string(), + mode: mode.to_owned(), + started_unix_ms: payload.get("started_unix_ms").and_then(Value::as_u64), }); } ObservedKind::StdoutChunk | ObservedKind::StderrChunk => { @@ -896,6 +934,10 @@ impl ObservationDecoder { if !function_id.contains("::") { return Err("call.enter function_id is not canonical".to_string()); } + if payload.get("parent_frame_id") == Some(&Value::Null) { + self.root_frame_count += 1; + self.root_function_id = Some(function_id.to_owned()); + } event.detail = Some(function_id.to_string()); } ObservedKind::CallExit => { @@ -1147,6 +1189,11 @@ impl ObservationDecoder { if let Some(detail) = self.invalid { return Err(ViewError::ObservationInvalid { detail }); } + if self.terminal.is_some() && !self.partial.is_empty() { + return Err(ViewError::ObservationInvalid { + detail: "Observation contains trailing bytes after its terminal event".into(), + }); + } let expected_digest = self.analysis_digest.clone(); // A run rejected before start legitimately has no run.started; every // other lifecycle requires the exact source binding. @@ -1191,9 +1238,14 @@ impl ObservationDecoder { kind: TerminalKind::Completed { value, value_type }, .. }) => { - let result_value = value.as_ref().map(|value| RunValue { + let wire = value.clone().filter(value_wire_v1::transferable); + let result_value = Some(RunValue { ty: value_type.clone(), - display: display_value(value), + display: wire + .as_ref() + .map(display_value) + .unwrap_or_else(|| "返回值不可传递".into()), + wire, }); if self.truncated.is_some() { ( @@ -1267,19 +1319,22 @@ impl ObservationDecoder { process_stderr.trim().chars().take(400).collect::() )); } - let complete = self.terminal.is_some() - && self - .capture - .as_ref() - .is_some_and(|capture| !capture.level.is_empty()); + let complete = self.terminal.is_some() && !self.stdout_truncated; Ok(RunProjection { run_id: self.run_id.clone().unwrap_or_default(), entry: self.entry.clone(), + root_function_id: self.root_function_id.filter(|_| self.root_frame_count == 1), + producer_version: self.producer_version, + mode: self.started.as_ref().map(|started| started.mode.clone()), + started_unix_ms: self + .started + .as_ref() + .and_then(|started| started.started_unix_ms), run_status, state, error_code, analysis_digest: expected_digest, - source_verified: true, + source_verified: self.started.is_some(), truncated: self.truncated.clone(), capture_level: self .capture @@ -1301,7 +1356,15 @@ impl ObservationDecoder { } fn normalized_event(event: &ObservedEvent, raw: &RawEvent) -> Value { - let mut value = raw.payload.clone(); + let mut value = match event.kind { + ObservedKind::RunCompleted => { + json!({"status": raw.payload["status"], "value_type": raw.payload["value_type"]}) + } + ObservedKind::RunFailed | ObservedKind::RunRejected => json!({ + "status": raw.payload["status"], "error_code": raw.payload["error"]["code"], + }), + _ => raw.payload.clone(), + }; if let Some(object) = value.as_object_mut() { object.insert( "kind".to_string(), @@ -1395,36 +1458,31 @@ fn validate_error_location(error: &serde_json::Map) -> Result<(), if let Some(span) = error.get("span") { parse_span_value(span)?; } - if error.keys().any(|key| { - !matches!( - key.as_str(), - "code" - | "message" - | "module_id" - | "span" - | "relative_path" - | "line" - | "column" - | "hint" - ) - }) { - return Err("Observation error carries an unknown field".to_string()); - } + // Observation 1 permits additional diagnostic fields, including frames + // and origin. The View only projects the facts it validates and displays. Ok(()) } fn display_value(value: &Value) -> String { let ty = value.get("type").and_then(Value::as_str).unwrap_or("value"); let display = match ty { + "unit" => Some("无返回值"), + "none" => Some("None"), "int" => value.get("decimal").and_then(Value::as_str), - "float" => value.get("value").and_then(Value::as_f64).map(|_| ""), - "bool" => None, + "float" => { + return value + .get("special") + .and_then(Value::as_str) + .map(str::to_owned) + .unwrap_or_else(|| value["value"].to_string()) + } + "bool" => return value["value"].to_string(), "text" => value.get("value").and_then(Value::as_str), _ => None, }; if let Some(text) = display { - if !text.is_empty() { - return text.chars().take(80).collect(); + if text.len() <= 64 * 1024 { + return text.to_owned(); } } let compact = value.to_string(); @@ -1544,151 +1602,72 @@ struct RawSnapshotCapture { truncated: Value, } -/// Decode the atomic observation snapshot and validate that it agrees with its -/// own events and with the Analysis it binds. Production consumes the live -/// JSONL stream; this entry point exists for the stream/snapshot equivalence -/// test and for verifying a snapshot handed to the exporter. +/// Validate the atomic snapshot header against its own events and decode the +/// event sequence through the same validator as a live run. pub fn decode_snapshot(bytes: &[u8], analysis: &SemanticProjection) -> ViewResult { - let raw: RawSnapshot = - serde_json::from_slice(bytes).map_err(|err| ViewError::ObservationInvalid { - detail: format!("Observation snapshot is not valid `marqdo.observation`: {err}"), - })?; + let invalid = |detail: &str| ViewError::ObservationInvalid { + detail: detail.to_string(), + }; + if bytes.len() > MAX_SNAPSHOT_BYTES { + return Err(invalid("Observation snapshot exceeds the transport limit")); + } + let raw: RawSnapshot = serde_json::from_slice(bytes) + .map_err(|_| invalid("invalid marqdo.observation snapshot JSON"))?; if raw.schema != SCHEMA || raw.schema_version != SCHEMA_VERSION { - return Err(ViewError::ObservationInvalid { - detail: format!( - "Observation snapshot schema {:?} revision {} is not `{SCHEMA}` revision {SCHEMA_VERSION}", - raw.schema, raw.schema_version - ), - }); + return Err(invalid( + "unsupported Observation snapshot schema or revision", + )); } if raw.run.id.is_empty() || raw.events.is_empty() { - return Err(ViewError::ObservationInvalid { - detail: "Observation snapshot has no run.id or events".to_string(), - }); - } - if !matches!( - raw.run.status.as_str(), - "ok" | "error" | "rejected" | "incomplete" - ) { - return Err(ViewError::ObservationInvalid { - detail: format!( - "Observation snapshot run.status {:?} is not ok/error/rejected/incomplete", - raw.run.status - ), - }); - } - if !matches!(raw.capture.level.as_str(), "base" | "structural" | "values") { - return Err(ViewError::ObservationInvalid { - detail: format!( - "Observation snapshot capture.level {:?} is unknown", - raw.capture.level - ), - }); - } - let has_truncation = raw - .events - .iter() - .any(|event| event.kind == "observation.truncated"); - match &raw.capture.truncated { - Value::Null => { - if has_truncation { - return Err(ViewError::ObservationInvalid { - detail: "snapshot capture.truncated is null but an observation.truncated event exists" - .to_string(), - }); - } - } - Value::Object(_) => { - if !has_truncation { - return Err(ViewError::ObservationInvalid { - detail: "snapshot capture.truncated is set but no observation.truncated event exists" - .to_string(), - }); - } - } - _ => { - return Err(ViewError::ObservationInvalid { - detail: "snapshot capture.truncated is not an object or null".to_string(), - }) - } + return Err(invalid("Observation snapshot has no run.id or events")); } - let capture_values = raw.capture.values; - let capture_selected_variables = raw.capture.selected_variables.clone(); - let capture_selected_parameters = raw.capture.selected_parameters.clone(); - let capture_allow_text_values = raw.capture.allow_text_values; - let _ = ( - capture_values, - capture_selected_variables, - capture_selected_parameters, - capture_allow_text_values, - ); - let mut lines = Vec::with_capacity(raw.events.len()); + let mut decoder = ObservationDecoder::new(analysis); + let mut source = &Value::Null; + let mut truncated = &Value::Null; for event in &raw.events { if event.run_id != raw.run.id { - return Err(ViewError::ObservationInvalid { - detail: "snapshot events mix a different run_id than run.id".to_string(), - }); + return Err(invalid( + "snapshot events mix a different run_id than run.id", + )); } - let encoded = serde_json::to_vec(event).map_err(|err| ViewError::ObservationInvalid { - detail: format!("snapshot event cannot be encoded: {err}"), - })?; - lines.push(encoded); - } - let mut decoder = ObservationDecoder::new(analysis); - let mut chunk = Vec::new(); - for line in lines { - chunk.extend_from_slice(&line); - chunk.push(b'\n'); - decoder.push(&chunk); - chunk.clear(); + let mut line = + serde_json::to_vec(event).map_err(|_| invalid("snapshot event cannot be encoded"))?; + line.push(b'\n'); + decoder.push(&line); if let Some(detail) = decoder.invalid() { - return Err(ViewError::ObservationInvalid { - detail: format!("snapshot event sequence is invalid: {detail}"), - }); + return Err(invalid(detail)); + } + match event.kind.as_str() { + "run.started" => { + source = &event.payload["source"]; + } + "observation.truncated" => truncated = &event.payload, + _ => {} } } - let projection = decoder.finish(0, "", false)?; - if let Some(started) = projection.events.iter().find(|event| event.seq == 1) { - let _ = started; - } - if let Some(source) = raw.run.source.as_object() { - let root = source - .get("root_id") - .and_then(Value::as_str) - .unwrap_or_default(); - let digest = source - .get("analysis_digest") - .and_then(Value::as_str) - .unwrap_or_default(); - if root != analysis.project_root_id || digest != analysis.analysis_digest { - return Err(ViewError::ObservationStale { - detail: "snapshot run.source does not match the verified Analysis".to_string(), - }); - } - } else if !raw.run.source.is_null() { - return Err(ViewError::ObservationInvalid { - detail: "snapshot run.source is not an object or null".to_string(), - }); - } - let terminal_agrees = match raw.run.status.as_str() { - "ok" => matches!( - projection.state, - RunDisplayState::Succeeded | RunDisplayState::Truncated - ), - "error" | "rejected" => projection.state == RunDisplayState::Failed, - "incomplete" => projection.state == RunDisplayState::Incomplete, - _ => false, + let snapshot_capture = Capture { + level: raw.capture.level, + values: raw.capture.values, + selected_variables: raw.capture.selected_variables, + selected_parameters: raw.capture.selected_parameters, + allow_text_values: raw.capture.allow_text_values, }; - if !terminal_agrees { - return Err(ViewError::ObservationInvalid { - detail: format!( - "snapshot run.status {:?} disagrees with its terminal event ({:?})", - raw.run.status, projection.state - ), - }); + if decoder.capture.as_ref() != Some(&snapshot_capture) || &raw.capture.truncated != truncated { + return Err(invalid( + "snapshot capture metadata disagrees with its events", + )); } - Ok(projection) + if &raw.run.source != source { + return Err(invalid("snapshot run.source disagrees with run.started")); + } + let run = decoder.finish(0, "", false)?; + if raw.run.status != run.run_status { + return Err(invalid( + "snapshot run.status disagrees with its terminal state", + )); + } + Ok(run) } /// Build a stale run projection that keeps the raw result accessible without @@ -1697,6 +1676,10 @@ pub fn stale_projection(analysis_digest: &str) -> RunProjection { RunProjection { run_id: String::new(), entry: None, + root_function_id: None, + producer_version: String::new(), + mode: None, + started_unix_ms: None, run_status: "stale".to_string(), state: RunDisplayState::Stale, error_code: Some("view.observation_stale".to_string()), diff --git a/src/protocol/value_wire_v1.rs b/src/protocol/value_wire_v1.rs index 790c129..8f0ceb9 100644 --- a/src/protocol/value_wire_v1.rs +++ b/src/protocol/value_wire_v1.rs @@ -10,13 +10,39 @@ fn valid_at(value: &Value, depth: usize) -> bool { if depth > 64 { return false; } + let Some(fields) = value.as_object() else { + return false; + }; + let ty = value["type"].as_str(); + let allowed_fields: &[&str] = match ty { + Some("unit" | "none" | "memory" | "resource") => &[], + Some("bool" | "text") => &["value"], + Some("int") => &["decimal"], + Some("float") => &["value", "special"], + Some("list") => &["items"], + Some("map") => &["entries"], + Some("table") => &["header", "rows"], + Some("formula") => &["latex", "display", "unit", "span"], + Some("code") => &["source", "language", "content_hash", "unit", "span"], + Some("function_ref") => &["module", "name"], + Some("plugin_handle") => &["plugin", "export", "id"], + _ => return false, + }; + if fields + .keys() + .any(|key| key != "type" && !allowed_fields.contains(&key.as_str())) + { + return false; + } let child = |item: &Value| valid_at(item, depth + 1); - match value["type"].as_str() { + match ty { Some("unit" | "none" | "resource" | "memory") => true, Some("bool") => value["value"].is_boolean(), Some("int") => value["decimal"].as_str().is_some_and(|value| { let digits = value.strip_prefix('-').unwrap_or(value); - !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit()) + !digits.is_empty() + && (digits.len() == 1 || !digits.starts_with('0')) + && digits.bytes().all(|byte| byte.is_ascii_digit()) }), Some("float") => match (value.get("value"), value.get("special")) { (Some(value), None) => value.as_f64().is_some_and(f64::is_finite), @@ -43,12 +69,15 @@ fn valid_at(value: &Value, depth: usize) -> bool { }) }), Some("formula") => { - value["latex"].is_string() && optional(value, "display", Value::is_boolean) + value["latex"].is_string() + && optional(value, "display", Value::is_boolean) + && valid_source_metadata(value) } Some("code") => { value["source"].is_string() && optional(value, "language", Value::is_string) && optional(value, "content_hash", Value::is_string) + && valid_source_metadata(value) } Some("function_ref") => value["module"].is_string() && value["name"].is_string(), Some("plugin_handle") => { @@ -58,6 +87,17 @@ fn valid_at(value: &Value, depth: usize) -> bool { } } +fn valid_source_metadata(value: &Value) -> bool { + optional(value, "unit", Value::is_string) + && optional(value, "span", |span| { + span.as_object().is_some_and(|fields| fields.len() == 2) + && span["start"] + .as_u64() + .zip(span["end"].as_u64()) + .is_some_and(|(start, end)| start <= end) + }) +} + fn optional(value: &Value, name: &str, check: fn(&Value) -> bool) -> bool { value.get(name).is_none_or(check) } @@ -65,7 +105,7 @@ fn optional(value: &Value, name: &str, check: fn(&Value) -> bool) -> bool { /// Archive terminal values that can be represented as data without handle IDs. pub fn transferable(value: &Value) -> bool { match value["type"].as_str() { - Some("memory" | "resource" | "plugin_handle" | "function_ref") => false, + Some("memory" | "resource" | "plugin_handle") => false, Some("list") => value["items"] .as_array() .is_some_and(|items| items.iter().all(transferable)), diff --git a/src/reader/assemble.rs b/src/reader/assemble.rs index a4313a9..7dc3a94 100644 --- a/src/reader/assemble.rs +++ b/src/reader/assemble.rs @@ -69,11 +69,24 @@ pub fn build(input: BuildInput<'_>) -> PresentationModel { .map(|projection| projection.warnings.clone()) .unwrap_or_default(); let outline = semantic.as_ref().map(build_outline).unwrap_or_default(); + let verified_headings = semantic + .as_ref() + .into_iter() + .flat_map(|projection| { + projection.anchors.iter().filter_map(|anchor| { + let heading = projection.unit(&anchor.unit_id)?.heading_span?; + Some((heading, super::links::content_anchor(&anchor.anchor))) + }) + }) + .collect(); PresentationModel { version: PRESENTATION_VERSION, title: document.title(), - heading_slugs: super::links::heading_slugs(&document.blocks), + heading_slugs: super::links::heading_slugs_with_verified( + &document.blocks, + verified_headings, + ), media: Default::default(), document, semantic, @@ -226,7 +239,10 @@ impl DocumentService { let mut verified = None; let mut source = disk_source.clone(); - if let Some(client) = &self.core { + if relative.as_str().ends_with(".md") && !relative.as_str().ends_with(".mq.md") { + status = SourceStatus::MarkdownOnly; + status_note = None; + } else if let Some(client) = &self.core { match client.check( &self.project, relative, diff --git a/src/reader/links.rs b/src/reader/links.rs index 2481d82..95c14fc 100644 --- a/src/reader/links.rs +++ b/src/reader/links.rs @@ -43,9 +43,18 @@ pub fn relative_url(current: &SafeRelativePath, url: &str) -> Option HashMap { - let mut slugs = HashMap::new(); - let mut used = HashSet::new(); + heading_slugs_with_verified(blocks, HashMap::new()) +} + +pub(crate) fn heading_slugs_with_verified( + blocks: &[DocBlock], + mut slugs: HashMap, +) -> HashMap { + let mut used: HashSet<_> = slugs.values().cloned().collect(); visit_headings(blocks, &mut |span, content| { + if slugs.contains_key(&span) { + return; + } let label = content.iter().map(Inline::plain_text).collect::(); let label = ["@exec", "@knowledge"] .into_iter() @@ -70,11 +79,7 @@ pub fn heading_slugs(blocks: &[DocBlock]) -> HashMap { }) .collect(); let base = if base.is_empty() { "section" } else { &base }; - let base = if base.starts_with("mq-") { - format!("section-{base}") - } else { - base.to_string() - }; + let base = content_anchor(base); let mut slug = base.clone(); let mut suffix = 1; while !used.insert(slug.clone()) { @@ -86,6 +91,14 @@ pub fn heading_slugs(blocks: &[DocBlock]) -> HashMap { slugs } +pub(crate) fn content_anchor(name: &str) -> String { + if name.starts_with("mq-") { + format!("section-{name}") + } else { + name.to_string() + } +} + fn visit_headings(blocks: &[DocBlock], visit: &mut impl FnMut(SourceSpan, &[Inline])) { for block in blocks { match block { diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 7303d04..c18b13a 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -12,5 +12,6 @@ pub mod math; pub mod media; pub mod model; pub mod render; +pub mod result_value; pub mod snapshot; pub mod source; diff --git a/src/reader/model.rs b/src/reader/model.rs index 706cebb..7a6dab0 100644 --- a/src/reader/model.rs +++ b/src/reader/model.rs @@ -15,6 +15,8 @@ pub const PRESENTATION_VERSION: u32 = 1; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SourceStatus { + /// Ordinary Markdown has no Marqdo semantic projection. + MarkdownOnly, /// No usable `MARQDO_BIN`; prose only, semantics explicitly unverified. CoreUnavailable, /// `check` succeeded and Analysis v3 was verified. @@ -32,6 +34,7 @@ pub enum SourceStatus { impl SourceStatus { pub fn data_value(&self) -> &'static str { match self { + SourceStatus::MarkdownOnly => "markdown-only", SourceStatus::CoreUnavailable => "core-unavailable", SourceStatus::StaticOk => "static-ok", SourceStatus::CoreError => "core-error", @@ -43,6 +46,7 @@ impl SourceStatus { pub fn label(&self) -> &'static str { match self { + SourceStatus::MarkdownOnly => "Markdown · 只读", SourceStatus::CoreUnavailable => "核心不可用 · 语义未验证", SourceStatus::StaticOk => "静态检查已通过 · 未运行", SourceStatus::CoreError => "Core 检查失败 · 语义不可用", @@ -125,17 +129,20 @@ pub enum OutlineKind { } impl PresentationModel { + pub(crate) fn has_heading_anchor(&self, id: &str) -> bool { + self.heading_slugs + .iter() + .any(|(span, slug)| slug == id || anchor_for_span(span.start, span.end) == id) + } + /// True when the entry module exposes a resolvable `main` (canonical or /// unique local name). The dock Run button never substitutes another /// function for a missing entry function (RFC-VIEW-0002 §2.4). pub fn has_entry_main(&self) -> bool { - let Some(semantic) = self.semantic.as_ref() else { - return false; - }; - semantic.functions.iter().any(|function| { - let canonical = canonical_function_name(&function.id, &semantic.module_id); - canonical == "main" || function.local_name == "main" - }) + self.semantic + .as_ref() + .and_then(SemanticProjection::entry_main) + .is_some() } pub fn run_state(&self) -> RunDisplayState { @@ -148,17 +155,7 @@ impl PresentationModel { /// True when a run button may be offered (explicit confirmation still /// required). Never true for exports or without a verified core. pub fn can_offer_run(&self) -> bool { - self.source_status.semantics_usable() - && self - .semantic - .as_ref() - .map(|semantic| { - semantic - .functions - .iter() - .any(|function| function.local_name == "main") - }) - .unwrap_or(false) + self.source_status.semantics_usable() && self.has_entry_main() } pub fn functions(&self) -> impl Iterator { @@ -180,14 +177,6 @@ pub fn anchor_for_span(start: u64, end: u64) -> String { format!("mq-h-{start:x}-{end:x}") } -/// Analysis v3 function ids are `::`. -fn canonical_function_name(function_id: &str, module_id: &str) -> String { - function_id - .strip_prefix(&format!("{module_id}::")) - .unwrap_or(function_id) - .to_string() -} - #[cfg(test)] mod tests { use super::*; diff --git a/src/reader/render.rs b/src/reader/render.rs index 5c19834..789aa3d 100644 --- a/src/reader/render.rs +++ b/src/reader/render.rs @@ -14,6 +14,7 @@ use crate::protocol::analysis_v3::{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::result_value::render_result_value; use crate::reader::source::SafeRelativePath; use crate::reader::source::SourceSpan; use std::fmt::Write as _; @@ -92,6 +93,8 @@ pub struct RenderContext { /// Whether a frozen Core was negotiated (an explicit run form can exist). pub core_available: bool, pub snapshot_package: bool, + pub embedded: bool, + pub dark_theme: bool, pub overlay: Option>, } @@ -106,6 +109,8 @@ impl RenderContext { run_timeout_secs: 30, core_available: false, snapshot_package: false, + embedded: false, + dark_theme: false, overlay: None, } } @@ -120,6 +125,8 @@ impl RenderContext { run_timeout_secs: 0, core_available: false, snapshot_package: false, + embedded: false, + dark_theme: false, overlay: None, } } @@ -159,7 +166,8 @@ impl ReaderRenderer { let logo_uri = self.assets.logo().data_uri(); let navigation = &model.navigation; - let script = if ctx.snapshot_package { + let scriptless = ctx.snapshot_package || ctx.embedded; + let script = if scriptless { String::new() } else { format!( @@ -174,7 +182,10 @@ impl ReaderRenderer { .as_ref() .map(|semantic| semantic.analysis_digest.clone()) .unwrap_or_default(); - let has_main = model.has_entry_main(); + let entry_main = model + .semantic + .as_ref() + .and_then(|analysis| analysis.entry_main()); let page_title = if navigation.site_title.is_empty() { model.title.clone() } else { @@ -195,20 +206,32 @@ impl ReaderRenderer { {script} - + 跳到正文 "##, presentation_version = model.version, view_version = env!("CARGO_PKG_VERSION"), - csp = csp_policy(ctx.snapshot_package), + csp = csp_policy(scriptless), title = escape_text(&page_title), logo = escape_attr(&logo_uri), css = escape_attr(&format!("{asset_prefix}{css_name}")), status = model.source_status.data_value(), + theme = if ctx.dark_theme { "dark" } else { "light" }, + embedded = ctx.embedded, annotations = if ctx.annotations { "on" } else { "off" }, run_state = model.run_state().data_value(), run_available = if ctx.run_available { "true" } else { "false" }, - has_main = if has_main { "true" } else { "false" }, + has_main = entry_main.is_some(), + entry_function = escape_attr( + entry_main + .map(|function| function.id.as_str()) + .unwrap_or_default() + ), + entry_needs_parameters = entry_main.is_some_and(|function| function + .signature + .params + .iter() + .any(|param| param.required)), core_available = if ctx.core_available { "true" } else { "false" }, document = escape_attr(&relative_path), analysis_digest = escape_attr(&analysis_digest), @@ -216,14 +239,18 @@ impl ReaderRenderer { live = if ctx.live { "true" } else { "false" }, ); - self.render_topbar(&mut html, model, ctx, navigation); - self.render_ornament(&mut html); + if !ctx.embedded { + self.render_topbar(&mut html, model, ctx, navigation); + self.render_ornament(&mut html); + } let _ = write!(html, "
\n"); - if navigation.welcome { + if !ctx.embedded && navigation.welcome { self.render_welcome(&mut html, navigation); } - self.render_document_meta(&mut html, model, ctx.overlay.is_some()); + if !ctx.embedded { + self.render_document_meta(&mut html, model, ctx.overlay.is_some()); + } if ctx.overlay.is_some() { let prefix = match ctx.links { LinkPolicy::StaticRelative { page_depth } => "../".repeat(page_depth), @@ -231,25 +258,29 @@ impl ReaderRenderer { }; let _ = write!(html, "

此文档包含一次执行快照。来源摘要见 manifest.json。

"); } - self.render_diagnostics(&mut html, model); - self.render_functions(&mut html, model, ctx); + if !ctx.embedded { + self.render_diagnostics(&mut html, model); + self.render_functions(&mut html, model, ctx); + } self.render_document(&mut html, model, ctx); - if ctx.live { - self.render_live_run_shell(&mut html, ctx); - } else { - self.render_run_panel(&mut html, model, ctx); + if !ctx.embedded { + if ctx.live { + self.render_live_run_shell(&mut html, ctx); + } else { + self.render_run_panel(&mut html, model, ctx); + } + if ctx.snapshot_package { + let _ = write!(html, "
原始源码
{}
", + escape_text(&model.document.source)); + html.push_str(&self.render_file_list(model, ctx)); + } else { + self.render_source_pane(&mut html, model, ctx); + } + self.render_footer(&mut html, model); } - if ctx.snapshot_package { - let _ = write!(html, "
原始源码
{}
", - escape_text(&model.document.source)); - html.push_str(&self.render_file_list(model, ctx)); - } else { - self.render_source_pane(&mut html, model, ctx); - } - self.render_footer(&mut html, model); let _ = write!(html, "
\n"); - if !ctx.snapshot_package { + if !scriptless { self.render_dock(&mut html, ctx); self.render_toast(&mut html); self.render_dialogs(&mut html, model, ctx); @@ -258,7 +289,7 @@ impl ReaderRenderer { RenderedPage { html, - assets_used: if ctx.snapshot_package { + assets_used: if scriptless { vec![css_name] } else { vec![css_name, js_name] @@ -463,7 +494,7 @@ impl ReaderRenderer { }); let call_button = if ctx.live && ctx.core_available { function - .map(|function| function_call_button(function, &entry.label)) + .map(|function| function_call_button(function, &function.local_name)) .unwrap_or_default() } else { String::new() @@ -579,6 +610,10 @@ impl ReaderRenderer {
+