From cbb62051af7bb89c0a86006fb1274bcda05134ac Mon Sep 17 00:00:00 2001 From: cflmy Date: Sat, 28 Nov 2026 23:11:19 +0800 Subject: [PATCH 01/12] ci: verify View against the published RC.6 CLI (#14) --- .github/workflows/ci.yml | 9 +++--- .woodpecker/ci.yml | 14 ++++---- COMPATIBILITY.md | 8 ++--- README.md | 18 +++++------ docs/ACCEPTANCE.md | 32 +++++++++---------- docs/CONFORMANCE.md | 13 ++++---- docs/STATUS.md | 26 +++++++-------- .../observation-v1-and-analysis-v3.md | 2 +- scripts/acceptance.sh | 19 ++++++++--- scripts/check-docs.sh | 10 +++--- scripts/check-no-legacy.sh | 6 ++-- scripts/frozen-beta.sh | 18 ++++++++--- scripts/test-browser.sh | 2 +- 13 files changed, 96 insertions(+), 81 deletions(-) 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..db9cf4e 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,6 @@ 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 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/README.md b/README.md index dbd953d..682a804 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`。 @@ -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 @@ -135,15 +135,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 摘要。 diff --git a/docs/ACCEPTANCE.md b/docs/ACCEPTANCE.md index e1e9d78..c231922 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,14 @@ 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 +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 ``` 单项: @@ -147,4 +147,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..c923d70 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -1,11 +1,10 @@ -# 合规矩阵(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。 @@ -59,7 +58,7 @@ | 快照/错误无绝对主机路径;错误只用 relative_path | 实现(已验收) | `src/protocol/observation_v1.rs`、renderer | | Tool 安装/分发/卸载/篡改拒绝;CLI SHA 前后一致 | 实现(已验收) | `scripts/install-smoke.sh`、acceptance G03 | -## 5. 门禁与证据 +## 5. 历史门禁与证据 | 门禁 | 状态 | 证据 | |---|---|---| @@ -73,7 +72,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 +83,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..5d6fdf5 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-28。当前目标:`marqdo-view 0.3.0`,只支持 +> `marqdo 3.0.0-rc.6` 的公开契约(adaptation #4,验收 #5,公共 Analysis 边界 #6)。 > 机器证据只认绑定 CLI 源码 SHA 的 manifest;未生成的证据一律 `UNVERIFIED`。 ## 版本与基线 @@ -9,18 +9,18 @@ | 项 | 值 | |---|---| | 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` | +| 冻结 CLI 版本 | `marqdo 3.0.0-rc.6` | +| CLI 源码 SHA | `63776735e924ade279cdf59d5c733dc24bfdabbb` | +| CLI 归档 SHA-256 | `8dc0b006302e03c23451b8ea9f8a0fcdae8bf67c80c546bee2434bf69755bfe3` | +| CLI 二进制 SHA-256 | `4f12e6b8a2edb327c0d9ab6165f74e8e88a01b05350527e3aade6f52d4f7a06c` | | 平台 | Linux x86_64 / glibc 2.39(唯一正式验证) | | 视觉基准 | `docs/design/reference-old-view-reader.png`(**2048×1133**) | -| 验收 manifest | `docs/evidence/c44b0f943875d563bb7c170f8ccd3fd56a82360f/manifest.json`(**result: PASS,G01–G12 全部 PASS**) | +| 验收 manifest | `docs/evidence/c44b0f943875d563bb7c170f8ccd3fd56a82360f/manifest.json`(历史记录,候选证据另行生成) | ## 0.3.0 适配交付(实现状态) @@ -37,10 +37,10 @@ | 验收 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` | -## 发布门禁 G01–G12(issue #5) +## 历史发布门禁 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 +59,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` 时,候选缺少发布证据。 ## 能力基线 @@ -77,7 +77,7 @@ | 引用/调用/分支/循环/副作用标注 + 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(welcome/branch-loop/function-params/knowledge-only/unsafe-side-effect) | 实现,RC.6 check/call/run 验收脚本 | | 逐语句变量值 / 参数实际值 / 内存快照 | **默认不请求、不展示**(协议支持显式选择;View 0.3.0 不请求,绝不伪造) | | 知识“已证明” / Prove / Lint | **UNSUPPORTED**(等待独立版本化报告协议) | | 调试器/断点/单步/调用栈、Notebook/持久内核、Session/journal | **不实现**(明确非目标) | @@ -97,7 +97,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` | diff --git a/docs/architecture/observation-v1-and-analysis-v3.md b/docs/architecture/observation-v1-and-analysis-v3.md index fce2aaa..6b4e78a 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`)。 diff --git a/scripts/acceptance.sh b/scripts/acceptance.sh index 6a413e9..ed17a76 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" 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-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..7d0107f 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 -- 2.54.1 From 84f76366274445d05d13b16479cd0abab90e2431 Mon Sep 17 00:00:00 2001 From: cflmy Date: Sat, 28 Nov 2026 23:16:12 +0800 Subject: [PATCH 02/12] feat: export a selected completed Observation snapshot (#15) --- README.md | 18 +++ scripts/test-export.sh | 68 ++++++++- src/cli.rs | 12 ++ src/execution/export_candidate.rs | 4 +- src/export.rs | 17 ++- src/export_result.rs | 137 +++++++++++++++++- src/lib.rs | 16 ++- src/protocol/observation_v1.rs | 229 ++++++++++++------------------ src/reader/render.rs | 13 +- src/reader/snapshot.rs | 5 +- 10 files changed, 367 insertions(+), 152 deletions(-) diff --git a/README.md b/README.md index 682a804..58d4568 100644 --- a/README.md +++ b/README.md @@ -124,6 +124,24 @@ ExecutionController ─ 单任务、取消、SSE 事件(仅 POST /api/runs 可 `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 diff --git a/scripts/test-export.sh b/scripts/test-export.sh index 48b2000..fdfb34d 100755 --- a/scripts/test-export.sh +++ b/scripts/test-export.sh @@ -49,10 +49,69 @@ 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 + rg -q '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}" \ @@ -144,6 +204,8 @@ const { chromium } = require(path.join(process.argv[2], "node_modules/playwright 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 diff --git a/src/cli.rs b/src/cli.rs index f2b4698..39581ee 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -82,7 +82,12 @@ pub struct ExportArgs { pub no_annotations: bool, /// Import a trusted, already completed CLI Observation snapshot. - #[arg(long, value_name = "FILE", requires = "run_id")] + #[arg( + long, + value_name = "FILE", + requires = "run_id", + conflicts_with = "embed" + )] pub observation: Option, /// Exact Observation run.id selected for export. @@ -92,6 +97,22 @@ pub struct ExportArgs { /// 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/export.rs b/src/export.rs index 08bb60f..39753b3 100644 --- a/src/export.rs +++ b/src/export.rs @@ -8,7 +8,7 @@ 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; @@ -32,14 +32,21 @@ pub struct ExportSummary { pub manifest_sha256: String, } -pub fn export(context: &DocumentService, options: &ExportOptions) -> ViewResult { - export_with_observation(context, options, None) +pub(crate) struct EmbedOptions<'a> { + pub dark_theme: bool, + pub anchor: Option<&'a str>, + pub expected_sha256: Option<&'a str>, } -pub(crate) fn export_with_observation( +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)?; @@ -55,13 +62,38 @@ pub(crate) fn export_with_observation( 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 site = build_site(context, &entry, &staging, !options.no_annotations, overlay)?; + let site = build_site( + context, + &entry, + &staging, + !options.no_annotations, + overlay, + embed, + )?; publish(&staging, &out)?; Ok(ExportSummary { out, @@ -130,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(), @@ -147,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" { @@ -177,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(), @@ -200,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, @@ -258,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}"), @@ -310,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/lib.rs b/src/lib.rs index 3094047..2f5263c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -69,13 +69,19 @@ fn export_command(opts: &RuntimeOpts, args: &ExportArgs) -> ViewResult { }) } }; - let summary = export::export_with_observation( + 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/reader/assemble.rs b/src/reader/assemble.rs index a4313a9..f9180c6 100644 --- a/src/reader/assemble.rs +++ b/src/reader/assemble.rs @@ -226,7 +226,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/model.rs b/src/reader/model.rs index 706cebb..dca93d2 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,6 +129,12 @@ 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). diff --git a/src/reader/render.rs b/src/reader/render.rs index ec17c5b..237e79a 100644 --- a/src/reader/render.rs +++ b/src/reader/render.rs @@ -92,6 +92,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 +108,8 @@ impl RenderContext { run_timeout_secs: 30, core_available: false, snapshot_package: false, + embedded: false, + dark_theme: false, overlay: None, } } @@ -120,6 +124,8 @@ impl RenderContext { run_timeout_secs: 0, core_available: false, snapshot_package: false, + embedded: false, + dark_theme: false, overlay: None, } } @@ -159,7 +165,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!( @@ -195,16 +202,18 @@ 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" }, @@ -216,14 +225,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 +244,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 +275,7 @@ impl ReaderRenderer { RenderedPage { html, - assets_used: if ctx.snapshot_package { + assets_used: if scriptless { vec![css_name] } else { vec![css_name, js_name] @@ -1046,7 +1063,7 @@ fn render_block( } let _ = write!( html, - "
{}
\n", + "
{}
\n", escape_text(literal) ); } @@ -1056,7 +1073,7 @@ fn render_block( rows, .. } => { - html.push_str("
\n"); + html.push_str("
\n"); if !header.is_empty() { html.push_str(""); for (index, cell) in header.iter().enumerate() { @@ -1351,18 +1368,22 @@ fn render_inline( } _ => None, }); - let target = match reference { - // A local target the loaded catalog did not cover is shown as - // unverified, never as a broken link: keep the navigation href - // only when the document is known to the project. - Some(_reference) - if reference_state - == Some(crate::protocol::analysis_v3::ReferenceState::NotLoaded) => - { - resolve_link(url, current, model, &ctx.links) + let target = if ctx.embedded { + resolve_embedded_link(url, current, model) + } else { + match reference { + // A local target the loaded catalog did not cover is shown as + // unverified, never as a broken link: keep the navigation href + // only when the document is known to the project. + Some(_reference) + if reference_state + == Some(crate::protocol::analysis_v3::ReferenceState::NotLoaded) => + { + resolve_link(url, current, model, &ctx.links) + } + Some(_) => reference_href, + None => resolve_link(url, current, model, &ctx.links), } - Some(_) => reference_href, - None => resolve_link(url, current, model, &ctx.links), }; let state = reference_state.map(|state| state.data_value()); let state_title = match reference_state { @@ -1605,6 +1626,25 @@ fn percent_encode_path(raw: &str) -> String { out } +pub(crate) fn fragment_href(anchor: &str) -> String { + format!("#{}", percent_encode_path(anchor)) +} + +fn resolve_embedded_link( + raw: &str, + current: &SafeRelativePath, + model: &PresentationModel, +) -> Option { + let (path, fragment) = raw.trim().split_once('#')?; + if !path.is_empty() && super::links::relative_url(current, path).as_ref() != Some(current) { + return None; + } + let fragment = super::links::decode(fragment)?; + model + .has_heading_anchor(&fragment) + .then(|| fragment_href(&fragment)) +} + /// Sanitize one Markdown link destination. Returns `None` for schemes the /// reader must never expose (`javascript:`, `data:`, `file:`, ...) and for /// console-control-looking payloads. diff --git a/src/server/routes.rs b/src/server/routes.rs index 8f2d052..21b7360 100644 --- a/src/server/routes.rs +++ b/src/server/routes.rs @@ -187,15 +187,11 @@ fn serve_page( }; let (session, set_cookie) = state.security.page_session(&request); let ctx = RenderContext { - links: crate::reader::render::LinkPolicy::LocalServer, - live: true, csrf_token: Some(session.csrf), run_available: state.service.core().is_some() && model.can_offer_run(), - annotations: true, run_timeout_secs: state.controller.config().run_timeout_secs(), core_available: state.service.core().is_some(), - snapshot_package: false, - overlay: None, + ..RenderContext::live() }; let page = state.renderer.render(&model, &ctx); let mut headers = Vec::new(); diff --git a/tests/browser/embedded.browser.cjs b/tests/browser/embedded.browser.cjs new file mode 100644 index 0000000..2f9ed99 --- /dev/null +++ b/tests/browser/embedded.browser.cjs @@ -0,0 +1,133 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const { spawn } = require("node:child_process"); +const { createHash } = require("node:crypto"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { setTimeout: delay } = require("node:timers/promises"); +const { pathToFileURL } = require("node:url"); +const { chromium } = require("playwright"); + +const [work, executable, ...entryArgs] = process.argv.slice(2); +const digest = (bytes) => createHash("sha256").update(bytes).digest("hex"); + +function startReader(source) { + const child = spawn(executable, [...entryArgs, source, "--port", "0", "--no-open"]); + const address = new Promise((resolve, reject) => { + let output = ""; + const timer = setTimeout(() => reject(new Error("View did not print a loopback address")), 10000); + function read(chunk) { + output += chunk; + const match = output.match(/http:\/\/127\.0\.0\.1:[0-9]+\//); + if (match) { + clearTimeout(timer); + resolve(match[0]); + } + } + child.stdout.on("data", read); + child.stderr.on("data", read); + child.on("error", (error) => { clearTimeout(timer); reject(error); }); + child.on("exit", (code) => { clearTimeout(timer); reject(new Error(`View quit (${code}): ${output}`)); }); + }); + return { child, address }; +} + +async function compareReading(browser, name) { + const source = path.join(work, "project", name); + const bundle = path.join(work, name); + const manifest = JSON.parse(await fs.readFile(path.join(bundle, "manifest.json"))); + assert.equal(manifest.mode, "embedded"); + assert.equal(manifest.theme, "dark"); + assert.equal(manifest.executed, false); + assert.equal(manifest.requires.api_revision, 1); + assert.equal(manifest.pages.length, 1); + assert.equal(manifest.pages[0].source_sha256, digest(await fs.readFile(source))); + assert.equal(manifest.pages[0].source_status, name === "plain.md" ? "markdown-only" : "static-ok"); + assert.equal(manifest.entry.href, "index.html#detail"); + assert.ok(manifest.entry.heading_ids.includes("detail")); + assert.equal(manifest.files.filter((file) => file.mime === "image/png").length, 1); + for (const file of [...manifest.files, ...manifest.assets]) { + assert.equal(digest(await fs.readFile(path.join(bundle, file.path))), file.sha256); + assert.ok(!file.path.endsWith(".js")); + } + + const standalone = await browser.newPage({ viewport: { width: 390, height: 600 } }); + const reader = startReader(source); + let standaloneStyle; + try { + await standalone.goto(await reader.address); + await standalone.locator('[data-action="settings"]').click(); + await standalone.locator('[data-action="theme"]').click(); + standaloneStyle = await style(standalone.locator(".mq-document")); + assert.equal(await standalone.locator(".mq-document img").count(), 1); + } finally { + reader.child.kill(); + await standalone.close(); + } + + const offline = await browser.newContext({ offline: true, viewport: { width: 390, height: 720 } }); + try { + const page = await offline.newPage(); + const requests = []; + const errors = []; + page.on("request", (request) => requests.push(request.url())); + page.on("pageerror", (error) => errors.push(String(error))); + const host = path.join(work, "host.html"); + await fs.writeFile(host, ``); + await page.goto(pathToFileURL(host).href); + const frame = page.frameLocator("iframe"); + const article = frame.locator(".mq-document"); + assert.deepEqual(await style(article), standaloneStyle); + assert.equal(await article.locator("math").count(), 1); + assert.equal(await article.locator("blockquote").count(), 1); + assert.equal(await article.locator("img").count(), 1); + assert.equal(await article.locator("img").evaluate((image) => image.naturalWidth), 1); + assert.equal(await frame.locator("script,button,.mq-topbar,.mq-dock").count(), 0); + assert.equal(await article.getByRole("link").count(), 1); + assert.equal(await frame.locator(":target").getAttribute("id"), "detail"); + for (const selector of [".mq-table-wrap", ".mq-codeblock pre"]) { + const scroller = article.locator(selector); + assert.ok(await scroller.evaluate((node) => node.scrollWidth > node.clientWidth)); + await scroller.focus(); + await scroller.press("ArrowRight"); + let scrolled = false; + for (let attempt = 0; attempt < 20 && !scrolled; attempt += 1) { + await delay(25); + scrolled = await scroller.evaluate((node) => node === document.activeElement && node.scrollLeft > 0); + } + assert.ok(scrolled, `${selector} did not scroll using the keyboard`); + } + assert.ok(requests.every((url) => url.startsWith("file:") || url.startsWith("data:")), requests); + assert.deepEqual(errors, []); + } finally { + await offline.close(); + } +} + +function style(article) { + return article.evaluate(async (element) => { + await document.fonts.ready; + const style = getComputedStyle(element); + return { + family: style.fontFamily, + color: style.color, + size: style.fontSize, + scheme: style.colorScheme, + mathFont: [...document.fonts].find((font) => font.family === "Noto Sans Math")?.status, + stylesheet: document.querySelector('link[rel="stylesheet"]').href.split("/").pop(), + }; + }); +} + +(async () => { + const browser = await chromium.launch(); + try { + for (const name of ["index.mq.md", "plain.md"]) { + await compareReading(browser, name); + } + console.log("Embedded reader: PASS (standalone and sandboxed offline frame, theme, font, anchor, media, keyboard)"); + } finally { + await browser.close(); + } +})().catch((error) => { console.error(error); process.exitCode = 1; }); -- 2.54.1 From 4af54afe68f7ca6e28045edd49724218abec3eab Mon Sep 17 00:00:00 2001 From: cflmy Date: Sat, 28 Nov 2026 23:34:50 +0800 Subject: [PATCH 04/12] feat: bind function results and share typed return rendering (#17) --- Cargo.toml | 2 +- assets/reader.css | 4 + assets/reader.js | 42 ++++- src/execution/controller.rs | 44 +++++- src/execution/export_candidate.rs | 21 ++- src/export_result.rs | 41 ++--- src/protocol/observation_v1.rs | 127 +++++++++------ src/protocol/value_wire_v1.rs | 48 +++++- src/reader/mod.rs | 1 + src/reader/render.rs | 19 +-- src/reader/result_value.rs | 250 ++++++++++++++++++++++++++++++ src/reader/snapshot.rs | 2 +- tests/integration/execution.rs | 27 ++++ 13 files changed, 525 insertions(+), 103 deletions(-) create mode 100644 src/reader/result_value.rs 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/assets/reader.css b/assets/reader.css index b73b4bf..9cfc088 100644 --- a/assets/reader.css +++ b/assets/reader.css @@ -1385,6 +1385,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 { diff --git a/assets/reader.js b/assets/reader.js index ce37554..f18149b 100644 --- a/assets/reader.js +++ b/assets/reader.js @@ -886,6 +886,42 @@ } } + // 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".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 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 && + !/^(on|href$|src$|style$)/i.test(attr.name); + var safeHtmlAttribute = !isMath && ( + (attr.name === "class" && /^mq-[a-z-]+$/.test(attr.value)) || + (attr.name === "open" && name === "details") || + (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 +933,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,9 +983,7 @@ 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) { diff --git a/src/execution/controller.rs b/src/execution/controller.rs index d9d3a27..f8051ee 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; @@ -547,7 +548,31 @@ 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 binding = decoder.finish(exit_code, &process_stderr, stale).and_then(|projection| { + 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 +792,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, }) } @@ -1017,6 +1047,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(render_result_value) + .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 +1069,8 @@ fn observation_result( _ => serde_json::Value::Null, }; result["core_run_id"] = serde_json::json!(projection.run_id); + 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 +1158,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 8e9e597..88b26ac 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,21 @@ 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(render_result_value); + 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 +109,7 @@ impl TerminalExportCandidate { terminal_at: crate::execution::events::utc_now(), state, value, + value_markup, value_is_public_scalar, stdout, stderr, @@ -113,9 +120,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, }) } diff --git a/src/export_result.rs b/src/export_result.rs index cb64904..39e634d 100644 --- a/src/export_result.rs +++ b/src/export_result.rs @@ -7,13 +7,14 @@ use crate::{ export_candidate::{counts_map, public_scalar_type, TerminalExportCandidate}, }, protocol::{ - observation_v1::{decode_snapshot_evidence, RunDisplayState, MAX_SNAPSHOT_BYTES}, + 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}, }, @@ -184,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()), @@ -231,8 +232,7 @@ impl ObservationImport<'_> { .read_to_end(&mut bytes) }) .map_err(|err| ViewError::io("read Observation snapshot", err))?; - let evidence = decode_snapshot_evidence(&bytes, analysis)?; - let run = &evidence.run; + 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", @@ -243,42 +243,27 @@ impl ObservationImport<'_> { "Observation export requires a complete, successful, untruncated run", )); } - if analysis.module_id != analysis.entry_module_id - || evidence.producer_version != analysis.producer_version - { - return Err(invalid( - "Observation producer or entry module does not match the verified Analysis", - )); - } - let mode = evidence - .mode - .ok_or_else(|| invalid("Observation has no execution mode"))?; let function = analysis .functions .iter() - .find(|function| Some(function.id.as_str()) == evidence.root_function_id.as_deref()) + .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") })?; - let module_prefix = format!("{}::", analysis.module_id); - let entry_target = run - .entry - .as_deref() - .and_then(|entry| entry.strip_prefix(&module_prefix)); - let canonical_name = function.id.strip_prefix(&module_prefix); - if entry_target.is_none() - || (entry_target != canonical_name - && entry_target != Some(function.local_name.as_str())) - { + 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| value.display.clone()); + .map(render_result_value); + let result_complete = value.as_ref().is_none_or(|value| !value.clipped); Ok(ExportResultOverlay { source: SnapshotSource { project_root_id: analysis.project_root_id.clone(), @@ -292,7 +277,7 @@ impl ObservationImport<'_> { execution: SnapshotExecution { included: true, core_run_id: run.run_id.clone(), - core_version: evidence.producer_version, + core_version: run.producer_version, target: function.id.clone(), status: RunState::Succeeded.data_value(), terminal_at: None, @@ -300,7 +285,7 @@ impl ObservationImport<'_> { source_verified: true, observation_status: "verified".into(), capture_level: run.capture_level.clone(), - result_complete: true, + result_complete, output_complete: true, observation_truncated: false, parameters: "omitted", diff --git a/src/protocol/observation_v1.rs b/src/protocol/observation_v1.rs index 9f55faa..3437e8f 100644 --- a/src/protocol/observation_v1.rs +++ b/src/protocol/observation_v1.rs @@ -229,6 +229,7 @@ impl Truncation { pub struct RunValue { pub ty: String, pub display: String, + pub wire: Option, } #[derive(Debug, Clone, Default, PartialEq, Eq)] @@ -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() { ( @@ -1271,6 +1323,13 @@ impl ObservationDecoder { 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, @@ -1412,15 +1471,23 @@ fn validate_error_location(error: &serde_json::Map) -> Result<(), 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(); @@ -1540,23 +1607,9 @@ struct RawSnapshotCapture { truncated: Value, } -pub(crate) struct SnapshotEvidence { - pub run: RunProjection, - pub producer_version: String, - pub mode: Option, - pub root_function_id: Option, -} - /// 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 { - Ok(decode_snapshot_evidence(bytes, analysis)?.run) -} - -pub(crate) fn decode_snapshot_evidence( - bytes: &[u8], - analysis: &SemanticProjection, -) -> ViewResult { let invalid = |detail: &str| ViewError::ObservationInvalid { detail: detail.to_string(), }; @@ -1577,9 +1630,6 @@ pub(crate) fn decode_snapshot_evidence( let mut decoder = ObservationDecoder::new(analysis); let mut source = &Value::Null; let mut truncated = &Value::Null; - let mut mode = None; - let mut root_function_id = None; - let mut root_frames = 0; for event in &raw.events { if event.run_id != raw.run.id { return Err(invalid( @@ -1596,13 +1646,8 @@ pub(crate) fn decode_snapshot_evidence( match event.kind.as_str() { "run.started" => { source = &event.payload["source"]; - mode = event.payload["mode"].as_str().map(str::to_owned); } "observation.truncated" => truncated = &event.payload, - "call.enter" if event.payload.get("parent_frame_id") == Some(&Value::Null) => { - root_frames += 1; - root_function_id = event.payload["function_id"].as_str(); - } _ => {} } } @@ -1627,17 +1672,7 @@ pub(crate) fn decode_snapshot_evidence( "snapshot run.status disagrees with its terminal state", )); } - Ok(SnapshotEvidence { - run, - producer_version: raw.events[0].payload["producer"]["version"] - .as_str() - .unwrap_or_default() - .to_owned(), - mode, - root_function_id: root_function_id - .filter(|_| root_frames == 1) - .map(str::to_owned), - }) + Ok(run) } /// Build a stale run projection that keeps the raw result accessible without @@ -1646,6 +1681,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/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/render.rs b/src/reader/render.rs index 237e79a..1da167f 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 _; @@ -774,12 +775,7 @@ impl ReaderRenderer { ); } if let Some(value) = &run.result_value { - let _ = write!( - html, - "

Core 本次返回值(公开 JSON):{} 类型 {}

\n", - escape_text(&value.display), - escape_text(&value.ty) - ); + html.push_str(render_result_value(value).as_html()); } if !run.stdout.is_empty() { let _ = write!( @@ -1511,7 +1507,7 @@ fn source_id_id(model: &PresentationModel, span: SourceSpan) -> String { )) } -fn escape_text(raw: &str) -> String { +pub(super) fn escape_text(raw: &str) -> String { let mut out = String::with_capacity(raw.len() + 8); for ch in raw.chars() { match ch { @@ -1557,11 +1553,10 @@ fn render_snapshot(html: &mut String, overlay: &super::snapshot::ExportResultOve ); } html.push_str("

"); - for (label, value) in [ - ("返回值", &overlay.value), - ("stdout", &overlay.stdout), - ("stderr", &overlay.stderr), - ] { + if let Some(value) = &overlay.value { + html.push_str(value.as_html()); + } + for (label, value) in [("stdout", &overlay.stdout), ("stderr", &overlay.stderr)] { if let Some(value) = value { let _ = write!( html, diff --git a/src/reader/result_value.rs b/src/reader/result_value.rs new file mode 100644 index 0000000..b65083f --- /dev/null +++ b/src/reader/result_value.rs @@ -0,0 +1,250 @@ +//! One bounded, inert return-value renderer for Live and offline snapshots. + +use crate::protocol::observation_v1::RunValue; +use serde_json::Value; +use std::fmt::Write as _; + +use super::render::escape_text; + +#[derive(Debug, Clone)] +pub struct ResultMarkup { + html: String, + pub(crate) clipped: bool, +} + +impl ResultMarkup { + pub(crate) fn as_html(&self) -> &str { + &self.html + } +} + +pub(crate) fn render_result_value(value: &RunValue) -> ResultMarkup { + let mut markup = String::from("
返回值:"); + let mut budget = Budget { + nodes: 256, + bytes: 16 * 1024, + clipped: false, + }; + if let Some(wire) = &value.wire { + budget.render(&mut markup, wire, 0); + } else { + markup.push_str("不可传递"); + } + let _ = write!( + markup, + "
类型 {}", + escape_text(&value.ty) + ); + if budget.clipped { + markup.push_str("

返回值达到展示上限,仅显示部分内容。

"); + } + markup.push_str("
"); + ResultMarkup { + html: markup, + clipped: budget.clipped, + } +} + +struct Budget { + nodes: usize, + bytes: usize, + clipped: bool, +} + +impl Budget { + fn text(&mut self, html: &mut String, text: &str) { + let mut end = text.len().min(self.bytes); + while !text.is_char_boundary(end) { + end -= 1; + } + self.bytes -= end; + self.clipped |= end < text.len(); + // Keep every ordinary character inert. Spell out control characters + // that cannot appear in a parsed XML fragment. + let mut sanitized = String::with_capacity(end); + for ch in text[..end].chars() { + if (ch.is_control() && !matches!(ch, '\n' | '\r' | '\t')) + || matches!(ch, '\u{fffe}' | '\u{ffff}') + { + sanitized.extend(ch.escape_unicode()); + } else { + sanitized.push(ch); + } + } + html.push_str(&escape_text(&sanitized)); + } + + fn render(&mut self, html: &mut String, value: &Value, depth: usize) { + if self.nodes == 0 || self.bytes == 0 || depth >= 12 { + self.clipped = true; + html.push_str("…"); + return; + } + self.nodes -= 1; + let string = |name: &str| value[name].as_str().unwrap_or_default(); + match value["type"].as_str() { + Some("list") => { + html.push_str("
列表
    "); + if let Some(items) = value["items"].as_array() { + for item in items { + if self.nodes == 0 || self.bytes == 0 { + self.clipped = true; + break; + } + html.push_str("
  1. "); + self.render(html, item, depth + 1); + html.push_str("
  2. "); + } + } + html.push_str("
"); + } + Some("map") => { + html.push_str("
映射
"); + if let Some(entries) = value["entries"].as_object() { + for (key, item) in entries { + if self.nodes == 0 || self.bytes == 0 { + self.clipped = true; + break; + } + html.push_str("
"); + self.text(html, key); + html.push_str("
"); + self.render(html, item, depth + 1); + html.push_str("
"); + } + } + html.push_str("
"); + } + Some("table") => self.table(html, value, depth), + Some("formula") => { + let latex = string("latex"); + let block = value["display"].as_bool().unwrap_or_default(); + if let Some(math) = + super::math::render(latex, block).filter(|math| math.len() <= self.bytes) + { + self.bytes -= math.len(); + html.push_str(&math); + } + html.push_str("
LaTeX
");
+                self.text(html, latex);
+                html.push_str("
"); + } + Some("code") => { + html.push_str("
");
+                self.text(html, string("source"));
+                html.push_str("
"); + } + Some("function_ref") => { + html.push_str(""); + self.text(html, string("module")); + html.push_str("::"); + self.text(html, string("name")); + html.push_str(""); + } + Some("text") => { + html.push_str(""); + self.text(html, string("value")); + html.push_str(""); + } + kind => { + let scalar = match kind { + Some("unit") => "无返回值".into(), + Some("none") => "None".into(), + Some("int") => string("decimal").into(), + Some("float") if value["special"].is_string() => string("special").into(), + Some("float" | "bool") => value["value"].to_string(), + _ => "不可传递".into(), + }; + html.push_str(""); + self.text(html, &scalar); + html.push_str(""); + } + } + } + + fn table(&mut self, html: &mut String, value: &Value, depth: usize) { + let Some(header) = value["header"].as_array() else { + return; + }; + let Some(rows) = value["rows"].as_array() else { + return; + }; + let width = header.len().min(32); + self.clipped |= width < header.len(); + html.push_str("
"); + for heading in &header[..width] { + html.push_str(""); + } + html.push_str(""); + for row in rows { + if self.nodes <= width || self.bytes == 0 { + self.clipped = true; + break; + } + let Some(cells) = row.as_array() else { + continue; + }; + html.push_str(""); + self.nodes -= 1; + for cell in cells.iter().take(width) { + html.push_str(""); + } + html.push_str(""); + } + html.push_str("
"); + self.text(html, heading.as_str().unwrap_or_default()); + html.push_str("
"); + self.render(html, cell, depth + 1); + html.push_str("
"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn render(wire: Value) -> ResultMarkup { + render_result_value(&RunValue { + ty: wire["type"].as_str().unwrap().into(), + display: String::new(), + wire: Some(wire), + }) + } + + #[test] + fn preserves_json_integer_precision_and_renders_inert_nested_values() { + let result = render(json!({"type":"map", "entries": { + "