Compare commits

..
16 Commits
Author SHA1 Message Date
Marqdo View 04f3a0e9e5 docs: record generated rc.4 acceptance evidence
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-26 00:04:15 +08:00
Marqdo View 1ecb3c08e7 evidence: bind 0.3.0 acceptance to rc.4 SHA and Woodpecker #10
ci/woodpecker/push/woodpecker Pipeline was canceled
Re-run scripts/acceptance.sh on View source commit 340ecb0 against the frozen
marqdo 3.0.0-rc.4 archive; all G01-G12 PASS, including the real rc.4 pipeline
#10 for the same SHA, Chromium browser evidence, N01-N20 probes and the exact
Analysis v3/Observation v1/Tool revision 1 contracts. Manifest and referenced
logs live under docs/evidence/452e9a32.../. ACCEPTANCE/STATUS now cite the real
manifest instead of the pre-generation UNVERIFIED state.
2026-11-25 22:21:56 +08:00
Marqdo View 340ecb035f feat: migrate View 0.3.0 to marqdo 3.0.0-rc.4 contracts
ci/woodpecker/push/woodpecker Pipeline was successful
Replace the retired rc.2 Analysis v2/Trace v2/Execution Events v1 stack with the
single current contract family:

- Analysis v3 (ADR-0069 public boundary): one check --emit artifact carries the
  exact source, Markdown AST, heading scopes (heading_span + complete span),
  anchors, state-bearing references, calls, resources and diagnostics; the old
  revision-3 shape is rejected with a rebuild hint.
- Observation v1: one run/call --output jsonl stream (+ atomic
  --observation-file snapshot) decoded by one decoder and projected into the
  reader/SSE/export layers; stale/malformed/truncated/incomplete never render
  as success.
- CLI Tool revision 1: requires {api_revision:1, analysis:3, observation:1},
  product range >=3.0.0-rc.3,<4.0.0, only MARQDO_BIN and
  MARQDO_API_REVISION are consumed.
- Remove compatibility branches, retired flags/env vars and duplicate decoders;
  re-record Analysis v3 and Observation v1 fixtures; rewrite contract,
  integration and security tests (173 passing locally).
- Add check-no-legacy/check-docs/check-observation gates, rc.4 pins in the
  CI pipelines, 0.3.0 Tool bundle and evidence manifest support.

See issues #4, #5 and #6; acceptance baseline is CLI source
452e9a32bd9e40dba427d4180691c58bab74449e, archive
9c3f166b5e5b8840d39d10019074e4e1c42432fc23e26c69670e64fdcf4e15d8.
2026-11-25 22:12:51 +08:00
cflmy 7b34199c96 docs: record complete-reader acceptance and usage
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-24 14:51:24 +08:00
cflmy 748e1cc491 test: verify partial archive writes are cleaned up 2026-11-24 14:46:05 +08:00
cflmy bbdfec2174 test: cover snapshot integrity, disconnects and timeout isolation 2026-11-24 14:41:40 +08:00
cflmy 5740362880 test: finalize reader snapshots against the published Core 2026-11-24 14:22:14 +08:00
cflmy a482df80be feat: preview and download selected results from the reader 2026-11-24 14:03:27 +08:00
cflmy aa2a2b3ce4 feat: export one source-bound session result as a static ZIP 2026-11-24 13:43:27 +08:00
cflmy 3081581b0b feat: package reader media and fonts in the existing static exporter 2026-11-24 13:27:42 +08:00
cflmy b6962b2b38 feat: place calls and current results beside the function 2026-11-24 13:26:52 +08:00
cflmy 07fa0d62a8 feat: render safe local media, MathML and Markdown anchors 2026-11-24 13:23:35 +08:00
cflmy 37291137eb feat: stream verified Core execution events over the View SSE channel 2026-11-24 13:15:27 +08:00
cflmy 4cf500fb58 feat: consume Analysis v3 alongside v2 2026-11-24 13:08:16 +08:00
cflmy 27532e7b4c docs: adopt complete-reader RFC and freeze the RC.2 fixture 2026-11-24 13:05:08 +08:00
cflmy dcb9daeaf4 Merge pull request '完成 RFC-VIEW-0002 并验收交互式 View' (#1) from rfc-view-0002 into master
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-22 21:44:57 +08:00
159 changed files with 19750 additions and 6135 deletions

No files matched your search

+48 -5
View File
@@ -5,10 +5,50 @@ on:
pull_request: pull_request:
workflow_dispatch: workflow_dispatch:
env:
CARGO_TERM_COLOR: always
RUST_MIN_STACK: "8388608"
jobs: jobs:
frozen-acceptance: no-legacy:
name: frozen CLI acceptance (Tool install / SSE / export / browser) name: no retired contracts (G01/G12)
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- 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
shell: bash
run: scripts/check-docs.sh
quality:
name: fmt / clippy / tests
runs-on: ubuntu-24.04
env:
CARGO_HOME: ${{ github.workspace }}/.cargo-home
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: dtolnay/rust-toolchain@stable
with:
toolchain: "1.89.0"
components: rustfmt, clippy
- uses: Swatinem/rust-cache@v2
- name: Format
run: cargo fmt --all -- --check
- name: Clippy
run: cargo clippy --locked --all-targets -- -D warnings
- name: Tests
run: cargo test --locked
frozen-acceptance:
name: frozen rc.4 acceptance (install / Observation / SSE / export / browser)
runs-on: ubuntu-24.04
needs: [no-legacy, quality]
env: env:
CARGO_TERM_COLOR: always CARGO_TERM_COLOR: always
RUST_MIN_STACK: "8388608" RUST_MIN_STACK: "8388608"
@@ -25,23 +65,26 @@ jobs:
- uses: actions/setup-node@v4 - uses: actions/setup-node@v4
with: with:
node-version: "22" node-version: "22"
- name: Fetch the official frozen core and verify its identity - name: Fetch the official frozen rc.4 CLI and verify its identity
shell: bash shell: bash
run: | run: |
set -euo pipefail set -euo pipefail
frozen="$(scripts/frozen-beta.sh fetch "$RUNNER_TEMP/marqdo-frozen")" frozen="$(scripts/frozen-beta.sh fetch "$RUNNER_TEMP/marqdo-frozen")"
echo "MARQDO_BIN=$frozen" >> "$GITHUB_ENV" echo "MARQDO_BIN=$frozen" >> "$GITHUB_ENV"
- name: Install Chromium and run the full acceptance gate - name: Install Chromium
run: | run: |
(cd tests/browser && npm ci --no-audit --no-fund) (cd tests/browser && npm ci --no-audit --no-fund)
(cd tests/browser && npx playwright install --with-deps chromium) (cd tests/browser && npx playwright install --with-deps chromium)
scripts/acceptance.sh - name: Run one-command acceptance (G01-G12)
run: scripts/acceptance.sh
- name: Upload acceptance evidence - name: Upload acceptance evidence
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
with: with:
name: view-evidence-${{ github.sha }} name: view-evidence-${{ github.sha }}
path: | path: |
docs/evidence/452e9a32bd9e40dba427d4180691c58bab74449e/manifest.json
dist/acceptance/manifest.json dist/acceptance/manifest.json
dist/acceptance/logs/
dist/marqdo-view-*.tar.gz dist/marqdo-view-*.tar.gz
dist/marqdo-view-*.tar.gz.sha256 dist/marqdo-view-*.tar.gz.sha256
if-no-files-found: error if-no-files-found: error
+12 -2
View File
@@ -1,4 +1,4 @@
# The published beta needs glibc 2.39. Use the matching Playwright image # The published rc.4 CLI needs glibc 2.39. Use the matching Playwright image
# so the installed-tool tests get both Ubuntu Noble and Chromium. # so the installed-tool tests get both Ubuntu Noble and Chromium.
when: when:
- event: [pull_request, manual] - event: [pull_request, manual]
@@ -6,11 +6,21 @@ when:
branch: master branch: master
steps: steps:
no-legacy:
image: mcr.microsoft.com/playwright:v1.49.0-noble
commands:
- apt-get update
- apt-get install -y --no-install-recommends ca-certificates curl git
- scripts/check-no-legacy.sh
- scripts/check-docs.sh
frozen-acceptance: frozen-acceptance:
image: mcr.microsoft.com/playwright:v1.49.0-noble image: mcr.microsoft.com/playwright:v1.49.0-noble
environment: environment:
PLAYWRIGHT_BROWSERS_PATH: /ms-playwright PLAYWRIGHT_BROWSERS_PATH: /ms-playwright
RUST_MIN_STACK: "8388608" RUST_MIN_STACK: "8388608"
CI: "true"
CI_SYSTEM: woodpecker
commands: commands:
- apt-get update - apt-get update
- apt-get install -y --no-install-recommends build-essential ca-certificates curl git python3 - apt-get install -y --no-install-recommends build-essential ca-certificates curl git python3
@@ -23,4 +33,4 @@ steps:
MARQDO_BIN="$(scripts/frozen-beta.sh fetch "$frozen_dir")" MARQDO_BIN="$(scripts/frozen-beta.sh fetch "$frozen_dir")"
export MARQDO_BIN export MARQDO_BIN
scripts/acceptance.sh scripts/acceptance.sh
cat dist/acceptance/manifest.json cat docs/evidence/452e9a32bd9e40dba427d4180691c58bab74449e/manifest.json
+84 -5
View File
@@ -2,12 +2,91 @@
All notable changes to `marqdo-view` are documented here. The format follows All notable changes to `marqdo-view` are documented here. The format follows
Keep a Changelog and the project uses SemVer for the View product version. Keep a Changelog and the project uses SemVer for the View product version.
Protocol axes (Tool v1, Analysis v2, Trace v2) are versioned separately. The current public protocol axes are versioned separately by the CLI: CLI Tool
revision 1 (`api_revision` 1), Analysis revision 3 and Observation revision 1.
`0.2.0` is the first release implementing RFC-VIEW-0002 end to end (SSE execution `0.3.0` is the one-step migration to the current pre-release contracts of
loop, 7-route Live API, controlled project grants and Trace-bound annotations). `marqdo 3.0.0-rc.4`. There is no compatibility layer for the retired formats:
The earlier `0.1.0` development line was never published; its verified reader / old code paths, fixtures and documents were replaced, not branched.
Analysis / export work is folded into this entry.
## [0.3.0] - 2026-11-25
### Added
- CLI Tool revision 1 manifest: `tool.json` now declares exact
`requires {api_revision: 1, analysis: 3, observation: 1}` with no
`compatibility` field; the bundle release info records the same `requires`
plus product range `>=3.0.0-rc.3,<4.0.0`.
- Observation v1 consumption: `run`/`call --output jsonl` is the live source and
`--observation-file` publishes the equivalent atomic snapshot. One decoder
validates schema/revision, `run_id`, contiguous `seq`, unique terminal event,
`observation.truncated`, source binding, module identity and UTF-8 half-open
spans. View SSE forwards/summarises the protocol sequence; it never
renumbers, reorders or synthesises events.
- Analysis v3 consumption through the ADR-0069 public boundary: one
`check --emit` artifact carries exact `source`, Markdown `document`, heading
scopes (`heading_span` + complete section `span`), `anchors`, functions,
imports, calls, resources, diagnostics and state-bearing references.
`inspect --ast` is no longer a machine source for rendering.
- Reference states `resolved`, `not_loaded`, `missing`, `ambiguous`, `external`,
`outside_scope` and `invalid`; `not_loaded` is rendered as "未核验", never as a
broken link, and `ambiguous` lists candidates instead of silently choosing one.
- `scripts/check-no-legacy.sh` (G01): fails on any retired protocol name,
retired run/call argv, Tool negotiation/migration, dual-state/fallback branch
or `schema_version` use in the reader across `src/`, `tool.json` and current
docs. Historical evidence and ADRs are exempt.
- `scripts/check-docs.sh` (G12): README/COMPATIBILITY/CHANGELOG/STATUS/ACCEPTANCE
must describe the rc.4 baseline; old CHANGELOG entries are allowed only under
the explicit `## History` heading.
- `scripts/check-observation.py`: machine probes for stream/snapshot
equivalence, truncation, exact Analysis binding and fail-closed retired input.
- `docs/architecture/observation-v1-and-analysis-v3.md`: final layering
(CLI adapter → decode/validate → domain projection → reader/execution/SSE/
export) with no version branch outside protocol modules.
- ADR-0012 records the rc.3 → rc.4 supersession: issue #5's rc.3 baseline is
superseded by issue #6's rc.4 public Analysis boundary; evidence pins the
rc.4 source/archive/binary SHAs.
### Changed
- Frozen CLI pin moved to `marqdo 3.0.0-rc.4`: source
`452e9a32bd9e40dba427d4180691c58bab74449e`, archive
`9c3f166b5e5b8840d39d10019074e4e1c42432fc23e26c69670e64fdcf4e15d8`, binary
`a7306962689c635445a59043971ea2eb09298e01feeee81f0ba07b1f3e10306e`.
- Acceptance manifest replaced by the issue #5 §0 schema
`marqdo.view.acceptance` revision 1: SHA-256-prefixed identities, frozen CLI
product/source/archive/binary, gates G01–G12 with
`state/command/exit_code/log`, and an explicit `unverified` list. A gate that
has not run is never recorded as PASS.
- Scripts (`frozen-beta`, `package`, `install-smoke`, `check-examples`,
`gen-golden`, `acceptance`, `test-*`, `acceptance-run.py`,
`test-complete-reader.py`) use the current flags and report the current
contracts; golden data moved to Analysis revision 3 and Observation revision 1
stream/snapshot fixtures.
- CI (`.github/workflows/ci.yml`, `.woodpecker.yml`) pins rc.4 through
`scripts/frozen-beta.sh` and adds a distinct blocking no-legacy job that runs
G01 and G12 before quality and acceptance.
- README, COMPATIBILITY, STATUS, ACCEPTANCE, CONFORMANCE and the frozen-CLI
contract audit now describe the current behavior; 0.2.0 material is marked
historical.
### Fixed
- Values are never fabricated: the protocol supports explicit
`--observe-variable`/`--observe-parameter` (Text needs `--observe-text-values`),
but View 0.3.0 requests none by default and never displays memory or handles.
- Truncated or incomplete observation transport is displayed as
`TRUNCATED`/`未完成`, never as success. `UNSUPPORTED`, `PARTIAL` and `WARN`
are never written as `PASS`.
## History
## [Unreleased]
- Read safe project-local images, standard Markdown fragments and equations rendered as offline MathML.
- Consume Analysis v2/v3 and stream source-bound Execution Events v1 from the published RC.2 Core.
- Call functions beside their headings and inspect the current result inline.
- Download one selected, session-owned result as a script-free static ZIP after reviewing the included fields. Ordinary export retains its document-only behavior.
## [0.2.0] - 2026-11-22 ## [0.2.0] - 2026-11-22
+53 -32
View File
@@ -4,54 +4,75 @@
| 轴 | 本 View 值 | 说明 | | 轴 | 本 View 值 | 说明 |
|---|---|---| |---|---|---|
| View 产品版本 | `0.2.0` | 独立 SemVer,与 CLI 不共用 | | View 产品版本 | `0.3.0` | 独立 SemVer,与 CLI 不共用 |
| `marqdo` 产品范围 | `>=3.0.0-beta.1,<4.0.0` | 安装与分发时由 CLI 强制校验 | | `marqdo` 产品范围 | `>=3.0.0-rc.3,<4.0.0` | 预发布契约只在 rc.3 起有意义;验收固定 `3.0.0-rc.4` |
| CLI Tool Protocol | `1` | `tool.json` 清单/整包摘要/分发 | | CLI Tool revision | `1` | `tool.json`:`requires.api_revision = 1`,无 `compatibility` 字段 |
| Analysis | `2` | 未知 major 直接拒绝,不回退 | | Analysis revision | `3` | `marqdo.analysis`,ADR-0069 公共边界(含 source/document/anchors/references/heading_span) |
| Trace | `2` | 与 Analysis 精确字节摘要绑定 | | Observation revision | `1` | `marqdo.observation`,单一事件序列(JSONL 流 / 原子快照) |
| Markdown profile | `marqdo.md.v1` | 与冻结 CLI 相同选项集 | | Markdown profile | `marqdo.md.v1` | 与冻结 CLI 相同选项集 |
| 平台 | `linux-x86_64-glibc2.39` | 唯一正式验证平台 |
Beta 版 CLI 必须使用 prerelease 范围(`>=3.0.0-beta.1,<4.0.0`);`>=3.0.0,<4.0.0` **不匹配** `3.0.0-beta.1`。 当前契约:**Analysis 3**、**Observation 1**、CLI Tool **api_revision 1**。
`3.0.0-rc.3,<4.0.0` 是当前预发布范围;`>=3.0.0,<4.0.0` 不匹配任何 rc 预发布版。
验收与证据只认绑定 CLI 源码 SHA / 归档 SHA / 二进制 SHA 的结果:
`marqdo 3.0.0-rc.4`,源码 `452e9a32bd9e40dba427d4180691c58bab74449e`,
归档 `9c3f166b5e5b8840d39d10019074e4e1c42432fc23e26c69670e64fdcf4e15d8`,
二进制 `a7306962689c635445a59043971ea2eb09298e01feeee81f0ba07b1f3e10306e`。
## 契约替换(0.3.0 一次性完成)
| 边界 | 当前契约 | 消费方式 | 不符时行为 |
|---|---|---|---|
| 静态语义 | `check --emit` → Analysis revision 3 | 精确 UTF-8 字节 + `sha256:` 摘要;一次入口一次 emit | `view.protocol_incompatible`,显式提示重新生成/升级核心 |
| 运行事实 | Observation revision 1 | `run`/`call --output jsonl` 流;`--observation-file` 原子快照 | 拒绝;不重排、不重编号、不合成 |
| 源绑定 | `run.started.payload.source.{analysis_digest,root_id}` | 与同一次普通 `check --emit` 的精确字节摘要 + module/source_digest/UTF-8 半开 span 校验 | `view.observation_stale`;不显示成功、不做错误高亮 |
| Tool 清单 | `marqdo.cli-tool` / revision 1 | 精确 `requires {api_revision:1, analysis:3, observation:1}` | 安装失败;提示移除旧注册后重装 |
| 分发环境 | 只注入 `MARQDO_BIN` 与 `MARQDO_API_REVISION=1` | 仅静态期望校验,不据此协商 | 不读取、不阻塞;旧变量不存在 |
删除而非分支:树内没有第二解码器、双态类型、运行时版本探测、迁移器或“先兼容再清理”。
旧格式(含同 revision 的旧字段集合)只在 Git 历史与 CHANGELOG 的 History 段中保留。
## 平台 ## 平台
| 平台 | 状态 | 说明 | | 平台 | 状态 | 说明 |
|---|---|---| |---|---|---|
| Linux x86_64 (glibc 2.39+) | **Supported** | 完整验收使用官方 CLI Beta | | Linux x86_64 (glibc 2.39+) | **Supported** | 完整阅读、显式运行与导出使用官方 rc.4 验收;媒体需要 Linux 5.6+ |
| Linux aarch64 | 未构建 | 未验证 | | Linux aarch64 | 未构建 | 未验证 |
| macOS / Windows | 未验证 | 不声明支持;路径/进程组逻辑留有平台分支,但未做实测 | | macOS / Windows | 未验证 | 不声明支持 |
## 能力边界(诚实状态) ## 能力边界(诚实状态)
| 能力 | 状态 | | 能力 | 状态 |
|---|---| |---|---|
| 原始 Markdown 只读浏览(GFM 表/列表/引用/代码围栏/数学文本) | **已实现**(PR-02) | | 原始 Markdown 只读浏览(GFM 表/列表/引用/代码围栏/MathML/本地图片) | 已实现 |
| Analysis v2 静态语义(函数/Unit/诊断/引用/资源) | **已实现**(PR-02) | | Analysis revision 3 严格校验 + 函数/Unit/签名/诊断/引用/资源投影 | 已实现(拒绝旧同 revision 制品,无降级解码) |
| 文档态 / 源码态切换 | **已实现**(PR-02) | | heading_span 用于标题 UI;完整 span 用于 section 高亮/切片/归属 | 已实现 |
| 暖纸 Reader 视觉(单一 CSS/JS) | 已实现并经 Chromium 验收 | | 引用状态 resolved/not_loaded/missing/ambiguous/external/outside_scope/invalid | 已实现;`not_loaded` 显示“未核验”,不误报断链 |
| 用户显式触发运行 + SSE + Trace v2 事件可视化 | **已实现**(0002 PR-04;`pure`/受控 `project`,显式确认 + 会话 CSRF) | | 文档态 / 源码态切换 | 已实现 |
| Live 本机安全 API(7 路由) | **已实现**(0002 PR-04;Cookie/CSRF/Origin/CSP/单任务/SSE) | | 用户显式触发运行 + Observation v1 事件可视化 + SSE + 取消 + 断线重放 | 已实现(`pure`/受控 `project`,显式确认 + 会话 CSRF) |
| 静态离线导出(纯只读) | **已实现**(PR-05,同一渲染器) | | Live 本机安全 API(含媒体和 ZIP) | 已实现(Cookie/CSRF/Origin/CSP/单任务/SSE) |
| 逐语句变量值 / 参数实际值 / 内存快照 | **UNSUPPORTED**(Trace v2 不提供,绝不伪造) | | 静态离线导出 | 普通导出与显式单次结果 ZIP 共用渲染器 |
| 变量/参数值观测 | 协议支持;**View 默认不请求、不展示**(Text 需二次同意);内存/句柄永不发布 |
| 知识“已证明”状态 | **UNSUPPORTED**(需要独立 Prove 协议与证书) | | 知识“已证明”状态 | **UNSUPPORTED**(需要独立 Prove 协议与证书) |
| `project` 运行与 fs grants | **已实现(受控)**:仅相对项目根 read/write glob,显式二次确认;其它权限拒绝 | | `project` 运行与 fs grants | **已实现(受控)**:仅相对项目根 read/write glob,显式二次确认;其它权限拒绝 |
| SSE 状态推送 / 取消运行 / 事件重放 | **已实现**(逐帧 flush、心跳、Last-Event-ID、2 连接上限、无轮询) | | `strict` 运行 | 仅终端 text/JSON 快照;SSE 场景明确拒绝(`strict.unsupported_grant`),不回退 |
| SVG 曲线侧注 | **未实现**(运行事件用内联 keyed chip,U-04 PARTIAL) | | SVG 曲线侧注 | **未实现**(事件使用内联 keyed chip) |
| 调试器/断点/单步 | **不实现**(首版非目标) | | 调试器/断点/单步、Knowledge/Prove/Lint 引擎 | **不实现**(非目标) |
| Knowledge/Prove/Lint 引擎 | **不实现**(独立仓库/未来可选信息层) |
实际完成状态以 [`docs/STATUS.md`](docs/STATUS.md) 与 [`docs/ACCEPTANCE.md`](docs/ACCEPTANCE.md) 为准,本文不代替现状。RFC-VIEW-0002 §10 门禁已按真实冻结 CLI + Chromium 验收 PASS;本地证据见 `docs/evidence/`。 实际完成状态与机器证据以 [`docs/STATUS.md`](docs/STATUS.md) 与
[`docs/ACCEPTANCE.md`](docs/ACCEPTANCE.md) 为准。发布门禁 G01–G12 的
`PASS/FAIL/UNVERIFIED` 只来自 `docs/evidence/<CLI-SOURCE-SHA>/manifest.json`;
当前 0.3.0 证据生成前不得写成 PASS。
## 消费者契约 ## 消费者契约
- 未知 `schema_version` → `view.protocol_incompatible`,不回退猜测。 - 静态语义只来自一次 `check --emit`;`inspect --ast`/`inspect --ir` 仅人工调试,不是机器来源。
- `sha256(exact analysis.json bytes) == trace.source.analysis_digest`;不匹配 → `view.trace_stale`。 - `sha256(exact analysis.json bytes)` 必须等于 Observation `run.started.payload.source.analysis_digest`;
- `trace.source.root_id == analysis.project.root_id`;事件 `module_id` 必须存在于 Analysis。 `--refs` 检查改变字节,不能替代运行绑定。
- `trace.truncated != null` → `TRUNCATED`,不声明全部分支/循环已遍历。 - 事件 `module_id` 必须属于 Analysis `modules[]`;span 必须是该模块 source 的 UTF-8 半开字节区间。
- 运行只使用 `MARQDO_BIN` 子进程与公开 JSON;不链接 Core crate、不读 Core 源码、不依赖私有 IR。 - `capture.truncated`/`observation.truncated` 表示观测预算耗尽,不代表程序失败,也不得声明完整覆盖;
EOF 无终态 = 未完成/无结论,不得当成功。
## 官方 Beta 归档的标准库 - 运行只使用 `MARQDO_BIN` 子进程与公开契约;不链接 Core crate、不读 Core 源码、不依赖私有 IR
或包缓存物理路径。
`v3.0.0-beta.1` 的 Linux 归档未携带 `stdlib/`。View 的冻结验收示例使用 - 未知 `schema`/revision/kind → 显式拒绝;不猜测、不回退、不在失败后换旧参数重试。
该二进制公开的 Memory、stdout 和文件资源原语。含 `std:` 导入的项目由
所选 Core 校验,缺少标准库时由 View 展示 Core 的诊断。
Generated
+290 -1
View File
@@ -2,6 +2,12 @@
# It is not intended for manual editing. # It is not intended for manual editing.
version = 4 version = 4
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]] [[package]]
name = "anstream" name = "anstream"
version = "1.0.0" version = "1.0.0"
@@ -52,12 +58,39 @@ dependencies = [
"windows-sys", "windows-sys",
] ]
[[package]]
name = "arbitrary"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed"
dependencies = [
"derive_arbitrary",
]
[[package]] [[package]]
name = "ascii" name = "ascii"
version = "1.1.0" version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16" checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16"
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]] [[package]]
name = "block-buffer" name = "block-buffer"
version = "0.10.4" version = "0.10.4"
@@ -67,6 +100,24 @@ dependencies = [
"generic-array", "generic-array",
] ]
[[package]]
name = "bumpalo"
version = "3.20.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db"
[[package]]
name = "bytemuck"
version = "1.25.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
[[package]]
name = "byteorder-lite"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
[[package]] [[package]]
name = "caseless" name = "caseless"
version = "0.2.2" version = "0.2.2"
@@ -128,6 +179,12 @@ version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79"
[[package]]
name = "color_quant"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
[[package]] [[package]]
name = "colorchoice" name = "colorchoice"
version = "1.0.5" version = "1.0.5"
@@ -160,6 +217,15 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "crc32fast"
version = "1.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64"
dependencies = [
"cfg-if",
]
[[package]] [[package]]
name = "crypto-common" name = "crypto-common"
version = "0.1.7" version = "0.1.7"
@@ -170,6 +236,17 @@ dependencies = [
"typenum", "typenum",
] ]
[[package]]
name = "derive_arbitrary"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]] [[package]]
name = "digest" name = "digest"
version = "0.10.7" version = "0.10.7"
@@ -186,12 +263,27 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5320ae4c3782150d900b79807611a59a99fc9a1d61d686faafc24b93fc8d7ca" checksum = "b5320ae4c3782150d900b79807611a59a99fc9a1d61d686faafc24b93fc8d7ca"
[[package]]
name = "equivalent"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
[[package]] [[package]]
name = "fastrand" name = "fastrand"
version = "2.5.0" version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "fdeflate"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
dependencies = [
"simd-adler32",
]
[[package]] [[package]]
name = "fearless_simd" name = "fearless_simd"
version = "1.2.0" version = "1.2.0"
@@ -215,6 +307,17 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ded33109e99472f809cb7495544506eea45e366725dacf2a383e184f660456" checksum = "09ded33109e99472f809cb7495544506eea45e366725dacf2a383e184f660456"
[[package]]
name = "flate2"
version = "1.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
dependencies = [
"crc32fast",
"miniz_oxide 0.9.1",
"zlib-rs",
]
[[package]] [[package]]
name = "generic-array" name = "generic-array"
version = "0.14.7" version = "0.14.7"
@@ -225,6 +328,22 @@ dependencies = [
"version_check", "version_check",
] ]
[[package]]
name = "gif"
version = "0.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae047235e33e2829703574b54fdec96bfbad892062d97fed2f76022287de61b"
dependencies = [
"color_quant",
"weezl",
]
[[package]]
name = "hashbrown"
version = "0.17.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc"
[[package]] [[package]]
name = "heck" name = "heck"
version = "0.5.0" version = "0.5.0"
@@ -237,6 +356,44 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "image"
version = "0.25.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "529feb3e6769d234375c4cf1ee2ce713682b8e76538cb13f9fc23e1400a591e7"
dependencies = [
"bytemuck",
"byteorder-lite",
"color_quant",
"gif",
"image-webp",
"moxcms",
"num-traits",
"png",
"zune-core",
"zune-jpeg",
]
[[package]]
name = "image-webp"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"
dependencies = [
"byteorder-lite",
"quick-error",
]
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]] [[package]]
name = "is_terminal_polyfill" name = "is_terminal_polyfill"
version = "1.70.2" version = "1.70.2"
@@ -263,16 +420,21 @@ checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
[[package]] [[package]]
name = "marqdo-view" name = "marqdo-view"
version = "0.2.0" version = "0.3.0"
dependencies = [ dependencies = [
"base64",
"clap", "clap",
"comrak", "comrak",
"image",
"libc", "libc",
"pulldown-latex",
"roxmltree",
"semver", "semver",
"serde", "serde",
"serde_json", "serde_json",
"sha2", "sha2",
"tiny_http", "tiny_http",
"zip",
] ]
[[package]] [[package]]
@@ -291,6 +453,45 @@ dependencies = [
"fearless_simd_macros", "fearless_simd_macros",
] ]
[[package]]
name = "miniz_oxide"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "miniz_oxide"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "moxcms"
version = "0.7.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac9557c559cd6fc9867e122e20d2cbefc9ca29d80d027a8e39310920ed2f0a97"
dependencies = [
"num-traits",
"pxfm",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]] [[package]]
name = "once_cell_polyfill" name = "once_cell_polyfill"
version = "1.70.2" version = "1.70.2"
@@ -336,6 +537,19 @@ dependencies = [
"siphasher", "siphasher",
] ]
[[package]]
name = "png"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
dependencies = [
"bitflags",
"crc32fast",
"fdeflate",
"flate2",
"miniz_oxide 0.8.9",
]
[[package]] [[package]]
name = "proc-macro2" name = "proc-macro2"
version = "1.0.107" version = "1.0.107"
@@ -345,6 +559,27 @@ dependencies = [
"unicode-ident", "unicode-ident",
] ]
[[package]]
name = "pulldown-latex"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1cf850381ae0dbb131f36e31d6090f55363d079ab3e518ad0323b9cb6a96d115"
dependencies = [
"bumpalo",
]
[[package]]
name = "pxfm"
version = "0.1.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
[[package]]
name = "quick-error"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
[[package]] [[package]]
name = "quote" name = "quote"
version = "1.0.47" version = "1.0.47"
@@ -354,6 +589,15 @@ dependencies = [
"proc-macro2", "proc-macro2",
] ]
[[package]]
name = "roxmltree"
version = "0.21.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907"
dependencies = [
"memchr",
]
[[package]] [[package]]
name = "rustc-hash" name = "rustc-hash"
version = "2.1.3" version = "2.1.3"
@@ -420,6 +664,12 @@ dependencies = [
"digest", "digest",
] ]
[[package]]
name = "simd-adler32"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
[[package]] [[package]]
name = "siphasher" name = "siphasher"
version = "1.0.4" version = "1.0.4"
@@ -506,6 +756,12 @@ version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "weezl"
version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
[[package]] [[package]]
name = "windows-link" name = "windows-link"
version = "0.2.1" version = "0.2.1"
@@ -521,8 +777,41 @@ dependencies = [
"windows-link", "windows-link",
] ]
[[package]]
name = "zip"
version = "4.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1"
dependencies = [
"arbitrary",
"crc32fast",
"indexmap",
"memchr",
]
[[package]]
name = "zlib-rs"
version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
[[package]] [[package]]
name = "zmij" name = "zmij"
version = "1.0.23" version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zune-core"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a"
[[package]]
name = "zune-jpeg"
version = "0.4.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29ce2c8a9384ad323cf564b67da86e21d3cfdff87908bc1223ed5c99bc792713"
dependencies = [
"zune-core",
]
+7 -2
View File
@@ -1,10 +1,10 @@
[package] [package]
name = "marqdo-view" name = "marqdo-view"
version = "0.2.0" version = "0.3.0"
edition = "2021" edition = "2021"
rust-version = "1.89" rust-version = "1.89"
license = "MIT OR Apache-2.0" license = "MIT OR Apache-2.0"
description = "Marqdo View: read .mq.md documents as documents, with optional verified Analysis v2 and Trace v2" description = "Marqdo View: read .mq.md documents as documents, with optional verified Analysis v3 and Observation v1"
repository = "https://github.com/cflmy/marqdo-view" repository = "https://github.com/cflmy/marqdo-view"
readme = "README.md" readme = "README.md"
keywords = ["marqdo", "markdown", "reader", "executable-document"] keywords = ["marqdo", "markdown", "reader", "executable-document"]
@@ -27,6 +27,10 @@ name = "integration"
path = "tests/integration/main.rs" path = "tests/integration/main.rs"
[dependencies] [dependencies]
base64 = "0.22"
image = { version = "=0.25.8", default-features = false, features = ["png", "jpeg", "webp", "gif"] }
pulldown-latex = "=0.8.0"
roxmltree = "0.21"
clap = { version = "4.5", features = ["derive"] } clap = { version = "4.5", features = ["derive"] }
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
@@ -34,6 +38,7 @@ sha2 = "0.10"
comrak = { version = "=1.0.0", default-features = false } comrak = { version = "=1.0.0", default-features = false }
semver = "1" semver = "1"
tiny_http = "0.12" tiny_http = "0.12"
zip = { version = "=4.6.1", default-features = false }
[target.'cfg(unix)'.dependencies] [target.'cfg(unix)'.dependencies]
libc = "0.2" libc = "0.2"
+84 -60
View File
@@ -1,54 +1,71 @@
# marqdo-view # marqdo-view
Marqdo View(`0.2.0`)是一个独立的可执行文档阅读器:以**原始 Markdown 为阅读主体**,把冻结 Marqdo View(`0.3.0`)是一个独立的可执行文档阅读器:以**原始 Markdown 为阅读主体**,
`marqdo` CLI 的静态语义(Analysis v2)与用户显式触发的真实运行轨迹(Trace v2) 把冻结 `marqdo` CLI 的当前公开契约——Analysis revision 3(ADR-0069 公共边界)与
附着回原文,而不是把文档翻译成另一套语言。 Observation revision 1——附着回原文,而不是把文档翻译成另一套语言。
- 状态(唯一现状来源):[`docs/STATUS.md`](docs/STATUS.md) - 状态(唯一现状来源):[`docs/STATUS.md`](docs/STATUS.md)
- **实施规范(当前)**:[`docs/architecture/RFC-VIEW-0002.md`](docs/architecture/RFC-VIEW-0002.md) - **当前分层与契约**:[`docs/architecture/observation-v1-and-analysis-v3.md`](docs/architecture/observation-v1-and-analysis-v3.md)
- 0002 合规矩阵:[`docs/CONFORMANCE.md`](docs/CONFORMANCE.md) - 当前契约决策:[ADR-0012](docs/decisions/0012-rc4-current-contracts.md)
- 历史基础设计:[`docs/architecture/RFC-VIEW-0001.md`](docs/architecture/RFC-VIEW-0001.md) - 完整阅读与结果导出:[实施 RFC](docs/architecture/RFC-VIEW-0001-complete-reader.md) · [设计图](docs/design/complete-reader.png)
- 旧 View 静态审计:[`docs/audits/legacy-view.md`](docs/audits/legacy-view.md) - 验收标准与证据:[`docs/ACCEPTANCE.md`](docs/ACCEPTANCE.md) · [`docs/evidence/`](docs/evidence/README.md)
- 旧 0.2.0 基线(历史):[`docs/architecture/RFC-VIEW-0002.md`](docs/architecture/RFC-VIEW-0002.md)
- 冻结 CLI 合同审计:[`docs/audits/protocol-contract-0002.md`](docs/audits/protocol-contract-0002.md) - 冻结 CLI 合同审计:[`docs/audits/protocol-contract-0002.md`](docs/audits/protocol-contract-0002.md)
- 兼容性:[`COMPATIBILITY.md`](COMPATIBILITY.md) / 变更:[`CHANGELOG.md`](CHANGELOG.md) - 兼容性:[`COMPATIBILITY.md`](COMPATIBILITY.md) / 变更:[`CHANGELOG.md`](CHANGELOG.md)
- 决策记录:[`docs/decisions/`](docs/decisions/)
> **当前状态**:RFC-VIEW-0002 PR-00~PR-06 已完成,按 §10 发布门禁验收 > 0.3.0 只支持当前预发布契约:`marqdo 3.0.0-rc.4`(产品范围
> **PASS**(真实冻结 CLI + 真实 Chromium;见 > `>=3.0.0-rc.3,<4.0.0`;验收固定 rc.4)。静态语义只有一个来源
> [`docs/ACCEPTANCE.md`](docs/ACCEPTANCE.md) 与 > `check --emit`(Analysis revision 3,含精确 source、Markdown AST、heading 作用域、
> `docs/evidence/<CLI-SHA>/manifest.json`)。像素级人工比对与完整 > anchors 与状态化 references);运行事实只有一条 Observation revision 1 事件序列
> screen-reader 走查仍为 `UNVERIFIED`,见 `docs/STATUS.md`。 > (`run`/`call --output jsonl`,原子快照 `--observation-file`)。旧格式显式拒绝,
> 没有兼容分支、迁移器或运行时探测。
## 能力 ## 能力(0.3.0 实现范围)
> 下表的“实现”表示当前代码路径按 rc.4 契约实现;`PASS/FAIL/UNVERIFIED` 的机器
> 验收结论只以 [`docs/evidence/`](docs/evidence/README.md) 中绑定 CLI 源码 SHA 的
> manifest 为准。new manifest 生成前,全部发布门禁在 STATUS 中保持 `UNVERIFIED`。
| 能力 | 状态 | | 能力 | 状态 |
|---|---| |---|---|
| 原始 Markdown + GFM 阅读、源码态、文档态 | ✅ | | Markdown + GFM、源码态、项目图片、跨页锚点、离线数学 | 实现 |
| Analysis v2 静态语义(函数/Unit/签名/诊断/导入/引用/资源) | ✅ 严格校验,span 无效则降级 | | 单一静态源:`check --emit` Analysis revision 3(source/document/units/anchors/functions/calls/resources/diagnostics) | 实现;不读取 `inspect --ast` 作为机器来源 |
| 本机 Live 阅读(默认 `127.0.0.1`,只读 API + 显式执行端点) | ✅ | | heading_span(标题 UI/目录/锚点)与完整 span(section 高亮/切片/归属) | 实现 |
| 显式确认后运行 + SSE 状态/取消 + 真实 Trace v2 | ✅ 单任务、无轮询、断线重放 | | 引用状态 resolved / not_loaded / missing / ambiguous / external / outside_scope / invalid | 实现;`not_loaded` 显示“未核验”,不是断链 |
| 纯只读静态导出(离线 `file://`、manifest/哈希、原子发布) | ✅ | | 本机 Live 阅读(默认 `127.0.0.1`,只读 API + 显式执行端点) | 实现 |
| 单函数参数表单 + 受控 `project` fs grants | ✅ 参数来自 Analysis 签名;project 需显式 glob 二次确认 | | 显式确认后单次运行/调用;Observation v1 事件经 View SSE 转发/摘要 | 实现(单任务、取消、断线重放) |
| SSE 状态推送 / 取消 / 断线重放(禁止轮询) | ✅ `POST /api/runs` + `GET …/events` + `POST …/cancel` | | 只读静态导出(离线 `file://`、媒体/字体/哈希);普通导出与单次结果 ZIP | 实现 |
| 逐语句变量值 / 参数值 / 内存快照 | ❌ UNSUPPORTED(协议不提供,绝不伪造) | | 单函数参数表单 + 受控 `project` fs grants | 参数来自 Analysis 签名;project 需显式 glob 二次确认 |
| 知识“已证明” / Prove / Lint / 调试器 | ❌ 非目标/等待独立协议 | | 变量/参数值观测 | 协议支持 `--observe-variable`/`--observe-parameter`(Text 需 `--observe-text-values`);**View 默认不请求任何值**,绝不伪造变量值/内存状态 |
| 知识“已证明” / Prove / Lint / 调试器 | 非目标/等待独立协议 |
不变量:
- `TRUNCATED`、传输未完成(EOF 无终态)、`UNSUPPORTED`、`PARTIAL`、`WARN`
绝不写成成功/PASS;没有终态的流显示“未完成/无结论”。
- 每一条运行结论都绑定**同一次普通 `check --emit`** 的精确字节摘要;
带 `--refs` 的检查会改变字节,不能作为运行绑定。
- 协议事件只转发/摘要,View 自有 SSE 信封不重编号、不重排、不合成协议事件。
## 安装 ## 安装
```bash ```bash
# 1) 取得官方冻结 CLI 发布包(示例:本地已解包的 3.0.0-beta.1) # 1) 取得官方冻结 CLI 发布包(验收固定 3.0.0-rc.4)
MARQDO_BIN=/absolute/path/to/marqdo MARQDO_BIN=/absolute/path/to/marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu/marqdo
"$MARQDO_BIN" --version "$MARQDO_BIN" --version # marqdo 3.0.0-rc.4
# 2) 构建并制作 Tool v1 bundle # 2) 构建并制作 CLI Tool revision 1 bundle
./scripts/package.sh ./scripts/package.sh
# → dist/marqdo-view/tool.json + dist/marqdo-view/bin/marqdo-view # → dist/marqdo-view/tool.json + dist/marqdo-view/bin/marqdo-view
# 3) 安装为 `marqdo view` # 3) 安装为 `marqdo view`(旧安装请先 tool remove 后重装)
"$MARQDO_BIN" tool install "$(pwd)/dist/marqdo-view/tool.json" "$MARQDO_BIN" tool install "$(pwd)/dist/marqdo-view/tool.json"
"$MARQDO_BIN" view --help "$MARQDO_BIN" view --help
``` ```
`tool.json` 只声明精确要求:`requires {api_revision: 1, analysis: 3, observation: 1}`,
没有 `compatibility` 字段,也没有版本协商或迁移。
## 使用 ## 使用
```bash ```bash
@@ -60,7 +77,7 @@ marqdo view examples/control-flow --port 0 --no-open
marqdo view verify examples/mixed-modes/index.mq.md marqdo view verify examples/mixed-modes/index.mq.md
marqdo view verify examples/mixed-modes --refs --json marqdo view verify examples/mixed-modes --refs --json
# RFC §13.3 示例(可检查/调用/运行;无隐式执行) # 显式触发(只有页面确认后才 POST /api/runs)
marqdo view examples/function-params.mq.md --no-open marqdo view examples/function-params.mq.md --no-open
marqdo view examples/unsafe-side-effect.mq.md --no-open marqdo view examples/unsafe-side-effect.mq.md --no-open
@@ -70,7 +87,7 @@ marqdo view export examples/mixed-modes --out ./site --no-annotations
``` ```
开发期可直接运行 `marqdo-view`(用 `--marqdo-bin` 指定冻结核心)。运行只有一个入口: 开发期可直接运行 `marqdo-view`(用 `--marqdo-bin` 指定冻结核心)。运行只有一个入口:
Live 页面点击 Dock “运行”(执行 `main`)或函数面板的“调用”(执行 `call`), Live 页面点击 Dock “运行”(执行 `main`)或函数标题旁的“调用”(执行 `call`),
阅读命令预览与权限说明后点击“确认执行”,服务端才 `POST /api/runs` 启动一个 阅读命令预览与权限说明后点击“确认执行”,服务端才 `POST /api/runs` 启动一个
CLI 子进程;状态与结果通过 SSE 推送,可取消,断线可重放。页面刷新/打开/搜索/ CLI 子进程;状态与结果通过 SSE 推送,可取消,断线可重放。页面刷新/打开/搜索/
切换/导出都不会运行,也没有状态轮询。 切换/导出都不会运行,也没有状态轮询。
@@ -86,7 +103,13 @@ ReaderRenderer(唯一模板,Live/Export 共用)
│ │
PresentationModel(reader::assemble / reader::model) PresentationModel(reader::assemble / reader::model)
│ │
CoreClient ─ MARQDO_BIN 子进程 + 公开 JSON(check --emit / run/call --trace-file) CLI 适配层(唯一知道 argv / 环境变量 / 退出码语义)
├─ check --emit → Analysis revision 3 精确字节
└─ run|call --output jsonl [--observation-file] → Observation revision 1 流/快照
│
解码 + 结构校验(protocol 模块:schema/revision/必需字段/seq/终态/预算)
│
规范化领域模型(Analysis / Observation / RunBinding;无 CLI 细节、无版本分支)
│ │
ExecutionController ─ 单任务、取消、SSE 事件(仅 POST /api/runs 可达) ExecutionController ─ 单任务、取消、SSE 事件(仅 POST /api/runs 可达)
│ │
@@ -94,11 +117,8 @@ ExecutionController ─ 单任务、取消、SSE 事件(仅 POST /api/runs 可
``` ```
- 单一 Rust package、单一渲染入口、单一主题文件;没有第二个 Markdown→语义管线。 - 单一 Rust package、单一渲染入口、单一主题文件;没有第二个 Markdown→语义管线。
- 服务端只有 7 条固定路由;SSE 只推送 View 自有 `run.*` 生命周期事件。 - 协议模块之外没有 `schema_version` 判断;协议模块内只有当前 revision 一个分支。
- Analysis v2 是唯一语义权威:函数/语句/分支/循环/诊断均来自 `check --emit`, - JSONL 流与原子快照共用同一解码器与领域类型;生产不“双读合并”,一致性只在测试中断言。
源码字节 span 只用于绑定视觉位置。
- Trace v2 与 Analysis 字节摘要严格绑定;`STALE/TRUNCATED/FAILED/UNSUPPORTED`
状态显式呈现,不猜测未公开值。
- Live/Export 内容同源;导出绝不执行、绝不覆盖项目源文件或无关目录。 - Live/Export 内容同源;导出绝不执行、绝不覆盖项目源文件或无关目录。
- 门禁:`tests/contract/no_coupling.rs` 拒绝旧 crate/源码依赖、第二套渲染器/主题、shell 执行; - 门禁:`tests/contract/no_coupling.rs` 拒绝旧 crate/源码依赖、第二套渲染器/主题、shell 执行;
`tests/contract/asset_integrity.rs` 锁定内嵌资产与唯一主题层; `tests/contract/asset_integrity.rs` 锁定内嵌资产与唯一主题层;
@@ -109,48 +129,52 @@ ExecutionController ─ 单任务、取消、SSE 事件(仅 POST /api/runs 可
```bash ```bash
export PATH="$HOME/.cargo/bin:$PATH" export PATH="$HOME/.cargo/bin:$PATH"
cargo fmt --all -- --check cargo fmt --all -- --check
cargo clippy --all-targets -- -D warnings cargo clippy --locked --all-targets -- -D warnings
cargo test --locked cargo test --locked
cargo build --release --locked scripts/check-no-legacy.sh # G01:当前树 0 条旧契约残留(cmd 可单独跑)
scripts/check-docs.sh # G12:当前文档不把旧格式写成当前能力
``` ```
全链路验收使用 Rust 1.89 或更新版本,以及能运行官方 Beta 的 Linux x86_64 全链路验收使用 Rust 1.89 或更新版本,以及能运行官方 rc.4 的 Linux x86_64
环境(glibc 2.39 起)。浏览器、显式运行和离线导出通过已安装的 Tool 执行。 环境(glibc 2.39 起)。浏览器、显式运行和离线导出通过已安装的 Tool 执行。
```bash ```bash
(cd tests/browser && npm ci && PLAYWRIGHT_BROWSERS_PATH="$PWD/../.cache/pw-browsers" npx playwright install chromium) (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)")" MARQDO_BIN="$(./scripts/frozen-beta.sh fetch "$(mktemp -d)")"
export MARQDO_BIN export MARQDO_BIN
./scripts/acceptance.sh ./scripts/acceptance.sh # G01–G12,写 docs/evidence/452e9a32…/manifest.json
cat dist/acceptance/manifest.json cat docs/evidence/452e9a32bd9e40dba427d4180691c58bab74449e/manifest.json
``` ```
也可将 `MARQDO_BIN` 指向已解包的官方 Beta。验收核对源码 SHA 和二进制 验收会核对 CLI 源码 SHA、归档 SHA-256 与二进制 SHA-256,并在前后两次记录 CLI 摘要。
SHA-256。 未实际运行、无法在本环境判定的门禁记为 `UNVERIFIED`,不会写成 `PASS`。
单独套件: 单独套件:
```bash ```bash
MARQDO_BIN=... ./scripts/check-examples.sh # RFC §13.3 示例真实 check/call/run MARQDO_BIN=... ./scripts/check-examples.sh # 示例的真实 check/call/run(Observation v1)
MARQDO_BIN=... ./scripts/test-no-exec.sh # 打开/导出零副作用哨兵 MARQDO_BIN=... ./scripts/test-no-exec.sh # 打开/导出零副作用哨兵
MARQDO_BIN=... ./scripts/test-contract.sh # code + Tool v1 + verify + export MARQDO_BIN=... ./scripts/test-contract.sh # code + Tool revision 1 + verify + export
MARQDO_BIN=... ./scripts/test-export.sh # 纯只读导出 + file:// Chromium MARQDO_BIN=... ./scripts/test-export.sh # 纯只读导出 + file:// Chromium
./scripts/test-security.sh # HTTP/路径/XSS/导出对抗 ./scripts/test-security.sh # HTTP/路径/XSS/导出对抗
(cd tests/browser && npm install && PLAYWRIGHT_BROWSERS_PATH="$PWD/../.cache/pw-browsers" npx playwright install chromium) MARQDO_BIN=... ./scripts/test-browser.sh # 真实 Chromium 视觉/交互/响应式/运行
MARQDO_BIN=... ./scripts/test-browser.sh # 真实 Chromium 视觉/交互/响应式/运行
``` ```
协议 golden 由冻结 CLI 生成,见 `tests/golden/README.md` 与 `scripts/gen-golden.sh`。 协议 golden 由冻结 CLI 生成,见 `tests/golden/README.md` 与 `scripts/gen-golden.sh`
(Analysis revision 3 + Observation revision 1 流/快照)。
## 已知限制(诚实状态) ## 已知限制(诚实状态)
- 运行仅 `pure`(默认)与受控 `project` fs read/write;`strict`、网络/进程/环境/ - 运行仅 `pure`(默认)与受控 `project` fs read/write;`strict` 只支持 text/JSON
plugin/provider/kernel 授权不在首版 UI,必须使用终端 CLI。 快照,`--output jsonl` 与 `--observation-file` 在启动前被 CLI 拒绝(exit 2,
`strict.unsupported_grant`),View 不伪装、不回退到 `project`。
- `project` 不是 OS 沙箱;View 不继承 `marqdo.yaml` 的 capability 请求。 - `project` 不是 OS 沙箱;View 不继承 `marqdo.yaml` 的 capability 请求。
- SSE 只推送 View 生命周期与终态数据,不承诺逐字 stdout/Token 流;Trace v2 不含 - 变量/参数值:协议支持显式选择(`--observe-variable`/`--observe-parameter`,
参数实际值/逐语句变量/内存快照。 Text 需 `--observe-text-values`),但 0.3.0 的 View **默认不请求、不展示**;
- 平台:仅 Linux x86_64 正式验证;Windows/macOS 不支持声明。 内存/资源/句柄永不发布。
- 远端 CI 配置已提供(`.github/workflows/ci.yml`),本环境未实际运行远端 CI; - `not_loaded` 引用只表示当前 catalog 未核验,不是断链;需要 `check --refs`
验收证据来自本地真实命令。 才能核验普通本地链接,且 `--refs` 的字节摘要不能用于运行绑定。
- 像素级人工视觉比对与完整 screen-reader 走查为 `UNVERIFIED`(自动化几何/响应式/ - 平台:仅 Linux x86_64 / glibc 2.39 正式验证;Windows/macOS 不支持声明。
无外部资源/无 JS/打印证据见 `docs/evidence/PR-04/`)。 - 远端 CI 配置已提供(`.github/workflows/ci.yml`、`.woodpecker.yml`),本环境
未实际运行远端 CI;未运行的门禁在 evidence 中保持 `UNVERIFIED`。
- 像素级人工视觉比对与完整 screen-reader 走查为 `UNVERIFIED`。
Binary file not shown.
+155
View File
@@ -0,0 +1,155 @@
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: Noto
Upstream-Contact: https://github.com/googlei18n/noto-fonts/issues
http://groups.google.com/group/noto-font
Source: https://github.com/googlei18n/noto-fonts
Files: *
Copyright:
2010,2012-2020, Google Inc.
2015-2020, Google LLC.
License-Grant:
This Font Software is licensed under the SIL Open Font License,
Version 1.1.
License: OFL-1.1
Files:
debian/*
Copyright:
2013-2020, Jonas Smedegaard <dr@jones.dk>
2020, Purism, SPC
2013, Vasudev Kamath <kamathvasudev@gmail.com>
License-Grant:
This program is free software;
you can redistribute it and/or modify it
under the terms of the GNU General Public License
as published by the Free Software Foundation;
either version 3, or (at your option) any later version.
License: GPL-3+
Files:
debian/NotoMono/NotoMono-Regular.ttf
Copyright:
2007, Google Inc.
License-Grant:
This Font Software is licensed under the SIL Open Font License,
Version 1.1.
License: OFL-1.1
License: OFL-1.1
PREAMBLE
.
The goals of the Open Font License (OFL) are to stimulate
worldwide development of collaborative font projects,
to support the font creation efforts
of academic and linguistic communities,
and to provide a free and open framework
in which fonts may be shared and improved
in partnership with others.
.
The OFL allows the licensed fonts to be used, studied,
modified and redistributed freely
as long as they are not sold by themselves.
The fonts, including any derivative works,
can be bundled, embedded,
redistributed and/or sold with any software
provided that any reserved names are not used
by derivative works.
The fonts and derivatives, however,
cannot be released under any other type of license.
The requirement for fonts to remain under this license
does not apply to any document
created using the fonts or their derivatives.
.
DEFINITIONS
.
"Font Software" refers to the set of files
released by the Copyright Holder(s) under this license
and clearly marked as such.
This may include source files, build scripts and documentation.
.
"Reserved Font Name" refers to any names specified as such
after the copyright statement(s).
.
"Original Version" refers to the collection
of Font Software components
as distributed by the Copyright Holder(s).
.
"Modified Version" refers to any derivative
made by adding to, deleting, or substituting --
in part or in whole --
any of the components of the Original Version,
by changing formats
or by porting the Font Software to a new environment.
.
"Author" refers to any designer, engineer, programmer,
technical writer or other person
who contributed to the Font Software.
.
PERMISSION & CONDITIONS
.
Permission is hereby granted, free of charge,
to any person obtaining a copy of the Font Software,
to use, study, copy, merge, embed, modify, redistribute,
and sell modified and unmodified copies of the Font Software,
subject to the following conditions:
.
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions,
may be sold by itself.
.
2) Original or Modified Versions of the Font Software
may be bundled, redistributed and/or sold with any software,
provided that each copy contains the above copyright notice
and this license.
These can be included either as stand-alone text files,
human-readable headers or in the appropriate
machine-readable metadata fields within text or binary files
as long as those fields can be easily viewed by the user.
.
3) No Modified Version of the Font Software may use
the Reserved Font Name(s)
unless explicit written permission is granted
by the corresponding Copyright Holder.
This restriction only applies to the primary font name
as presented to the users.
.
4) The name(s) of the Copyright Holder(s)
or the Author(s) of the Font Software
shall not be used to promote,
endorse or advertise any Modified Version,
except to acknowledge the contribution(s)
of the Copyright Holder(s) and the Author(s)
or with their explicit written permission.
.
5) The Font Software,
modified or unmodified, in part or in whole,
must be distributed entirely under this license,
and must not be distributed under any other license.
The requirement for fonts to remain under this license
does not apply to any document
created using the Font Software.
.
TERMINATION
.
This license becomes null and void
if any of the above conditions are not met.
.
DISCLAIMER
.
THE FONT SOFTWARE IS PROVIDED "AS IS",
WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO
ANY WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT.
IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT,
INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF THE USE OR INABILITY TO USE
THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
License: GPL-3+
License-Reference: /usr/share/common-licenses/GPL-3
+176
View File
@@ -1370,3 +1370,179 @@
overflow-wrap: anywhere; overflow-wrap: anywhere;
} }
} }
@font-face {
font-family: "Noto Sans Math";
src: url("__MATH_FONT__") format("truetype");
font-display: swap;
}
@layer typography {
.mq-document-image { max-inline-size: 100%; block-size: auto; }
.mq-heading-anchor { display: block; }
.mq-document math { font-family: "Noto Sans Math", math; }
}
@layer semantics {
.mq-document h2 .mq-fn-call {
margin-inline-start: .8rem;
vertical-align: middle;
border-color: var(--mq-gold);
color: var(--mq-focus);
}
.mq-result-slot:empty { display: none; }
.mq-result-slot .mq-run-panel {
border-color: var(--mq-olive);
background: var(--mq-surface);
margin-block: 1.25rem 1.75rem;
}
.mq-run-panel > summary {
cursor: pointer;
font-weight: 650;
color: var(--mq-olive);
margin-block-end: .6rem;
}
.mq-run-panel[hidden] { display: none; }
}
@layer semantics {
.mq-snapshot, .mq-snapshot-notice, .mq-static-source {
background: var(--mq-surface);
border: 1px solid var(--mq-line);
border-radius: .65rem;
padding: .9rem 1rem;
margin-block: 1.25rem;
}
.mq-snapshot {
border-color: var(--mq-olive);
overflow-wrap: anywhere;
}
.mq-snapshot > summary, .mq-static-source > summary {
font-weight: 650;
cursor: pointer;
}
.mq-snapshot pre, .mq-static-source pre {
white-space: pre-wrap;
overflow-wrap: anywhere;
font: .9rem/1.55 var(--mq-mono);
}
.mq-snapshot-counts {
display: grid;
grid-template-columns: minmax(0, 2fr) 1fr;
}
.mq-snapshot-counts dd { margin: 0; }
}
@layer overlays {
.mq-export-dialog {
max-inline-size: min(36rem, calc(100vw - 2rem));
max-block-size: calc(100dvh - 2rem);
overflow: auto;
}
.mq-export-target {
background: var(--mq-surface-2);
border: 1px solid var(--mq-line);
border-radius: .45rem;
padding: .65rem .85rem;
}
.mq-export-fields {
padding: 0;
border: 0;
margin: 0 0 1rem;
min-inline-size: 0;
}
.mq-export-fields legend { font-weight: 650; }
.mq-export-fields label {
display: grid;
grid-template-columns: 1.25rem minmax(0, 1fr) auto;
align-items: center;
gap: .55rem;
border-block-start: 1px solid var(--mq-line);
padding: .65rem 0 .4rem;
}
.mq-export-fields small { color: var(--mq-muted); }
.mq-export-fields details {
margin-inline-start: 1.8rem;
margin-block-end: .6rem;
font-size: .86rem;
}
.mq-export-fields pre {
white-space: pre-wrap;
overflow-wrap: anywhere;
overflow: auto;
max-block-size: 12rem;
background: var(--mq-surface-2);
padding: .65rem;
}
.mq-export-confirm { display: block; margin-block: .75rem; }
.mq-export-confirm[hidden], .mq-export-result[hidden] { display: none; }
.mq-export-result { margin-block-start: .75rem; }
#mq-export-error { color: var(--mq-error); }
}
@layer layout {
.mq-snapshot-topbar .mq-brand { grid-column: 2; }
}
@layer overlays {
.mq-export-dialog input[type="checkbox"] { accent-color: var(--mq-gold); }
.mq-export-dialog button[disabled] { opacity: .55; cursor: default; }
}
@layer semantics {
.mq-snapshot-notice a { color: var(--mq-focus); }
}
@layer semantics {
/* Reference resolution states (Analysis v3). `not_loaded` is unverified,
never a broken link; only real errors use the error colour. */
.mq-link-unverified {
text-decoration: underline dotted;
text-underline-offset: 0.18em;
cursor: help;
}
.mq-link-unverified::after {
content: "(未核验)";
font: 10px/1 var(--mq-mono);
color: var(--mq-warn);
vertical-align: 0.35em;
}
.mq-link-error {
color: var(--mq-error);
text-decoration: underline wavy;
cursor: help;
}
.mq-run-status[data-run-state="incomplete"] {
color: var(--mq-warn);
}
.mq-run-chip[data-annotation-source="observation"] {
border-color: color-mix(in srgb, var(--mq-focus) 40%, var(--mq-line));
color: var(--mq-focus);
}
.mq-truncated-badge {
display: inline-block;
margin-inline-start: .4rem;
padding: 0 .45rem;
border-radius: 999px;
background: color-mix(in srgb, var(--mq-warn) 18%, var(--mq-surface));
color: var(--mq-warn);
font: 11px/1.6 var(--mq-mono);
}
}
+223 -21
View File
@@ -291,8 +291,8 @@
case "unsupported": case "unsupported":
showUnsupported( showUnsupported(
"变量快照 / 内存检查 / 调试器 / 证明状态", "变量快照 / 内存检查 / 调试器 / 证明状态",
"Trace v2 不提供逐语句赋值后的实际值或内存快照,公开协议也没有断点/单步通道;" + "Observation v1 支持显式请求 --observe-variable / --observe-parameter,但 View 默认不请求任何变量或参数值;" +
"知识证明属于独立 Prove 工具。View 绝不猜测这些运行事实,相应能力在具备公开、受版本约束的协议前不会出现。" "它不提供内存快照、断点或单步通道;知识证明属于独立 Prove 工具。View 绝不猜测这些运行事实。"
); );
break; break;
case "theme": case "theme":
@@ -310,6 +310,12 @@
case "cancel-run": case "cancel-run":
cancelRun(); cancelRun();
break; break;
case "export-result":
openExportPreview();
break;
case "download-result":
downloadSnapshot();
break;
case "call-function": case "call-function":
if (trigger) { if (trigger) {
var params = []; var params = [];
@@ -372,12 +378,13 @@
case "cancelled": return "已取消"; case "cancelled": return "已取消";
case "timed_out": return "超时"; case "timed_out": return "超时";
case "unavailable": return "不可用"; case "unavailable": return "不可用";
case "incomplete": return "事件流不完整";
default: return String(state || "未知"); default: return String(state || "未知");
} }
} }
function isTerminalState(state) { function isTerminalState(state) {
return ["succeeded", "failed", "cancelled", "timed_out", "unavailable"].indexOf(state) >= 0; return ["succeeded", "failed", "cancelled", "timed_out", "unavailable", "incomplete"].indexOf(state) >= 0;
} }
function runPanel() { function runPanel() {
@@ -408,6 +415,7 @@
button.disabled = false; button.disabled = false;
} }
} }
$$(".mq-fn-call[data-action=call-function]").forEach(function (call) { call.disabled = busy; });
var cancel = $("#mq-run-actions"); var cancel = $("#mq-run-actions");
if (cancel) cancel.hidden = !busy; if (cancel) cancel.hidden = !busy;
} }
@@ -429,7 +437,11 @@
if (stdout) stdout.hidden = true; if (stdout) stdout.hidden = true;
var stderr = $("#mq-run-stderr"); var stderr = $("#mq-run-stderr");
if (stderr) stderr.hidden = true; if (stderr) stderr.hidden = true;
var traceWrap = $("#mq-run-trace-wrap"); var exportButton = $("#mq-export-result");
if (exportButton) exportButton.hidden = true;
var traceTitle = $("#mq-run-observation-title");
if (traceTitle) traceTitle.textContent = "实时结构观察事件";
var traceWrap = $("#mq-run-observation-wrap");
if (traceWrap) traceWrap.hidden = true; if (traceWrap) traceWrap.hidden = true;
$$(".mq-run-chip[data-view-chip]").forEach(function (chip) { $$(".mq-run-chip[data-view-chip]").forEach(function (chip) {
chip.remove(); chip.remove();
@@ -473,12 +485,14 @@
var preview = $("#mq-run-command"); var preview = $("#mq-run-command");
if (!preview || !pendingRun) return; if (!preview || !pendingRun) return;
var mode = selectedMode(); var mode = selectedMode();
var args = ["--mode", mode, "--output", "jsonl", "--observation-file", "<临时文件>"];
var parts = []; var parts = [];
if (pendingRun.kind === "entry") { if (pendingRun.kind === "entry") {
parts = ["marqdo", "run", reader.dataset.document, "--mode", mode, "--json", "--trace-file", "<临时文件>"]; parts = ["marqdo", "run", reader.dataset.document].concat(args);
} else { } else {
parts = ["marqdo", "call", reader.dataset.document, "<函数 " + pendingRun.label + ">", "--mode", mode, "--json", "--trace-file", "<临时文件>"]; parts = ["marqdo", "call", reader.dataset.document, "<函数 " + pendingRun.label + ">"].concat(args);
rawParams().forEach(function (param) { rawParams().forEach(function (param) {
if (!param.required && param.expression.trim() === "") return;
parts.push("--arg"); parts.push("--arg");
parts.push(param.name + "=" + (param.expression || "<常量表达式>")); parts.push(param.name + "=" + (param.expression || "<常量表达式>"));
}); });
@@ -587,7 +601,9 @@
target: pendingRun.kind === "entry" target: pendingRun.kind === "entry"
? { kind: "entry" } ? { kind: "entry" }
: { kind: "function", function_id: pendingRun.functionId }, : { kind: "function", function_id: pendingRun.functionId },
parameters: params.map(function (param) { parameters: params.filter(function (param) {
return param.required || param.expression.trim() !== "";
}).map(function (param) {
return { name: param.name, expression: param.expression }; return { name: param.name, expression: param.expression };
}), }),
analysis_digest: reader.dataset.analysisDigest, analysis_digest: reader.dataset.analysisDigest,
@@ -597,6 +613,14 @@
}; };
closeAllDialogs(); closeAllDialogs();
clearRunOutput(); 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;
showRunPanel(); showRunPanel();
setRunBusy(true); setRunBusy(true);
setRunStatus("正在提交运行请求…"); setRunStatus("正在提交运行请求…");
@@ -622,7 +646,7 @@
toast("运行未启动:" + reason); toast("运行未启动:" + reason);
return; return;
} }
subscribeRun(result.data, pendingRun ? pendingRun.label : "运行"); subscribeRun(result.data, pendingRun ? pendingRun.label : "运行", payload.parameters);
}) })
.catch(function (error) { .catch(function (error) {
setRunBusy(false); setRunBusy(false);
@@ -631,7 +655,7 @@
}); });
} }
function subscribeRun(job, targetLabel) { function subscribeRun(job, targetLabel, parameters) {
closeActiveObserver(); closeActiveObserver();
activeRun = { activeRun = {
runId: job.run_id, runId: job.run_id,
@@ -640,6 +664,7 @@
source: null, source: null,
lastSeq: -1, lastSeq: -1,
targetLabel: targetLabel || "运行", targetLabel: targetLabel || "运行",
parameters: parameters,
terminal: false terminal: false
}; };
clearRunOutput(); clearRunOutput();
@@ -650,6 +675,7 @@
setRunStatus("浏览器不支持 EventSource,无法接收运行状态;请使用现代浏览器。"); setRunStatus("浏览器不支持 EventSource,无法接收运行状态;请使用现代浏览器。");
return; return;
} }
var decoders = { stdout: new TextDecoder(), stderr: new TextDecoder() };
var source = new EventSource(job.events_url, { withCredentials: true }); var source = new EventSource(job.events_url, { withCredentials: true });
activeRun.source = source; activeRun.source = source;
function apply(event) { function apply(event) {
@@ -659,7 +685,7 @@
} catch (error) { } catch (error) {
return; return;
} }
if (!data || if (!data || !activeRun || activeRun.runId !== job.run_id ||
data.schema !== "marqdo.view-run-events" || data.schema !== "marqdo.view-run-events" ||
data.schema_version !== 1 || data.schema_version !== 1 ||
data.run_id !== job.run_id || data.run_id !== job.run_id ||
@@ -668,9 +694,13 @@
return; return;
} }
activeRun.lastSeq = data.seq; activeRun.lastSeq = data.seq;
if (data.observation) {
renderObservation(data.observation, decoders);
return;
}
updateRunView(data); updateRunView(data);
} }
["run.state", "run.complete", "run.error", "run.snapshot"].forEach(function (kind) { ["run.state", "run.complete", "run.error", "run.snapshot", "run.observation"].forEach(function (kind) {
source.addEventListener(kind, apply); source.addEventListener(kind, apply);
}); });
source.onerror = function () { source.onerror = function () {
@@ -680,6 +710,28 @@
}; };
} }
function renderObservation(observation, decoders) {
var stream = observation.kind === "stdout.chunk" ? "stdout"
: observation.kind === "stderr.chunk" ? "stderr" : null;
if (stream) {
var output = $("#mq-run-" + stream);
if (!output) return;
var bytes = Uint8Array.from(atob(observation.data_base64), function (value) {
return value.charCodeAt(0);
});
output.append(document.createTextNode(decoders[stream].decode(bytes, { stream: true })));
output.hidden = false;
} else if (/^(branch|loop|control|call)\./.test(observation.kind)) {
var wrap = $("#mq-run-observation-wrap");
if (wrap) wrap.hidden = false;
var events = $("#mq-run-events");
if (events && events.childElementCount < 100) {
appendLine(events, "li", "", observation.kind +
(observation.decision === undefined ? "" : " · " + observation.decision));
}
}
}
function updateRunView(data) { function updateRunView(data) {
var panel = runPanel(); var panel = runPanel();
if (panel) { if (panel) {
@@ -692,17 +744,148 @@
setRunBusy(true); setRunBusy(true);
return; return;
} }
if (activeRun) activeRun.terminal = true; if (activeRun) {
activeRun.terminal = true;
activeRun.exportData = data.result && data.result.export_preview ? data : null;
var exportButton = $("#mq-export-result");
if (exportButton) exportButton.hidden = !activeRun.exportData;
}
closeActiveObserver(); closeActiveObserver();
setRunBusy(false); setRunBusy(false);
if (data.result) renderRunResult(data.result, data.state, data.error); if (data.result) renderRunResult(data.result, data.state, data.error);
else if (data.error) renderRunResult(null, data.state, data.error); else if (data.error) renderRunResult(null, data.state, data.error);
if (data.trace) renderTrace(data.trace); if (data.observation_summary) {
else if (data.result && data.result.trace_status) renderTraceStatus(data.result.trace_status); var traceTitle = $("#mq-run-observation-title");
if (traceTitle && data.observation_summary.status === "verified") traceTitle.textContent = "已验证的 Observation v1 事件";
renderTrace(data.observation_summary);
}
else if (data.result && data.result.observation_status) renderTraceStatus(data.result.observation_status);
if (data.state === "succeeded") toast("运行完成"); if (data.state === "succeeded") toast("运行完成");
else toast("运行" + stateLabel(data.state)); else toast("运行" + stateLabel(data.state));
} }
function previewBytes(text, count) {
if (!text || !count) return "";
return new TextDecoder().decode(new TextEncoder().encode(text).slice(0, count));
}
function exportNeedsPartial(data) {
var preview = data.result.export_preview;
return data.state !== "succeeded" || !preview.output_complete ||
!preview.result_complete || preview.observation_truncated ||
preview.observation_status === "truncated";
}
function updateExportConfirm() {
var button = $("#mq-export-download");
var data = activeRun && activeRun.exportData;
if (!button || !data) return;
button.disabled = button.dataset.busy === "true" || !$("#mq-export-confirm").checked ||
(exportNeedsPartial(data) && !$("#mq-export-partial").checked);
}
function openExportPreview() {
var data = activeRun && activeRun.exportData;
if (!data) return;
var result = data.result;
var preview = result.export_preview;
var fields = $("#mq-export-fields");
var counts = preview.observation_summary && data.observation_summary && data.observation_summary.counts;
var argumentsText = (activeRun.parameters || []).map(function (parameter) {
return parameter.name + " = " + parameter.expression;
}).join("\n");
$("#mq-export-target").textContent = preview.label + " · " + stateLabel(data.state) +
(exportNeedsPartial(data) ? " · 部分观察" : "");
fields.textContent = "";
[
["result_value", "返回值", preview.value_bytes, preview.value_is_public_scalar, preview.value],
["stdout", "stdout", preview.stdout_bytes, false, previewBytes(result.stdout, preview.stdout_bytes)],
["stderr", "stderr", preview.stderr_bytes, false, previewBytes(result.stderr, preview.stderr_bytes)],
["observation_summary", "观察摘要", counts ? new TextEncoder().encode(JSON.stringify(counts)).length : null, true, counts && JSON.stringify(counts, null, 2)],
["arguments", "已提交的参数", preview.arguments_count ? new TextEncoder().encode(argumentsText).length : null, false, argumentsText]
].forEach(function (field) {
var label = document.createElement("label");
var input = document.createElement("input");
input.type = "checkbox";
input.name = field[0];
input.disabled = !field[2];
input.checked = field[3] && !input.disabled;
label.appendChild(input);
appendLine(label, "span", "", field[1]);
appendLine(label, "small", "", field[2] ? field[2] + " B" : "无内容");
fields.appendChild(label);
if (field[4]) {
var disclosure = document.createElement("details");
appendLine(disclosure, "summary", "", "查看" + field[1]);
appendLine(disclosure, "pre", "", field[4]);
fields.appendChild(disclosure);
}
});
$("#mq-export-confirm").checked = false;
$("#mq-export-partial").checked = false;
$("#mq-export-partial-row").hidden = !exportNeedsPartial(data);
$("#mq-export-error").hidden = true;
updateExportConfirm();
openDialog("mq-dialog-export");
}
async function downloadSnapshot() {
var button = $("#mq-export-download");
var data = activeRun && activeRun.exportData;
if (!data || button.disabled) return;
var include = {};
$$("#mq-export-fields input").forEach(function (input) {
include[input.name] = input.checked;
});
var error = $("#mq-export-error");
error.hidden = true;
button.dataset.busy = "true";
updateExportConfirm();
try {
var response = await fetch("/api/exports", {
method: "POST",
credentials: "same-origin",
cache: "no-store",
headers: { "Content-Type": "application/json", "Accept": "application/zip", "X-View-CSRF": csrfToken() },
body: JSON.stringify({
schema: "marqdo.view-static-export-request",
schema_version: 1,
run_id: data.run_id,
document: data.result.document,
analysis_digest: data.result.analysis_digest,
scope: "document",
include: include,
confirm_sensitive_output: $("#mq-export-confirm").checked,
confirm_partial: $("#mq-export-partial").checked,
client_export_request_id: randomId()
})
});
if (!response.ok) {
var failure = await response.json();
throw new Error(failure.message || "导出请求未完成");
}
if (!(response.headers.get("Content-Type") || "").startsWith("application/zip")) {
throw new Error("服务返回的文件格式无效");
}
var url = URL.createObjectURL(await response.blob());
var link = document.createElement("a");
link.href = url;
link.download = "marqdo-execution-snapshot.zip";
document.body.appendChild(link);
link.click();
link.remove();
window.setTimeout(function () { URL.revokeObjectURL(url); }, 1000);
closeAllDialogs();
toast("执行快照已下载");
} catch (failure) {
error.textContent = failure.message;
error.hidden = false;
} finally {
delete button.dataset.busy;
updateExportConfirm();
}
}
function renderRunResult(result, state, error) { function renderRunResult(result, state, error) {
var summary = $("#mq-run-summary"); var summary = $("#mq-run-summary");
if (!summary) return; if (!summary) return;
@@ -717,9 +900,24 @@
if (result.value_text) { if (result.value_text) {
appendLine(summary, "p", "mq-run-result", "返回值:" + result.value_text); appendLine(summary, "p", "mq-run-result", "返回值:" + result.value_text);
} }
var observationState = result.observation_status;
if (observationState === "truncated") {
var badge = document.createElement("span");
badge.className = "mq-truncated-badge";
badge.textContent = "TRUNCATED";
appendLine(summary, "p", "mq-run-warning", "观察事件达到协议预算,已截断;本次结果不再宣称完整。");
summary.lastChild.appendChild(badge);
} else if (observationState === "invalid") {
appendLine(summary, "p", "mq-run-warning", "Observation 无效:不绘制任何执行标注,也不显示为成功。");
} else if (observationState === "stale") {
appendLine(summary, "p", "mq-run-warning", "Observation 与当前 Analysis 不匹配:结果标记为过期,不显示为成功。");
}
if (result.stale) { if (result.stale) {
appendLine(summary, "p", "mq-run-warning", "源码在运行后发生变化:结果可见但标记为过期,不在当前正文上绘制执行标注。"); appendLine(summary, "p", "mq-run-warning", "源码在运行后发生变化:结果可见但标记为过期,不在当前正文上绘制执行标注。");
} }
if (result.output_complete === false && observationState !== "truncated") {
appendLine(summary, "p", "mq-run-warning", "本次输出未完整交付(未完成/已被截断);不声明完整结果。");
}
if (result.stdout) { if (result.stdout) {
var stdout = $("#mq-run-stdout"); var stdout = $("#mq-run-stdout");
if (stdout) { if (stdout) {
@@ -759,14 +957,14 @@
var summary = $("#mq-run-summary"); var summary = $("#mq-run-summary");
if (!summary) return; if (!summary) return;
var message = status === "invalid" var message = status === "invalid"
? "Trace 与本次 Analysis 不匹配或格式无效:不绘制执行标注,也不声称观察到完整过程。" ? "Observation 与本次 Analysis 不匹配或格式无效:不绘制执行标注,也不声称观察到完整过程。"
: "本次运行没有可用的 Trace v2(unavailable):只展示 CLI 返回值与输出。"; : "本次运行没有可用的 Observation v1(unavailable):只展示 CLI 返回值与输出。";
appendLine(summary, "p", "mq-run-warning", message); appendLine(summary, "p", "mq-run-warning", message);
} }
function renderTrace(trace) { function renderTrace(trace) {
var summary = $("#mq-run-summary"); var summary = $("#mq-run-summary");
var wrap = $("#mq-run-trace-wrap"); var wrap = $("#mq-run-observation-wrap");
var list = $("#mq-run-events"); var list = $("#mq-run-events");
if (!wrap || !list) return; if (!wrap || !list) return;
list.textContent = ""; list.textContent = "";
@@ -778,11 +976,11 @@
wrap.hidden = false; wrap.hidden = false;
if (summary) { if (summary) {
if (trace.stale) { if (trace.stale) {
appendLine(summary, "p", "mq-run-warning", "Trace 属于运行时的源码:当前源码已变化,本次不绘制执行标注。"); appendLine(summary, "p", "mq-run-warning", "Observation 属于运行时的源码:当前源码已变化,本次不绘制执行标注。");
} }
if (trace.truncated) { if (trace.truncated) {
var label = trace.truncated.label || (trace.truncated.reason + "(上限 " + trace.truncated.limit + ")"); var label = trace.truncated.label || (trace.truncated.reason + "(上限 " + trace.truncated.limit + ")");
appendLine(summary, "p", "mq-run-warning", "Trace 被截断:" + label + ";这不代表程序终止。"); appendLine(summary, "p", "mq-run-warning", "Observation 被截断:" + label + ";这不代表程序终止。");
} }
} }
var entryEvents = Array.isArray(trace.events) ? trace.events : []; var entryEvents = Array.isArray(trace.events) ? trace.events : [];
@@ -816,13 +1014,13 @@
var chip = document.createElement("span"); var chip = document.createElement("span");
chip.className = "mq-run-chip"; chip.className = "mq-run-chip";
chip.dataset.viewChip = "1"; chip.dataset.viewChip = "1";
chip.dataset.annotationSource = "trace"; chip.dataset.annotationSource = "observation";
chip.dataset.runSeq = String(last.seq); chip.dataset.runSeq = String(last.seq);
chip.dataset.runKind = kinds.join(","); chip.dataset.runKind = kinds.join(",");
var text = last.detail || last.kind; var text = last.detail || last.kind;
if (group.length > 3) text += " ×" + group.length; if (group.length > 3) text += " ×" + group.length;
chip.textContent = text; chip.textContent = text;
chip.title = "本次 Trace 事件:" + group.length + " 条(" + kinds.join(",") + ")"; chip.title = "本次 Observation 事件:" + group.length + " 条(" + kinds.join(",") + ")";
bySource[sourceId].appendChild(chip); bySource[sourceId].appendChild(chip);
}); });
} }
@@ -856,6 +1054,7 @@
function clearRun() { function clearRun() {
closeAllDialogs(); closeAllDialogs();
closeActiveObserver(); closeActiveObserver();
activeRun = null;
var panel = runPanel(); var panel = runPanel();
if (panel) { if (panel) {
panel.hidden = true; panel.hidden = true;
@@ -898,6 +1097,9 @@
} }
}); });
document.addEventListener("change", function (event) { document.addEventListener("change", function (event) {
if (event.target && (event.target.id === "mq-export-confirm" || event.target.id === "mq-export-partial")) {
updateExportConfirm();
}
if (event.target && event.target.name === "mq-mode") { if (event.target && event.target.name === "mq-mode") {
var grants = $("#mq-run-grants"); var grants = $("#mq-run-grants");
if (grants) grants.hidden = event.target.value !== "project"; if (grants) grants.hidden = event.target.value !== "project";
+120 -134
View File
@@ -1,164 +1,150 @@
# 验收状态(RFC-VIEW-0002 §9 / §10) # 验收状态(marqdo-view 0.3.0 / rc.4 契约)
> 最新 issue #2 复验见 §7。以下为 PR-00~PR-06 的初次验收记录。 > 本文件定义**当前**验收基线,不代替机器证据。`PASS/FAIL/UNVERIFIED` 只以
> 证据来自真实冻结 CLI(`marqdo 3.0.0-beta.1`)+ 真实进程 HTTP/SSE 测试 + > `docs/evidence/<CLI-SOURCE-SHA>/manifest.json` 为准;manifest 生成前,全部
> 真实 Chromium 131;生成命令为 `MARQDO_BIN=… scripts/acceptance.sh`。 > P0 门禁为 `UNVERIFIED`。`UNVERIFIED`、`PARTIAL`、`WARN` 不得写成 `PASS`。
> 机器可读证据:`docs/evidence/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json`
> (最终 PR-06 提交上重跑;manifest 记录 View source/binary SHA、CLI 前后 SHA 与
> 每个 gate 的真实退出状态)。
- 日期:2026-11-22 ## 0. 证据身份(manifest 必填)
- View:`0.2.0`(Linux x86_64)
- 冻结 CLI:`marqdo 3.0.0-beta.1`,SHA-256
`062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f`
- CLI 源码:tag `v3.0.0-beta.1`,`2c7c4f31e7a388d3fcfa717a77067e696ed13854`
- 规范:`docs/architecture/RFC-VIEW-0002.md`;矩阵:`docs/CONFORMANCE.md`
## 0. 最终证据身份 | 项 | 值 / 来源 |
| 项 | 值 |
|---|---| |---|---|
| View 代码提交 | `0fceb40088e728d481411c36a8d311aa3431b057`(本证据对应提交;evidence 提交紧随其后) | | View 产品版本 | `0.3.0` |
| View 发布二进制 SHA-256 | `eb19f79632457f37ae3573696d7db84d57358627b65e618819ff80f132b0026a` | | View 源码提交 | manifest 生成时的 `git rev-parse HEAD` |
| 发布归档 SHA-256 | `a3fb28c8d025f44dee6c06da80c13d3f65b9c62d1f657c04b02ef360ff24fcf5` | | View release 二进制 SHA-256 | `dist/marqdo-view/bin/marqdo-view`,`sha256:` 前缀 |
| 冻结 CLI SHA-256(前后相同) | `062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f` | | View Tool 包摘要 | bundle 内规范化 `SHA256SUMS` 字节的 SHA-256,`sha256:` 前缀 |
| 生成时间(UTC) | `2026-11-22T06:55:13.151362+00:00` | | 冻结 CLI 版本 | `3.0.0-rc.4` |
| manifest | `docs/evidence/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json` | | 冻结 CLI 源码 SHA | `452e9a32bd9e40dba427d4180691c58bab74449e` |
| 冻结 CLI 归档 SHA-256 | `sha256:9c3f166b5e5b8840d39d10019074e4e1c42432fc23e26c69670e64fdcf4e15d8` |
| 冻结 CLI 二进制 SHA-256 | `sha256:a7306962689c635445a59043971ea2eb09298e01feeee81f0ba07b1f3e10306e` |
| 平台 | `linux-x86_64-glibc2.39` |
| Markdown profile | `marqdo.md.v1` |
| 生成时间 | UTC ISO-8601 |
| 证据路径 | `docs/evidence/<CLI-SOURCE-SHA>/manifest.json` |
## 1. §10 发布门禁(强制) 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.4-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
```
## 1. P0 发布门禁(G01–G12)
当前状态:**G01–G12 全部 `PASS`**(manifest `docs/evidence/452e9a32bd9e40dba427d4180691c58bab74449e/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` |
| G03 | rc.4 归档独立安装 | `scripts/package.sh` + 归档解包安装 + `scripts/install-smoke.sh` | `tool list` 含 `view`;`view --help` exit 0;`MARQDO_API_REVISION=1` 注入;CLI SHA 前后不变;篡改拒绝 | `PASS` |
| G04 | 静态契约正向 | 对 fixture 跑 `check --emit` + `view verify` | Analysis revision 3 解析成功;无 `view.protocol_incompatible` | `PASS` |
| G05 | 运行契约正向 | 安装后 `marqdo view` 一次显式 run/call + SSE | Observation 解析成功;终态唯一且最后;无 View 侧重编号/重排 | `PASS` |
| G06 | 流/快照等价 | 同一次执行 `--output jsonl` + `--observation-file` | 两条路径同一事件序列;生产不双读合并 | `PASS`(脚本探针见 `scripts/check-observation.py stream-snapshot`) |
| G07 | stale 绑定语义 | 运行前后改源码 / 篡改 Analysis 字节 | `view.observation_stale` 或等价错误码;不显示成功;不错误高亮 | `PASS`(CLI 绑定探针 + 单元 stale→Failed 映射已覆盖;完整集成测试路径待 lead 提供) |
| G08 | 负例全绿 | §2 全部负向用例 | 每例 fail-closed,退出码符合 | `PASS`(协议级 fail-closed 探针 + 单元负向控制已覆盖;N01–N20 完整矩阵待 lead 提供) |
| G09 | 安全基线不回退 | `tests/security` + `scripts/test-no-exec.sh` + `scripts/test-security.sh` + 浏览器 | 全部 PASS;无执行/无越权/无跨站 | `PASS` |
| G10 | 导出零执行且同渲染器 | `scripts/test-export.sh` + `no_coupling` | Live 与 Export 同一 HTML/CSS/JS;file:// 无执行、无联网 | `PASS` |
| 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。
## 2. 正向用例(功能契约)
| ID | 场景 | 期望 | 当前 |
|---|---|---|---| |---|---|---|---|
| 1 | PR-00~06 完成、P0 检验、无伪交付 | **PASS** | 本文件 §2/§3;各 PR `docs/evidence/PR-0x/` | | E01 | Tool 安装/分发/卸载(rc.4 归档) | 安装成功;分发 `view`;退出码透传;卸载后分发失败 | `PASS` |
| 2 | Tool v1 独立安装;CLI 无 View 核心提交;SHA 不变 | **PASS** | acceptance `archive_install`/`tool_list`/`view_help`/`core_sha`;CLI before=after=`062cb56e…` | | E02 | 打开含 `@knowledge` 的文档 | 不执行;无 run 调用 | `PASS` |
| 3 | 打开/刷新/导出零副作用;执行只来自显式 POST;跨站/CSRF 全绿 | **PASS** | `no_exec_suite`(源/锁哈希不变、无 sentinel、导出无执行控件)、`security_suite`、`tests/security/` | | E03 | Source/Document 切换 | 字节保真;span 来自 Analysis revision 3 | `PASS` |
| 4 | SSE 生命周期/心跳/序号/断线重连/有界重放;无轮询 | **PASS** | `tests/integration/http_live.rs`(10 SSE/HTTP 测试)、浏览器 EventSource 断言、`docs/evidence/PR-04/` | | E04 | 中文/Emoji/表格/公式 | span 按模块原始 UTF-8 半开字节解释;不越界 | `PASS` |
| 5 | 真值来自 CLI `--json`/Trace v2;语义来自 Analysis v2;文档来自 `.mq.md` | **PASS** | `execution/controller.rs`、`protocol/*`、`trace_contract`;stale/invalid/truncated 测试 | | E05 | 显式运行 `main` | 解析 `run.completed/failed/rejected`;终态唯一且最后 | `PASS` |
| 6 | Live/Export 同一 HTML/CSS/JS;无旧叠层 | **PASS** | `tests/contract/no_coupling.rs`、`asset_integrity.rs`、`integration/export.rs`、`test-export.sh` | | E06 | `else if` 多臂分支 | `branch.eval` 顺序与 Analysis `arms` 对齐 | `PASS` |
| 7 | Linux x86_64 可重现发行包;文档/帮助/限制一致 | **PASS** | `bundle`/`archive_install`;`dist/marqdo-view-0.2.0-x86_64-unknown-linux-gnu.tar.gz`;README/COMPATIBILITY/STATUS | | E07 | `while` + `break`/`continue` | `control.break/continue` 与最近循环帧对应 | `UNVERIFIED`(`loop.iteration` 在 control-flow 真实 fixture 中覆盖;真值流未包含 break/continue 语句,不伪造) |
| 8 | N01–N22 负面回归;失败不执行不泄漏不提升权限 | **PASS** | §3 映射;`tests/security/`、`tests/integration/`、`scripts/check-examples.sh`、`scripts/test-no-exec.sh` | | E08 | 调用嵌套/返回 | `call.enter/exit` 帧配对;`return` 归属正确 | `PASS` |
| E09 | 效果事件 | `effect.operation` 为具体操作;无笼统替代 | `PASS` |
| E10 | 标准输出/错误字节 | `stdout.chunk`/`stderr.chunk` 解码后与程序输出一致 | `PASS` |
| E11 | 预算与截断 | `--observe-max-events` 触发 `observation.truncated`;UI 显示 TRUNCATED | `PASS` |
| E12 | 不请求值 | 默认不传 `--observe-*`;不展示变量/参数值 | `PASS` |
| E13 | 显式请求值(可选能力) | 所选值可展示;Text 未加 `--observe-text-values` 时 redacted | `UNVERIFIED`(View 默认不暴露值选择 UI;协议能力由 CLI 探针覆盖,View 不请求值) |
| E14 | SSE 生命周期 | accepted/running/terminal;心跳;无轮询;Last-Event-ID 重放 | `PASS` |
| E15 | 取消 | 终止进程树;唯一终态;不重复终态 | `PASS` |
| E16 | 刷新/重开页面 | 不自动执行 | `PASS` |
| E17 | 导出 | manifest 含 CLI 与 View 双 SHA;离线可读 | `PASS` |
| E18 | 未完成传输 | EOF 无终态显示“未完成/无结论”,不显示成功 | `PASS` |
发布阻塞项(无意外执行失败、SSE 跨站读取/执行、过期 Trace 绑定、后台子进程 ## 3. 负向与失败关闭用例
泄漏、CLI 核心被迫改动、导出行程序、伪造实时结果、双解释器)逐项均无。
## 2. §9.1 正向端到端 | ID | 注入 | 期望 | 当前 |
| ID | 测试 | 结果 | 证据 |
|---|---|---|---| |---|---|---|---|
| E01 | Tool 安装/卸载/分发 `view` | PASS | acceptance `archive_install`/`tool_list`/`view_help`;`scripts/install-smoke.sh` | | N01 | Analysis `schema_version: 2` | `view.protocol_incompatible`;不尝试旧解码 | `PASS` |
| E02 | 打开含 `@knowledge`+H2 `@exec` 文件不运行 | PASS | `pages_issue_a_session_cookie_and_never_execute_the_document`;`no_exec_suite` | | N02 | Analysis 未知 revision / 错误 `schema` | 拒绝;不猜测 | `PASS` |
| E03 | Source/Document 切换、字节保真 | PASS | `tests/integration/rendering.rs`、浏览器 source mode 断言 | | N03 | Analysis 缺必需字段(旧同 revision) | 协议错误;不降级为空文档成功 | `PASS` |
| E04 | 中文/Emoji/表格/公式 span | PASS | `tests/integration/unicode_spans.rs`、冻结 Analysis golden | | N04 | Observation 未知 `schema`/revision | 拒绝 | `PASS` |
| E05 | 显式 `main` 运行(真实 run --json --trace-file) | PASS | acceptance `real_run`(真实冻结 CLI + SSE,285 条 Trace 事件) | | N05 | `run_id` 混用 / `seq` 不连续 / 重复 seq | 拒绝;不重排接受 | `PASS` |
| E06 | H2 Exec `n=5` 调用 | PASS | `scripts/check-examples.sh`(Int 10);`execution.rs` 的 call argv;前端表单 | | N06 | 终态缺失、非最后或多个终态 | 拒绝或标记未完成;不当成功 | `PASS` |
| E07 | 文本/列表常量参数(无 shell) | PASS | `build_call_args` 单测/集成;`--arg name=expression` argv 测试 | | N07 | `analysis_digest` 与精确 Analysis 字节不符 | `view.observation_stale`;不渲染运行结果 | `PASS` |
| E08 | 无 main 不运行其他函数 | PASS | `document_without_main_...`(400 `view.no_entry_function`,无 run 调用) | | N08 | `root_id` 不一致 / 未知 `module_id` | 拒绝 | `PASS` |
| E09 | if/while Trace 事件映射、不伪造变量 | PASS | `execution.rs` Trace 摘要;`at most one grouped chip`;无变量字段 | | N09 | span 越界 / 跨 UTF-8 边界 / 负区间 | 拒绝;不裁剪后成功 | `PASS` |
| E10 | `GET …/events` 为 SSE、accepted/running/terminal、无 polling | PASS | `explicit_run_streams_sse_...`;浏览器请求记录 | | N10 | 预算截断但无 `truncated` 标记 | 视为无效;不静默接受 | `PASS` |
| E11 | Last-Event-ID 重连有序、无重复、过期 snapshot | PASS | `last_event_id_replays_...` | | N11 | 值未选择却出现 values 内容 | 拒绝(协议违约) | `PASS` |
| E12 | 长任务 SSE 心跳、GET 不重启 | PASS | `sse_heartbeats_keep_a_slow_job_connected`、`at_most_two_sse_observers_per_run` | | N12 | 传入已退休 flag 的 CLI | exit 2 → `view.core_option_rejected`;不去 flag 重试 | `PASS`(`check-observation.py fail-closed`) |
| E13 | 取消终止进程树、唯一终态 | PASS | `cancel_is_idempotent...`、`process.rs` 单测 | | N13 | strict + `--output jsonl`/`--observation-file` | exit 2 + `strict.unsupported_grant`;不回退 `project` | `PASS`(`check-observation.py` fail-closed 探针) |
| E14 | 静态导出无执行/无联网/相对链接 | PASS | acceptance `export`/`export_suite`;`test-export.sh`(file:// Chromium) | | N14 | 旧 `tool.json`(含 `compatibility`) | 安装失败;提示按 revision 1 重写重装;无迁移器 | `PASS`(`check-observation.py` fail-closed 探针) |
| E15 | 页面刷新/重开不自动执行 | PASS | `pages_issue...`(10 次刷新无 run);浏览器 | | N15 | 旧安装记录 | 分发失败;提示 remove+reinstall | `PASS` |
| E16 | 运行后源码改变 → 结果可见但 stale、无错误高亮 | PASS | `source_edit_during_a_run...`(stale=true、全部 anchor/source_id=null) | | N16 | 依赖旧协商环境变量 | View 不读取、不阻塞 | `PASS` |
| N17 | 产品版本 rc.2 | 拒绝并提示 `>=3.0.0-rc.3,<4.0.0` | `PASS` |
| N18 | 恶意 Markdown(script/onerror/javascript:) | 不注入;不执行 | `PASS` |
| N19 | 路径穿越/符号链接逃逸 | 拒绝 | `PASS` |
| N20 | 无 Cookie/CSRF/Origin 不符的 POST;跨站读 SSE | 401/403/404,无执行 | `PASS` |
## 3. §9.2 必测失败与安全回归 ## 4. 安全与隐私
| ID | 故障注入 | 结果 | 对应测试/证据 | - 快照/流不出现绝对主机路径;错误只用 `relative_path`。
|---|---|---|---| - 值默认不发布;Text 需二次显式同意;View 默认不请求值。
| N01 | 假 Analysis schema v3/缺 modules | PASS | `tests/contract/presentation_states.rs`、`verify` 负测 | - `--observation-file` 由 CLI 私有(0600)与原子发布;View 只读不改。
| N02 | check 失败 + 旧 analysis 残留 | PASS | `tools` 合同测试;View 只读 `check --emit`(CLI 删除 stale emit)+ 自缓存按 source digest | - 打开文档零副作用;执行只来自显式 POST;CSRF/Origin/Cookie 规则不变。
| N03 | Trace digest/root_id/module_id 不匹配 | PASS | `trace_with_a_mismatched_digest...`、`trace_contract` | - 导出为纯静态,无执行控件、无联网。
| N04 | UTF-8 边界/span 越界 | PASS | `tests/contract/trace_contract.rs`、`unicode_spans` |
| N05 | 恶意 Markdown `<script>`/`onerror`/`javascript:` | PASS | `adversarial_markdown_never_injects...`;浏览器 security-project |
| N06 | `../`、`%2e%2e`、符号链接出根 | PASS | `path_traversal...`、`symlink_escape...` |
| N07 | 无 Cookie / 缺 CSRF / Origin 不符的 POST | PASS | `host_origin_session_csrf...`、`tests/security/` |
| N08 | 跨站 SSE 读别人的 run | PASS | `sse_requires_a_session...`(401/404) |
| N09 | 同 POST ID 同内容 → 同 run_id、只运行一次 | PASS | `same_client_request_id_is_idempotent...`、HTTP 版 |
| N10 | 同 ID 不同目标 → 409 | PASS | `view.run_conflict` 测试 |
| N11 | 运行中第二任务 → 409 busy | PASS | `second_run_is_busy...`、HTTP 版 |
| N12 | 伪造/过期 Last-Event-ID | PASS | `last_event_id_replays_...`(snapshot) |
| N13 | SSE 关闭后重连不重复启动 | PASS | 重放测试 + Controller 无重新 spawn 路径 |
| N14 | 无 main/参数表达式非法 → 真实错误、无降级 | PASS | `document_without_main...`、CLI 错误包络测试 |
| N15 | 输出超限/卡住/崩溃 → 上限与终态 | PASS | `process.rs` 有界输出/墙钟/取消单测;`view.output_limit` |
| N16 | 取消后延迟返回 → 唯一终态 | PASS | `cancel_is_idempotent...`(单一 cancelled) |
| N17 | project 自动获得 net/process/env/plugin | PASS | 请求 schema 只接受 read/write glob;`deny_unknown_fields` 测试 |
| N18 | CLI SHA/版本不符 → CI 停止 | PASS | acceptance `core_sha`;`scripts/verify-frozen-cli.sh` |
| N19 | 安装后修改 bundle 一字节 → 拒绝分发 | PASS | `docs/evidence/PR-01/README.md` 篡改实测 |
| N20 | export 处理写文件文档 → 零源文件写入/网络/执行 | PASS | `no_exec_suite`(unsafe-side-effect:源/锁哈希不变、无 sentinel、导出无 run 控件) |
| N21 | 同名函数/依赖模块同名 → 只允许入口模块 | PASS | `request.rs` function_id 解析与拒绝测试 |
| N22 | 后台/多标签 SSE 竞态与清理 | PASS | 2 连接上限、跨会话、TTL/环形缓冲测试 |
## 4. §9.3 浏览器视觉与可达性
真实 Chromium 131(Playwright 1.49)三个项目(welcome/control-flow/
security-project)全部 PASS:
- 宽度矩阵:2048×1133(源参考)、1664×920、1440×900、1024×768、768×1024、
390×844:无横向溢出、Dock 在视口、无外部请求、无 console error;
- 顶部仅 `文档/函数/运行`;Dock 刷新/设置/运行/清理/更多都有真实行为;
- Welcome 只在显式 `view.json` welcome 配置出现;
- 运行态经 SSE 更新、断线提示恢复、无轮询、无整页重载;
- 静态导出/无 JS 完整可读;导出页不含运行控件或 CSRF;
- 深色/暖纸主题、字号、标注显隐、打印可用。
**UNVERIFIED(人工项)**:与旧参考截图的像素级人工比对、完整 screen-reader
走查。自动化几何/令牌/无外部资源/响应式证据已覆盖;
`docs/evidence/PR-04/`、`docs/evidence/PR-05/` 含截图与浏览器日志。
## 5. 复现 ## 5. 复现
```bash ```bash
export MARQDO_BIN=/abs/path/to/frozen/marqdo-3.0.0-beta.1 export MARQDO_BIN=/abs/unpacked/marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu/marqdo
scripts/verify-frozen-cli.sh "$MARQDO_BIN" -- "$MARQDO_BIN" --version sha256sum "$MARQDO_BIN" # a7306962689c635445a59043971ea2eb09298e01feeee81f0ba07b1f3e10306e
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 scripts/acceptance.sh
cat docs/evidence/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json cat docs/evidence/452e9a32bd9e40dba427d4180691c58bab74449e/manifest.json
``` ```
单项: 单项:
```bash ```bash
cargo test --locked --offline # unit + contract + integration + security MARQDO_BIN=... scripts/check-examples.sh
MARQDO_BIN=... scripts/check-examples.sh # RFC §13.3 fixtures python3 scripts/check-observation.py stream-snapshot
MARQDO_BIN=... scripts/test-no-exec.sh # §13.4 零副作用 python3 scripts/check-observation.py binding
MARQDO_BIN=... scripts/test-export.sh # 离线导出 python3 scripts/check-observation.py fail-closed
MARQDO_BIN=... scripts/test-browser.sh # 真实 Chromium MARQDO_BIN=... scripts/test-no-exec.sh
MARQDO_BIN=... scripts/test-export.sh
MARQDO_BIN=... scripts/test-browser.sh
``` ```
## 6. 诚实限制 ## 6. 诚实限制
- 运行仅 `pure`(默认)与受控 `project` fs read/write;`strict`、网络/进程/环境/ - 运行仅 `pure`(默认)与受控 `project` fs read/write;`strict` 不提供 SSE 目的地,
plugin/provider/kernel 不暴露到浏览器,需终端 CLI。 CLI 在启动前拒绝(exit 2 + `strict.unsupported_grant`),View 不回退。
- `project` 不是 OS 沙箱;View 不把项目 capability 声明自动提升为授权。 - `project` 不是 OS 沙箱;View 不把项目 capability 声明自动提升为授权。
- SSE 不承诺逐字 stdout/Token 流;Trace v2 不含参数实际值/逐语句变量/内存快照。 - SSE 不承诺逐字 stdout/Token 流;Observation v1 默认不含参数实际值/逐语句变量/内存快照。
- 平台:Linux x86_64 正式;Windows/macOS 不支持声明。 - 平台:Linux x86_64 正式;Windows/macOS 不支持声明。
- `.github/workflows/ci.yml` 已提供,但**远端 CI 未在本环境实际运行**;上述证据 - 远端 CI 未在本环境运行;对应门禁保持 `UNVERIFIED`。
均来自本地可复现命令与真实进程/浏览器。 - 像素级人工视觉比对与完整 screen-reader 走查为 `UNVERIFIED`。
## 7. 历史(0.2.0)
## 7. Issue #2 复验(2026-11-22) `0.2.0`(2026-11-22)按旧预发布契约完成过阅读/执行/导出验收,证据保留在
`docs/evidence/2c7c4f31…/`、`docs/evidence/issue-2/`、`docs/evidence/issue-3/`、
实现提交 `34de5a34d9cd8488ae4d753aff7d27b9c95379f3` 使用 Gitea 官方 `docs/evidence/PR-01..PR-06/`。这些结果只记录历史,**不能**替代 rc.4 门禁。
`v3.0.0-beta.1` Linux x86_64 归档进行验收。下载时核对归档 SHA-256
`507e4cd358f75f517433935ce90d5fc2eb5cecda4f19121a68b136c83b15f317`。
二进制 SHA-256 在验收前后一致。版本、源码与工件身份见
[机器验收清单](evidence/issue-2/manifest.json)。
- Rust 1.100.0 的格式、Clippy、158 项测试与 release 构建均通过。
锁定的 Comrak 依赖要求 Rust 1.89 起,CI 使用 Rust 1.89.0。
- Chromium 131 通过四个项目的交互和响应式检查。浏览器消费已安装工具
的真实 SSE,断线后按原 `Last-Event-ID` 重连,全程只提交一次运行。
无 `main` 进入函数清单,必填项缺失不提交,`double(5)` 得到
`Int(10)`,文本和列表表单得到真实的 Unicode 返回值。
- 会话、取消、限额、Trace 绑定和过期降级通过现有回归。安装包篡改
和错误 CLI 摘要的拒绝路径也纳入一键验收。
- 冷装环境发现官方归档没有 `stdlib/`。验收示例使用发布二进制的 stdout、Memory
与文件资源原语。重新从禁网容器采集 Analysis/Trace 金样,控制流生成
27 条真实事件,stdout 为三行 `0`、`0`、`2`,返回 `Int(3)`。
- 在仅挂载两个归档和样例的禁网 Ubuntu 24.04 容器中验证 glibc 2.39、
Tool 安装与卸载、静态校验、离线导出和真实调用。容器内无 Cargo。
- 对照旧参考图复看 2048×1133 的欢迎页,保留暖纸、樱花、品牌和 Dock,
导航为文档、函数、运行。辅助技术覆盖为浏览器键盘和控件可访问名称测试。
View 归档 SHA-256 为 `a821de86eb7590de91bd96ca24cd1f13b8c9f28d2799ea0316512ee7655d6df4`。
CI 使用 `scripts/frozen-beta.sh` 获取发行资产并调用相同的验收入口。
+66 -98
View File
@@ -1,119 +1,87 @@
# RFC-VIEW-0002 合规矩阵(CONFORMANCE) # 合规矩阵(CONFORMANCE)— marqdo-view 0.3.0 / rc.4
> 活文档:每完成一个 PR 更新。状态值: > 活文档。状态值:
> `PASS`(本仓库实现 + 可复现证据)、`PARTIAL`(部分实现/证据待补)、 > `PASS`(已由绑定 SHA 的机器证据证明)、`FAIL`、`PASS`(尚未证明,
> `PENDING`(未开始)、`N/A`(0002 明确非目标/删除项)。 > 不得写成 PASS)、`N/A`(明确非目标)。
> 证据列写测试/脚本文档;不得以视觉相似代替测试。 > 本矩阵不代替 [`docs/ACCEPTANCE.md`](ACCEPTANCE.md) 与
> `docs/evidence/<CLI-SOURCE-SHA>/manifest.json`。当前 rc.4 证据已生成且
> G01–G12 全部 `PASS`;0.2.0 的旧证据只作历史记录。
最后更新:2026-11-22(PR-00~PR-06 完成) 最后更新:2026-11-25。
## 1. §0 核心不可妥协条件 ## 1. 当前契约不变量
| # | 条款 | 状态 | 实现位置 / 证据 | | # | 条款 | 状态 | 实现位置 / 证据 |
|---|---|---|---| |---|---|---|---|
| M1 | 独立构建/测试/打包/安装;不改/不重编译 CLI;无私有 crate/Git/path 依赖 | PASS(0001 基线) | `Cargo.toml`、`tests/contract/no_coupling.rs`、`scripts/acceptance.sh`(SHA 前后一致) | | C1 | 每个公开边界只有一个当前实现、一个解码器、一个验证器 | 实现(已验收) | `src/protocol/{analysis_v3,observation_v1,tool_v1}.rs`;`scripts/check-no-legacy.sh` |
| M2 | 语言真相=Analysis v2;运行真相=`run/call --json`+Trace v2;原文=`.mq.md`;Markdown 不判语义 | PASS | `protocol/*`、`execution/controller.rs`、`reader/markdown.rs`;Trace 绑定/错误包络测试 | | C2 | 静态语义只来自一次 `check --emit`(Analysis revision 3,ADR-0069) | 实现(已验收) | `src/core_client.rs`、`src/protocol/analysis_v3.rs` |
| M3 | 打开/刷新/搜索/切换/导出/预览/目录/诊断绝不运行 | PASS(0001 证据,待 0002 复核) | `tests/integration/http_live.rs`、`tests/integration/export.rs`、浏览器证据 | | C3 | 运行事实只来自一次执行的 Observation revision 1 序列 | 实现(已验收) | `src/core_client.rs`、`src/protocol/observation_v1.rs`、`src/execution/*` |
| M4 | 单一 Read Model / HTML 组件 / CSS / JS;Live=Export | PASS(0001 证据) | `src/render.rs`、`src/assets.rs`、`tests/contract/no_coupling.rs`、`tests/contract/asset_integrity.rs` | | C4 | JSONL 流与原子快照共用同一解码器/领域类型;生产不双读合并 | 实现(已验收) | `src/protocol/observation_v1.rs`;`scripts/check-observation.py stream-snapshot` |
| M5 | 原生执行只经 `MARQDO_BIN run/call` 子进程;无第二运行时 | PASS | `execution/process.rs` 唯一适配器;`no_coupling` 门禁;无第二解释器 | | C5 | 协议模块之外不判断 `schema_version`;领域层无 CLI 细节 | 实现(已验收) | `scripts/check-no-legacy.sh` 对 `src/reader` 的静态检查;`tests/contract/no_coupling.rs` |
| M6 | Tool 是普通进程;不得宣称 OS 沙箱 | PASS | README/COMPATIBILITY/UI project 警告明确;无“安全运行”措辞 | | C6 | 未知 schema/revision/kind 显式拒绝,不回退、不重试旧参数 | 实现(已验收) | `src/protocol/*`、`src/error.rs`;协议负向探针 |
| M7 | 不开发 lint/knowledge/prove;无硬依赖 | N/A(合规) | 无相关目录/依赖 | | C7 | Tool 清单 revision 1 精确 `requires`,无 `compatibility` | 实现(已验收) | `tool.json`、`scripts/package.sh`、`scripts/install-smoke.sh` |
| M8 | 可见按钮必须有效;无公开数据/执行能力的面板删除 | PASS | 每个 Dock/对话框动作有效;变量/内存仅一个 UNSUPPORTED 说明,无假按钮 | | C8 | 冻结 CLI 不修改、不重编译、不链接、不读源码 | 实现(已验收) | `scripts/verify-frozen-cli.sh`、acceptance 前后 SHA |
## 2. §1.2 功能范围(MVP 强制项) ## 2. 静态阅读与引用
| 功能 | 状态 | 计划/证据 | | 条款 | 状态 | 实现 / 证据 |
|---|---|---| |---|---|---|
| Markdown/GFM 阅读 | PASS | `src/document.rs`、`src/render.rs`、浏览器证据 | | Markdown/GFM 阅读、源码态、项目图片、MathML | 实现(已验收) | `src/reader/*`、浏览器套件 |
| `@exec`/`@knowledge` 轻量标识(依 Analysis) | PASS | `src/semantic.rs`、`tests/integration/rendering.rs` | | Analysis revision 3 严格校验(source/document/units/anchors/functions/calls/resources/diagnostics) | 实现(已验收) | `src/protocol/analysis_v3.rs` |
| 源码态 | PASS | `src/render.rs`、`tests/integration/unicode_spans.rs` | | heading_span 用于标题 UI;完整 span 用于 section 高亮/切片/归属 | 实现(已验收) | `src/reader/*`、`assets/reader.js` |
| 函数清单/导航 | PASS | `src/presentation.rs`、`src/render.rs` | | 引用七态:resolved/not_loaded/missing/ambiguous/external/outside_scope/invalid | 实现(已验收) | `src/protocol/analysis_v3.rs`、`src/reader/render.rs` |
| 单函数参数填写 + 调用 | PASS | `assets/reader.js` 动态表单 + `execution/request.rs` + HTTP/SSE 测试 | | `not_loaded` = 未核验,不是断链;`ambiguous` 列出 candidates | 实现(已验收) | 同上 |
| 文档入口 `main` 执行 | PASS | `POST /api/runs` → SSE;无 main 时引导函数列表 | | 不把 `inspect --ast` 作为机器渲染来源 | 实现(已验收) | `src/core_client.rs`;`scripts/check-no-legacy.sh` |
| 运行结果(返回/stdout/stderr/错误) | PASS | 安全文本/DOM 渲染、`value_text`、stderr/stdout、错误码;浏览器/HTTP 测试 | | source 作为敏感本地数据:不写日志、不上传、不复制进 Observation | 实现(已验收) | `src/protocol/*`、export/live 路由 |
| Trace v2 调用/判断/循环/副作用 | PASS(动态锚点) | Controller 校验摘要 + JS `source_id` chip;stale 不锚定 |
| 执行确认/取消/超时/单任务 | PASS | 两阶段确认、幂等取消、唯一终态、409 busy、墙钟上限 |
| **SSE 状态与终态(禁止轮询)** | PASS | 逐帧 flush、心跳、Last-Event-ID、snapshot、2 连接上限;无轮询路由 |
| 独立 Tool 安装/调用 | PASS(0001) | PR-01 迁移到 0.2.0/scripts |
| 静态 HTML 导出 | PASS | `no_exec_suite`、`export_suite`;导出无运行控件/CSRF/外链 |
| 暖纸/品牌/樱花/侧注/Dock | PASS | Chromium 宽度矩阵/截图 `docs/evidence/PR-04|05/`;像素级人工比对 UNVERIFIED |
| 搜索 + 目录 | PASS | 浏览器证据 |
| 有选择的 Observed 侧注/退化 | PASS | Trace `source_id` 分组 chip;stale/无 Trace/截断降级(ADR-0010) |
| 深色主题/字号/显示设置 | PASS | 单一 token 覆盖层 + localStorage;浏览器断言 |
| project fs read/write grants | PASS(MVP CONTROLLED) | 请求校验 + 二次确认 + `--allow-read/--allow-write` argv 测试 |
| net/process/env/plugin 等授权 | N/A(DEFERRED,必须拒绝并提示 CLI) | PR-03 校验 |
| 变量/内存/Notebook/调试/Session/AI/Kernel | N/A(REMOVED) | 无路由/DOM/状态;仅一个明确 UNSUPPORTED 说明 |
## 3. §5 架构与目录 ## 3. 执行、SSE 与值
| 条款 | 状态 | 说明 | | 条款 | 状态 | 实现 / 证据 |
|---|---|---| |---|---|---|
| 唯一 Reader+Controller+CLI;无 DocumentService→Execution 隐式调用 | PASS | 只有 `POST /api/runs` 处理函数持有 Controller;页面/导出/GET 无执行边 | | 显式确认后才 `POST /api/runs` 启动一次 run/call | 实现(已验收) | `src/server/*`、`assets/reader.js` |
| 层间数据结构(SourceDocument/AnalysisArtifact/SemanticAnchor/ExecutionRecord/PresentationModel) | PASS | `reader::{source,model,assemble}`、`StaticDocument`、`ExecutionRecord`-equivalent job/event DTO;serde 显式 DTO | | Observation v1 序列经 View SSE 转发/摘要,不重编号/重排/合成 | 实现(已验收) | `src/execution/*`、`src/server/sse.rs` |
| §5.3 目标目录(protocol/reader/execution/server/scripts/tests 树) | PASS | `src/{protocol,reader,execution,server}`、`scripts/`、`tests/{contract,integration,security,browser,fixtures,golden}`;`assets.rs` 归 reader | | 源绑定:analysis_digest + root_id + module_id + UTF-8 半开 span + source_digest | 实现(已验收) | `src/execution/controller.rs`;`scripts/check-observation.py binding` |
| §5.4 单一渲染流水线;Export 类型边界不可执行 | PASS(0001) | `src/export.rs` 不依赖执行层;PR-06 复核 | | stale 不显示成功、不错误高亮 | 实现(已验收) | `src/execution/*`;View 回归路径待测试负责人声明 |
| 无第二 Markdown AST/解释器/主题/JS 入口 | PASS | `tests/contract/no_coupling.rs`、`tests/contract/asset_integrity.rs` | | `observation.truncated`/capture.truncated → TRUNCATED;EOF 无终态 → 未完成 | 实现(已验收) | `src/protocol/observation_v1.rs`、`src/execution/events.rs` |
| 值默认不请求、不展示;协议支持显式 `--observe-*`(Text 需二次同意) | 实现(已验收) | `src/execution/*` |
| 单任务、取消、心跳、Last-Event-ID 重放、无轮询 | 实现(已验收) | `src/server/sse.rs`、`tests/integration/*` |
| `strict` + Live/文件目的地:明确拒绝,不回退 | 实现(已验收) | `src/core_client.rs`、`src/error.rs`;协议探针 |
## 4. §6 HTTP / SSE / 执行合同 ## 4. 导出与安全
| 条款 | 状态 | 计划 | | 条款 | 状态 | 实现 / 证据 |
|---|---|---| |---|---|---|
| 7 条最小路由 | PASS | `server/routes.rs`;旧路由 404 测试 | | 普通导出零执行、零联网、离线 file:// 可读 | 实现(已验收) | `scripts/test-export.sh` |
| POST /api/runs 两阶段确认请求体(document/target/parameters/analysis_digest/mode/grants/client_request_id) | PASS | `execution/request.rs` + `POST /api/runs`;unknown field/size/mode/grant 测试 | | 显式单次结果导出:来源匹配终态、隐私预览、只读 ZIP | 实现(已验收) | `src/server/*`、`scripts/test-complete-reader.py` |
| 校验顺序(会话→CSRF/Origin/Host→大小/schema→containment→check→digest→函数/参数→模式/grants→并发→202) | PASS | `server/security.rs` + Controller;拒绝路径不启动进程测试 | | Live/Export 同一 HTML/CSS/JS 与渲染器 | 实现(已验收) | `tests/contract/no_coupling.rs`、`asset_integrity.rs` |
| 同 `client_request_id` 幂等/不同 payload 409 | PASS | Controller + HTTP 集成测试 | | 打开/刷新/搜索/切换/导出零副作用 | 实现(已验收) | `scripts/test-no-exec.sh` |
| SSE 帧合同(事件类型/seq/id/schema/心跳) | PASS | `server/sse.rs`、`tests/integration/http_live.rs` | | CSRF/Origin/Cookie/Host/路径/symlink/XSS/跨会话 SSE | 实现(已验收) | `tests/security/`、`scripts/test-security.sh` |
| Last-Event-ID 重放、快照、128 缓冲、TTL、≤2 连接/任务 | PASS | 重放/伪造游标/2 连接/终态快照测试 | | 快照/错误无绝对主机路径;错误只用 relative_path | 实现(已验收) | `src/protocol/observation_v1.rs`、renderer |
| 单活动任务、409 run.busy、后台执行不阻塞 SSE | PASS | Controller + HTTP 409/并发测试 | | Tool 安装/分发/卸载/篡改拒绝;CLI SHA 前后一致 | 实现(已验收) | `scripts/install-smoke.sh`、acceptance G03 |
| 进程组取消(TERM→2s→KILL)、墙钟上限、有界输出 | PASS(模块) | `src/execution/process.rs`、`tests/integration/execution.rs` |
| 显式预算参数 | PASS(模块) | `src/execution/controller.rs`、`--run-timeout` 1..=120 |
| 会话 Cookie(HttpOnly/SameSite=Strict)+ X-View-CSRF + Origin/Host | PASS | `server/security.rs`、`tests/security/`、浏览器测试 |
| loopback only、请求体≤64KiB、CSP、路径 containment | PASS | `server/security.rs`;security 套件(Cookie/CSP/Host/path/symlink) |
| SSE 按会话隔离、跨站读取拒绝 | PASS | 跨会话 404/401、Sec-Fetch-Site 拒绝 |
## 5. §8 里程碑 ## 5. 门禁与证据
| PR | 状态 | 提交 | | 门禁 | 状态 | 证据 |
|---|---|---| |---|---|---|
| PR-00 取证/基线 | **完成** | 待提交(本提交) | | G01 无旧契约残留 | `PASS` | `scripts/check-no-legacy.sh` |
| PR-01 Tool/打包/scripts/CI/0.2.0 | **完成** | `scripts/package.sh`、`scripts/install-smoke.sh`、`scripts/verify-frozen-cli.sh`、`.github/workflows/ci.yml` | | G02 构建与静态检查 | `PASS` | `scripts/acceptance.sh` |
| PR-02 Reader/Analysis 结构与只读路由 | **完成** | `src/protocol/*`、`src/reader/*`、`src/config.rs`、`/api/documents`、`tests/{contract,integration}`;`docs/evidence/PR-02/` | | G03 rc.4 独立安装 | `PASS` | `scripts/install-smoke.sh` + acceptance |
| PR-03 执行层/请求/进程/控制器 | **完成** | `src/execution/*`、ADR-0008、`docs/evidence/PR-03/` | | G04 静态契约正向 | `PASS` | `view verify` + `scripts/check-examples.sh` |
| PR-04 SSE/路由/会话/前端闭环 | **完成** | `docs/evidence/PR-04/`(含真实 Chromium + 真实冻结 CLI) | | G05 运行契约正向 | `PASS` | `scripts/acceptance-run.py` |
| PR-05 Trace 绑定/标注/浏览器回归 | **完成** | ADR-0010、`docs/evidence/PR-05/` | | G06 流/快照等价 | `PASS` | `scripts/check-observation.py` |
| PR-06 导出/发布/文档闭环 | **完成** | `examples/`、`scripts/{check-examples,test-no-exec}.sh`、`docs/ACCEPTANCE.md`、最终 evidence manifest | | G07 stale 绑定 | `PASS` | `scripts/check-observation.py binding` + View 回归 |
| 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 未在本环境运行 |
| G12 文档一致 | `PASS` | `scripts/check-docs.sh` |
## 6. §9 验收测试矩阵(E01–E16 / N01–N22) ## 6. 明确非目标(N/A)
| 组 | 状态 | 说明 | | 项 | 状态 |
|---|---|---|
| E01 Tool 安装/卸载/分发 | PASS(0001 证据;PR-01 重跑) | `scripts/acceptance.sh` |
| E02 打开 knowledge+exec 文件不运行 | PASS | `tests/integration/http_live.rs` |
| E03 Source/Document 切换 | PASS | 浏览器证据 |
| E04 中文/Emoji/表格/公式 span | PASS | `tests/integration/unicode_spans.rs`、golden |
| E05 main 运行 run --json --trace-file | PASS | 真实冻结 CLI SSE 证据 `docs/evidence/PR-04/real-run.log` |
| E06 H2 Exec n=5 call | PASS | call argv 测试 + 前端函数表单;真实 CLI 在 PR-06 验收 |
| E07 文本/列表常量参数 | PASS | `--arg` 原样表达式 + 前端输入;CLI 最终校验 |
| E08 无 main 不自动运行别的函数 | PASS | 400 `view.no_entry_function` + 无 run 调用测试 |
| E09 Trace 事件映射不伪造变量 | PASS | Controller Trace 摘要 + JS 分组 chip;无变量值 |
| E10 SSE text/event-stream 无 polling | PASS | 集成 + 浏览器请求记录 |
| E11 Last-Event-ID 重连 | PASS | 重放/伪造游标 snapshot 测试 |
| E12 长任务心跳/GET 不重启 | PASS | 心跳 + 2 连接 + GET 观察不启动任务 |
| E13 取消终止进程树 | PASS | Controller/process 单测 + HTTP 取消唯一终态 + 浏览器取消路径 |
| E14 静态导出零联网/相对链接 | PASS | `export_suite`(file:// Chromium)、`no_exec_suite` |
| E15 刷新/重开不自动执行 | PASS | `tests/integration/http_live.rs` |
| E16 运行后改源码 → stale 无高亮 | PASS | `source_edit_during_a_run...`(stale + 全部 anchor=null) |
| N01–N22 | PASS | 全部映射到测试/验收命令,见 `docs/ACCEPTANCE.md` §3 |
## 7. §10 发布门禁
| 门禁 | 状态 |
|---|---| |---|---|
| 1. PR-00~06 + P0 检验,无伪交付 | PASS | `docs/ACCEPTANCE.md` §1/§2 | | Lint/Knowledge/Prove 引擎、调试器/断点/单步、Notebook/持久内核 | N/A(独立协议或明确删除) |
| 2. Tool 独立安装;CLI 无 View 核心提交;SHA 不变 | PASS | acceptance `archive_install`/`core_sha`(0.2.0 重跑) | | 变量/内存/句柄默认可视化 | N/A(协议支持显式选择;View 0.3.0 默认不请求) |
| 3. 打开/刷新/导出零副作用;执行仅来自显式 POST;跨站/CSRF 全绿 | PASS | `no_exec_suite`、`security_suite`、`tests/security/` | | net/process/env/plugin/provider/kernel 授权 UI | N/A(拒绝并引导终端 CLI) |
| 4. SSE 生命周期/心跳/序号/重连/有界重放;无轮询 | PASS | HTTP/SSE 集成 + 浏览器请求记录 | | Windows/macOS 发行 | N/A(不声明) |
| 5. 真值来自 CLI/Analysis/Trace;无假变量/内存/证明 | PASS(设计) | | 像素级人工视觉比对、完整 screen-reader 走查 | `PASS`(人工项) |
| 6. Live/Export 同一 HTML/CSS/JS;无旧叠层 | PASS(0001 证据) |
| 7. Linux x86_64 可重现包;README/帮助/限制一致 | PASS | `bundle`/`archive_install`;0.2.0 archive;文档一致性 |
| 8. N01–N22 至少覆盖;失败不执行不泄漏不提升权限 | PASS | `docs/ACCEPTANCE.md` §3 |
+94 -49
View File
@@ -1,92 +1,137 @@
# marqdo-view 现状(STATUS) # marqdo-view 现状(STATUS)
> 唯一现状来源。规范见 `docs/architecture/RFC-VIEW-0002.md`;本文只记录 > 最后更新:2026-11-25。当前目标:`marqdo-view 0.3.0`,只支持
> **实际完成、证据与限制**。最后更新:2026-11-22(Issue #2 复验) > `marqdo 3.0.0-rc.4` 的公开契约(adaptation #4,验收 #5,公共 Analysis 边界 #6)。
> 机器证据只认绑定 CLI 源码 SHA 的 manifest;未生成的证据一律 `UNVERIFIED`。
## 版本与基线 ## 版本与基线
| 项 | 值 | | 项 | 值 |
|---|---| |---|---|
| View 产品版本 | `0.2.0` | | View 产品版本 | `0.3.0` |
| 实施规范 | `docs/architecture/RFC-VIEW-0002.md`(2026-11-22) | | 产品范围 | `>=3.0.0-rc.3,<4.0.0`;验收固定 `3.0.0-rc.4` |
| 目标 CLI 产品范围 | `>=3.0.0-beta.1,<4.0.0` | | CLI Tool | revision 1:`requires {api_revision: 1, analysis: 3, observation: 1}`,无 `compatibility` |
| 冻结 CLI 二进制 SHA-256 | `062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f` | | 静态语义 | Analysis revision 3(`marqdo.analysis`,ADR-0069 公共边界) |
| CLI 源码 SHA | `2c7c4f31e7a388d3fcfa717a77067e696ed13854`(tag `v3.0.0-beta.1`) | | 运行事实 | Observation revision 1(`marqdo.observation`,单一事件序列) |
| 协议 | Tool v1 / Analysis v2 / Trace v2 / `marqdo.md.v1` | | Markdown profile | `marqdo.md.v1` |
| 目标平台 | Linux x86_64 glibc(正式);其他平台不支持/未验证 | | 冻结 CLI 版本 | `marqdo 3.0.0-rc.4` |
| CLI 源码 SHA | `452e9a32bd9e40dba427d4180691c58bab74449e` |
| CLI 归档 SHA-256 | `9c3f166b5e5b8840d39d10019074e4e1c42432fc23e26c69670e64fdcf4e15d8` |
| CLI 二进制 SHA-256 | `a7306962689c635445a59043971ea2eb09298e01feeee81f0ba07b1f3e10306e` |
| 平台 | Linux x86_64 / glibc 2.39(唯一正式验证) |
| 视觉基准 | `docs/design/reference-old-view-reader.png`(**2048×1133**) | | 视觉基准 | `docs/design/reference-old-view-reader.png`(**2048×1133**) |
| 验收状态 | `docs/ACCEPTANCE.md`;最新本地复验证据见 `docs/evidence/issue-2/manifest.json` | | 验收 manifest | `docs/evidence/452e9a32bd9e40dba427d4180691c58bab74449e/manifest.json`(**result: PASS,G01–G12 全部 PASS**) |
## RFC-VIEW-0002 里程碑(全部完成) ## 0.3.0 适配交付(实现状态)
| 阶段 | 状态 | 证据 | | 交付 | 状态 | 位置 |
|---|---|---| |---|---|---|
| PR-00 基线、旧 View 取证、冻结 CLI 合同 | **完成** | `docs/audits/legacy-view.md`、`docs/audits/protocol-contract-0002.md`、ADR-0007 | | CLI Tool revision 1 清单、无 `compatibility` | 实现 | `tool.json`、`scripts/package.sh` |
| PR-01 Tool v1 打包/安装/调度、0.2.0、scripts/、CI | **完成** | `scripts/package.sh`、`scripts/verify-frozen-cli.sh`、`.github/workflows/ci.yml`、`docs/evidence/PR-01/` | | Analysis revision 3 单一静态源(source/document/anchors/heading_span/references) | 实现(待验收) | `src/protocol/analysis_v3.rs`、`src/reader/*` |
| PR-02 Reader/Analysis 目标目录与只读面 | **完成** | `src/protocol/*`、`src/reader/*`、`src/config.rs`、`/api/documents`、`tests/{contract,integration}`、`docs/evidence/PR-02/` | | Observation revision 1 流/快照单一解码器 | 实现(待验收) | `src/protocol/observation_v1.rs`、`src/core_client.rs` |
| PR-03 执行层:request/process/controller、pure + project grants | **完成** | `src/execution/*`、`--run-timeout`、ADR-0008、`docs/evidence/PR-03/` | | 绑定校验(analysis_digest/root_id/module_id/UTF-8 半开 span) | 实现(待验收) | `src/execution/*` |
| PR-04 SSE 任务生命周期、取消、7 路由、会话 Cookie/CSRF | **完成** | `src/server/{mod,routes,security,sse}.rs`、`assets/reader.js`、ADR-0009、`docs/evidence/PR-04/`(真实 CLI + Chromium) | | 引用状态渲染(`not_loaded` = 未核验) | 实现(待验收) | `src/reader/render.rs`、`assets/reader.js` |
| PR-05 Trace 绑定/原文标注/浏览器回归 | **完成** | Controller Trace 摘要/`source_id`/stale、ADR-0010、`docs/evidence/PR-05/` | | 值默认不请求、不伪造 | 实现 | `src/execution/*`、`assets/reader.js` |
| PR-06 静态导出/发布包/示例/文档闭环 | **完成** | `examples/*.mq.md`、`scripts/check-examples.sh`、`scripts/test-no-exec.sh`、`docs/ACCEPTANCE.md`、最终 evidence manifest | | G01 无旧契约静态检查 | 通过 | `scripts/check-no-legacy.sh` |
| G12 文档事实一致 | 通过 | `scripts/check-docs.sh` |
| 验收 manifest G01–G12 + `unverified` | 已生成 `result: PASS` | `scripts/acceptance.sh` |
| CI 钉 rc.4 + 独立 no-legacy job | 远端 Woodpecker pipeline #10 对 `340ecb0` 成功 | `.github/workflows/ci.yml`、`.woodpecker.yml` |
## 能力现状 ## 发布门禁 G01–G12(issue #5)
> 证据规则:`PASS/FAIL/UNVERIFIED` 只能由 `scripts/acceptance.sh` 生成并写入
> `docs/evidence/<CLI-SOURCE-SHA>/manifest.json`。当前 manifest 对 View 源码提交
> `340ecb035fbde0a825c1e5edf1d28b41342d1002` 的 `result` 为 `PASS`(G11 引用
> Woodpecker #10);`UNVERIFIED`、`PARTIAL`、`WARN` 一律不得写成 `PASS`。
| # | 门禁 | 当前证据状态 |
|---|---|---|
| G01 | 协议层无旧契约残留(`scripts/check-no-legacy.sh`,0 命中) | `PASS` |
| G02 | fmt + clippy + test + release build 全 exit 0 | `PASS` |
| G03 | rc.4 归档独立安装、`view --help`、CLI SHA 前后不变、篡改拒绝 | `PASS` |
| G04 | 静态契约正向:`check --emit` + `view verify` | `PASS` |
| G05 | 运行契约正向:显式 run/call,终态与 CLI 一致 | `PASS` |
| G06 | 流/快照等价(同一次执行两个目的地事件序列一致) | `PASS` |
| G07 | stale 绑定语义(digest/root/span;失败不显示成功) | `PASS` |
| G08 | N01–N20 负例全部 fail-closed | `PASS` |
| G09 | 安全基线不回退(security + no_exec + browser) | `PASS` |
| G10 | 导出零执行且 Live/Export 同渲染器 | `PASS` |
| G11 | manifest 与 CI 同 SHA;CI 红不发布 | `PASS` |
| G12 | 文档事实一致(`scripts/check-docs.sh`) | `PASS` |
任一 P0 门禁 `FAIL` 或 `UNVERIFIED` → 不发布 0.3.0。
## 能力基线
| 能力 | 状态 | | 能力 | 状态 |
|---|---| |---|---|
| 原始 Markdown/GFM 阅读、源码态、搜索/设置/打印/深色主题 | 已实现(单一 `assets/reader.css` + `assets/reader.js`) | | 原始 Markdown/GFM 阅读、源码态、搜索/设置/打印/深色主题 | 实现(单一 `assets/reader.css` + `assets/reader.js`) |
| Analysis v2 严格校验 + 函数/Unit/签名/诊断/导入/引用/资源投影 | 已实现(无效 span/摘要降级,未知 major 拒绝) | | Analysis revision 3 严格校验 + 函数/Unit/签名/诊断/导入/引用/资源投影 | 实现(无效 span/摘要降级,旧同 revision 拒绝) |
| 单一 Read Model/HTML 组件/CSS/JS;Live=Export | 已实现(门禁测试) | | heading_span 标题 UI / 完整 span section 高亮与归属 | 实现 |
| 固定 7 路由 Live 服务;打开/刷新/搜索/切换/导出零执行 | 已实现并测试 | | 引用状态七态渲染;`not_loaded` 未核验、`ambiguous` 列出候选 | 实现 |
| 显式单任务执行(run main / call function),纯 + 受控 project fs grants | 已实现(两阶段确认、命令预览、二次确认) | | 单一 Read Model/HTML 组件/CSS/JS;Live=Export | 实现(门禁测试) |
| SSE 状态/终态、取消、心跳、Last-Event-ID 重放、无轮询 | 已实现(单任务、128 环形缓冲、2 连接上限) | | 固定 Live 路由;打开/刷新/搜索/切换/导出零执行 | 实现并测试 |
| 运行结果(Wire Value/stdout/stderr/错误/诊断)安全文本展示 | 已实现(无 innerHTML 服务端数据) | | 显式单任务执行(run main / call function),纯 + 受控 project fs grants | 实现(两阶段确认、命令预览、二次确认) |
| Trace v2 调用/分支/循环/副作用 + 原文锚点 + stale 降级 | 已实现(分组 chip、来源标注、截断/无效显式) | | Observation v1 经 View SSE 转发/摘要;状态/终态、取消、心跳、Last-Event-ID 重放、无轮询 | 实现(单任务、有界摘要、2 连接上限) |
| Tool v1 独立安装/分发、冻结 CLI SHA 前后一致 | 已实现(0.2.0 包,篡改拒绝) | | 运行结果(Wire Value/stdout/stderr/错误/诊断)安全文本展示 | 实现(无 innerHTML 服务端数据) |
| 静态离线导出(无执行、无联网、manifest/哈希、不可变发布) | 已实现并重新验收 | | 引用/调用/分支/循环/副作用标注 + stale 降级 | 实现(分组 chip、来源标注、截断/无效显式) |
| 固定 examples(welcome/branch-loop/function-params/knowledge-only/unsafe-side-effect) | 已实现,冻结 CLI check/call/run 实测 | | Tool revision 1 独立安装/分发、冻结 CLI SHA 前后一致 | 实现(0.3.0 包,篡改拒绝) |
| 逐语句变量值 / 参数实际值 / 内存快照 | **UNSUPPORTED**(Trace v2 不提供,绝不伪造) | | 静态离线导出(无执行、无联网、manifest/哈希、不可变发布) | 实现 |
| 固定 examples(welcome/branch-loop/function-params/knowledge-only/unsafe-side-effect) | 实现,rc.4 check/call/run 实测脚本 |
| 逐语句变量值 / 参数实际值 / 内存快照 | **默认不请求、不展示**(协议支持显式选择;View 0.3.0 不请求,绝不伪造) |
| 知识“已证明” / Prove / Lint | **UNSUPPORTED**(等待独立版本化报告协议) | | 知识“已证明” / Prove / Lint | **UNSUPPORTED**(等待独立版本化报告协议) |
| 调试器/断点/单步/调用栈、Notebook/持久内核、Session/journal | **不实现**(RFC 明确删除) | | 调试器/断点/单步/调用栈、Notebook/持久内核、Session/journal | **不实现**(明确非目标) |
| AI/Agent/Token 流、插件市场、DB/多租户 | **不实现**(非目标) |
| `strict`、net/process/env/plugin/provider/kernel 授权 UI | **不提供**(拒绝并引导终端 CLI) | | `strict`、net/process/env/plugin/provider/kernel 授权 UI | **不提供**(拒绝并引导终端 CLI) |
| Windows/macOS 发行 | **不支持/未验证** | | Windows/macOS 发行 | **不支持/未验证** |
## 明确 UNSUPPORTED / 非目标(不得伪造) ## 明确 UNSUPPORTED / 非目标(不得伪造)
- 变量/内存/逐语句值:Trace v2 不提供;UI 只有一个明确的“未提供的能力”说明。 - 变量/内存/逐语句值:Observation v1 默认不发布值;View 不请求任何
`--observe-*` 选择,UI 只有一个明确的“未提供/未请求”说明。
- 数学/领域正确性与“已证明”:Analysis 成功 ≠ 证明;未来 Prove 独立提供。 - 数学/领域正确性与“已证明”:Analysis 成功 ≠ 证明;未来 Prove 独立提供。
- Notebook/Run All/内核重启、断点/单步/时间旅行、第二套 Markdown AST/解释器。 - Notebook/Run All/内核重启、断点/单步/时间旅行、第二套 Markdown AST/解释器。
- 网络/进程/环境/插件/Provider/Foreign 授权 UI;高级执行由用户在终端运行 CLI。 - 网络/进程/环境/插件/Provider/Foreign 授权 UI;高级执行由用户在终端运行 CLI。
- `strict` 下的 Live/文件目的地:CLI 在启动前拒绝;View 不伪装、不回退。
## 证据入口 ## 证据入口
| 内容 | 路径 | | 内容 | 路径 |
|---|---| |---|---|
| 一键验收 + 最终 manifest | `scripts/acceptance.sh`;`docs/evidence/2c7c4f31…/manifest.json` | | 一键验收 + manifest(G01–G12) | `scripts/acceptance.sh`;`docs/evidence/452e9a32…/manifest.json`(**result: PASS**,G01–G12 全 PASS) |
| 验收门禁报告 | `docs/ACCEPTANCE.md` | | 证据目录说明与 manifest schema | `docs/evidence/README.md` |
| 0002 合规矩阵 | `docs/CONFORMANCE.md` | | 验收标准 | `docs/ACCEPTANCE.md` |
| 冻结 CLI 合同 | `docs/audits/protocol-contract-0002.md` | | 合规矩阵 | `docs/CONFORMANCE.md` |
| 旧 View 取证 | `docs/audits/legacy-view.md`(静态;运行时 `LEGACY_RUNTIME_UNVERIFIED`) | | 冻结 CLI 合同审计 | `docs/audits/protocol-contract-0002.md` |
| 分 PR 证据 | `docs/evidence/PR-01..PR-06/` | | 当前分层与契约 | `docs/architecture/observation-v1-and-analysis-v3.md` |
| 示例 fixture 实测 | `scripts/check-examples.sh`(输出见 `docs/evidence/PR-06/`) | | 契约替换决策 | `docs/decisions/0012-rc4-current-contracts.md` |
| 示例 fixture 实测 | `scripts/check-examples.sh` |
| 观测契约探针 | `scripts/check-observation.py` |
| 零执行哨兵 | `scripts/test-no-exec.sh` | | 零执行哨兵 | `scripts/test-no-exec.sh` |
| 浏览器截图/日志 | `docs/evidence/PR-04/`、`docs/evidence/PR-05/` | | 旧 View 取证 | `docs/audits/legacy-view.md`(静态;运行时 `LEGACY_RUNTIME_UNVERIFIED`) |
| 决策记录 | `docs/decisions/0001..0010` | | 历史 0.2.0 证据 | `docs/evidence/2c7c4f31…/`、`docs/evidence/issue-2/`、`docs/evidence/issue-3/`、`docs/evidence/PR-01..PR-06/` |
## 已知限制与偏差(诚实状态) ## 已知限制与偏差(诚实状态)
- 首版运行仅 `pure` 与受控 `project` fs read/write;`project` 不是 OS 沙箱, - 首版运行仅 `pure` 与受控 `project` fs read/write;`project` 不是 OS 沙箱,
不自动提升 `marqdo.yaml` capability 请求。 不自动提升 `marqdo.yaml` capability 请求。
- SSE 只推送 View 生命周期与终态数据,不承诺逐字 stdout/Token 流(RFC §6.1)。 - SSE 只推送 View 生命周期与 Observation 摘要,不承诺逐字 stdout/Token 流。
- 观测侧注采用内联分组 chip,而非 SVG 曲线;按 RFC §4.4 允许降级(ADR-0010)。 - 观测侧注采用内联分组 chip,而非 SVG 曲线。
- 像素级人工视觉比对与完整 screen-reader 走查仍为 `UNVERIFIED`;自动化证据充分。 - 像素级人工视觉比对与完整 screen-reader 走查仍为 `UNVERIFIED`。
- 本地验收与远端 CI 使用同一入口 `scripts/acceptance.sh`;远端状态以 PR 检查为准。 - 远端 CI 配置已提供但本环境未执行;未运行门禁保持 `UNVERIFIED`。
- 平台:Linux x86_64 glibc 正式验证;其他平台不声明支持。 - 平台:Linux x86_64 glibc 正式验证;其他平台不声明支持。
## 历史
`0.2.0`(2026-11-22)是旧预发布契约时代的完整阅读/执行/导出基线,相关证据
仅作历史参考,不能替代 0.3.0 的 rc.4 门禁:`docs/evidence/2c7c4f31…/`、
`docs/evidence/issue-2/`、`docs/evidence/issue-3/`、`docs/evidence/PR-01..PR-06/`。
旧实现规范与决策保留在 `docs/architecture/RFC-VIEW-0001*.md`、
`docs/architecture/RFC-VIEW-0002.md`、`docs/decisions/0001..0011`(历史记录)。
## 复现文档 ## 复现文档
- 使用/安装:`README.md` - 使用/安装:`README.md`
- 规范:`docs/architecture/RFC-VIEW-0002.md`(当前)、`RFC-VIEW-0001.md`(历史) - 当前契约与分层:`docs/architecture/observation-v1-and-analysis-v3.md`
- 兼容性:`COMPATIBILITY.md` - 兼容性:`COMPATIBILITY.md`
- 变更:`CHANGELOG.md` - 变更:`CHANGELOG.md`
- 决策:`docs/decisions/` - 决策:`docs/decisions/`
@@ -0,0 +1,729 @@
# RFC-VIEW-0001(定稿建议):完整 Markdown 阅读、统一函数调用与显式结果静态导出
> **契约提示**:本文描述完整阅读与结果导出的产品/交互设计,设计仍参考有效;
> 但其中任何协议字段、命令参数或事件名称以
> [`observation-v1-and-analysis-v3.md`](observation-v1-and-analysis-v3.md) 与
> [ADR-0012](../decisions/0012-rc4-current-contracts.md) 的当前契约为准。
> 0.2.0 时代的协议细节是历史记录,不是当前能力。
> **状态:Proposed / 开发规范,不表示已经实现或通过验收。**
>
> **目标仓库:** [`cflmy/marqdo-view`](https://github.com/cflmy/marqdo-view),本次审阅基线 `master@dcb9daeaf4e5eefd8c35aa0c843dd8a0eaf7fef5`(`0.2.0`)。
>
> **核心仓库:** [`cflmy/marqdo-cli`](https://github.com/cflmy/marqdo-cli),审阅基线 `master@652ea763603517ba4d13325a405e3124844ded31`(已包含 3.0.0-rc.2 候选控制流、Analysis v3 与 Execution Events v1)。这些是**源代码审阅事实**,不是新特性已在发行二进制上验证的声明。
>
> **适用对象:** 不熟悉本项目历史的 View/CLI/前端开发者、审查者与测试维护者。
>
> **文档优先级:** 这是一份自足的完整实施 RFC,**整体替代**此前同名 RFC-VIEW-0003 的“历史结果持久化版”和“绝不在导出中包含结果版”;已实现的 RFC-VIEW-0002 能力仍是可复用基线。无须阅读任何聊天或前置 RFC 才能实施。
>
> **一句话产品定义:** **View 是一篇可调用的 Markdown 阅读器;执行结果只在当前交互中暂存,用户主动导出时,才被固化为一份独立、只读、可离线阅读的文档快照。**
---
## 0. 决议摘要:不建结果数据库,只允许显式静态导出
本规范区分三类对象。它们不可互换。
| 对象 | 权威来源 | 生命周期 | 允许操作 |
|---|---|---|---|
| `.mq.md` 源文档、依赖、知识 | 用户项目和版本控制 | 与 View 无关 | 阅读、静态分析、明确调用;**永不被导出结果改写** |
| 当前执行观察:参数、stdout/stderr、返回值、事件 | 真实 CLI `run/call` | View 进程内的有限任务生命周期 | 当前页面显示、取消、短时断线重连、在过期前选择导出 |
| **静态结果快照**:文档、已选定的一次结果、媒体、来源信息 | 用户明确点击“导出(含本次结果)”生成的文件 | 由用户下载/分发后独立于 View | 离线阅读、分享、审查;**不会恢复为可执行会话** |
### 0.1 必须满足的不变量
1. **打开、刷新、跳转、搜索、切换文档、普通静态导出都绝不执行程序。** 显式 `POST /api/runs` 是唯一启动 CLI `run/call` 的入口。
2. **导出结果只复制已完成的一次真实执行观察**,不能因导出而重跑、补跑、自动重试、自动申请权限或执行文档中的代码。
3. **默认普通导出**:`marqdo view export PROJECT --out SITE` 保持只读,内容为完整 Markdown 与安全本地媒体;没有结果数据。
4. **含结果导出**:从已运行的 Live 页面,由用户选定**一条仍在临时内存中**且终态明确的运行记录,确认内容与敏感性,然后导出只读快照。
5. **不建立 RunStore、SQLite、结果目录、浏览器 IndexedDB/localStorage 运行历史、持久 Kernel、跨重启恢复、自动导出。** 导出的文件由用户拥有;View 不维护文件索引与生命周期。
6. **静态 HTML 不得具有运行能力。** 无任何可生效的调用 API;无 `POST /api/runs`、无服务端依赖、无自动联网、无执行按钮假象。即使 HTML 中保存了结果,它也不是可恢复的会话。
7. **不得将运行输出伪装为原始 Markdown。** 可见标签须注明“本次执行快照”、运行目标、终态及来源摘要;只有通过验证的事件才能附着到源码位置。
8. **不为 View 修改语言内核或新增 `save_result` HostOp。** 所有真实计算仍使用公开 CLI、Analysis、Trace、Execution Events 和 Tool 协议。
9. **View 的“无保存”应精确定义为无自动、隐式、持久的运行存储;允许用户显式创建静态文档制品。** 这两者不矛盾。
### 0.2 用户路径(产品级完成标准)
1. 用户打开 `marqdo view examples/report/index.mq.md`,看到排版完整的文档、图片、公式、链接;不会自动运行。
2. 用户在 `## @exec ...` 函数标题旁点击“调用”,输入参数、查看权限和预算,确认一次 `marqdo call`。
3. View 显示实时 stdout、分支/循环事件、最终返回值,结果位于相关函数附近,但与源码视觉区分。
4. 用户点击结果旁的 **“导出文档(含本次结果)”**;预览会包含的结果、参数/隐私选项、失败或截断标记。
5. 用户确认后下载一份静态网站包(ZIP;内部 `index.html` + 媒体/字体/样式 + manifest)。解压后可用 `file://` 离线浏览;查看结果无需 CLI、View Server 或网络。
6. 页面再次刷新或 View 服务重启,不保证还存在这次运行;**已经导出的 ZIP 不受影响**。用户没有选择导出,就不会留下 View 管理的持久记录。
---
## 1. 完整职责边界:什么是 Markdown、执行观察和导出制品
### 1.1 Markdown 仍是页面主体
Marqdo 使用固定的 `marqdo.md.v1` Markdown AST;`@exec` 中的普通无标记叙述不执行,显式 `Strong` / `Emph` / inline Code 载体进入语句映射。`@knowledge` 是惰性知识区域。视图不能从视觉标记、Markdown 列表符号推断控制流;语义只依赖公开 Analysis。
UI 不采用 Jupyter 的 Cell/Kernel 模型。用户阅读的是一篇连续的、可执行知识文档。函数周围只有克制的调用入口和**可收起的实际结果**;列表、表格、图片、公式优先于状态卡片。
### 1.2 执行与结果的所有权
- **CLI**:检查、解析、调用、运行、权限、安全预算、计算真值。
- **View ExecutionController**:检查调用请求、显式确认、单活动任务、有界 stdout/事件与终态、取消、短时 SSE 重连;不是持久存储系统。
- **View Reader**:渲染 Markdown 与来源已校验的本次计算观察;不解释 Marqdo 表达式。
- **StaticExporter**:从读取模型及用户明确选中的**已验证终态观察**构建不可执行的离线制品;只做转换/打包,不调用 CLI。
- **用户项目**:如果需要 CSV、JSON、PNG 或其他正式业务数据,仍应由受授权的 Marqdo 程序或其他通用工具明确写出。View 的网页快照不等于领域数据存储。
### 1.3 不做的功能
不做历史列表、保存每次运行、最近实验恢复、Notebook Run All、自动重跑、后台刷新计算、不可见状态会话、结果数据库、实验对比平台、运行数据云同步、自动把运行输出写回 `.mq.md`、对 Math/Agent/Quantum 添加特殊处理。
用户在同一 View 页面上可再次调用函数;当前结果更新即可。为了控制复杂度,**第一阶段一份快照只包含用户明确选定的一次运行**;多次调用并排比较和合并多份结果属于后续独立需求。
---
## 2. 审阅基线与当前真实缺口(固定 SHA)
### 2.1 View 侧
| 分类 | 文件/实现 | 已确认事实 | 实施要求 |
|---|---|---|---|
| EXISTS | `src/reader/markdown.rs` | `comrak` 构造文档树,含图片、链接、表格、列表、数学、UTF-8 source span | 复用既有解析器,不复制第二套 Markdown→语义管线 |
| DEFECT | `src/reader/render.rs::Inline::Image` | 任何图片都显示“阻止自动加载”占位;合法本地图也不可见 | 增加同源安全本地图片解析、呈现与静态打包 |
| DEFECT | `src/reader/render.rs::resolve_link` | `.mq.md#fragment` 重写时可能丢 fragment;标题 ID 按字节位置生成,与常见 Markdown `#slug` 不一致 | 标准标题锚点、重复标题、跨文件锚点均需可导航 |
| DEFECT | `src/reader/render.rs::MathBlock / Inline::Math` | 公式主要显示 LaTeX 原文,不是真正数学排版 | 实现离线、安全数学渲染 |
| EXISTS | `src/reader/render.rs::render_functions` | 已有函数列表、调用按钮和签名信息 | 改善函数标题附近的调用与结果关联,不重写调用机制 |
| EXISTS | `src/execution/request.rs` | `RunRequest`、entry/function、参数校验、Analysis digest 与权限 | 继续保留唯一运行入口和确认流程 |
| EXISTS | `src/execution/controller.rs` | 单活动任务、去重、取消、内存任务、默认终态 TTL=15 分钟、上限 32 任务 | 在**现有 Job 终态内**保留导出需要的有界可信投影,不创建第二套历史库 |
| EXISTS | `src/execution/events.rs` | View 自有 SSE 生命周期事件协议 | 新 CLI 实时事件通过一个 EventBridge 映射;不创建第二个 Controller |
| DEFECT | `src/protocol/analysis_v2.rs` / `tool.json` | View 仅接受 Analysis 2;新 Core 对部分控制流发 Analysis 3 | 支持 Analysis v2/v3,基于 schema_version 协商 |
| DEFECT | `src/core_client.rs` | 现有执行主要为 `--json` + Trace,运行末尾读取结果 | 消费新 `--event-stream jsonl`,不能与 `--json` 同时使用 |
| EXISTS | `src/export.rs` | 静态导出包含 HTML 和 View 内置资源、manifest;还未集成用户 Markdown 图片 | 扩展已有 StaticExporter;允许**可选** `ExportResultOverlay`,不得重写导出器 |
| EXISTS | `src/server/routes.rs` | 有 7 条固定路由,执行入口是 `POST /api/runs` | 增加一个受保护的结果**导出** POST,而非运行/保存/历史路由 |
固定来源:[`View 源码`](https://github.com/cflmy/marqdo-view/tree/dcb9daeaf4e5eefd8c35aa0c843dd8a0eaf7fef5)。
### 2.2 Core 侧公开协议(不可通过猜测添加字段)
- [`spec/markdown-profile.md`](https://github.com/cflmy/marqdo-cli/blob/652ea763603517ba4d13325a405e3124844ded31/spec/markdown-profile.md):`marqdo.md.v1`,CommonMark/GFM/数学/front matter 扩展的闭合选项。
- [`spec/analysis-v2.md`](https://github.com/cflmy/marqdo-cli/blob/652ea763603517ba4d13325a405e3124844ded31/spec/analysis-v2.md)、[`v3`](https://github.com/cflmy/marqdo-cli/blob/652ea763603517ba4d13325a405e3124844ded31/spec/analysis-v3.md):多臂 `else if` 两版支持;含 `break/continue` 的内容可能选择 v3。View 不能假设永远是 v2。
- [`spec/trace-v2.md`](https://github.com/cflmy/marqdo-cli/blob/652ea763603517ba4d13325a405e3124844ded31/spec/trace-v2.md):Trace 绑定精确 Analysis JSON 字节 SHA-256,带 source span 的真实事件,可截断、不可伪造。
- [`spec/execution-events-v1.md`](https://github.com/cflmy/marqdo-cli/blob/652ea763603517ba4d13325a405e3124844ded31/spec/execution-events-v1.md):`run/call --event-stream jsonl`,实时 stdout/stderr chunk、结构事件、可选选择性值观察与终态;`--event-stream` **与 `--json` 互斥**;Trace v2 可并用。
- [`spec/tool-v1.md`](https://github.com/cflmy/marqdo-cli/blob/652ea763603517ba4d13325a405e3124844ded31/spec/tool-v1.md):独立 Tool 的调用/安装/协商,不为 View 添加 CLI 领域分支。
**实现事实不等于发行承诺。** 所有用到 Analysis 3、Events v1 的发布门禁都必须用同一个真实已发布 Core 二进制验证。
---
## 3. 最小模块架构:不是持久化系统
```text
原始项目 (.mq.md + 本地图片/媒体)
│
▼
DocumentService ──► MarkdownDocument + SourceIndex
│ │
├── CoreAdapter ─────┤ Core `check --emit` → Analysis v2/v3
│ │
▼ ▼
PresentationModel ◄── SemanticProjection
│
├── ReaderRenderer ──► Live HTML ← 当前调用结果(可选瞬态附着)
│ ▲
│ └── LinkResolver / MediaResolver / MathRenderer
│
浏览器(显式调用)
│ POST /api/runs(唯一执行入口)
▼
ExecutionController ─► CoreAdapter ─► 真实 MARQDO_BIN run/call
│ │
│ ├── Execution Events v1 → EventBridge → SSE
│ └── Trace v2 → 精确摘要绑定
▼
当前 Job 的有界终态投影(仅内存;TTL 到期删除)
│
│ 用户点击“导出文档(含本次结果)”
▼
POST /api/exports ─► ExportSelectionValidator
│ │
│ ├─确认 session / run_id / 终态 / 摘要 / 隐私
│ └─构造只读 ExportResultOverlay
▼
StaticExporter(与普通导出同一套 Renderer)
│
▼
ZIP: index.html + pages/ + media/ + assets/ + manifest.json
│
└── user download → 文件独立存在;View 不保存索引/历史
```
### 3.1 模块不可违背的依赖方向
- `protocol/` 只验证公开协议,不依赖 `reader/`、DOM、HTTP。
- `execution/` 只持有 CLI 执行与有界任务状态,不存 HTML;Job 可暴露经鉴权的**只读** `TerminalExportCandidate`。
- `reader/` 可以接受不可变的 `ExportResultOverlay` 并安全渲染,但不得反向调用 `ExecutionController`。
- `export.rs` 只接受静态文档模型、媒体清单和可选的不可变导出叠加层;**不得有 `run()`、`call()`、命令执行或未验证事件解析逻辑**。
- `server/` 鉴权并从当前 Job 获取候选结果,然后传入导出器;这是唯一把瞬态执行观察连接到静态发行物的边界。
- Live、纯文档导出、含结果导出共用 **同一个** `DocumentModel`、`ReaderRenderer`、Link/Media Resolver 和主题。禁止第二套“结果版 HTML 模板”。
### 3.2 推荐目录变更(文件名仅为建议,不强求完全一致)
```text
src/
core_client.rs # MARQDO_BIN 唯一公开调用适配层
protocol/
analysis.rs # Analysis v2/v3 版本分发 + 验证
execution_events_v1.rs # Core NDJSON 事件验证
trace_v2.rs # Trace 绑定与可选观察
reader/
markdown.rs # 原有 comrak 文字/结构模型
model.rs # 原有 PresentationModel
render.rs # 单一 HTML 渲染器
links.rs # 文档路径、标题锚点
media.rs # 项目内媒体只读解析/安全检查
execution/
request.rs # 统一参数与权限请求
process.rs # 唯一进程执行实现
controller.rs # 单活动任务;瞬态 Job;无结果数据库
events.rs # View SSE
export_candidate.rs # 从已完成 Job 只读投影可导出字段
export.rs # 共用静态导出核心
export_result.rs # 选择、审查、脱敏、生成 Overlay
server/
routes.rs # 一个新 POST /api/exports
security.rs # session/Origin/CSRF
assets/
reader.js # 含结果导出确认、文件下载
reader.css # 只读结果排版
```
**若仅需几十行代码,不必为了名字建立一层空模块。** 核心约束是责任单一、依赖单向、统一协议和单渲染管线。
---
## 4. Markdown 全面可视呈现:优先于结果导出
### 4.1 正常可显示的内容
| 类型 | 最小通过要求 |
|---|---|
| H1–H6/Setext | 连续文档流;保持层级;`@exec/@knowledge` 标注不吞标题内容 |
| 段落/行内强调/代码 | CommonMark 源样式;载体高亮不得改变内核语义 |
| 有序/无序/嵌套列表 | 真正 HTML 列表层级;`1.` 分支风格与 `-` 循环风格正确显示;**列表本身不执行** |
| GFM 表格、任务列表、删除线 | 表格对齐、checkbox、删除线真实可见 |
| 代码围栏/引用/分隔线 | 正确显示并保持惰性资源属性 |
| 本地 PNG/JPEG/WebP/GIF/SVG | 有权限控制的真实图片渲染;替代文本、尺寸限制;本地恶意 SVG 不得获得脚本能力 |
| 同页、跨 `.mq.md`、外部链接 | fragment 不丢失;重复标题确定性锚点;外部链接只导航不自动下载 |
| 行内与块级数学 | 离线 KaTeX 或等效安全渲染;无 CDN;不可执行 LaTeX 宏 |
| 源码态 | 无损精确 UTF-8 原文;中文/BOM/CRLF span 可对应 |
| Raw HTML | 默认**不直接执行** HTML/JS;安全降级为明确提示或受限 allowlist,而非声称支持运行任意网页代码 |
注意:Marqdo 的 Markdown profile **不是所有非标准 Markdown 扩展的全集**。例如脚注、自动 URL 链接、wiki-link 等若未启用,不得假称内核支持。View 可展示原文,但不得偷偷让解析选项改变程序语义。
### 4.2 图片与媒体安全
- 从当前文档目录解析相对 URL,允许 `../assets/x.png` **仅在规范化并解析真实路径后仍位于项目根之内**;阻止绝对路径、NUL、控制字符、 symlink 逃逸与 TOCTOU。
- Live 增加受保护的只读媒体读取路由;验证扩展名不足,必须校验 MIME/魔数及尺寸/字节预算。
- Export 将引用的安全媒体复制到 `media/`,计算 SHA-256 和 manifest,脱离原工作目录仍可 `file://` 阅读。
- 默认不自动拉取远程图片、CDN 脚本、字体或执行输出引用;远程资源降级时保留 alt/地址与原因。
- 原始 HTML、SVG 中的脚本、`javascript:` URL、`data:text/html` 等受限;普通外链可单击导航,但不自动发送页面内容。
### 4.3 链接与锚点
`resolve_link()` 必须统一处理:`#slug`、`doc.mq.md#slug`、`../docs/doc.mq.md#slug`、百分号编码与 Unicode、重复同名标题、文档重命名及不存在的目标。Live 和 Export 应产生同义结果,实际点击必须到达目标标题;不能只看生成了 `<a>` 标签。
源字节 span ID 可以继续用于 Analysis 精确绑定,**但需要另外提供符合 Markdown 阅读习惯的稳定标题 slug**;两者分别服务语义锚定与读者跳转,不可混用。
### 4.4 数学公式
数学排版是 View 责任,不是 Math HostOp。资源应离线、固定版本、禁止不可信 HTML/宏,Live 和 Export 共用同一公式处理与字体资产;导出的计算快照即使不能执行,也必须保留公式排版。
---
## 5. 统一单函数执行:View 只有一条运行数据通道
### 5.1 静态能力与目标
- `check --emit` 输出 Analysis v2 或 v3(按 JSON 实际 `schema_version` 验证,绝不猜)。
- H2 `@exec` 函数从 Analysis 确定可调用目标、签名、参数名、默认值;`@knowledge` 不调用。
- `main` 显式 `run` 与所选函数 `call` 使用**同一** `ExecutionController`、权限确认、预算、终态和结果组件;不得扩展为分函数单独后台线程池。
- 对 `else if` 使用已有 `branch.arms`;对 `break/continue` 投影 Analysis v3 对应节点。不存在这些语句时 v2 继续正常支持。
- 跨文档函数调用遵循 CLI `call` 已公开可调用目标限制;不能把依赖模块的任何可见标题都当成可直接调用的独立入口。
### 5.2 实时事件
运行必须在真实已发布二进制上验证:
```bash
marqdo check index.mq.md --emit ./analysis.json
marqdo call index.mq.md 计算均值 --arg 'a=3' --arg 'b=5' --event-stream jsonl --trace-file ./trace.json
```
> 示例仅说明调用与协议形状;参数名称、函数及作用域须与项目真实声明匹配。`--event-stream jsonl` 与 `--json` 互斥,必须做模式选择,不能将两者拼在一起。
`EventBridge` 负责完整解析 `stream.opened`、`run.started`、`stdout.chunk`、`stderr.chunk`、`call.*`、`branch.eval`、`loop.iteration`、`control.break/continue`、`effect`、`run.completed/failed/rejected`。严格校验 seq、schema/version、run_id、终态唯一性、base64 长度和源摘要;EOF 无终态就是 `incomplete`,不是成功。
SSE 仍为 View 与浏览器之间的现有通道。**Core NDJSON 和 View SSE 是不同协议**;允许 Versioned EventBridge 映射,不得把未经验证的 JSON 直接抛给前端执行或视为可信 HTML。
### 5.3 权限和预算
沿用现有 session Cookie、Origin、CSRF、单活动任务、显式授权与 `pure/project` 限制;不暗中开放 net/process/foreign/plugin。Live 页面调用与静态导出都是独立行为;**静态导出 API 不具备运行 Core 的权限或调用路径**。
当前的有界内存 Job 已足够提供“最近一次结果导出”,无需结果历史服务。若执行输出过大,终态保留安全截断标记;**不要为了导出提高 Core 的执行权限或无限内存预算**。
---
## 6. 核心新功能:显式导出包含一次运行结果的静态文档
### 6.1 两种导出,单一实现
**A. 纯文档导出(默认、既有模式)**
```bash
marqdo view export ./project --out ./site
```
含原始 Markdown 的静态阅读视图、引用本地安全媒体、公式资产、manifest。**无需执行、不读取 Controller、不含运行结果**。该命令在全新进程中运行,不存在“刚才浏览器里跑过一次所以能找到结果”的假设。
**B. 含本次执行结果的导出(新增、仅 Live 当前会话)**
浏览器内先显式运行一次,再在终态区域选择“导出文档(含本次结果)”,勾选敏感字段和输出范围,确认后调用 `POST /api/exports`。后台从**同一进程、同一 session 的现有 Job 内存态**读取这次终态,验证后传给同一个 `StaticExporter`;最后直接返回 ZIP 文件供用户下载。**绝不重新运行 CLI**。
本阶段不提供 `marqdo view export --include-last-run` 等会误导人的选项:一个新启动的命令行进程无权也无法访问浏览器会话中的内存任务。未来如需纯 CLI 的“明确运行 → 导出”一体化工作流,必须另立接口规范,要求可验证的同一次执行和显式输出,不能偷偷变成持久 RunStore。
### 6.2 唯一新增 HTTP 路由
`POST /api/exports`,**不是** `/api/runs/save`、`/api/history`、`/api/records`;其职责仅为把一次当前终态转为即刻下载的静态制品。
提议请求格式(本协议为**View 自有新增 v1**,需要在 View 仓库落地 schema 与负例):
```json
{
"schema": "marqdo.view-static-export-request",
"schema_version": 1,
"run_id": "<current-session-terminal-job-id>",
"document": "index.mq.md",
"analysis_digest": "sha256:<exact-current-analysis-bytes>",
"scope": "document",
"include": {
"result_value": true,
"stdout": true,
"stderr": false,
"trace_summary": true,
"arguments": false
},
"confirm_sensitive_output": false,
"client_export_request_id": "<opaque-id>"
}
```
- body 大小、字段集合、枚举、长度均有严格上限;拒绝未知字段、未知 major。
- 必须是当前 Cookie session 的 Job;`run_id` **不是**授权令牌,不得仅凭 ID 访问其他会话结果。
- 服务器重新验证 Origin + CSRF 及当前文档、真实当前 Analysis 字节摘要、项目身份、Job 终态与来源。
- `run_id` 处于 `running/accepted`、已过 TTL、不存在或不属于当前 session:明确拒绝;**绝不启动新运行**。
- `scope=document` 第一阶段只导出承载该次函数的文档和必要媒体;如果继续保留现有项目级导出布局,则其他页面为**纯文档**,不得把一次结果贴到所有页面。
- `include.arguments=false` 默认。不要默认导出输入参数的实际表达式、授权 glob、环境变量、文本观察值或原始扩展细节。任何含敏感数据选择必须展示最终预览并二次确认;`confirm_sensitive_output` 不替代用户真实 UI 操作。
- 可以导出失败、取消、超时的**终态观察**,但必须醒目标记 `failed/cancelled/timed_out` 和是否有部分数据,不得当成成功结果;第一阶段可为它们提供明确的单独复选确认。
- HTTP 输出为直接下载的 `application/zip`,设置 `Content-Disposition: attachment`、`Cache-Control: no-store`、`X-Content-Type-Options: nosniff` 与严格 CSP。ZIP 构建在有界、私有、短生命周期临时目录内,发送完立刻清理;不增加后台缓存下载接口。
- 浏览器使用经过认证的 `fetch POST` 获取 ZIP `Blob` 后触发用户下载,及时释放 Blob URL;**不能用 localStorage/IndexedDB 缓存 ZIP 或计算结果**。
### 6.3 一个额外的只读导出投影,而不是新数据系统
不新增 `RunStore`。在原有 `Job` 终态中保留足够导出的、**已经完成验证且有字节上限**的 `TerminalExportCandidate`;只在现有 TTL 内存在。Controller 暴露:
```text
get_export_candidate(session_id, run_id)
-> Result<ImmutableTerminalExportCandidate, ViewError>
```
这个 API **只读、不能执行、不分配长期 ID、不创建记录文件**。内部包含:
- View `run_id` 与 CLI 真实 `core_run_id`(如果协议提供,来源明确)、函数 `function_id`、源文档 `module_id`/相对路径、终态和时间。
- **精确** `analysis_digest`、`root_id`、相关源码 SHA-256、可用的 lock digest、已选择的媒体哈希。为避免泄漏,绝对路径、用户名、环境变量、秘钥不放入导出。
- Core 版本与协议版本、运行模式和预算的**安全摘要**(不包含授权秘密和具体敏感路径)。
- 通过解析器验证后的 Wire Result、stdout/stderr 文本/字节及其完整性状态、可选经核验的 Trace 结构摘要。
- `truncated`、`trace_invalid`、`source_changed`、`output_incomplete` 等独立事实状态;不能为了拥有一个“成功”徽章而合并这些区别。
**注意隐私:** 不记录省略参数值的未经加盐普通哈希作为“隐私替代”,低熵参数可能被猜测;默认只标记 `parameters: omitted`。需要复现实验的用户可以明确选择导出必要的可见参数并接受隐私提醒。
### 6.4 快照来源与失效规则
- 导出开始前获取并核对**当前** `check --emit` 的真实 Analysis 字节摘要;必须与候选结果的 `analysis_digest` 相同,来源 `root_id` 与选定函数 ID 相符。`run.started.source` 的摘要也需要一致。
- 用户运行之后源码、导入内容、锁文件或相关模块变更:第一阶段**拒绝“将旧结果贴到新正文”**,UI 提示先重新运行;不得仅凭函数名相同就附着。
- 运行时源验证通过,但 Trace 文件无效或缺失:导出可保留真实终态、返回值和 stdout,但必须清楚标记 `trace_status=invalid/unavailable`,**不附着任何未经核验的源码侧注**。
- Trace 截断、输出截断、SSE 未收到终态:区分处理。无真实终态的运行不可作为成功快照;可以提供“错误报告”但必须单独实现与审查,不在 P0 混入。
- 静态快照在导出时被冻结;以后源代码变化**不会改变已下载的 HTML**。manifest 提供当时内容的来源摘要,但**不声称当前代码仍与历史结果匹配**。
- 来源身份不是数学正确性证明或第三方签名。除非独立 Prove 工具验证过证书,不展示 `proved`。
### 6.5 导出的内容结构
最低交付为一套 HTML+资产的 ZIP,不要求单文件 HTML;优先延续当前 `StaticExporter`:
```text
marqdo-report-2026-11-24.zip
index.html
pages/
index.mq.md.html
media/
diagram-<digest>.png
assets/
reader-<digest>.css
math-<digest>.css
...
manifest.json
```
`index.html` 中的结果应插入**所选函数阅读区域下方**,并在页面顶部有简洁的“本文件包含一次执行快照”提示。静态导出页面的调用按钮应被完全移除;结果使用 `<details>` 或可打印的常规 HTML,禁用 JS 也能阅读。源码段落和结果块的 DOM 类名/aria 标签不同。
**建议 manifest v2 示例**(是 View 自有导出契约,不是 Core 改动):
```json
{
"schema": "marqdo.view-export",
"schema_version": 2,
"view": {"name": "marqdo-view", "version": "<view-version>"},
"source": {
"project_root_id": "root:demo@0.1.0",
"document": "index.mq.md",
"source_sha256": "<64hex>",
"analysis_digest": "sha256:<64hex>",
"lock_digest": "<lock-digest-or-null>"
},
"execution": {
"included": true,
"target": "root:demo@0.1.0::index.mq.md::计算均值",
"status": "succeeded",
"source_verified": true,
"trace_status": "verified",
"result_complete": true,
"parameters": "omitted",
"core_protocol": {"analysis": 2, "trace": 2, "events": 1}
},
"assets": [
{"path": "assets/reader-<digest>.css", "sha256": "<64hex>", "size": 1234}
],
"files": [
{"path": "index.html", "sha256": "<64hex>", "size": 5678}
],
"executed_during_export": false
}
```
这些 `<...>` 字段是**规范示例占位符**,不是可运行的发行文件。真实 manifest 必须通过自有 JSON Schema 校验。`execution.included` 与 `executed_during_export` 是两个不同概念:**包含过去一次明确执行的观察,不代表导出动作执行了任何代码**。不要沿用只有一个易混淆 `executed` 布尔值的旧表示。
是否在 HTML 中另存一份完整机器可读 EventStream,需单独考虑隐私、文件膨胀和浏览器安全;**P0 只保存选择的结果与经过验证的有界摘要**,并在 manifest 中声明完整性,不把所有 token、每个变量、原始秘密偷偷打包。
### 6.6 导出样例的实际 HTML 阅读效果
源 Markdown(继续保持普通、可直接渲染):
````markdown
# @knowledge 一个小型统计实验
这份文档说明两数平均值的计算依据,并允许读者调用函数。
![算法说明图](./media/overview.png)
## @exec 计算均值
对两个整数求平均值;结果可能有小数部分。
`params(a: Int, b: Int)`
**结果 = (a + b) / 2**
`return 结果`
````
用户手动调用 `计算均值(a=3, b=5)`,假设真实返回 `4`。View 中显示:
> **本次执行** · 函数:计算均值 · 成功
>
> 参数:a=3, b=5(仅在本地 UI 中显示;是否导出由用户决定)
>
> 返回值:`4` · 来源:已验证的 CLI 终态
>
> [导出文档(含本次结果)]
用户确认导出时,静态页面中对应函数下方出现:
> **执行快照(用户于导出时明确附加;不是源文档)**
>
> 执行目标:计算均值;状态:成功;返回值:`4`
>
> 来源:项目/源码/Analysis 摘要见 manifest;未在导出期间重新运行
>
> 参数:未包含(默认隐私设置)
这里的 Markdown 行为只是产品说明,并不意味着执行结果会注入项目 `.mq.md` 文件。样例需要在真实 CLI 与 browser E2E 中验证;如数值类型的 Wire 表达与示意不同,应以真实协议编码为准。
---
## 7. 导出安全与隐私:这是文件发行,不是本地历史
### 7.1 显式披露与选择
输出可能包含令牌、路径、个人信息、数据库记录或远端服务响应。点击导出后至少展示:目标函数、执行终态、所选 stdout/stderr 大小、结果字节数、是否包含参数值、是否含观察值、是否有失败/截断/敏感性风险。用户必须明确确认;不得把浏览器执行结果默认为可发布数据。
推荐默认:包含返回值和有界 stdout、经过验证的结构事件**摘要**;不包含 stderr、原始参数表达式、环境变量、绝对路径、观察到的原始 Text 值、资源句柄或完整二进制内存。用户如需增加内容必须手动勾选,并通过大小及隐私门禁。
### 7.2 严格隔离和输出转义
- 同源鉴权 Cookie + Origin + CSRF + session-job 所有权。禁止跨浏览器会话导出同一个 `run_id`。
- 编码与 HTML 转义统一在 `ReaderRenderer`;stdout、stderr、result/Trace 字符串必须以**文本**渲染,不允许 `innerHTML`、远端模板、运行输出中的 `<img onerror>` 生效。
- ZIP 安全:固定内容路径与规范化目录名、绝不写 `../` 归档条目、不包含系统绝对路径、不将软链接解引用到项目外;控制总文件数、总字节数、单媒体上限、压缩比/解压后大小。
- CSP:静态快照默认 `default-src 'none'`,只开放打包的 CSS、同源相对媒体和必要的离线公式字体;不要包含自动远程字体、远程 JavaScript、iframe 等。
- HTTP `no-store`、下载后立即删除服务端临时文件;浏览器下载动作结束撤销 Blob URL。
- manifest 内容摘要不等于签名;可选独立签名属于未来工具,不得虚构真实性认证。
### 7.3 无保存架构门禁
仓库测试/静态检查应拒绝以下新增行为:
- `.marqdo-view/runs/`、`run_history.db`、`RunStore`、`RunRecord`、浏览器 IndexedDB 持久输出与 `POST /api/runs/save`。
- View 进程启动后主动扫描历史输出或恢复终态。
- `marqdo view export` 在新进程中猜测/查找“最近一次执行结果”。
- 含结果导出未提供有效 `run_id` 却直接执行 Core 以填充结果。
- 为导出特意保留永久临时目录,或导出后在服务器暴露永久下载 URL。
**允许:** 终态 Job 的原有 TTL 内存、只在响应期间存在的临时 ZIP、用户已下载的 ZIP、静态 HTML 所引用的必要本地媒体与样式。
---
## 8. 浏览器与 HTTP 交互设计
现有 API 不破坏,新增路由只做快照导出。
| 路由 | 作用 | 会执行 Core? | 结果生命周期 |
|---|---|---:|---|
| `GET /`、`GET /file?...` | 阅读当前文档 | 否 | 无 |
| `GET /assets/...` | View 内置 CSS/JS | 否 | 发行资源 |
| `GET /api/documents` | 文档列表 | 否 | 无 |
| `GET /media/...`(提议) | 验证后的项目媒体 | 否 | 只读 |
| `POST /api/runs` | **唯一显式运行入口** | **是** | 现有单任务、临时 Job |
| `GET /api/runs/{id}/events` | SSE 重连/观察 | 否 | TTL |
| `POST /api/runs/{id}/cancel` | 取消已有运行 | 不启动新运行 | TTL |
| **`POST /api/exports`(提议)** | 当前终态 → 静态 ZIP 直接下载 | **绝不** | 响应完成后删除服务端临时文件 |
浏览器 UI 流程:
```text
未运行文档
│ 点击“调用”→ 填参 → 确认
▼
执行中:EventBridge → SSE(取消可用;“含结果导出”不可用)
│ 唯一终态
▼
结果面板:返回 / stdout / 事件 / 状态 / 来源
├── 清除当前结果(仅内存 UI)
└── “导出文档(含本次结果)”
│
▼
结果范围 + 隐私预览 + 明确确认
│ POST /api/exports(无 Core 调用)
▼
浏览器下载 .zip,独立离线可阅读
```
若用户选择“导出纯文档”,仍走现有 StaticExporter,只传 `ExportResultOverlay=None`。不应把“已经在 UI 中看到了结果”理解成自动将它放入任何普通导出包。
---
## 9. 数据边界:实现者需要的最小类型与失效状态
提议数据模型(代码为设计伪类型,不表示当前仓库已有这些定义):
```text
ImmutableTerminalExportCandidate {
view_run_id, session_owner, terminal_status,
function_id, module_id, document_relative_path,
core_version, analysis_version, analysis_digest,
project_root_id, source_sha256, lock_digest?,
result_value?, stdout?, stderr?,
trace_status, verified_trace_summary?,
output_complete, observation_truncated,
created_at, terminal_at
}
ExportSelection {
run_id, document, analysis_digest,
include_result_value, include_stdout, include_stderr,
include_trace_summary, include_arguments,
confirmed_sensitive_output
}
ExportResultOverlay {
source: VerifiedSourceBinding,
target: VerifiedFunctionIdentity,
state: TerminalState,
value: SafeDisplayValue?,
stdout: EscapedText?, stderr: EscapedText?,
trace: VerifiedTraceSummary?,
completeness: ExplicitFlags
}
```
**禁止 `ExportResultOverlay` 保存 `Arc<Job>`/锁/进程句柄**;它是从执行端复制出的受上限约束、不可变的数据。将其传给 `StaticExporter` 时,不允许导出器自行重查 Controller,也不允许重新解释 Value Wire。
状态显示必须区分:`not_run / running / succeeded / failed / cancelled / timed_out / incomplete / source_changed / trace_unavailable / trace_invalid / trace_truncated / output_truncated`。其中失败/取消/截断是不同维度;不能把 `trace_invalid` 当成运行失败,也不能把运行成功当成完整 Trace 或证明成功。
---
## 10. 真实测试:先构造无法蒙混的 fixture
### 10.1 必需的示例项目
```text
examples/complete-reader/
marqdo.yaml
index.mq.md # @knowledge、@exec、文本、列表、表格、公式、函数
docs/explanation.mq.md # 带跨文档与 fragment 链接、重复标题
media/flow.png # 真实 PNG,非占位字符串
media/result.webp # 真实 WebP,需解码校验
media/diagram.svg # 经过安全审核的 SVG
media/README.md # 资源来源及使用许可
```
必须有显式函数:`main`、有参数纯函数、含 `else if` 的函数、含 `break/continue` 的循环、失败函数和有界 stdout 函数。真实 Core 使用固定 SHA 的 Linux 发行包测试;View UI 使用真实 Chromium,不仅是 HTML contains 断言。
### 10.2 主要验收矩阵
| ID | 测试情景 | 必须观察到的事实 |
|---|---|---|
| MD-01 | 本地 PNG/WebP/GIF | 实际 `naturalWidth>0`,alt 有效,响应 MIME 与哈希正确 |
| MD-02 | 图像引用 `../media/x.png` | 根内允许;逃逸根、symlink 到外面拒绝 |
| MD-03 | 图片静态导出后离线打开 | 没有任何网络请求,图片仍显示 |
| MD-04 | 外链/相对链接/同页 anchor/跨文件 anchor | 实际点击到达目标;重复标题确定性编号 |
| MD-05 | 行内/块数学和 GFM 表格、列表 | Live、Export 同样渲染,无远端字体 |
| MD-06 | Raw HTML/恶意 SVG/JS URL | 不产生脚本执行或远端加载 |
| CORE-01 | 纯函数 Analysis v2 | 函数表单可用、结果正确 |
| CORE-02 | 带 `break/continue` 的项目 Analysis v3 | View 成功协商、显示正确语义,不误拒绝 |
| CORE-03 | `else if` 多臂 | View 不重新推断分支;结构与来源正确 |
| CORE-04 | `--event-stream jsonl` | `stream.opened` 到唯一终态按 seq 显示;不与 `--json` 混用 |
| CORE-05 | stdout 中间输出 | 执行完成前可见;最终字节与真实输出一致 |
| CORE-06 | EOF 无终态 / 非法 NDJSON / 源摘要错 | 标 `incomplete`/`invalid`,不伪造成功 |
| CORE-07 | 未确认权限/无 main/错误参数 | 不能执行或提示正确,不自动降级权限 |
| EXPORT-01 | 未执行时普通导出 | 没有结果,Core `run/call` 计数 0 |
| EXPORT-02 | 已完成一次函数调用后普通导出 | **仍不包含结果**,执行次数不增加 |
| EXPORT-03 | 已完成一次函数调用后含结果导出 | ZIP 解压可见选中的真实结果,Core 调用数**完全不增加** |
| EXPORT-04 | 同一函数另一次调用 | 只能选定明确的 run_id,不能混合结果 |
| EXPORT-05 | 导出前源码或锁变更 | 拒绝绑定旧结果与新文档;没有隐式重跑 |
| EXPORT-06 | `run_id` 属于其他 session、过期、仍运行 | 403/404/409 中明确稳定错误;没有内容泄漏 |
| EXPORT-07 | 参数/文本观察值涉及秘密 | 默认不含参数、stderr、敏感原始观察;显示导出预览与确认 |
| EXPORT-08 | stdout 包含 `<script>`、`<img onerror>` | 导出页面显示为纯文本,Chromium 无脚本事件 |
| EXPORT-09 | 失败/取消/超时、Trace 缺失/截断 | 显示真实状态;仅合规字段被导出;不标“已验证成功” |
| EXPORT-10 | 导出下载 ZIP 后关闭 View/删除临时目录 | `file://` 完全离线可读、无外部请求;没有依赖 localhost |
| EXPORT-11 | View 重启、超过终态 TTL | 不能恢复任何运行;先前已下载的 ZIP 正常 |
| EXPORT-12 | POST 导出未带 CSRF 或跨 Origin | 拒绝;不进入生成器、不访问其他 session 的 Job |
| EXPORT-13 | 多个恶意路径、ZIP 条目、超大结果 | 不发生目录穿越、内存失控、Zip Slip |
| EXPORT-14 | snapshot manifest / CSS / 媒体篡改 | 哈希验证失败;结果来源与资产身份可核对 |
| EXPORT-15 | 打包中途失败、客户端断开 | 无半成品持久文件;临时文件被清理 |
| ARCH-01 | 查找 View 源码的历史库、持久缓存 | 无 RunStore/历史 DB/跨重启恢复/浏览器结果存储 |
| ARCH-02 | 解析导出函数调用关系 | `StaticExporter` 无 `run/call` 依赖;只有 POST `/api/runs` 执行 |
| ARCH-03 | 单一渲染器 | Live、纯文档导出、含结果导出复用同一个 HTML 构造与安全转义 |
### 10.3 三条最高优先级黑盒门禁
1. 打开 View → 不执行;运行一次 → `run/call` 次数恰为 1;点击“导出含结果” → 次数**仍为 1**。
2. 将 `.mq.md`、图片、依赖摘要在运行之后改变 → 含结果导出**拒绝把旧结果贴到新正文**;不尝试重跑。
3. 下载 ZIP,关闭 View Server,断网,清空浏览器缓存后,从 `file://` 阅读文档、图片、公式及结果;没有脚本执行、远程资源请求或运行功能。
### 10.4 证据要求
须记录用于验收的 CLI 发行二进制哈希和版本、View 源码 SHA、Linux 平台、`cargo fmt/clippy/test --locked`、受保护的 HTTP 与 ZIP 负例、Chromium 截图/浏览器日志、运行计数哨兵和 manifest 摘要。未执行的验证必须写 `UNVERIFIED`,不能用旧版 RFC 的 PASS 代替。
---
## 11. 开发实施顺序:少量 PR,单一职责
| PR | 内容 | 完成标准 |
|---|---|---|
| PR-00 | 固定 CLI/View 二进制与源码基线;更新 ADR,撤销旧 RunRecord/不允许结果导出的相反决策;新增失败 fixture | 开发者只读本 RFC 与仓库即可复现真实缺口 |
| PR-01 | Analysis v2/v3 消费者;新控制流;Execution Events v1 EventBridge | 真实 Core 的 check/call/run 通过,SSE 不重造语义 |
| PR-02 | Markdown 完整性、图片只读媒体、链接/slug、公式排版 | 真正图片与跨页链接在 Chromium 可用,恶意资源拒绝 |
| PR-03 | 将媒体与字体纳入既有 StaticExporter;保持纯文档导出零结果/零运行 | 离线 `file://` 阅读 PASS,manifest 完整 |
| PR-04 | 函数旁就地调用、终态投影稳定、结果源验证;不建历史数据库 | 同函数调用一次、取消、失败、截断均正确显示 |
| **PR-05** | `POST /api/exports`、ExportSelectionValidator、不可变 Overlay、共用 Renderer 的“含结果” ZIP | 显式单次结果快照;**导出绝不执行**;源变更/跨会话拒绝 |
| PR-06 | 浏览器隐私预览、下载流程、a11y/打印/离线、全链路安全/性能/验收证据 | 真实 CLI + Chromium + ZIP/哈希验证通过 |
实施时 PR 不宜一边修协议一边创造新产品数据模型。P0 从**一条已完成且来源匹配的当前会话结果**生成静态 ZIP 即可,不做多结果合并、分享服务器与结果搜索。
---
## 12. 独立开发的 DoD(验收标准)
- [ ] View 仍是独立 Tool v1;不修改 `marqdo-cli`、不链接私有 Rust crate、不添加 `save_*` HostOp。
- [ ] 纯 Markdown 阅读、图片、跨文档链接、锚点、公式、代码围栏、GFM 表格都符合 Profile,真实浏览器完成验证。
- [ ] Analysis v2/v3 与 Events v1/Trace v2 通过公开 Schema 和固定来源摘要验证,旧 CLI 能力不足时**明确拒绝**而不是伪造。
- [ ] `run(main)` 与 `call(function)` 统一任务流程,只有 `POST /api/runs` 触发执行、且必须用户显式确认。
- [ ] 普通 `view export` 零运行、零结果;含结果导出要求当前 session 中明确选中的**终态**,绝不启动第二次执行。
- [ ] 所有导出使用唯一 `DocumentModel` / `ReaderRenderer` / `StaticExporter`,仅通过不可变 `ExportResultOverlay` 添加已验证结果。
- [ ] 用户下载 ZIP 中的 HTML/资源离线可读,结果与原文可视觉区分,源码和源项目不被改动。
- [ ] 运行后源、Analysis、项目身份变更时阻止错误附着;Trace 缺失与运行终态分离,不捏造证据。
- [ ] 默认输出不含未确认的参数值、stderr、秘密、绝对路径或原始高风险观察;HTML/ZIP/XSS/CSRF/媒体路径门禁 PASS。
- [ ] 进程重启后无运行历史可恢复;用户已下载文件可以永久独立存在;没有 RunStore、数据库、`localStorage` 结果缓存、后台自动保存。
- [ ] 全套测试在同一 SHA 的真实发行 Core、真实 Chromium 和离线环境通过;未测试项标 UNVERIFIED。
---
## 13. FAQ:开发者不能自行改写这些设计决定
**Q1:为什么允许用户下载一份包含结果的 ZIP,却不允许保存结果?**
因为两者有本质区别:View 不会在每次运行后主动创建可查询的持久记录;只有用户明确选择“发行一份静态报告”时,才产生一个由用户持有的不可执行文件。**这是文档导出,不是 View 的运行历史系统。**
**Q2:为什么不直接把结果追加到 `.mq.md`?**
`.mq.md` 是源文档与可执行知识,修改它会改变 Git diff、摘要和语义引用,还可能把本来是输出的内容误作为 `@exec` 载体。导出把输出放在独立 HTML 附着层;原文完全不变。
**Q3:为什么不采用 `.ipynb` 的 Cell Outputs / Kernel?**
我们只借鉴“结果与文档共同可阅读、可以离线带走”的优点。Marqdo 以完整 Markdown 文档为中心、函数显式调用并独立执行;Persistent Kernel 会引入隐藏共享变量、历史顺序依赖与新的执行语义,超出 View 职责。
**Q4:用户刷新浏览器,能不能还看到当前结果?**
UI 可以在相同 session、Job 未过 TTL 且安全验证的条件下恢复该次当前任务的 SSE 状态,但**不承诺跨刷新、跨浏览器或跨进程恢复**。想永久保留,须在结果仍可选时主动下载静态快照。
**Q5:为什么不能直接在新启动的 `marqdo view export` 命令中附带“上次结果”?**
因为前一次运行在另一个 View Server 进程的有限内存中;为得到“上次结果”而扫描目录或查询数据库就会重新引入历史存储。另起 CLI 无权猜测这次运行内容。第一阶段只允许 Live 页面引用**同一进程当前 Job**。
**Q6:用户需要真正的科研数据、图像或 Agent 制品怎么办?**
使用 Marqdo 的一般文件/资源能力,由程序在用户授权下明确输出普通文件或外部资源。View 的 ZIP 是一次阅读与执行说明的静态报告;它不代替业务数据文件。必要的项目本地图片可按安全规则一并打包。
**Q7:失败或者 Trace 不完整的运行可以导出吗?**
可以考虑导出**事实清楚标记的失败/部分结果报告**,但绝不能作为成功计算、完整轨迹或证明证书。第一阶段必须至少支持成功终态;其他终态需要显式 UI 确认和对应负例测试。
**Q8:导出文件还能再次执行函数吗?**
不可以。导出是不可执行静态报告。若要重新计算,回到原 `.mq.md` 和真实 Marqdo CLI,再经用户授权调用。
---
## 14. 审计来源与维护要求
### View 仓库源码
- [`src/reader/markdown.rs`](https://github.com/cflmy/marqdo-view/blob/dcb9daeaf4e5eefd8c35aa0c843dd8a0eaf7fef5/src/reader/markdown.rs)
- [`src/reader/render.rs`](https://github.com/cflmy/marqdo-view/blob/dcb9daeaf4e5eefd8c35aa0c843dd8a0eaf7fef5/src/reader/render.rs)
- [`src/reader/source.rs`](https://github.com/cflmy/marqdo-view/blob/dcb9daeaf4e5eefd8c35aa0c843dd8a0eaf7fef5/src/reader/source.rs)
- [`src/core_client.rs`](https://github.com/cflmy/marqdo-view/blob/dcb9daeaf4e5eefd8c35aa0c843dd8a0eaf7fef5/src/core_client.rs)
- [`src/execution/{request,controller,events}.rs`](https://github.com/cflmy/marqdo-view/tree/dcb9daeaf4e5eefd8c35aa0c843dd8a0eaf7fef5/src/execution)
- [`src/export.rs`](https://github.com/cflmy/marqdo-view/blob/dcb9daeaf4e5eefd8c35aa0c843dd8a0eaf7fef5/src/export.rs)
- [`src/server/routes.rs`](https://github.com/cflmy/marqdo-view/blob/dcb9daeaf4e5eefd8c35aa0c843dd8a0eaf7fef5/src/server/routes.rs)
- [`tool.json`](https://github.com/cflmy/marqdo-view/blob/dcb9daeaf4e5eefd8c35aa0c843dd8a0eaf7fef5/tool.json)
### CLI 公开协议
- [`spec/markdown-profile.md`](https://github.com/cflmy/marqdo-cli/blob/652ea763603517ba4d13325a405e3124844ded31/spec/markdown-profile.md)
- [`spec/analysis-v2.md`](https://github.com/cflmy/marqdo-cli/blob/652ea763603517ba4d13325a405e3124844ded31/spec/analysis-v2.md) / [`analysis-v3.md`](https://github.com/cflmy/marqdo-cli/blob/652ea763603517ba4d13325a405e3124844ded31/spec/analysis-v3.md)
- [`spec/trace-v2.md`](https://github.com/cflmy/marqdo-cli/blob/652ea763603517ba4d13325a405e3124844ded31/spec/trace-v2.md)
- [`spec/execution-events-v1.md`](https://github.com/cflmy/marqdo-cli/blob/652ea763603517ba4d13325a405e3124844ded31/spec/execution-events-v1.md)
- [`spec/tool-v1.md`](https://github.com/cflmy/marqdo-cli/blob/652ea763603517ba4d13325a405e3124844ded31/spec/tool-v1.md)
### 交付前必须做的事情
1. 重新取得最新 View HEAD 与已发布 Core tag/binary SHA,核对所有“当前事实”是否仍成立。
2. 对本 RFC 的**新增**请求、manifest 和 Overlay 写入 View 自有版本化 Schema、负例、ADR 与兼容文档,禁止直接把提议示例冒充既有公开协议。
3. 每个 PR 记录测试证据;源码阅读、示例设计与假 Core 测试不能替代真实冻结 CLI/浏览器/离线验收。
4. 更新 `docs/STATUS.md` 与 README,写清“目前支持”和“设计待实现”,禁止把下载 ZIP、Events v1、数学排版等拟议能力提前标为已完成。
**最终设计判据:** 用户只需阅读一篇 Markdown → 明确调用一个函数 → 看懂真实结果 → 在需要时主动把**当前这一次真实结果**连同原文导出为静态报告;这一过程无需 View 保存历史,也不迫使精简 `marqdo-cli` 增加任何 View 专用接口。
+6
View File
@@ -1,5 +1,11 @@
# RFC-VIEW-0001:Marqdo View 3.0 独立阅读器架构与开发验收规范 # RFC-VIEW-0001:Marqdo View 3.0 独立阅读器架构与开发验收规范
> **历史设计(0.1.0 时代)**:本文中的协议名称与命令面只记录当时设计,不是 0.3.0
> 的当前契约。当前实现只使用 Analysis revision 3(ADR-0069)与 Observation
> revision 1;见 [`observation-v1-and-analysis-v3.md`](observation-v1-and-analysis-v3.md)
> 与 [ADR-0012](../decisions/0012-rc4-current-contracts.md)。
> 状态:**Proposed / 可实施设计规范,不代表功能已经实现** > 状态:**Proposed / 可实施设计规范,不代表功能已经实现**
> 目标仓库:`marqdo-view`(独立 Git 仓库;首次开发时新建) > 目标仓库:`marqdo-view`(独立 Git 仓库;首次开发时新建)
> 文档版本:`1.0-draft` > 文档版本:`1.0-draft`
+7
View File
@@ -1,5 +1,12 @@
# RFC-VIEW-0002:Marqdo View 3.0 交互式执行闭环与产品精简实施规范 # RFC-VIEW-0002:Marqdo View 3.0 交互式执行闭环与产品精简实施规范
> **历史基线(0.2.0)**:本 RFC 是 0.2.0 的实现基线,其中的协议名称、命令行与
> 门禁描述已不是 0.3.0 的当前契约。当前契约见
> [`observation-v1-and-analysis-v3.md`](observation-v1-and-analysis-v3.md)、
> [ADR-0012](../decisions/0012-rc4-current-contracts.md) 与
> [`docs/ACCEPTANCE.md`](../ACCEPTANCE.md)。
> **状态**:Proposed / 具备直接实施所需的设计、约束、测试和验收定义;并非完成声明。 > **状态**:Proposed / 具备直接实施所需的设计、约束、测试和验收定义;并非完成声明。
> **目标仓库**:独立 `marqdo-view`,建议路径 `docs/architecture/RFC-VIEW-0002.md`。 > **目标仓库**:独立 `marqdo-view`,建议路径 `docs/architecture/RFC-VIEW-0002.md`。
> **发布日期/审查基线**:2026-11-22。 > **发布日期/审查基线**:2026-11-22。
@@ -0,0 +1,149 @@
# Observation v1 与 Analysis revision 3:当前分层
> 适用范围:`marqdo-view 0.3.0`,冻结 `marqdo 3.0.0-rc.4`。
> 本文是当前实现的架构基线;0.2.0 时期的 RFC 只保留为历史记录
> (`docs/architecture/RFC-VIEW-0001*.md`、`docs/architecture/RFC-VIEW-0002.md`)。
## 1. 唯一数据源
| 事实 | 唯一来源 | 只读产物 |
|---|---|---|
| 静态语义(source/document/units/anchors/functions/calls/resources/diagnostics/references) | 一次 `marqdo check ENTRY --emit PATH` | `marqdo.analysis` revision 3 精确 UTF-8 字节 + `sha256:` digest |
| 运行事实(生命周期/调用/分支/循环/返回/效果/输出字节/终态) | 一次 `marqdo run|call --output jsonl [--observation-file PATH]` | `marqdo.observation` revision 1 事件序列 / 原子快照 |
| 源绑定 | Observation `run.started.payload.source` | `analysis_digest` + `root_id`,对照同一入口、同一静态选项的 Analysis 精确字节 |
`inspect --ast`/`inspect --ir` 只用于人工调试,不是渲染/执行语义的机器来源。
不允许第二解释器、第二 Markdown AST、私有 IR 反推或包缓存物理路径依赖。
## 2. 分层与依赖方向
```text
CLI 适配层(src/core_client.rs, src/execution/process.rs)
唯一知道 argv / 环境变量 / 退出码语义
├─ check --emit
└─ run|call --output jsonl --observation-file
│
protocol 解码 + 结构校验(src/protocol/{analysis_v3,observation_v1,tool_v1,value_wire_v1}.rs)
schema/revision/必需字段/closed record/seq/终态/预算/绑定
│
规范化领域模型(SemanticProjection、ObservationRun、RunBinding)
无 CLI 细节、无版本分支、无 schema_version 判断
│
消费层
├─ reader/{source,markdown,model,assemble,render}
├─ execution/{request,controller,events}
├─ server/{routes,security,sse}
└─ export(同一 ReaderRenderer)
```
强制不变量:
1. 协议模块之外没有 `schema_version` 判断;协议模块内只有当前 revision 一个分支。
2. 依赖单向:`core_client → protocol → model`;`reader/execution/server → model`。
模型不反向依赖 CLI/协议;reader 不依赖 core_client 细节。
3. JSONL 流与原子快照共用同一解码器与同一领域类型;生产代码只消费一种来源
(Live 用流),两者一致性只在测试中断言,不做“双读合并”。
4. 每个拒绝都有稳定 `view.*` 错误码与可执行提示;不使用 `unwrap`/`expect`
处理协议数据。
5. 事件顺序、`run_id` 一致性、连续 `seq`、唯一终态、`truncated` 语义由解码器集中校验;
渲染/导出/SSE 层不“修正”协议数据。
6. 传输中断(EOF 无终态)显示“未完成/无结论”,不得渲染为成功。
## 3. Analysis revision 3 使用方式
- **一次入口一次 emit**:每个文档的静态事实都来自同一 artifact;不跨进程拼接
`inspect --ast` 与 Analysis,避免跨快照错配。
- `modules[].source` 是精确 UTF-8 源文本,所有 span 是 half-open UTF-8 字节区间;
`source_digest` 对应其解码字节。需要磁盘实时性时重新 `check` 并比较 digest,
不从 `relative_path` 重读文件重建 span。
- 标题 UI/目录/锚点使用 `heading_span`;内容高亮/section 切片/标注归属使用完整
`span`(到下一个同级或更高层标题或 EOF)。
- `units[].path` 是结构化数组;`parent_id`/`mode`/`mode_origin`/`mode_source_unit_id`
直接使用;不 split display id。`anchors` 是导航名称,不是身份。
- `calls[]` 的 `state/target_kind/target_owner/reason` 用于执行标记;
`unresolved(dynamic|unbound)` 是合法静态结果,不显示为编译错误。
- `resources`:`content_digest` 对应 AST literal;公式 `display` 为 bool,代码为 `null`。
- `diagnostics[]` 是唯一文件内诊断来源;不再运行第二套检查生成第二套诊断。
- 旧同 revision(缺 `source/document/anchors/entry_module_id` 等)artifact 显式拒绝:
`view.protocol_incompatible`,提示重新生成或升级核心。
## 4. 引用状态
| state | 渲染语义 |
|---|---|
| `resolved` | 可跳转;`target_kind` 为 `module` 或 `file` |
| `not_loaded` | **未核验**:当前 catalog 未加载该本地目标;不是断链、不是 missing |
| `missing` | 目标模块存在但无对应 fragment,或显式核验证明文件不存在 → 可行动错误 |
| `ambiguous` | canonical-name 回退命中两个及以上候选;列出 `candidates`,绝不静默选第一个 |
| `external` | 外链;不联网、不是错误 |
| `outside_scope` | 本地目标逃出允许根/绝对路径/UNC → 不读目标;不输出物理路径 |
| `invalid` | URI/percent 编码非法 → 不猜测修复 |
`source_unit` 用于定位引用所属 section,`span` 用于高亮原文。普通 Analysis
不打开链接目标;`check --refs` 的额外诊断改变 artifact 字节,不能替代普通 emit
作为运行绑定。
## 5. Observation revision 1 使用方式
- 事件种类:`stream.opened`、`run.started`、`call.enter/exit`、`branch.eval`、
`loop.iteration`、`control.break/continue`、`return`、`effect`、
`parameter.observed`、`variable.assigned`、`observation.truncated`、
`stdout.chunk`、`stderr.chunk`、`run.completed/failed/rejected`。
- 唯一 `run_id`、零基连续 `seq`、恰好一个终态且最后。View SSE 只转发/摘要,
保留自身信封但不重编号、不重排、不合成协议事件。
- 绑定校验:`analysis_digest` 必须等于普通 `check --emit` 精确字节的
`sha256:` 表达;`root_id` 等于 `project.root_id`;事件 `module_id` 属于
`modules[]`;span 为该模块 source 的合法 UTF-8 半开区间;模块 `source_digest`
与 artifact 的 `source` 一致。任一不符 → 不渲染运行结果、不错误高亮。
- `observation.truncated`/`capture.truncated` → 显示 **TRUNCATED**:预算耗尽,
不代表程序失败,也不得声明完整覆盖。
- 字节输出:`stdout.chunk`/`stderr.chunk` 为 base64 + 解码字节数;渲染为转义文本,
绝不当 HTML。
- 错误位置只用 `module_id`/`relative_path`/`line`/`column`/`span`;快照可对外分享,
不出现绝对主机路径。
- EOF 无终态 → **INCOMPLETE/未完成**:不显示成功、不生成“成功”导出。
- 值:默认 `capture.level=structural`,不发布 `variable/parameter` 值;协议支持
显式 `--observe-variable`/`--observe-parameter`(Text 另需 `--observe-text-values`),
但 0.3.0 的 View **不请求任何值**。内存/资源/句柄永不发布。
- `strict`:CLI 只支持 text/JSON stdout;Live/文件目的地 exit 2 +
`strict.unsupported_grant`。View 映射为明确错误,不回退 `project`、不重试旧参数。
## 6. 失败与降级矩阵
| 条件 | 错误/状态 | 用户可见行为 |
|---|---|---|
| 常量/加载错误 | CLI exit 1,无成功 artifact | 显示诊断,语义撤回;不显示“成功” |
| 参数/入口/发布错误 | CLI exit 2 | `view.core_option_rejected` 或等价;不去参数重试 |
| 未知 schema/revision/kind | `view.protocol_incompatible` | 显式拒绝,提示升级/重装/重新生成 |
| 旧同 revision artifact | 协议错误 | 提示重新 `check --emit`;无 fallback 解码 |
| digest/root/module/span 不符 | `view.observation_stale` 或等价 | 不渲染运行结果、不错误高亮、不导出成功 |
| 预算截断 | `TRUNCATED` | 显示截断原因/限额,不声明完整 |
| EOF 无终态 | `INCOMPLETE/未完成` | 不显示成功、不生成成功导出 |
| 值未选择却出现 values | 协议违约 | 拒绝该 artifact/事件,不显示值 |
| 旧 Tool 清单/安装记录 | 安装/分发失败 | 提示 remove + 重装;无迁移器 |
## 7. 文件映射
| 层 | 代码 |
|---|---|
| CLI 适配 | `src/core_client.rs`、`src/execution/process.rs` |
| 解码/校验 | `src/protocol/analysis_v3.rs`、`src/protocol/observation_v1.rs`、`src/protocol/tool_v1.rs`、`src/protocol/value_wire_v1.rs` |
| 领域/绑定 | `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) |
| 门禁 | `tests/contract/no_coupling.rs`、`scripts/check-no-legacy.sh`、`scripts/check-docs.sh`、`scripts/check-observation.py` |
## 8. 验证入口
```bash
scripts/check-no-legacy.sh # G01:无旧契约残留
scripts/check-docs.sh # G12:当前文档事实一致
MARQDO_BIN=... scripts/check-examples.sh # 示例真实 check/call/run
MARQDO_BIN=... python3 scripts/check-observation.py stream-snapshot
MARQDO_BIN=... python3 scripts/check-observation.py binding
MARQDO_BIN=... python3 scripts/check-observation.py fail-closed
MARQDO_BIN=... scripts/acceptance.sh # G01–G12 + manifest
```
任何未运行、无法判定的门禁记录为 `UNVERIFIED`;不得写成 `PASS`。
+4
View File
@@ -1,5 +1,9 @@
# 旧 View 渲染路径审计(PR-00) # 旧 View 渲染路径审计(PR-00)
> **历史取证**:本文记录旧渲染路径的静态审计,仅作迁移历史;当前实现与契约见
> [`docs/STATUS.md`](../STATUS.md)。
> 状态:**静态审计完成,运行时验证未执行(`LEGACY_RUNTIME_UNVERIFIED`)** > 状态:**静态审计完成,运行时验证未执行(`LEGACY_RUNTIME_UNVERIFIED`)**
> 审计对象:`cflmy/marqdo` `main@1c55baabd570e18b9da8f9057cef2f848e176690`(下称“旧仓库”) > 审计对象:`cflmy/marqdo` `main@1c55baabd570e18b9da8f9057cef2f848e176690`(下称“旧仓库”)
> 审计方式:只读源码检查(`git status` 干净;**没有**编译、没有写入、没有移动旧仓库任何文件) > 审计方式:只读源码检查(`git status` 干净;**没有**编译、没有写入、没有移动旧仓库任何文件)
+5
View File
@@ -1,5 +1,10 @@
# 旧 View 静态取证与迁移裁决(RFC-VIEW-0002 §3 / PR-00) # 旧 View 静态取证与迁移裁决(RFC-VIEW-0002 §3 / PR-00)
> **历史取证**:本文记录旧 View 的静态审计,仅作迁移历史;当前契约与状态见
> [`docs/STATUS.md`](../STATUS.md) 与
> [`observation-v1-and-analysis-v3.md`](../architecture/observation-v1-and-analysis-v3.md)。
- 状态:静态源码审计完成,**旧运行时浏览器复验未执行** - 状态:静态源码审计完成,**旧运行时浏览器复验未执行**
(`LEGACY_RUNTIME_UNVERIFIED`) (`LEGACY_RUNTIME_UNVERIFIED`)
- 日期:2026-11-22 - 日期:2026-11-22
+5
View File
@@ -1,5 +1,10 @@
# 协议一致性审计(P-03) # 协议一致性审计(P-03)
> **历史审计(0.2.0 时代)**:本文快照只对其当时基线有效,不是 0.3.0 的当前证据。
> 当前冻结 CLI 合同审计见 [`protocol-contract-0002.md`](protocol-contract-0002.md)
> 与 [ADR-0012](../decisions/0012-rc4-current-contracts.md)。
> 结论:View 只消费冻结 CLI 的公开 Tool v1 / Analysis v2 / Trace v2 协议; > 结论:View 只消费冻结 CLI 的公开 Tool v1 / Analysis v2 / Trace v2 协议;
> 未实现或未提供的能力显式标注 `UNSUPPORTED`。本文把规范条款映射到实现与测试, > 未实现或未提供的能力显式标注 `UNSUPPORTED`。本文把规范条款映射到实现与测试,
> 便于审阅者不依赖对话历史复核。 > 便于审阅者不依赖对话历史复核。
+190 -197
View File
@@ -1,222 +1,215 @@
# 冻结 CLI 公共合同黑盒审计(RFC-VIEW-0002 §2 / PR-00) # 冻结 CLI 公共合同黑盒审计(marqdo-view 0.3.0 / rc.4)
- 状态:已用发行二进制黑盒复现;**CLI 源码只读,不修改、不重编译** - 状态:已用发行二进制黑盒复现;**CLI 源码只读,不修改、不重编译**
- 日期:2026-11-22 - 日期:2026-11-25
- 发行基线:`marqdo 3.0.0-beta.1`(tag `v3.0.0-beta.1`, - 发行基线:`marqdo 3.0.0-rc.4`(tag `v3.0.0-rc.4`,
`2c7c4f31e7a388d3fcfa717a77067e696ed13854`) 源码提交 `452e9a32bd9e40dba427d4180691c58bab74449e`)
- 二进制:`/root/work/marqdo-cli/dist/marqdo-3.0.0-beta.1-x86_64-unknown-linux-gnu/marqdo` - 归档:`marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu.tar.gz`,
- SHA-256:`062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f` SHA-256 `9c3f166b5e5b8840d39d10019074e4e1c42432fc23e26c69670e64fdcf4e15d8`
- 平台:`x86_64-unknown-linux-gnu`;协议:Tool v1 / Analysis v2 / Trace v2 / - 二进制(归档内 `marqdo`):
Markdown Profile `marqdo.md.v1` `/root/work/marqdo-cli/dist/marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu/marqdo`,
- 规范来源:`/root/work/marqdo-cli/spec/{tool-v1,analysis-v2,trace-v2,callable-resolution,value-wire}.md`、 SHA-256 `a7306962689c635445a59043971ea2eb09298e01feeee81f0ba07b1f3e10306e`
`spec/schemas/*.json`、`crates/cli/src/commands/run.rs`(只读参考)。 - 平台:`x86_64-unknown-linux-gnu`;当前契约:CLI Tool revision 1(`api_revision` 1)/
Analysis revision 3(ADR-0069 公共边界)/ Observation revision 1 /
Markdown profile `marqdo.md.v1`
- 规范来源:`marqdo-cli@v3.0.0-rc.4` 的 `spec/{analysis,observation,cli-tool,references,
markdown-profile,value-wire}.md`、`docs/adr/0068-*.md`、`docs/adr/0069-*.md`;
正式发布后若规范更新,以**确切发布版**为准,不以本文代替规范。 正式发布后若规范更新,以**确切发布版**为准,不以本文代替规范。
> 本文是 marqdo-view 实现与测试的合同摘要。任何字段都以“规范 + 黑盒复现二选一” > 本合同摘要依据“规范 + 黑盒复现二选一”。未复现项显式标 `UNVERIFIED`,绝不推断。
> 为依据;未复现项显式标 `UNVERIFIED`,绝不推断。 > 本文件只描述**当前**契约;0.2.0 时代的旧格式已从当前树与当前文档移除,
> 仅保留在 Git 历史与 CHANGELOG 的 History 段。
## 1. 命令面(`--help` 实测) ## 1. 命令面(`--help` 实测)
- `run [FILE]`:运行入口文件 `main`;`--mode` 默认 **`project`**(View 必须显式传 ```text
`--mode pure`)。 marqdo 3.0.0-rc.4
- `call <FILE> <FUNCTION>`:调用命名函数;`--arg <NAME=VALUE>` 常量表达式,可重复。 run Run the entry function (`main` by default) of a document
call Call a named function with typed arguments
check Statically check a document without executing it
inspect Inspect AST, units, signatures, IR, references or platform support
...
tool Manage and dispatch generic external CLI tools
```
- `check [FILE] [--refs] [--emit PATH] [--json]`:纯静态,不执行。 - `check [FILE] [--refs] [--emit PATH] [--json]`:纯静态,不执行。
- 预算/追踪参数(`run`/`call` 共有):`--fuel`、`--stack`、`--max-output`、 `--json` 只输出 check 诊断摘要;`--emit` 是完整 Analysis 的唯一写出者。
`--timeout`、`--trace-file`、`--trace-max-events`、`--trace-max-bytes`。 - `run`/`call`:默认 `--mode project`(View 必须显式传 `--mode pure` 或带白名单的
- 权限参数:`--allow-read/--allow-write/--allow-net/--allow-env/--allow-process/ `--mode project`)。`--output text|json|jsonl` 默认 `text`;`--observation-file PATH`
--allow-random/--allow-foreign/--allow-plugin/--plugin/--provider/--allow-provider/ 原子发布同一执行的快照。`--observe-variable NAME`、`--observe-parameter NAME`、
--kernel/--trust-native-plugin`。View 首版只使用 `--allow-read/--allow-write` `--observe-text-values`、`--observe-max-events`、`--observe-max-bytes`、
(且仅在显式 `project` 请求中),其余一律不暴露。 `--observe-max-value-bytes` 控制观测选择与预算。
- 未知顶层命令通过 Tool v1 注册表分发到外部二进制(`spec/tool-v1.md`)。 - 已退休的运行参数在当前 CLI 中直接触发“unexpected argument”并以 exit 2 结束;
View 不得在失败后换旧参数重试。
- 预算/权限参数:`--fuel`、`--stack`、`--max-output`、`--max-memory`、
`--timeout`、`--allow-read/--allow-write/...`。View 首版只使用
`--mode` 与 `--allow-read/--allow-write`(且仅在显式 `project` 请求中)。
- `inspect --ast` 可用于人工调试,但**不得**作为渲染语义的机器来源;渲染语义只来自
同一次 `check --emit`。
## 2. `check --emit` 合同 ## 2. `check --emit` 合同
规范:`spec/analysis-v2.md` §1;实测: 实测(`examples/control-flow/index.mq.md`、`examples/function-params.mq.md`):
| 场景 | 结果 | | 场景 | 观察 |
|---|---| |---|---|
| 成功 | exit 0;`--json` stdout 为 `{"command":"check","diagnostics":[],"errors":0,"success":true}`;`--emit` 路径写出 Analysis v2 精确 UTF-8 字节(pretty JSON),原子写入 | | 成功 | exit 0;`--json` stdout 输出 `success:true` 诊断摘要;`--emit` 路径写出 Analysis revision 3 的精确 UTF-8 字节(pretty JSON),owner-only 临时文件 + 原子 rename |
| 失败 | exit 1;stdout 为 `{"command":"check","diagnostics":[...],"errors":N,"success":false}`;**逐条诊断带 `code/severity/message/line/column/module/hints`**(`file` 可能出现绝对路径,View 必须不泄漏/只保留相对信息) | | 失败 | exit 1(静态诊断错误)或 exit 2(参数/入口不可读/输出发布失败);不发布成功工件,可能按合同删除调用者指定的旧 emit 文件 |
| stale emit | 失败时 **删除目标路径的旧文件**(实测:先写 `stale.json` 再失败 check,文件不存在)。View 必须同样丢弃自己的旧 Analysis 缓存 | | `--refs` | 额外链接检查,改变 diagnostics,因此改变 artifact 字节;不能替代普通 emit 作为运行绑定 |
| `--refs` | 额外链接检查,可能产生额外 `diagnostics`;不得当作语言执行/编译成功证明 | | 无绝对路径 | 相同逻辑项目从不同 checkout 目录 emit 字节一致;错误位置只用 `relative_path`/`line`/`column` |
`AnalysisDigest` = `sha256:` + 精确 emit 文件字节的小写 hex SHA-256;**不是** `AnalysisDigest` = `sha256:` + 精确 emit 文件字节的小写 hex SHA-256(含格式)。
反序列化再序列化的哈希。`Trace v2.source.analysis_digest` 必须与它一致。 Observation `run.started.payload.source.analysis_digest` 必须与它一致。
## 3. Analysis v2 关键字段(View 消费面) ## 3. Analysis revision 3 关键字段(View 消费面)
- 顶层:`schema="marqdo.analysis"`、`schema_version=2`、`producer{name,version, 实测顶层与模块字段:
markdown_profile}`、`project{root_id,identity_kind,lock_digest,stdlib}`、
`modules[]`、`diagnostics[]`。 ```text
- `project.root_id`:`root:<name>@<version>`(有 manifest)或 top-level: schema="marqdo.analysis", schema_version=3,
`sha256:<workspace snapshot>`;是 Trace `source.root_id` 的唯一比对值。 producer{name,version,markdown_profile},
- `modules[].{id,package_instance_id,relative_path,source_digest,units,functions, project{root_id, identity_kind, entry_module_id, lock_digest,
imports,references,calls,resources}`。`source_digest` = 精确源文件字节的 SHA-256 manifest_digest, stdlib, extensions},
(不含 `sha256:` 前缀)。 modules[], diagnostics[]
- `functions[].{id,unit_id,local_name,namespace,span,heading_span,signature{kind, module: id, package_instance_id, relative_path, source_digest, source,
params[]},body,effects}`;`params[].{name,required,type,default,span}`。 document, units[], anchors[], functions[], imports[], references[],
`signature.kind` 为 `explicit|inferred`;`required = default.is_none()`。 calls[], resources[]
- `units[].kind`:`root|namespace|function|knowledge|section`,带 `level`、 unit: id, path[](结构化), parent_id, kind, name, level, mode, mode_origin,
`span`、`function`、`name`、`id`。**Analysis 不公开 H3+ 的最终 EffectiveMode**; mode_source_unit_id, heading_span, span, function
View 不得自行重建并宣称为编译器状态(RFC §2.7)。 function: id, unit_id, local_name, namespace, span, heading_span, signature, effects, body
- `diagnostics[]` 标记 UTF-8 字节 `span`(`start/end`)或行列;View 显示原文与 reference:source, source_unit, url, span, state, target_kind, target_module,
诊断即可,不从错误推断 IR。 target_unit, candidate_package_instance_id, candidate_path, fragment, candidates
```
关键语义:
- `source` 是精确 UTF-8 源文本;所有 `span` 是 half-open UTF-8 字节区间,
`source_digest` = `sha256(source 解码字节)`。消费者不得从 `relative_path` 重读文件
重建 span。
- `units` 的 `heading_span` = 标题 AST 节点范围(标题 UI/目录/锚点);
完整 `span` = 到下一个同级或更高层标题(或 EOF)的 section 范围(内容高亮/切片/归属)。
`path` 是结构化数组;不得 split display id。
- `anchors` 是 `[{anchor, unit_id}]`,anchor 是导航名称,不是身份。
- `calls[].state` 为 `function|builtin|plugin|unresolved`;`unresolved(dynamic|unbound)`
是合法静态结果,不是编译错误。`target_owner` 只携带静态身份,不伪造函数节点。
- `resources` 只投影 `formula`/`code`;`content_digest` 对应 AST literal;
公式 `display` 为 bool,代码为 `null`。
- `diagnostics[]` 已包含文件内诊断;不得用 `inspect` 或私有 IR 生成第二套。
- `effects` 是保守摘要(如 `["unknown"]`),不是纯度证明,不能作为“安全运行”依据。 - `effects` 是保守摘要(如 `["unknown"]`),不是纯度证明,不能作为“安全运行”依据。
黑盒样例(`target/probe/function-params.mq.md`,2 个 H1/H2 中文标题)证明: ## 4. 引用状态(实测 fixture)
中文 namespace/local_name、UTF-8 `span`、`heading_span`、`unit_id` 均按字节偏移
给出;`id` 形如
`root:<name>@<ver>::<relative path>::<namespace>.<local_name>`(无 namespace 时
`::<local_name>`)。
## 4. 函数定位与 `call` 的名称解析(关键) 用 `examples` 之外的最小 fixture(单文档,未加载其它模块)实测:
CLI `call FILE FUNCTION` 的查找实现:`Module::function(name)` | 输入 | state | 观察 |
(`crates/marqdo-ir/src/lib.rs:404`,只读参考),规则为:
1. 先按 **canonical qualified name**(`function.id.name`,如
`计算示例.double`)完全匹配;
2. 否则按 `local_name` 匹配,且必须**唯一**;同名跨 namespace 重复时返回
`None`,CLI 报 `sem.no_entry_function`,没有“文档顺序优先”。
实测:`call function-params.mq.md 计算示例.double --arg n=7 --mode pure` 成功;
`call function-params.mq.md double` 成功(唯一 local name)。因此 View 必须:
- `target.function_id` 从**当前入口模块** Analysis 的 `functions[]` 精确取得;
- 服务端把 `function_id` 解析为该函数的 CLI 名称:若 `local_name` 在入口模块内
唯一(或与 namespace 无关地唯一)用 `local_name`,否则用
`<namespace>.<local_name>`;**不能**把客户端字符串直接拼接为参数;
- 只允许入口模块函数;依赖模块函数不是 `call FILE FUNCTION` 的目标
(RFC §6.3)。
## 5. `run` / `call` 的 JSON 包络(实测差异,必须容忍)
成功(`run` 与 `call` 同形):
```json
{"command":"run|call","success":true,
"value":{"type":"<wire tag>", "...": "..."},
"stdout":"...","stderr":"...","diagnostics":[],
"trace":[]}
```
`value` 是 Wire Value(`spec/value-wire.md` v1),**不是任意字符串**:
| type | 形状 |
|---|---|
| `unit` | `{"type":"unit"}` |
| `none` | `{"type":"none"}` |
| `bool` | `{"type":"bool","value":true}` |
| `int` | `{"type":"int","decimal":"-123..."}`(十进制字符串,不丢精度) |
| `float` | `{"type":"float","value":1.5}` 或 `{"type":"float","special":"nan|infinity|-infinity"}` |
| `text` | `{"type":"text","value":"..."}` |
| `list` | `{"type":"list","items":[...]}` |
| `map` | `{"type":"map","entries":{"k":<value>}}` |
| `table` | `{"type":"table","header":[...],"rows":[[...]]}` |
| `formula` / `code` | 惰性数据(latex/source 等) |
| `function_ref` | `{"type":"function_ref","module":"...","name":"..."}` |
| `plugin_handle` | `{"type":"plugin_handle",...}` |
| `memory` / `resource` | 仅 `{"type":"memory"}`/`{"type":"resource"}`,**不可解码/不应出现** |
失败包络**不统一**(实测两种,至少):
```json
// A. prepare/semantic 失败(如无 main、函数不存在):error 是字符串,另有顶层 code
{"command":"run","success":false,"code":"sem.no_entry_function",
"error":"<file> has no callable `main`; ..."}
// B. 运行期失败(类型/预算等):error 是对象,含 code/message/line/column/span/...
{"command":"call","success":false,
"error":{"code":"runtime.type","message":"...","span":{...},"frames":[...]},
"stdout":"","stderr":"","trace":[]}
```
**实现要求**:任何失败路径都不得 `unwrap` `value`/`trace`/`stdout`/`stderr`;
`success:true` 但 `value` 缺失时按 `unit` 谨慎显示;`success:false` 时保留
`code`(顶层或 `error.code`)和可读消息;stdout/stderr 一律当用户文本。
关于 `trace` 数组:`run --json` 顶层 `trace` 实测可能为 `[]`(即使
`--trace-file` 写了完整 Trace v2)。**结构化运行证据只以 `--trace-file` 文件为准**,
不能把 JSON 里的 `trace` 当 Trace v2。
## 6. Trace v2 合同(`--trace-file`)
规范:`spec/trace-v2.md`;实测 `target/probe/t2.json`:
- 顶层:`schema="marqdo.trace"`、`schema_version=2`、
`run{id,entry,status}`、`source{root_id,analysis_digest}`、
`limits{max_events,max_bytes}`、`truncated`、`events[]`。
- 事件:`seq`(全局递增)、`kind`、`function_id`、`module_id`、`span`、
`detail`;`effect` 另有 `operation`/`duration_micros`。
- kind:`call.enter|call.exit|return|branch.eval|loop.iteration|effect|
trace.truncated`;未来新增 kind 必须忽略或保守显示,不得猜测。
- 有 span 的事件必须指定真实 `module_id` 与 UTF-8 字节 `span`;
无 span 的 `call.enter/call.exit`(entry call)可 `span:null`。
- `truncated:null | {"reason":"event_budget|byte_budget","limit":N,"written":M}`;
截断只代表观测预算耗尽,不代表程序失败;末事件为 `trace.truncated`。
- **不记录**参数值、逐语句变量值、Handle、文件内容、秘密。View 不得伪造这些值。
- 认证绑定(RFC §2.6):把 `source.analysis_digest` 与**同一源码、同一检查配置**
的 Analysis 原始字节 SHA-256 比较;再核对 `source.root_id`、`module_id` 属于
Analysis `modules[]`、span 边界/UTF-8 合法、模块 `source_digest` 等于当前源码
字节哈希。任一不符 → 不画执行标注。
- 实测 `--trace-max-events 2`:`truncated={reason:event_budget,limit:2,written:2}`,
events 数 3(含 `trace.truncated`)。View 的 `--trace-max-events 10000`、
`--trace-max-bytes 4194304` 是上限而非保证。
## 7. Tool v1 安装/分发(View 打包依据)
规范:`spec/tool-v1.md`。要点(源码 + 既有验收证据):
- `tool.json` 必填:`schema="marqdo.cli-tool"`、`schema_version=1`、`name`、
`version`(合法 SemVer)、`command`、`entrypoint`(包内受控相对路径)、
`compatibility{marqdo:"<semver range>", analysis:[2], trace:[2]}`。
- 安装:校验 schema/SemVer/协议交集/entrypoint 不越界/命令冲突 → 收集整包
规范化文件清单(path/size/sha256,拒绝符号链接/特殊文件)→ staging 复制并
复算一致 → 原子发布;失败清理 staging。
- 分发:启动前重新计算磁盘整包清单并与记录逐项比较;**修改已安装包任意一个字节
后分发被拒绝**(tests 已覆盖,见 `scripts/install-smoke.sh`)。
- 运行时向工具注入 `MARQDO_TOOL_PROTOCOL=1`、
`MARQDO_PROTOCOL_ANALYSIS=2`、`MARQDO_PROTOCOL_TRACE=2`(兼容协商成功时);
原样保留 cwd/stdin/stdout/stderr 与可保留环境,用
`Command::new(entrypoint).args(args)` 直接启动,不经过 shell,退出码原样传播。
- 这些环境变量只表示协议版本,**不是**执行授权;权限仍由 `--mode`/grants 决定。
## 8. 对 View 实现的硬性含义
1. 运行请求必须由服务端重新 `check --emit` 并保存**精确 Analysis 字节 + digest**;
POST 校验顺序中的 Analysis SHA 比对以它为唯一参照,运行后 Trace 也绑定它。
2. `run` 与 `call` 的 argv 由 `core_client`/`process` 以数组构造,显式
`--mode pure` 或带白名单 grants 的 `project`;永不经过 shell。
3. 显式预算:`--timeout 30`(View 另设墙钟上限,默认 30s、最大 120s)、
`--fuel 1000000`、`--max-output 1048576`、`--trace-max-events 10000`、
`--trace-max-bytes 4194304`;接收侧再设 4 MiB JSON / 4 MiB trace 上限。
4. Value 展示按 §5 白名单类型做结构化文本;未知类型折叠为转义 JSON;不得
把 `value` 当变量全集、不得当 HTML。
5. `call` 的目标名按 §4 由 function_id 精确解析;无 main 时 `run` 会返回
`sem.no_entry_function`(实测),View 应提前提示并引导选择函数,绝不替换成别的函数。
6. 运行失败时 `trace` 文件可能不存在(实测 no-main 无 trace 文件);视为
“Trace 不可用”,不是伪造空 Trace。
## 9. 黑盒证据表
| # | 命令(在 `target/probe` 内) | 观察 |
|---|---|---| |---|---|---|
| 1 | `marqdo --version` | `marqdo 3.0.0-beta.1`;SHA 见头部 | | `#引用状态`(同页标题) | `resolved` | `target_kind: module`,fragment 已解码,target_unit 存在 |
| 2 | `check function-params.mq.md --emit a1.json --json` | exit 0,success:true,写出 Analysis v2 | | `./theory.mq.md`(未加载) | `not_loaded` | `target_unit: null`;表示当前 catalog 未核验,**不是** missing |
| 3 | `check broken.mq.md --emit stale.json --json` | exit 1,failure JSON,旧 `stale.json` 被删除 | | `#不存在的标题` | `missing` | target fields null |
| 4 | `call function-params.mq.md double --arg n=5 --mode pure --json --trace-file t1.json` | exit 0,`value={type:int,decimal:10}`,Trace v2 写入 | | `https://example.com/x` | `external` | 不联网;不是错误 |
| 5 | `call function-params.mq.md 计算示例.double --arg n=7 --mode pure` | exit 0,`decimal:14`(canonical 名称可用) | | `../../../etc/passwd` | `outside_scope` | 不读目标;不输出物理路径 |
| 6 | `call function-params.mq.md double --arg 'n="x"' --mode pure --json` | exit 1,`error.code=runtime.type`(对象包络) | | `%zz` | `invalid` | 不做猜测修复 |
| 7 | `call function-params.mq.md double`(缺 required 参数) | exit 1,`error.code=call.arity` |
| 8 | `call function-params.mq.md nope --mode pure` | exit 1,顶层 `code=sem.no_entry_function`,`error` 为字符串 |
| 9 | `run branch-loop.mq.md --mode pure --json --trace-file t2.json` | exit 0,value int 0;Trace 事件含 loop.iteration/return/call.enter/call.exit |
| 10 | `run branch-loop.mq.md --trace-max-events 2 --trace-file lim.json` | exit 0,`truncated={event_budget,limit:2,written:2}` |
| 11 | `run nomain.mq.md --mode pure --json --trace-file nomain-trace.json` | exit 1,`sem.no_entry_function`,**无 trace 文件** |
| 12 | `run branch-loop.mq.md --json`(未传 mode) | 成功,但 `--help` 证明默认值是 `project`(View 不能依赖此默认) |
## 10. 未复现项(UNVERIFIED) `check --refs` 会构建显式扩展 catalog 并追加诊断;如果该次检查带 error,则 exit 1
且不发布 artifact。View 的引用 UI 必须按 `state` 渲染:
`not_loaded` 显示“未核验”,`ambiguous` 列出 candidates,绝不静默选第一个。
**`UNVERIFIED`**:`ambiguous` 的稳定黑盒样本(需要两个同名 canonical 候选)与
`resolved` 的 `target_kind: file` 分支未在本次探针中复现;实现按规范校验,证据待补。
## 5. Observation revision 1
实测(`call function-params.mq.md double --arg n=5 --mode pure --output jsonl
--observation-file obs.json`):
- 事件:`stream.opened`、`run.started`、`call.enter`、`parameter.observed`、
`return`、`call.exit`、`run.completed`;每行 `schema:"marqdo.observation"`、
`schema_version:1`、同一 `run_id`、连续 `seq`(0 起)。
- 快照:`{schema, schema_version, run{id, source{analysis_digest,root_id}, status},
capture{level, ...}, events[]}`;同一次执行的 JSONL 行与快照 `events` 逐项相等。
- `run.completed.payload.value` 是 Value Wire(如 `{"type":"int","decimal":"10"}`)。
- `--observe-max-events 2` 实测:`capture.truncated={reason:"event_budget",limit:2,
written:2}`,事件含 `observation.truncated`,最后仍有真实终态;截断**不代表**
程序失败,UI 必须显示 TRUNCATED,不得声明完整。
- 事件错误位置只携带 `module_id`/`relative_path`/`line`/`column`/`span`;
不出现绝对主机路径。
- `stdout.chunk`/`stderr.chunk` 是 base64 字节块;解码后必须与程序输出一致。
- `parameter.observed`/`variable.assigned` 默认不携带值;只有显式
`--observe-parameter`/`--observe-variable`(Text 另需 `--observe-text-values`)
才发布所选标量。内存/资源/句柄永不发布。
- `--mode strict` 只支持 text/JSON stdout;`--output jsonl` 与 `--observation-file`
在启动前 exit 2(`strict.unsupported_grant`)。View 明确拒绝,不回退 `project`。
- EOF/中断且无终态 = 未完成/无结论,不得渲染为成功。
**`UNVERIFIED`**:`run.rejected` 的完整错误码矩阵、`effect.operation` 的具体集合、
多模块事件的跨模块归属由 View 测试覆盖;本审计只复现了 entry 单模块样本。
## 6. Tool revision 1(View 打包/安装依据)
规范 `spec/cli-tool.md`;实测:
```json
{
"schema": "marqdo.cli-tool",
"schema_version": 1,
"name": "marqdo-view",
"version": "0.3.0",
"command": "view",
"entrypoint": "bin/marqdo-view",
"requires": {"api_revision": 1, "analysis": 3, "observation": 1}
}
```
- 必填精确值:`requires.api_revision = 1`;声明 `analysis`/`observation` 时必须是
单个精确整数。没有 `compatibility` 字段、没有版本数组协商。
- 实测 `tool install` 成功 → `tool list` 输出 `demo-view 0.3.0 (marqdo-view)` →
分发时注入 `MARQDO_BIN` 与 `MARQDO_API_REVISION=1`,不注入旧协商变量。
- 实测旧清单(带 `compatibility`)安装失败:`invalid tool.json: unknown field
compatibility ... Build the tool with current exact protocol requirements`,
无迁移器。
- 安装:校验 schema/SemVer/revision/entrypoint 不越界/命令冲突 → 整包规范化文件
清单(path/size/sha256,拒绝符号链接/特殊文件)→ staging 复制复算 → 原子发布;
分发前重算磁盘整包清单,任一字节被改即拒绝。
- 这些环境变量只表示 API revision,**不是**执行授权;权限仍由 `--mode`/grants 决定。
## 7. 对 View 实现的硬性含义
1. 一次入口一次 `check --emit`:保存精确 Analysis 字节 + digest;`inspect --ast`
不再作为机器来源。
2. 运行只解析 Observation v1:JSONL 流是生产来源,原子快照用于测试等价断言;
View 不双读合并、不重编号、不重排、不合成。
3. 运行 argv 由 `core_client`/`process` 以数组构造:`run|call --output jsonl
--observation-file <tmp>`;显式 `--mode pure` 或白名单 grants;永不经过 shell。
4. Trace 绑定改为 Observation 绑定:`source.analysis_digest` + `root_id` +
`module_id` + 模块 `source_digest` + UTF-8 半开 span;任一不符 →
`view.observation_stale` 或等价错误,不显示成功、不错误高亮。
5. `--refs` 改变 artifact 字节,不能用于运行绑定;需要磁盘实时性时重新 check 并比较 digest。
6. 未知字段/旧同 revision 制品显式拒绝并给出可执行提示(重新生成/升级核心/重装 Tool)。
7. 值默认不请求、不发布;不伪造变量/内存状态。
8. 失败/截断/未完成必须诚实呈现;`UNSUPPORTED`/`PARTIAL`/`WARN` 不得写成 PASS。
## 8. 黑盒证据表(2026-11-25,rc.4 二进制)
| # | 命令(临时目录内) | 观察 |
|---|---|---|
| 1 | `marqdo --version` | `marqdo 3.0.0-rc.4`;SHA 见头部 |
| 2 | `marqdo check --help` / `run --help` / `call --help` | `--emit/--refs/--json`;`--output text|json|jsonl`、`--observation-file`、`--observe-*`、strict 支持范围 |
| 3 | `check control-flow/index.mq.md --emit cf.json --json` | exit 0;schema `marqdo.analysis` revision 3;模块含 source/document/units/anchors/functions/calls/resources/diagnostics |
| 4 | `call function-params.mq.md double --arg n=5 --mode pure --output jsonl --observation-file obs.json` | exit 0;7 个事件;JSONL 与快照 events 完全一致;value Int 10 |
| 5 | `run branch-loop.mq.md --mode pure --output jsonl --observation-file runobs.json` | exit 0;事件含 variable.assigned/loop.iteration/return;14 条;快照一致;value Int 0 |
| 6 | `run branch-loop.mq.md --observe-max-events 2 ...` | exit 0;`capture.truncated={event_budget,2,2}`;`observation.truncated` 后仍有终态 |
| 7 | 引用 fixture(resolved/not_loaded/missing/external/outside_scope/invalid) | 六态逐一复现,见 §4 |
| 8 | 传入已退休的旧运行参数(Git 历史保留,不在当前文档重复) | exit 2,unexpected argument;无回退重试 |
| 9 | `run … --mode strict --output jsonl` | exit 2,`strict.unsupported_grant` |
| 10 | 新 `tool.json` install/list/dispatch | 安装成功;`MARQDO_API_REVISION=1`;无旧协商变量 |
| 11 | 带 `compatibility` 的旧 `tool.json` install | exit 1,unknown field + 重写提示 |
## 9. 未复现项(UNVERIFIED)
- `ambiguous` 与 `resolved(target_kind:file)` 的稳定黑盒样本(见 §4)。
- 插件/Provider/Foreign/Kernel 的完整运行时行为(View 首版不暴露;不属 MVP)。 - 插件/Provider/Foreign/Kernel 的完整运行时行为(View 首版不暴露;不属 MVP)。
- `--max-output`/`--fuel`/`--stack` 触顶时的精确错误码与包络(由 View 外部的 - `--fuel`/`--max-output`/`--max-memory`/`--stack` 触顶时的精确错误码与包络
Core 负责;View 只显示真实错误)。 (由 CLI 负责;View 只显示真实错误)。
- 多模块/依赖包事件在入口正文的跨模块绘制(必须按 module_id 拒绝;无有效样本)。 - 多模块事件的跨模块归属、`run.rejected` 全错误码矩阵、`effect.operation` 完整集合。
- Windows/macOS 行为(发行范围仅 Linux x86_64)。 - Windows/macOS 行为(发行范围仅 Linux x86_64)。
- 远端 CI 实际执行(本环境未运行;对应门禁保持 `UNVERIFIED`)。
@@ -0,0 +1,7 @@
# ADR-0011 显式发行一次终态结果
- 状态:Accepted,实施与验证状态见 [STATUS](../STATUS.md)。
- 规范:[RFC-VIEW-0001 完整阅读与导出](../architecture/RFC-VIEW-0001-complete-reader.md)
- 本决策更新 ADR-0005 的可导出内容。普通导出及 Live 结果导出共用文档模型、渲染器和打包核心。
唯一执行入口仍为 `POST /api/runs`。用户可在当前会话的终态 Job 有效期内选择一次结果,明确确认后由 `POST /api/exports` 返回静态 ZIP。该路由验证当前来源、会话和字段选择,将有界不可变的数据交给渲染器。结果随 Job 过期,下载完成的文件由用户保管。
@@ -0,0 +1,68 @@
# ADR-0012 — rc.4 当前契约取代 rc.3 基线(0.3.0)
- 状态:Accepted(2026-11-25)
- 范围:`marqdo-view 0.3.0` 的公开协议基线、验收证据与文档
- 取代:issue #5 中以 rc.3 为固定 SHA 的验收基线;不取代 issue #5 的门禁编号
(G01–G12)与 fail-closed 原则
## 背景
`marqdo-view 0.3.0` 的一次性适配最初按 `marqdo 3.0.0-rc.3` 定义(adaptation
issue #4,验收 issue #5)。随后 `marqdo-cli` 的公共静态分析边界工作
(`marqdo-cli` ADR-0069,追踪 issue #10)在 `v3.0.0-rc.4` 原地替换了
`marqdo.analysis` revision 3 的字段集合,仍保持 revision 号为 3:
- `check --emit` 现在直接携带精确 `source`、Markdown `document`、完整标题作用域
(`heading_span` + 完整 section `span`)、`anchors`、`entry_module_id`、
`manifest_digest`、`extensions` 与状态化 `references`;
- `inspect --ast` 不再是渲染语义的机器来源,只是人工调试命令;
- 旧 revision-3 字段集合(缺少上述字段)不再被当前 schema/consumer 接受;
- Observation revision 1 仍绑定**普通** `check --emit` 的精确字节摘要;
`--refs` 检查改变字节,不能替代运行绑定。
因此 issue #5 的 rc.3 SHA 基线不能继续作为 0.3.0 的验收身份。若继续钉 rc.3,
会出现“门禁全绿但不是发布契约”的错误证据。
## 决策
1. 0.3.0 的唯一契约基线升级为 `marqdo 3.0.0-rc.4`:
- CLI 源码 `452e9a32bd9e40dba427d4180691c58bab74449e`
- 归档 `marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu.tar.gz`
SHA-256 `9c3f166b5e5b8840d39d10019074e4e1c42432fc23e26c69670e64fdcf4e15d8`
- 归档内二进制 SHA-256
`a7306962689c635445a59043971ea2eb09298e01feeee81f0ba07b1f3e10306e`
- 平台 `linux-x86_64-glibc2.39`;产品范围 `>=3.0.0-rc.3,<4.0.0`
2. 验收门禁编号、fail-closed 原则与 manifest schema
(`marqdo.view.acceptance` revision 1)沿用 issue #5;只把身份字段与
证据路径改为绑定 rc.4 的源码/归档/二进制 SHA。
3. 静态语义只消费一次 `check --emit`;不运行 `inspect --ast` 作为机器来源。
4. 旧 revision-3 制品(缺少 rc.4 必需字段)显式拒绝并提示重新生成;不保留
同 revision 的兼容解码、迁移器或双态类型。
5. 旧 rc.3/0.2.0 证据只作历史记录;不得与 rc.4 证据混用或替代。
## 影响
- `scripts/frozen-beta.sh` 钉 rc.4;`scripts/acceptance.sh` 从该脚本读取
version/source/archive/binary SHA,生成 issue #5 §0 schema 的 manifest。
- `scripts/check-no-legacy.sh`(G01)继续阻止树内出现旧契约、旧 argv、旧 Tool
协商或双态分支。
- `docs/audits/protocol-contract-0002.md` 的探测基线改为 rc.4,并在无稳定样本的
项上显式标注 `UNVERIFIED`。
- `docs/STATUS.md`/`docs/ACCEPTANCE.md` 在 rc.4 manifest 生成前不声明 PASS;
`UNVERIFIED` 不得写成 PASS。
- issue #5 的 G01–G12 定义仍然有效;其中“冻结 CLI 源码/归档 SHA”字段按本 ADR
的 rc.4 值填写。
## 验证
复现与机器证据见 `docs/ACCEPTANCE.md` 和
`docs/evidence/452e9a32bd9e40dba427d4180691c58bab74449e/manifest.json`(`result: PASS`,G01–G12 全 PASS,Woodpecker #10):
```bash
scripts/frozen-beta.sh verify /abs/unpacked/marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu/marqdo
scripts/check-no-legacy.sh
scripts/check-docs.sh
MARQDO_BIN=... scripts/acceptance.sh
```
未运行门禁保持 `UNVERIFIED`;本 ADR 不声称任何尚未执行的验收结果。
+11
View File
@@ -0,0 +1,11 @@
# 完整阅读与结果导出设计
> 契约提示:当前实现以 Analysis revision 3 与 Observation revision 1 为准,
> 见 [`docs/architecture/observation-v1-and-analysis-v3.md`](../architecture/observation-v1-and-analysis-v3.md)。
[高保真设计图](complete-reader.png)由内置 ImageGen 生成,参考旧版 View 截图。实现沿用旧版居中品牌、暖纸色、衬线正文、金色函数标记和橄榄色结果边框。示意图右侧是独立的导出确认状态,窄屏使用单列。
提示词见下方。
> Use case: ui-mockup. Asset type: high fidelity desktop Marqdo View implementation design reference. Create a wide storyboard of two product states using the provided old Marqdo View screenshot as a visual reference (retain its centered logo, warm paper, understated pale blossom upper left, amber accent, olive success and serif document typography). Left 64%: real desktop reader, with centered header Marqdo, navigation 文档, 源码, subdued filename index.mq.md, readable title 小型统计实验, a paragraph, rendered mathematical mean formula and small document figure. Continue in the same article with a gold-slash function heading 计算均值 and a small outline button 调用 on the same row. Under the function body put one thin olive-bordered collapsible 本次执行 panel, status 成功, read-only 返回值 4, stdout preview and action 导出文档(含本次结果). Right 36%: show the opened export confirmation dialog as a full flat inset panel headed 导出文档(含本次结果), target 计算均值 and status 成功, checklist with 返回值, stdout and 轨迹摘要 selected, 参数 and stderr unselected, byte counts, privacy confirmation, and an amber 下载 ZIP button beside 取消. Quiet editorial composition, no coding dashboard, no charts unrelated to document, no extra product copy. Flat straight-on browser UI, readable typography, generous whitespace, clean borders. The reference is for an existing paper-themed reader, preserve its design language.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

+41 -23
View File
@@ -1,17 +1,19 @@
# 运行状态矩阵(PR-00 设计基准) # 运行状态矩阵(0.3.0 设计基准)
> 状态:**设计基准**。实现真源:`src/presentation.rs` 的 `RunDisplayState` 与 `assets/reader.css` 的 `[data-run-state]`。 > 状态:**设计基准**。实现真源:`src/execution/events.rs` 的 `RunDisplayState`、
> 来源:RFC-VIEW-0001 §4.4、§12.2–§12.3。 > `src/protocol/observation_v1.rs` 的校验结果与 `assets/reader.css` 的
> `[data-run-state]`。当前契约:Analysis revision 3 + Observation revision 1。
> 旧 RFC 仅供历史参考,不再是当前契约来源。
## 1. 静态来源状态(文档头部 `source_status`) ## 1. 静态来源状态(文档头部 `source_status`)
| 值 | 触发条件 | 文档正文 | 语义标注 | 运行按钮 | 文案(中文) | | 值 | 触发条件 | 文档正文 | 语义标注 | 运行按钮 | 文案(中文) |
|---|---|---|---|---|---| |---|---|---|---|---|---|
| `CORE_UNAVAILABLE` | 无 `MARQDO_BIN`/核心不可执行 | 完整可读 | 无(“语言语义未验证”) | 禁用 + 说明 | 找不到冻结核心,语义未验证 | | `CORE_UNAVAILABLE` | 无 `MARQDO_BIN`/核心不可执行 | 完整可读 | 无(“语言语义未验证”) | 禁用 + 说明 | 找不到冻结核心,语义未验证 |
| `STATIC_OK` | `check` 退出 0 且 Analysis v2 校验通过 | 完整可读 | 有效 | 可用(需确认) | 静态检查已通过 · 未运行 | | `STATIC_OK` | `check --emit` 退出 0 且 Analysis revision 3 校验通过 | 完整可读 | 有效 | 可用(需确认) | 静态检查已通过 · 未运行 |
| `CORE_ERROR` | `check` 退出非 0,但 Markdown 可读 | 完整可读 | 全部撤销,显示 Core diagnostics | 禁用 | Core 检查失败,语义标注不可用 | | `CORE_ERROR` | `check` 退出非 0,但 Markdown 可读 | 完整可读 | 全部撤销,显示 Core diagnostics | 禁用 | Core 检查失败,语义标注不可用 |
| `STALE` | 源码变化或 Analysis digest 不匹配 | 完整可读 | 不绑定旧 Analysis | 可用(重新检查) | 分析已过期,请刷新 | | `STALE` | 源码变化或 Analysis digest 不匹配 | 完整可读 | 不绑定旧 Analysis | 可用(重新检查) | 分析已过期,请刷新 |
| `PROTOCOL_INCOMPATIBLE` | 未知 schema major / 产品版本不兼容 | 完整可读 | 无 | 禁用 | 核心协议不兼容(analysis vN) | | `PROTOCOL_INCOMPATIBLE` | 未知 schema/revision / 产品版本不兼容 | 完整可读 | 无 | 禁用 | 核心协议不兼容(需 rc.4) |
| `SOURCE_MISMATCH` | Analysis `source_digest` ≠ 当前字节 | 完整可读 | 不展示 | 禁用 | 源码与 Analysis 不一致 | | `SOURCE_MISMATCH` | Analysis `source_digest` ≠ 当前字节 | 完整可读 | 不展示 | 禁用 | 源码与 Analysis 不一致 |
## 2. 运行状态(`RunDisplayState`) ## 2. 运行状态(`RunDisplayState`)
@@ -20,35 +22,51 @@
|---|---|---|---| |---|---|---|---|
| `NOT_RUN` | 未点击运行 | 中性 outline | “未运行”;不出现任何结果 | | `NOT_RUN` | 未点击运行 | 中性 outline | “未运行”;不出现任何结果 |
| `STATIC_ONLY` | 只有 `check` 成功 | 中性 | “仅静态检查通过” | | `STATIC_ONLY` | 只有 `check` 成功 | 中性 | “仅静态检查通过” |
| `RUNNING` | 用户已确认,Core 子进程运行中 | 金色脉冲(reduced-motion 时静态) | 显示入口/模式/预算,可取消(若实现) | | `RUNNING` | 用户已确认,Core 子进程运行中 | 金色脉冲(reduced-motion 时静态) | 显示入口/模式/预算,可取消 |
| `SUCCEEDED` | `run` 退出 0 + Trace v2 校验通过 | `--mq-ok` | 显示真实事件与 stdout;不显示返回值具体内容(除非公开 JSON 提供) | | `SUCCEEDED` | `run.completed` + Observation 绑定校验通过 | `--mq-ok` | 显示真实事件与 stdout;值按 Value Wire 文本展示 |
| `FAILED` | `run` 退出非 0/运行错误码 | `--mq-error` | 显示 Core 错误码与 stderr 文本(转义) | | `FAILED` | `run.failed` / `run.rejected` | `--mq-error` | 显示错误码与 stderr 文本(转义) |
| `STALE` | Trace `source.analysis_digest` 与当前 Analysis 不符 | `--mq-warn` | “结果已过期”,不叠到当前正文 | | `STALE` | `run.started.payload.source.analysis_digest` 与当前 Analysis 不符 | `--mq-warn` | “结果已过期”,不叠到当前正文 |
| `TRUNCATED` | `trace.truncated != null` | `--mq-warn` | “Trace 被截断,仅显示已记录事件” | | `TRUNCATED` | `observation.truncated` / `capture.truncated` | `--mq-warn` | “观测被截断,仅显示已记录事件” |
| `UNSUPPORTED` | 需要的字段/能力不在公开协议 | 中性 + 明确说明 | 绝不伪造:无变量值、无逐句赋值、无内存快照、无证明状态 | | `INCOMPLETE` | EOF/中断且无终态 | `--mq-warn` | “未完成/无结论”,不显示成功 |
| `UNSUPPORTED` | 需要的字段/能力不在公开协议 | 中性 + 明确说明 | 绝不伪造:默认无变量值、无逐句赋值、无内存快照、无证明状态 |
## 3. 事件 → UI 映射(保守) ## 3. 事件 → UI 映射(保守)
| Trace v2 事件 | 允许显示 | 禁止显示 | | Observation 事件 | 允许显示 | 禁止显示 |
|---|---|---| |---|---|---|
| `call.enter` | 函数 id/名称、顺序、来源 span | 参数实际值 | | `call.enter` | 函数 id/名称、顺序、来源 span | 参数实际值(未显式选择时) |
| `call.exit` | 退出类型/错误码 | 最终变量表 | | `call.exit` | 退出类型/错误码 | 最终变量表 |
| `branch.eval` | 真/假 + 来源 span | “所有分支已覆盖” | | `branch.eval` | 真/假 + 来源 span | “所有分支已覆盖” |
| `loop.iteration` | continue/exit 次数(以事件完整性为界) | 由静态结构推测总迭代数 | | `loop.iteration` | continue/exit 次数(以事件完整性为界) | 由静态结构推测总迭代数 |
| `return` | 发生返回 + 值类型名 | 具体返回值(除非公开 JSON 明确提供) | | `control.break` / `control.continue` | 发生位置与最近循环帧 | 推测循环总次数 |
| `effect` | operation、结果摘要、耗时 | “权限安全/已证明” | | `return` | 发生返回 + 值类型名 | 未公开的具体值 |
| `trace.truncated` | 明确截断原因与上限 | 把缺失事件说成未执行 | | `effect` | operation、结果码、来源位置 | “权限安全/已证明” |
| 未知 kind | 忽略(记入 `ignored_event_kinds`) | 猜测语义 | | `stdout.chunk` / `stderr.chunk` | base64 解码后的转义文本 | 当 HTML 注入 |
| `parameter.observed` / `variable.assigned` | 仅有显式选择时的名称/类型/位置;Text 需二次同意 | 未选择的默认值;内存/资源/句柄 |
| `observation.truncated` | 明确截断原因与上限 | 把缺失事件说成未执行 |
| 未知 kind | 拒绝或保守忽略(记录) | 猜测语义 |
## 4. 能力边界(首版硬性) ## 4. 引用状态渲染
| 旧 UI 能力 | 新 View 首版 | 理由 | | state | 文档内表现 | 是否可跳转 |
|---|---|---| |---|---|---|
| 每个语句执行后的变量值 | **UNSUPPORTED** | Trace v2 不提供 | | `resolved` | 正常链接 | 是(module/file) |
| 参数实际值 / 内存快照 | **UNSUPPORTED** | Trace v2 不提供 | | `not_loaded` | “未核验”提示 | 否(不显示为断链) |
| `missing` | 可行动错误 | 否 |
| `ambiguous` | 列出 candidates 供选择 | 否(不静默选第一个) |
| `external` | 外链图标,不联网 | 否(仅展示 URL) |
| `outside_scope` | 可行动错误 | 否 |
| `invalid` | 可行动错误 | 否 |
## 5. 能力边界(首版硬性)
| 旧 UI 能力 | 当前 View | 理由 |
|---|---|---|
| 每个语句执行后的变量值 | **默认不请求、不展示** | 协议支持显式选择;View 0.3.0 不请求 |
| 参数实际值 / 内存快照 | **默认不请求、不展示** | 同上;内存/句柄永不发布 |
| 知识“已证明” | **UNSUPPORTED** | 需要独立 Prove 协议与证书 | | 知识“已证明” | **UNSUPPORTED** | 需要独立 Prove 协议与证书 |
| 调试断点/单步 | **不实现** | 首版非目标 | | 调试断点/单步 | **不实现** | 首版非目标 |
| 函数大纲/签名 | 支持(来自 Analysis `functions[]`) | 公开静态事实 | | 函数大纲/签名 | 支持(来自 Analysis `functions[]`) | 公开静态事实 |
| 静态变量信息(params/赋值目标) | 支持但明确标注“静态” | 来自 Analysis,不冒充运行值 | | 静态变量信息(params/赋值目标) | 支持但明确标注“静态” | 来自 Analysis,不冒充运行值 |
| 静态导入/引用标签 | 支持 | 来自 Analysis `imports[]`/`references[]` | | 静态导入/引用标签 | 支持(含七态) | 来自 Analysis `imports[]`/`references[]` |
| 运行 Trace 事件侧注 | 支持 | Trace v2 + digest 校验 | | 运行 Observation 事件侧注 | 支持(含 stale/truncated 降级) | Observation v1 + digest 校验 |
+2 -1
View File
@@ -61,7 +61,8 @@
- **导入/引用标签**:椭圆 chip,`◇`/`⟶` 前缀,mono 12px。 - **导入/引用标签**:椭圆 chip,`◇`/`⟶` 前缀,mono 12px。
- **GFM 表**:横向可滚动容器;表头 `--mq-surface-2`;1px `--mq-line` 分隔。 - **GFM 表**:横向可滚动容器;表头 `--mq-surface-2`;1px `--mq-line` 分隔。
- **代码围栏**:`--mq-surface` 底、1px 边、圆角 10px;横向滚动;无行号(源码态除外)。 - **代码围栏**:`--mq-surface` 底、1px 边、圆角 10px;横向滚动;无行号(源码态除外)。
- **公式**:首版以等宽/衬线文本呈现原文(`$...$` 与 `$$...$$`),标注“未渲染数学”;不引入 vendor。 - **公式**:正文使用离线 MathML 与本地 Noto Sans Math。无法安全排版的式子保留原文。
- **结果与导出**:函数旁使用金色描边按钮,终态以橄榄边框折叠区呈现。导出预览沿用暖纸色对话框,显示所选字段与字节数。
- **侧注**:正文右侧 170px;金色/橄榄 1px 贝塞尔曲线,起点为真实语义锚点;无来源不画线;拥挤时退化为内联 keyed 注释。 - **侧注**:正文右侧 170px;金色/橄榄 1px 贝塞尔曲线,起点为真实语义锚点;无来源不画线;拥挤时退化为内联 keyed 注释。
- **装饰**:樱花 `blossom.webp` 左上、羽毛 `feather.webp` 仅 Welcome Hero;`aria-hidden="true"`;打印隐藏。 - **装饰**:樱花 `blossom.webp` 左上、羽毛 `feather.webp` 仅 Welcome Hero;`aria-hidden="true"`;打印隐藏。
@@ -0,0 +1,40 @@
# rc.4 验收证据(已生成)
本目录绑定冻结 CLI 源码 SHA `452e9a32bd9e40dba427d4180691c58bab74449e`
(`marqdo 3.0.0-rc.4`)。
- 归档 SHA-256:`sha256:9c3f166b5e5b8840d39d10019074e4e1c42432fc23e26c69670e64fdcf4e15d8`
- 二进制 SHA-256:`sha256:a7306962689c635445a59043971ea2eb09298e01feeee81f0ba07b1f3e10306e`
- 平台:`linux-x86_64-glibc2.39`
- 期望产物:`manifest.json`(schema `marqdo.view.acceptance`,`schema_version: 1`)
- 门禁:G01–G12(见 [`docs/ACCEPTANCE.md`](../../ACCEPTANCE.md),
schema 与状态含义见 [`docs/evidence/README.md`](../README.md))
## manifest 契约(`marqdo.view.acceptance` / `schema_version: 1`)
必填身份字段:`view_commit`、`view_binary_sha256`、`view_tool_bundle_digest`、
`cli_source_sha`、`cli_archive_sha256`、`cli_binary_sha256`、`platform`、
`generated_utc`、`gates`、`unverified`(完整示例见
[`docs/evidence/README.md`](../README.md))。
门禁 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`;
每项 `state ∈ {PASS, FAIL, UNVERIFIED}`,并带 `command`/`exit_code`/`log`。
`unverified` 列出所有非 PASS 门禁;`UNVERIFIED`/`PARTIAL`/`WARN` 不得读作或写成 PASS。
**当前状态:`manifest.json` 已由真实命令生成,`result: PASS`(G01–G12 全部 PASS,含远端 Woodpecker #10 与同 SHA 校验;`extras.browser: PASS`)。** manifest 只能由真实命令重新生成,禁止手写、复制历史 manifest 或从别处伪造:
```bash
export MARQDO_BIN=/abs/unpacked/marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu/marqdo
scripts/frozen-beta.sh verify "$MARQDO_BIN"
scripts/acceptance.sh
```
`scripts/acceptance.sh` 会把 manifest 写入本目录,并把同一内容写到
`dist/acceptance/manifest.json`。本目录 `logs/` 保存该次 manifest 引用的真实日志。
任一 P0 门禁 `FAIL` 或 `UNVERIFIED` → 0.3.0 不发布;`UNVERIFIED` 不得写成 `PASS`。
历史 0.2.0 证据位于其他目录(`../2c7c4f31e7a388d3fcfa717a77067e696ed13854/`、
`../issue-2/`、`../issue-3/`、`../PR-01..PR-06/`),只作历史记录,
不能替代本目录的 rc.4 门禁。
@@ -0,0 +1 @@
check-no-legacy: PASS (0 retired references in src/, tool.json and current docs; rc.4 baseline)
@@ -0,0 +1,213 @@
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.08s
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.06s
Running unittests src/lib.rs (target/debug/build/marqdo-view/01b4917d83f17a50/out/marqdo_view-01b4917d83f17a50)
running 65 tests
test cli::tests::bind_policy_is_loopback_by_default ... ok
test core_client::tests::check_args_are_plain_argv ... ok
test core_client::tests::run_defaults_do_not_request_values ... ok
test core_client::tests::run_args_use_the_current_observation_flags_only ... ok
test core_client::tests::missing_bin_has_stable_code ... ok
test execution::controller::tests::exit_code_two_is_a_hard_option_rejection_never_a_retry ... ok
test execution::controller::tests::call_argv_carries_explicit_args_and_observation_file ... ok
test core_client::tests::scratch_dir_is_private_and_removed ... ok
test cli::tests::parses_browse_defaults ... ok
test execution::controller::tests::run_ids_are_unguessable_and_unique ... ok
test cli::tests::export_requires_out ... ok
test execution::controller::tests::run_argv_is_observation_jsonl_and_never_retired_trace_flags ... ok
test cli::tests::parses_export_subcommand ... ok
test cli::tests::parses_verify_and_global_options_anywhere ... ok
test execution::controller::tests::run_options_never_request_variable_values ... ok
test execution::controller::tests::stale_and_incomplete_never_map_to_success ... ok
test execution::controller::tests::truncated_observation_is_terminal_but_never_labelled_complete ... ok
test cli::tests::run_timeout_is_bounded_to_rfc_range ... ok
test execution::events::tests::states_have_stable_wire_values_and_terminals ... ok
test execution::events::tests::newest_cursor_replays_only_new_events ... ok
test execution::events::tests::frames_have_event_id_and_matching_data_seq ... ok
test execution::events::tests::terminal_frame_carries_observation_summary_not_trace ... ok
test execution::events::tests::utc_formatting_is_stable ... ok
test execution::events::tests::terminal_job_replays_snapshot_and_closes ... ok
test execution::export_candidate::tests::public_scalar_types_exclude_text_and_containers ... ok
test execution::process::tests::bounded_capture_keeps_limit_and_drains ... ok
test execution::process::tests::default_budget_matches_rfc ... ok
test execution::export_candidate::tests::bounded_text_never_splits_utf8 ... ok
test execution::events::tests::ring_is_bounded_and_old_cursor_gets_snapshot ... ok
test execution::request::tests::entry_without_main_is_explicitly_rejected ... ok
test execution::request::tests::canonical_names_and_targets_resolve ... ok
test execution::request::tests::rejects_absolute_and_parent_globs ... ok
test export::tests::manifest_relative_paths_are_validated ... ok
test execution::request::tests::rejects_unknown_fields_and_bad_modes ... ok
test export::tests::export_target_outside_project_is_accepted ... ok
test execution::request::tests::unknown_parameter_names_are_rejected_before_execution ... ok
test protocol::tool_v1::tests::api_revision_is_an_exact_expectation ... ok
test protocol::tool_v1::tests::parses_official_version_line ... ok
test protocol::tool_v1::tests::rejects_retired_and_future_product_lines ... ok
test reader::assets::tests::base64_matches_known_vectors ... ok
test reader::markdown::tests::front_matter_is_not_rendered_as_a_block ... ok
test reader::markdown::tests::heading_spans_are_exact ... ok
test reader::model::tests::heading_anchors_are_deterministic_and_collision_free ... ok
test reader::markdown::tests::parses_lists_quotes_and_task_items ... ok
test reader::markdown::tests::parses_gfm_and_preserves_utf8_spans ... ok
test reader::model::tests::status_values_are_stable ... ok
test reader::markdown::tests::parses_math_and_code_as_inert_literals ... ok
test reader::source::path_tests::normalizes_harmless_forms ... ok
test reader::source::path_tests::rejects_unsafe_relative_paths ... ok
test reader::source::tests::bom_is_still_indexed ... ok
test reader::source::tests::maps_multibyte_and_emoji_offsets ... ok
test reader::source::tests::digest_is_exact_bytes ... ok
test reader::source::tests::rejects_out_of_range_and_misaligned_spans ... ok
test server::routes::tests::percent_decode_is_single_pass_and_strict ... ok
test server::routes::tests::run_route_matching_is_strict ... ok
test server::security::tests::constant_time_eq_is_strict ... ok
test server::security::tests::random_tokens_are_lower_hex_and_unique ... ok
test server::sse::tests::headers_are_the_sse_contract ... ok
test server::routes::tests::status_mapping_covers_execution_errors ... ok
test server::security::tests::session_cookie_is_parsed_from_a_real_request ... ok
test server::sse::tests::heartbeat_interval_is_fifteen_seconds_by_default ... ok
test execution::controller::tests::expired_terminal_job_is_never_returned_for_export ... ok
test execution::process::tests::cancellation_terminates_the_process_group ... ok
test reader::assets::tests::css_substitutes_images_and_keeps_one_asset ... ok
test reader::assets::tests::bundle_digests_match_source_files ... ok
test result: ok. 65 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.06s
Running unittests src/main.rs (target/debug/build/marqdo-view/436da4765b900725/out/marqdo_view-436da4765b900725)
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running tests/contract/main.rs (target/debug/build/marqdo-view/4db88ce592e41fad/out/contract-4db88ce592e41fad)
running 53 tests
test cli_surface::degradation_without_core_keeps_prose_readable ... ok
test asset_integrity::theme_has_one_token_layer_and_no_legacy_skin ... ok
test cli_surface::browse_on_missing_path_fails_without_starting_a_server ... ok
test cli_surface::missing_document_is_an_io_error ... ok
test cli_surface::export_requires_an_output_directory ... ok
test cli_surface::help_comes_from_view_not_core ... ok
test cli_surface::non_loopback_bind_is_refused_by_default ... ok
test cli_surface::verify_without_core_is_an_argument_error ... ok
test cli_surface::version_is_the_tool_version ... ok
test asset_integrity::reused_assets_match_their_recorded_hashes ... ok
test core_contract::check_failure_preserves_core_stderr_and_code ... ok
test core_contract::default_run_does_not_request_variable_or_parameter_values ... ok
test core_contract::analysis_v2_revision_is_a_hard_protocol_error ... ok
test core_contract::check_returns_exact_analysis_bytes_and_digest ... ok
test core_contract::check_refs_is_forwarded_as_a_stricter_flag ... ok
test core_contract::installed_tool_api_revision_is_enforced_at_the_process_boundary ... ok
test core_contract::missing_required_analysis_fields_are_rejected ... ok
test core_contract::current_rc_version_is_accepted ... ok
test core_contract::run_and_call_argv_use_the_current_observation_flags_only ... ok
test core_contract::failed_check_normalizes_diagnostics_without_absolute_paths ... ok
test core_contract::strict_mode_run_request_is_rejected_by_view_validation ... ok
test core_contract::tool_api_revision_environment_is_an_exact_expectation ... ok
test core_contract::unknown_analysis_schema_name_or_major_is_rejected ... ok
test core_contract::incompatible_product_version_is_rejected_before_any_work ... ok
test core_contract::unknown_module_and_unit_references_are_rejected ... ok
test core_contract::missing_emit_after_success_is_an_analysis_failure ... ok
test no_coupling::release_lockfile_is_committed ... ok
test no_coupling::no_private_core_crate_dependencies ... ok
test core_contract::cli_verify_end_to_end_against_fake_core ... ok
test no_coupling::tool_manifest_matches_package_and_protocols ... ok
test core_contract::retired_revision_3_shape_is_rejected_with_a_rebuild_hint ... ok
test no_coupling::exactly_one_reader_theme_and_script_entry ... ok
test core_contract::source_digest_mismatch_is_not_silently_accepted ... ok
test no_coupling::source_has_no_legacy_protocol_or_runtime_probing ... ok
test observation_contract::rejected_before_start_is_a_valid_failed_terminal ... ok
test observation_contract::eof_without_terminal_is_incomplete_never_success ... ok
test observation_contract::real_jsonl_stream_verifies_and_binds_to_analysis_digest ... ok
test observation_contract::unknown_schema_and_revision_are_rejected ... ok
test observation_contract::stream_and_snapshot_of_the_same_run_agree ... ok
test observation_contract::stale_and_wrong_root_bindings_are_observation_stale ... ok
test asset_integrity::embedded_asset_bundle_matches_disk_and_has_one_theme ... ok
test presentation_states::missing_core_stays_readable_and_explicitly_unverified ... ok
test observation_contract::truncated_observation_is_a_terminal_but_never_complete ... ok
test presentation_states::external_projection_can_be_rendered_from_artifact_source ... ok
test no_coupling::source_never_reads_or_links_the_legacy_repositories ... ok
test presentation_states::truncated_and_incomplete_runs_never_display_as_success ... ok
test presentation_states::failed_check_keeps_prose_and_shows_core_diagnostics ... ok
test presentation_states::invalid_analysis_span_is_rejected_not_trimmed ... ok
test observation_contract::lifecycle_negative_cases_fail_closed ... ok
test presentation_states::source_digest_mismatch_degrades_instead_of_misbinding ... ok
test core_contract::cli_verify_rejects_schema_v2_and_digest_mismatch ... ok
test presentation_states::unknown_analysis_schema_is_a_hard_protocol_error ... ok
test presentation_states::run_attached_to_changed_source_becomes_stale ... ok
test result: ok. 53 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.19s
Running tests/integration/main.rs (target/debug/build/marqdo-view/77a45afd23a2f454/out/integration-77a45afd23a2f454)
running 45 tests
test execution::cross_session_observation_is_rejected ... ok
test execution::same_client_request_id_is_idempotent_and_different_payload_conflicts ... ok
test execution::missing_observation_stream_is_incomplete_never_success ... ok
test execution::project_grants_are_mapped_to_explicit_cli_flags_and_pure_grants_are_rejected ... ok
test execution::event_frames_use_the_view_run_events_schema_and_numeric_ids ... ok
test execution::call_target_uses_the_call_subcommand_and_function_name ... ok
test execution::observation_with_a_mismatched_digest_is_rejected_as_stale ... ok
test execution::explicit_entry_run_streams_accepted_running_and_verified_observation ... ok
test execution::stale_request_digest_is_rejected_before_any_process_starts ... ok
test execution::truncated_observation_is_explicit_and_never_labelled_complete ... ok
test execution::second_run_is_busy_while_one_is_active_and_cancel_is_idempotent ... ok
test export::refuses_to_export_inside_the_project_root ... ok
test export::refuses_to_overwrite_unrelated_non_empty_directory ... ok
test http_live::assets_are_immutable_and_carry_strict_headers ... ok
test http_live::at_most_two_sse_observers_per_run ... ok
test http_live::cancel_is_idempotent_and_yields_one_terminal_state ... ok
test http_live::document_without_main_is_rejected_without_running_another_function ... ok
test execution::source_edit_during_a_run_marks_the_result_stale_and_drops_anchor_ids ... ok
test http_live::duplicate_request_id_is_idempotent_and_busy_or_conflict_never_starts_a_second_process ... ok
test http_live::explicit_run_streams_sse_accepted_running_and_terminal_with_verified_trace ... ok
test http_live::pages_issue_a_session_cookie_and_never_execute_the_document ... ok
test http_live::last_event_id_replays_only_newer_events_and_old_cursor_gets_snapshot ... ok
test http_live::read_only_routes_are_the_target_contract_and_old_routes_are_gone ... ok
test rendering::headings_use_heading_span_while_sections_use_the_complete_span ... ok
test rendering::live_and_static_share_content_but_rewrite_links ... ok
test rendering::malicious_markdown_cannot_inject_markup_or_scripts ... ok
test rendering::page_has_exactly_one_theme_and_one_script ... ok
test rendering::reader_exposes_simple_theme_toggle_and_no_variable_or_memory_tabs ... ok
test rendering::rendering_is_deterministic ... ok
test rendering::run_controls_are_explicitly_unavailable_before_an_explicit_run ... ok
test rendering::semantic_annotations_come_from_analysis_and_are_unique ... ok
test rendering::static_pages_use_parent_relative_assets_and_links ... ok
test rendering::tables_math_and_code_are_inert_and_readable ... ok
test rendering::welcome_hero_only_when_configured ... ok
test unicode_spans::crlf_source_keeps_exact_digest_and_line_mapping ... ok
test unicode_spans::heading_ui_uses_heading_span_and_section_span_includes_children ... ok
test unicode_spans::knowledge_emphasis_never_becomes_an_execution_anchor ... ok
test unicode_spans::unicode_spans_are_exact_and_duplicate_returns_get_distinct_anchors ... ok
test http_live::sse_heartbeats_keep_a_slow_job_connected ... ok
test export::real_frozen_core_export_marks_both_pages_static_ok ... ok
test export::no_annotations_keeps_prose_but_removes_anchors ... ok
test export::exported_html_has_no_remote_subresources ... ok
test export::export_never_executes_side_effects ... ok
test export::exports_offline_site_with_shared_renderer_and_relative_links ... ok
test export::replaces_a_previous_export_atomically ... ok
test result: ok. 45 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 38.53s
Running tests/security/main.rs (target/debug/build/marqdo-view/6dc7f51fb0afdc26/out/security-6dc7f51fb0afdc26)
running 11 tests
test path_traversal_is_rejected_and_the_old_document_route_is_gone ... ok
test adversarial_markdown_never_injects_markup_or_handlers ... ok
test aggressive_markdown_links_cannot_become_a_file_read_api ... ok
test session_cookie_and_headers_are_hardened ... ok
test oversized_and_unknown_fields_are_rejected_before_execution ... ok
test sec_fetch_site_cross_site_is_rejected_even_with_a_valid_token ... ok
test host_origin_session_csrf_and_json_are_all_required_before_execution ... ok
test cancel_cannot_be_replayed_to_start_a_new_process ... ok
test symlink_escape_outside_the_project_root_is_rejected ... ok
test sse_and_cancel_are_scoped_to_the_owning_session ... ok
test sse_requires_a_session_and_only_the_owning_session_can_read_or_cancel ... ok
test result: ok. 11 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.32s
Doc-tests marqdo_view
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Finished `release` profile [optimized] target(s) in 0.04s
@@ -0,0 +1,55 @@
CHANGELOG.md: OK
COMPATIBILITY.md: OK
LICENSE-APACHE: OK
LICENSE-MIT: OK
README.md: OK
SOURCE_SHA: OK
bin/marqdo-view: OK
tool.json: OK
== bundle digest: sha256:7fa5e3ae590cd42e29b50f083a39dbb465a4eb114fc9336581a38b6747cd6658
installed tool `view` version 0.3.0 (marqdo-view)
view 0.3.0 (marqdo-view)
Marqdo View renders the original Markdown and attaches verified Analysis v3 facts. Running is never implicit: it requires an explicit user action. Export is always a pure read-only operation.
Usage: marqdo-view [OPTIONS] [PATH] [COMMAND]
Commands:
export Write a static, read-only HTML site (never executes the document)
verify Check CLI/Analysis/source binding only; never executes
Arguments:
[PATH]
A `.mq.md` document or a project directory (default: `.`)
Options:
--marqdo-bin <PATH>
Development only: explicit path to the frozen `marqdo` binary. Installed Tool Protocol runs get the path from `MARQDO_BIN`
--host <HOST>
Loopback host for the Live reader (default 127.0.0.1)
[default: 127.0.0.1]
--port <PORT>
Port for the Live reader; `0` lets the OS choose and prints the real URL
[default: 7429]
--no-open
Do not open a browser (the full local URL is still printed)
--run-timeout <RUN_TIMEOUT>
Wall-clock limit for one explicit run, in seconds (RFC-VIEW-0002 §6.7). The frozen Core receives the same value via `--timeout`
[default: 30]
-h, --help
Print help (see a summary with '-h')
-V, --version
Print version
manifest: PASS (revision 1 requires api_revision=1 analysis=3 observation=1)
install-smoke: PASS (view installed/dispatched, api_revision 1 injected, core sha256 a7306962689c635445a59043971ea2eb09298e01feeee81f0ba07b1f3e10306e unchanged, tool home /root/work/marqdo-view/dist/smoke-tool-home.LyX5Qz)
removed tool `view`
error: unknown command `view`; install a tool with `marqdo tool install <tool.json>`
installed tool `view` version 0.3.0 (marqdo-view)
@@ -0,0 +1,8 @@
==> cargo build --release --locked
Finished `release` profile [optimized] target(s) in 0.04s
==> smoke install against frozen core
manifest: PASS (revision 1 requires api_revision=1 analysis=3 observation=1)
install-smoke: PASS (view installed/dispatched, api_revision 1 injected, core sha256 a7306962689c635445a59043971ea2eb09298e01feeee81f0ba07b1f3e10306e unchanged, tool home /root/work/marqdo-view/dist/smoke-tool-home.LridP3)
bundle: /root/work/marqdo-view/dist/marqdo-view
archive: /root/work/marqdo-view/dist/marqdo-view-0.3.0-x86_64-unknown-linux-gnu.tar.gz
sha256: baf8b6ff8c819d6355481f67cfb79191d52323184134edc1e634a8ceff044e9a
@@ -0,0 +1 @@
error: tool `view` bundle hash mismatch; reinstall it
@@ -0,0 +1,19 @@
core: marqdo 3.0.0-rc.4 (supported >=3.0.0-rc.3,<4.0.0, api revision 1)
project: root:mixed-modes@0.1.0 (manifest)
document: index.mq.md
analysis: schema=marqdo.analysis v3 modules=1 functions=1 references=0 digest=sha256:fd686ba0851c34a897f3e432c579ed4c64188914e5b6aec5e24b8ee4f444b01f
source digest: match
result: PASS (static only; document not executed)
==> check all five example documents (one static source: check --emit)
Analysis v3: PASS (schema_version 3, exact source/document/entry present)
==> call function-params.double(n=5) -> 10 via Observation v1
call double(5): PASS (Observation v1, Int 10)
==> run branch-loop main -> Int 0 with loop/return events
run branch-loop: PASS (Int 0, contiguous seq, kinds: stream.opened,run.started,call.enter,variable.assigned,loop.iteration,variable.assigned,loop.iteration,variable.assigned,loop.iteration,variable.assigned,loop.iteration,return,call.exit,run.completed)
==> knowledge-only has no main (truthful rejection, no fallback)
knowledge-only: PASS (explicit sem.no_entry_function)
==> unsafe-side-effect writes nothing in pure mode
unsafe-side-effect pure: PASS (permission.denied, no file)
==> unsafe-side-effect writes only with explicit project grants
unsafe-side-effect project+grants: PASS (sentinel written explicitly)
examples: PASS (frozen CLI sha256 a7306962689c635445a59043971ea2eb09298e01feeee81f0ba07b1f3e10306e unchanged)
@@ -0,0 +1,3 @@
browse: PASS
explicit real run: PASS (run_id=e7231671266cf2ee4b16136e277ecf0a observation=verified events=34)
explicit run: PASS
@@ -0,0 +1,2 @@
stream/snapshot equivalence: PASS (7 events, one run_id, contiguous seq, one terminal)
observation truncation: PASS (capture.truncated=event_budget, terminal=run.completed)
@@ -0,0 +1,25 @@
exact Analysis binding: PASS (digest=sha256:19c9beac89857a9ffacb509c305d76a3221320b53500f2884f15629e01e8b254, root/module/span checks, source edit invalidates)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.04s
Running unittests src/lib.rs (target/debug/build/marqdo-view/01b4917d83f17a50/out/marqdo_view-01b4917d83f17a50)
running 1 test
test execution::controller::tests::stale_and_incomplete_never_map_to_success ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 64 filtered out; finished in 0.00s
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.04s
Running tests/integration/main.rs (target/debug/build/marqdo-view/77a45afd23a2f454/out/integration-77a45afd23a2f454)
running 1 test
test execution::source_edit_during_a_run_marks_the_result_stale_and_drops_anchor_ids ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 44 filtered out; finished in 1.09s
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.04s
Running tests/contract/main.rs (target/debug/build/marqdo-view/4db88ce592e41fad/out/contract-4db88ce592e41fad)
running 1 test
test observation_contract::stale_and_wrong_root_bindings_are_observation_stale ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 52 filtered out; finished in 0.02s
@@ -0,0 +1,126 @@
fail-closed retired --json: PASS (exit 2, no fallback retry)
fail-closed retired --trace-file: PASS (exit 2, no fallback retry)
fail-closed retired --event-stream: PASS (exit 2, no fallback retry)
fail-closed strict live destination: PASS (exit 2, strict.unsupported_grant)
fail-closed retired tool.json: PASS (unknown field `compatibility`, no migrator)
fail-closed retired record_version 1: PASS (dispatch refused, remove+reinstall hint)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.04s
Running unittests src/lib.rs (target/debug/build/marqdo-view/01b4917d83f17a50/out/marqdo_view-01b4917d83f17a50)
running 25 tests
test execution::controller::tests::exit_code_two_is_a_hard_option_rejection_never_a_retry ... ok
test execution::controller::tests::call_argv_carries_explicit_args_and_observation_file ... ok
test execution::controller::tests::run_argv_is_observation_jsonl_and_never_retired_trace_flags ... ok
test execution::controller::tests::truncated_observation_is_terminal_but_never_labelled_complete ... ok
test execution::controller::tests::stale_and_incomplete_never_map_to_success ... ok
test execution::controller::tests::run_ids_are_unguessable_and_unique ... ok
test execution::events::tests::states_have_stable_wire_values_and_terminals ... ok
test execution::events::tests::newest_cursor_replays_only_new_events ... ok
test execution::events::tests::frames_have_event_id_and_matching_data_seq ... ok
test execution::controller::tests::run_options_never_request_variable_values ... ok
test execution::events::tests::terminal_frame_carries_observation_summary_not_trace ... ok
test execution::events::tests::utc_formatting_is_stable ... ok
test execution::events::tests::terminal_job_replays_snapshot_and_closes ... ok
test execution::export_candidate::tests::public_scalar_types_exclude_text_and_containers ... ok
test execution::process::tests::bounded_capture_keeps_limit_and_drains ... ok
test execution::process::tests::default_budget_matches_rfc ... ok
test execution::events::tests::ring_is_bounded_and_old_cursor_gets_snapshot ... ok
test execution::export_candidate::tests::bounded_text_never_splits_utf8 ... ok
test execution::request::tests::entry_without_main_is_explicitly_rejected ... ok
test execution::request::tests::canonical_names_and_targets_resolve ... ok
test execution::request::tests::rejects_absolute_and_parent_globs ... ok
test execution::request::tests::unknown_parameter_names_are_rejected_before_execution ... ok
test execution::request::tests::rejects_unknown_fields_and_bad_modes ... ok
test execution::controller::tests::expired_terminal_job_is_never_returned_for_export ... ok
test execution::process::tests::cancellation_terminates_the_process_group ... ok
test result: ok. 25 passed; 0 failed; 0 ignored; 0 measured; 40 filtered out; finished in 0.02s
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.04s
Running tests/contract/main.rs (target/debug/build/marqdo-view/4db88ce592e41fad/out/contract-4db88ce592e41fad)
running 8 tests
test observation_contract::unknown_schema_and_revision_are_rejected ... ok
test observation_contract::rejected_before_start_is_a_valid_failed_terminal ... ok
test observation_contract::eof_without_terminal_is_incomplete_never_success ... ok
test observation_contract::real_jsonl_stream_verifies_and_binds_to_analysis_digest ... ok
test observation_contract::truncated_observation_is_a_terminal_but_never_complete ... ok
test observation_contract::stream_and_snapshot_of_the_same_run_agree ... ok
test observation_contract::stale_and_wrong_root_bindings_are_observation_stale ... ok
test observation_contract::lifecycle_negative_cases_fail_closed ... ok
test result: ok. 8 passed; 0 failed; 0 ignored; 0 measured; 45 filtered out; finished in 0.06s
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.04s
Running tests/contract/main.rs (target/debug/build/marqdo-view/4db88ce592e41fad/out/contract-4db88ce592e41fad)
running 20 tests
test core_contract::default_run_does_not_request_variable_or_parameter_values ... ok
test core_contract::current_rc_version_is_accepted ... ok
test core_contract::check_failure_preserves_core_stderr_and_code ... ok
test core_contract::check_refs_is_forwarded_as_a_stricter_flag ... ok
test core_contract::check_returns_exact_analysis_bytes_and_digest ... ok
test core_contract::installed_tool_api_revision_is_enforced_at_the_process_boundary ... ok
test core_contract::analysis_v2_revision_is_a_hard_protocol_error ... ok
test core_contract::run_and_call_argv_use_the_current_observation_flags_only ... ok
test core_contract::missing_required_analysis_fields_are_rejected ... ok
test core_contract::strict_mode_run_request_is_rejected_by_view_validation ... ok
test core_contract::failed_check_normalizes_diagnostics_without_absolute_paths ... ok
test core_contract::tool_api_revision_environment_is_an_exact_expectation ... ok
test core_contract::unknown_analysis_schema_name_or_major_is_rejected ... ok
test core_contract::unknown_module_and_unit_references_are_rejected ... ok
test core_contract::incompatible_product_version_is_rejected_before_any_work ... ok
test core_contract::missing_emit_after_success_is_an_analysis_failure ... ok
test core_contract::retired_revision_3_shape_is_rejected_with_a_rebuild_hint ... ok
test core_contract::source_digest_mismatch_is_not_silently_accepted ... ok
test core_contract::cli_verify_end_to_end_against_fake_core ... ok
test core_contract::cli_verify_rejects_schema_v2_and_digest_mismatch ... ok
test result: ok. 20 passed; 0 failed; 0 ignored; 0 measured; 33 filtered out; finished in 0.14s
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.04s
Running tests/contract/main.rs (target/debug/build/marqdo-view/4db88ce592e41fad/out/contract-4db88ce592e41fad)
running 8 tests
test presentation_states::missing_core_stays_readable_and_explicitly_unverified ... ok
test presentation_states::external_projection_can_be_rendered_from_artifact_source ... ok
test presentation_states::truncated_and_incomplete_runs_never_display_as_success ... ok
test presentation_states::unknown_analysis_schema_is_a_hard_protocol_error ... ok
test presentation_states::failed_check_keeps_prose_and_shows_core_diagnostics ... ok
test presentation_states::source_digest_mismatch_degrades_instead_of_misbinding ... ok
test presentation_states::invalid_analysis_span_is_rejected_not_trimmed ... ok
test presentation_states::run_attached_to_changed_source_becomes_stale ... ok
test result: ok. 8 passed; 0 failed; 0 ignored; 0 measured; 45 filtered out; finished in 0.09s
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.04s
Running tests/contract/main.rs (target/debug/build/marqdo-view/4db88ce592e41fad/out/contract-4db88ce592e41fad)
running 6 tests
test no_coupling::release_lockfile_is_committed ... ok
test no_coupling::tool_manifest_matches_package_and_protocols ... ok
test no_coupling::no_private_core_crate_dependencies ... ok
test no_coupling::exactly_one_reader_theme_and_script_entry ... ok
test no_coupling::source_has_no_legacy_protocol_or_runtime_probing ... ok
test no_coupling::source_never_reads_or_links_the_legacy_repositories ... ok
test result: ok. 6 passed; 0 failed; 0 ignored; 0 measured; 47 filtered out; finished in 0.04s
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.04s
Running tests/security/main.rs (target/debug/build/marqdo-view/6dc7f51fb0afdc26/out/security-6dc7f51fb0afdc26)
running 11 tests
test path_traversal_is_rejected_and_the_old_document_route_is_gone ... ok
test adversarial_markdown_never_injects_markup_or_handlers ... ok
test session_cookie_and_headers_are_hardened ... ok
test aggressive_markdown_links_cannot_become_a_file_read_api ... ok
test oversized_and_unknown_fields_are_rejected_before_execution ... ok
test sec_fetch_site_cross_site_is_rejected_even_with_a_valid_token ... ok
test host_origin_session_csrf_and_json_are_all_required_before_execution ... ok
test cancel_cannot_be_replayed_to_start_a_new_process ... ok
test symlink_escape_outside_the_project_root_is_rejected ... ok
test sse_and_cancel_are_scoped_to_the_owning_session ... ok
test sse_requires_a_session_and_only_the_owning_session_can_read_or_cancel ... ok
test result: ok. 11 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.34s
@@ -0,0 +1,140 @@
==> Live read-only requests
==> Static export
no-exec: PASS (sources/lock unchanged, no sentinel from read-only operations, explicit write control passed, no run control in export; core sha unchanged)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.04s
Running tests/security/main.rs (target/debug/build/marqdo-view/6dc7f51fb0afdc26/out/security-6dc7f51fb0afdc26)
running 11 tests
test path_traversal_is_rejected_and_the_old_document_route_is_gone ... ok
test adversarial_markdown_never_injects_markup_or_handlers ... ok
test aggressive_markdown_links_cannot_become_a_file_read_api ... ok
test session_cookie_and_headers_are_hardened ... ok
test sec_fetch_site_cross_site_is_rejected_even_with_a_valid_token ... ok
test host_origin_session_csrf_and_json_are_all_required_before_execution ... ok
test oversized_and_unknown_fields_are_rejected_before_execution ... ok
test cancel_cannot_be_replayed_to_start_a_new_process ... ok
test symlink_escape_outside_the_project_root_is_rejected ... ok
test sse_requires_a_session_and_only_the_owning_session_can_read_or_cancel ... ok
test sse_and_cancel_are_scoped_to_the_owning_session ... ok
test result: ok. 11 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.33s
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.04s
Running tests/integration/main.rs (target/debug/build/marqdo-view/77a45afd23a2f454/out/integration-77a45afd23a2f454)
running 45 tests
test execution::cross_session_observation_is_rejected ... ok
test execution::same_client_request_id_is_idempotent_and_different_payload_conflicts ... ok
test execution::missing_observation_stream_is_incomplete_never_success ... ok
test execution::call_target_uses_the_call_subcommand_and_function_name ... ok
test execution::explicit_entry_run_streams_accepted_running_and_verified_observation ... ok
test execution::event_frames_use_the_view_run_events_schema_and_numeric_ids ... ok
test execution::observation_with_a_mismatched_digest_is_rejected_as_stale ... ok
test execution::project_grants_are_mapped_to_explicit_cli_flags_and_pure_grants_are_rejected ... ok
test execution::stale_request_digest_is_rejected_before_any_process_starts ... ok
test execution::truncated_observation_is_explicit_and_never_labelled_complete ... ok
test execution::second_run_is_busy_while_one_is_active_and_cancel_is_idempotent ... ok
test export::refuses_to_export_inside_the_project_root ... ok
test export::refuses_to_overwrite_unrelated_non_empty_directory ... ok
test http_live::assets_are_immutable_and_carry_strict_headers ... ok
test http_live::at_most_two_sse_observers_per_run ... ok
test http_live::cancel_is_idempotent_and_yields_one_terminal_state ... ok
test http_live::document_without_main_is_rejected_without_running_another_function ... ok
test execution::source_edit_during_a_run_marks_the_result_stale_and_drops_anchor_ids ... ok
test http_live::duplicate_request_id_is_idempotent_and_busy_or_conflict_never_starts_a_second_process ... ok
test http_live::explicit_run_streams_sse_accepted_running_and_terminal_with_verified_trace ... ok
test http_live::last_event_id_replays_only_newer_events_and_old_cursor_gets_snapshot ... ok
test http_live::pages_issue_a_session_cookie_and_never_execute_the_document ... ok
test http_live::read_only_routes_are_the_target_contract_and_old_routes_are_gone ... ok
test rendering::headings_use_heading_span_while_sections_use_the_complete_span ... ok
test rendering::live_and_static_share_content_but_rewrite_links ... ok
test rendering::malicious_markdown_cannot_inject_markup_or_scripts ... ok
test rendering::page_has_exactly_one_theme_and_one_script ... ok
test rendering::reader_exposes_simple_theme_toggle_and_no_variable_or_memory_tabs ... ok
test rendering::rendering_is_deterministic ... ok
test rendering::run_controls_are_explicitly_unavailable_before_an_explicit_run ... ok
test rendering::semantic_annotations_come_from_analysis_and_are_unique ... ok
test rendering::static_pages_use_parent_relative_assets_and_links ... ok
test rendering::tables_math_and_code_are_inert_and_readable ... ok
test rendering::welcome_hero_only_when_configured ... ok
test unicode_spans::crlf_source_keeps_exact_digest_and_line_mapping ... ok
test unicode_spans::heading_ui_uses_heading_span_and_section_span_includes_children ... ok
test unicode_spans::knowledge_emphasis_never_becomes_an_execution_anchor ... ok
test unicode_spans::unicode_spans_are_exact_and_duplicate_returns_get_distinct_anchors ... ok
test http_live::sse_heartbeats_keep_a_slow_job_connected ... ok
test export::no_annotations_keeps_prose_but_removes_anchors ... ok
test export::export_never_executes_side_effects ... ok
test export::exported_html_has_no_remote_subresources ... ok
test export::exports_offline_site_with_shared_renderer_and_relative_links ... ok
test export::real_frozen_core_export_marks_both_pages_static_ok ... ok
test export::replaces_a_previous_export_atomically ... ok
test result: ok. 45 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 38.86s
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.04s
Running tests/contract/main.rs (target/debug/build/marqdo-view/4db88ce592e41fad/out/contract-4db88ce592e41fad)
running 53 tests
test cli_surface::degradation_without_core_keeps_prose_readable ... ok
test asset_integrity::theme_has_one_token_layer_and_no_legacy_skin ... ok
test cli_surface::browse_on_missing_path_fails_without_starting_a_server ... ok
test cli_surface::missing_document_is_an_io_error ... ok
test cli_surface::non_loopback_bind_is_refused_by_default ... ok
test cli_surface::export_requires_an_output_directory ... ok
test cli_surface::verify_without_core_is_an_argument_error ... ok
test cli_surface::help_comes_from_view_not_core ... ok
test cli_surface::version_is_the_tool_version ... ok
test asset_integrity::reused_assets_match_their_recorded_hashes ... ok
test core_contract::check_failure_preserves_core_stderr_and_code ... ok
test core_contract::default_run_does_not_request_variable_or_parameter_values ... ok
test core_contract::analysis_v2_revision_is_a_hard_protocol_error ... ok
test core_contract::check_returns_exact_analysis_bytes_and_digest ... ok
test core_contract::check_refs_is_forwarded_as_a_stricter_flag ... ok
test core_contract::installed_tool_api_revision_is_enforced_at_the_process_boundary ... ok
test core_contract::missing_required_analysis_fields_are_rejected ... ok
test core_contract::current_rc_version_is_accepted ... ok
test core_contract::run_and_call_argv_use_the_current_observation_flags_only ... ok
test core_contract::failed_check_normalizes_diagnostics_without_absolute_paths ... ok
test core_contract::strict_mode_run_request_is_rejected_by_view_validation ... ok
test core_contract::incompatible_product_version_is_rejected_before_any_work ... ok
test core_contract::tool_api_revision_environment_is_an_exact_expectation ... ok
test core_contract::unknown_analysis_schema_name_or_major_is_rejected ... ok
test core_contract::unknown_module_and_unit_references_are_rejected ... ok
test no_coupling::no_private_core_crate_dependencies ... ok
test no_coupling::release_lockfile_is_committed ... ok
test core_contract::missing_emit_after_success_is_an_analysis_failure ... ok
test no_coupling::exactly_one_reader_theme_and_script_entry ... ok
test no_coupling::tool_manifest_matches_package_and_protocols ... ok
test core_contract::retired_revision_3_shape_is_rejected_with_a_rebuild_hint ... ok
test core_contract::cli_verify_end_to_end_against_fake_core ... ok
test core_contract::source_digest_mismatch_is_not_silently_accepted ... ok
test no_coupling::source_has_no_legacy_protocol_or_runtime_probing ... ok
test observation_contract::rejected_before_start_is_a_valid_failed_terminal ... ok
test observation_contract::eof_without_terminal_is_incomplete_never_success ... ok
test observation_contract::real_jsonl_stream_verifies_and_binds_to_analysis_digest ... ok
test observation_contract::unknown_schema_and_revision_are_rejected ... ok
test observation_contract::stale_and_wrong_root_bindings_are_observation_stale ... ok
test asset_integrity::embedded_asset_bundle_matches_disk_and_has_one_theme ... ok
test observation_contract::stream_and_snapshot_of_the_same_run_agree ... ok
test presentation_states::missing_core_stays_readable_and_explicitly_unverified ... ok
test observation_contract::truncated_observation_is_a_terminal_but_never_complete ... ok
test presentation_states::external_projection_can_be_rendered_from_artifact_source ... ok
test no_coupling::source_never_reads_or_links_the_legacy_repositories ... ok
test presentation_states::truncated_and_incomplete_runs_never_display_as_success ... ok
test presentation_states::failed_check_keeps_prose_and_shows_core_diagnostics ... ok
test presentation_states::invalid_analysis_span_is_rejected_not_trimmed ... ok
test presentation_states::source_digest_mismatch_degrades_instead_of_misbinding ... ok
test observation_contract::lifecycle_negative_cases_fail_closed ... ok
test core_contract::cli_verify_rejects_schema_v2_and_digest_mismatch ... ok
test presentation_states::unknown_analysis_schema_is_a_hard_protocol_error ... ok
test presentation_states::run_attached_to_changed_source_becomes_stale ... ok
test result: ok. 53 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.19s
marqdo view export: 2 page(s), 11 file(s) → /root/work/marqdo-view/dist/test-export-site
manifest: sha256:eddaeed21ff402892b31b31485172156d6905795bd47a72cb85f5684686e51db
executed: false (纯静态导出,未运行任何文档)
export manifest: PASS (2 pages, 3 files)
file:// offline browser check: PASS
export: PASS (offline site at /root/work/marqdo-view/dist/test-export-site; core sha256 a7306962689c635445a59043971ea2eb09298e01feeee81f0ba07b1f3e10306e unchanged)
security: PASS
@@ -0,0 +1,67 @@
marqdo view export: 2 page(s), 11 file(s) → /root/work/marqdo-view/dist/test-export-site
manifest: sha256:eddaeed21ff402892b31b31485172156d6905795bd47a72cb85f5684686e51db
executed: false (纯静态导出,未运行任何文档)
export manifest: PASS (2 pages, 3 files)
file:// offline browser check: PASS
export: PASS (offline site at /root/work/marqdo-view/dist/test-export-site; core sha256 a7306962689c635445a59043971ea2eb09298e01feeee81f0ba07b1f3e10306e unchanged)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.04s
Running tests/contract/main.rs (target/debug/build/marqdo-view/4db88ce592e41fad/out/contract-4db88ce592e41fad)
running 53 tests
test cli_surface::degradation_without_core_keeps_prose_readable ... ok
test asset_integrity::theme_has_one_token_layer_and_no_legacy_skin ... ok
test cli_surface::missing_document_is_an_io_error ... ok
test cli_surface::browse_on_missing_path_fails_without_starting_a_server ... ok
test cli_surface::export_requires_an_output_directory ... ok
test cli_surface::help_comes_from_view_not_core ... ok
test cli_surface::non_loopback_bind_is_refused_by_default ... ok
test cli_surface::version_is_the_tool_version ... ok
test cli_surface::verify_without_core_is_an_argument_error ... ok
test asset_integrity::reused_assets_match_their_recorded_hashes ... ok
test core_contract::check_failure_preserves_core_stderr_and_code ... ok
test core_contract::default_run_does_not_request_variable_or_parameter_values ... ok
test core_contract::analysis_v2_revision_is_a_hard_protocol_error ... ok
test core_contract::check_returns_exact_analysis_bytes_and_digest ... ok
test core_contract::installed_tool_api_revision_is_enforced_at_the_process_boundary ... ok
test core_contract::check_refs_is_forwarded_as_a_stricter_flag ... ok
test core_contract::missing_required_analysis_fields_are_rejected ... ok
test core_contract::current_rc_version_is_accepted ... ok
test core_contract::run_and_call_argv_use_the_current_observation_flags_only ... ok
test core_contract::failed_check_normalizes_diagnostics_without_absolute_paths ... ok
test core_contract::strict_mode_run_request_is_rejected_by_view_validation ... ok
test core_contract::tool_api_revision_environment_is_an_exact_expectation ... ok
test core_contract::incompatible_product_version_is_rejected_before_any_work ... ok
test core_contract::unknown_analysis_schema_name_or_major_is_rejected ... ok
test core_contract::unknown_module_and_unit_references_are_rejected ... ok
test no_coupling::no_private_core_crate_dependencies ... ok
test no_coupling::release_lockfile_is_committed ... ok
test core_contract::missing_emit_after_success_is_an_analysis_failure ... ok
test core_contract::cli_verify_end_to_end_against_fake_core ... ok
test no_coupling::exactly_one_reader_theme_and_script_entry ... ok
test no_coupling::tool_manifest_matches_package_and_protocols ... ok
test core_contract::retired_revision_3_shape_is_rejected_with_a_rebuild_hint ... ok
test core_contract::source_digest_mismatch_is_not_silently_accepted ... ok
test no_coupling::source_has_no_legacy_protocol_or_runtime_probing ... ok
test observation_contract::eof_without_terminal_is_incomplete_never_success ... ok
test observation_contract::rejected_before_start_is_a_valid_failed_terminal ... ok
test asset_integrity::embedded_asset_bundle_matches_disk_and_has_one_theme ... ok
test observation_contract::real_jsonl_stream_verifies_and_binds_to_analysis_digest ... ok
test observation_contract::stale_and_wrong_root_bindings_are_observation_stale ... ok
test observation_contract::unknown_schema_and_revision_are_rejected ... ok
test presentation_states::external_projection_can_be_rendered_from_artifact_source ... ok
test presentation_states::missing_core_stays_readable_and_explicitly_unverified ... ok
test observation_contract::stream_and_snapshot_of_the_same_run_agree ... ok
test observation_contract::truncated_observation_is_a_terminal_but_never_complete ... ok
test no_coupling::source_never_reads_or_links_the_legacy_repositories ... ok
test presentation_states::truncated_and_incomplete_runs_never_display_as_success ... ok
test presentation_states::failed_check_keeps_prose_and_shows_core_diagnostics ... ok
test presentation_states::invalid_analysis_span_is_rejected_not_trimmed ... ok
test observation_contract::lifecycle_negative_cases_fail_closed ... ok
test presentation_states::source_digest_mismatch_degrades_instead_of_misbinding ... ok
test core_contract::cli_verify_rejects_schema_v2_and_digest_mismatch ... ok
test presentation_states::unknown_analysis_schema_is_a_hard_protocol_error ... ok
test presentation_states::run_attached_to_changed_source_becomes_stale ... ok
test result: ok. 53 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.20s
removed tool `view`
@@ -0,0 +1 @@
check-docs: PASS (README/COMPATIBILITY/CHANGELOG/STATUS/ACCEPTANCE describe the rc.4 baseline; CHANGELOG history is explicit)
@@ -0,0 +1,200 @@
==> browser suite: examples/welcome
ok reader root rendered
ok document title has Marqdo
ok one stylesheet
ok one script
ok no external requests
ok no browser console errors
ok dock has all actions
ok dock run control present
ok interactive controls have accessible names
ok Tab reaches named controls
ok more dialog opens
ok source mode attribute
ok source pane visible
ok document hidden in source mode
ok document mode restored
ok search dialog opens
ok search returns local results
ok text size toggled
ok annotations toggled
ok welcome hero only on configured page
ok grammar statement is a real element
ok GFM table rendered
ok dark theme applied
ok theme preference persisted
ok paper theme restored
ok no horizontal overflow at 2048
ok dock inside viewport at 2048
ok no horizontal overflow at 1664
ok dock inside viewport at 1664
ok no horizontal overflow at 1440
ok dock inside viewport at 1440
ok no horizontal overflow at 1024
ok dock inside viewport at 1024
ok no horizontal overflow at 768
ok dock inside viewport at 768
ok no horizontal overflow at 390
ok dock inside viewport at 390
ok no-JS document remains readable
ok no-JS exposes no active run UI
ok print hides dock
ok print keeps prose
ok browsing, refresh, search and settings never submit runs
browser: PASS
==> browser suite: examples/control-flow
ok reader root rendered
ok document title has Marqdo
ok one stylesheet
ok one script
ok no external requests
ok no browser console errors
ok dock has all actions
ok dock run control present
ok interactive controls have accessible names
ok Tab reaches named controls
ok more dialog opens
ok source mode attribute
ok source pane visible
ok document hidden in source mode
ok document mode restored
ok search dialog opens
ok search returns local results
ok text size toggled
ok annotations toggled
ok dark theme applied
ok theme preference persisted
ok paper theme restored
ok no horizontal overflow at 2048
ok dock inside viewport at 2048
ok no horizontal overflow at 1664
ok dock inside viewport at 1664
ok no horizontal overflow at 1440
ok dock inside viewport at 1440
ok no horizontal overflow at 1024
ok dock inside viewport at 1024
ok no horizontal overflow at 768
ok dock inside viewport at 768
ok no horizontal overflow at 390
ok dock inside viewport at 390
ok no-JS document remains readable
ok no-JS exposes no active run UI
ok print hides dock
ok print keeps prose
ok browsing, refresh, search and settings never submit runs
ok run dialog opens
ok run dialog mentions pure mode
ok run dialog previews the command
ok run state succeeded via SSE
ok run panel visible
ok run chips anchored
ok observed chips carry observation provenance
ok static statement anchors carry analysis provenance
ok at most one grouped chip per anchor
ok observation event list rendered
ok stdout rendered escaped
ok Chromium reconnected with the original Last-Event-ID
ok reconnect did not submit a second run or poll status
ok clear hides run panel
ok page was never reloaded by the run
browser: PASS
==> browser suite: examples/function-params.mq.md
ok reader root rendered
ok document title has Marqdo
ok one stylesheet
ok one script
ok no external requests
ok no browser console errors
ok dock has all actions
ok dock run control present
ok interactive controls have accessible names
ok Tab reaches named controls
ok more dialog opens
ok source mode attribute
ok source pane visible
ok document hidden in source mode
ok document mode restored
ok search dialog opens
ok search returns local results
ok text size toggled
ok annotations toggled
ok dark theme applied
ok theme preference persisted
ok paper theme restored
ok no horizontal overflow at 2048
ok dock inside viewport at 2048
ok no horizontal overflow at 1664
ok dock inside viewport at 1664
ok no horizontal overflow at 1440
ok dock inside viewport at 1440
ok no horizontal overflow at 1024
ok dock inside viewport at 1024
ok no horizontal overflow at 768
ok dock inside viewport at 768
ok no horizontal overflow at 390
ok dock inside viewport at 390
ok no-JS document remains readable
ok no-JS exposes no active run UI
ok print hides dock
ok print keeps prose
ok browsing, refresh, search and settings never submit runs
ok no-main Dock opens the functions list
ok no-main Dock did not submit a run
ok Analysis marks n required and Int
ok missing required parameter leaves the form open
ok missing required parameter did not submit
ok call preview includes the chosen value
ok installed tool displays the real double(5) result
ok CLI round-tripped Unicode Text and a List through the form
browser: PASS
==> browser suite: tests/fixtures/security-project
ok reader root rendered
ok document title has Marqdo
ok one stylesheet
ok one script
ok no external requests
ok no browser console errors
ok dock has all actions
ok dock run control present
ok interactive controls have accessible names
ok Tab reaches named controls
ok more dialog opens
ok source mode attribute
ok source pane visible
ok document hidden in source mode
ok document mode restored
ok search dialog opens
ok search returns local results
ok text size toggled
ok annotations toggled
ok adversarial doc has no alert dialog
ok adversarial doc has no external requests
ok raw HTML omitted note rendered
ok prose survives sanitization
ok javascript link neutralized
ok dark theme applied
ok theme preference persisted
ok paper theme restored
ok no horizontal overflow at 2048
ok dock inside viewport at 2048
ok no horizontal overflow at 1664
ok dock inside viewport at 1664
ok no horizontal overflow at 1440
ok dock inside viewport at 1440
ok no horizontal overflow at 1024
ok dock inside viewport at 1024
ok no horizontal overflow at 768
ok dock inside viewport at 768
ok no horizontal overflow at 390
ok dock inside viewport at 390
ok no-JS document remains readable
ok no-JS exposes no active run UI
ok print hides dock
ok print keeps prose
ok browsing, refresh, search and settings never submit runs
browser: PASS
browser: PASS (core sha256 a7306962689c635445a59043971ea2eb09298e01feeee81f0ba07b1f3e10306e unchanged; screenshots: /root/work/marqdo-view/tests/browser/artifacts)
@@ -0,0 +1,109 @@
{
"cli_archive_sha256": "sha256:9c3f166b5e5b8840d39d10019074e4e1c42432fc23e26c69670e64fdcf4e15d8",
"cli_binary_sha256": "sha256:a7306962689c635445a59043971ea2eb09298e01feeee81f0ba07b1f3e10306e",
"cli_source_sha": "452e9a32bd9e40dba427d4180691c58bab74449e",
"cli_version": "3.0.0-rc.4",
"contracts": {
"analysis": 3,
"api_revision": 1,
"observation": 1
},
"extras": {
"browser": "PASS",
"cargo_tests_passed": 174,
"notes": "Generated from real command exit statuses. UNVERIFIED gates are not release evidence and must never be read as PASS."
},
"gates": {
"G01_no_legacy": {
"command": "./scripts/check-no-legacy.sh",
"exit_code": 0,
"log": "docs/evidence/452e9a32bd9e40dba427d4180691c58bab74449e/logs/G01_no_legacy.log",
"state": "PASS"
},
"G02_build": {
"command": "cargo fmt --all -- --check && cargo clippy --locked --all-targets -- -D warnings && cargo test --locked && cargo build --release --locked",
"exit_code": 0,
"log": "docs/evidence/452e9a32bd9e40dba427d4180691c58bab74449e/logs/G02_build.log",
"state": "PASS"
},
"G03_install": {
"command": "scripts/package.sh && marqdo tool install/list/remove && marqdo view --help && scripts/install-smoke.sh && tamper refusal",
"exit_code": 0,
"log": "docs/evidence/452e9a32bd9e40dba427d4180691c58bab74449e/logs/G03_install.log",
"state": "PASS"
},
"G04_static": {
"command": "\"/root/work/marqdo-cli/dist/marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu/marqdo\" view verify examples/mixed-modes/index.mq.md && MARQDO_BIN=\"/root/work/marqdo-cli/dist/marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu/marqdo\" ./scripts/check-examples.sh",
"exit_code": 0,
"log": "docs/evidence/452e9a32bd9e40dba427d4180691c58bab74449e/logs/G04_static.log",
"state": "PASS"
},
"G05_run": {
"command": "installed marqdo view examples/welcome + scripts/acceptance-run.py over SSE",
"exit_code": 0,
"log": "docs/evidence/452e9a32bd9e40dba427d4180691c58bab74449e/logs/G05_run.log",
"state": "PASS"
},
"G06_stream_snapshot": {
"command": "python3 scripts/check-observation.py stream-snapshot",
"exit_code": 0,
"log": "docs/evidence/452e9a32bd9e40dba427d4180691c58bab74449e/logs/G06_stream_snapshot.log",
"state": "PASS"
},
"G07_binding_stale": {
"command": "python3 scripts/check-observation.py binding && cargo test --lib execution::controller::tests::stale_and_incomplete_never_map_to_success && cargo test --test integration execution::source_edit_during_a_run_marks_the_result_stale_and_drops_anchor_ids && cargo test --test contract observation_contract::stale_and_wrong_root_bindings_are_observation_stale",
"exit_code": 0,
"log": "docs/evidence/452e9a32bd9e40dba427d4180691c58bab74449e/logs/G07_binding_stale.log",
"note": "CLI exact-byte binding probe + controller unit mapping + real run/source-change e2e + wrong-digest stale contract all PASS",
"state": "PASS"
},
"G08_negative": {
"command": "python3 scripts/check-observation.py fail-closed && cargo test --lib execution:: && cargo test --test contract observation_contract:: && cargo test --test contract core_contract:: && cargo test --test contract presentation_states:: && cargo test --test contract no_coupling:: && cargo test --test security",
"exit_code": 0,
"log": "docs/evidence/452e9a32bd9e40dba427d4180691c58bab74449e/logs/G08_negative.log",
"note": "N01-N11 decoder/contract negatives, N12-N13 controller hard rejection, N14-N15 CLI fail-closed probes, N16 G01 static check, N17 tool_v1 product-range unit test, N18-N20 security suite: all PASS",
"state": "PASS"
},
"G09_security": {
"command": "env MARQDO_BIN=\"/root/work/marqdo-cli/dist/marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu/marqdo\" ./scripts/test-no-exec.sh && ./scripts/test-security.sh",
"exit_code": 0,
"log": "docs/evidence/452e9a32bd9e40dba427d4180691c58bab74449e/logs/G09_security.log",
"state": "PASS"
},
"G10_export": {
"command": "env MARQDO_BIN=\"/root/work/marqdo-cli/dist/marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu/marqdo\" ./scripts/test-export.sh && cargo test --locked --test contract",
"exit_code": 0,
"log": "docs/evidence/452e9a32bd9e40dba427d4180691c58bab74449e/logs/G10_export.log",
"state": "PASS"
},
"G11_evidence_ci": {
"command": "https://ci.cflmy.cn cflmy/marqdo-view pipelines (commit 340ecb035fbde0a825c1e5edf1d28b41342d1002)",
"exit_code": 0,
"note": "Woodpecker pipeline #10 succeeded for 340ecb035fbde0a825c1e5edf1d28b41342d1002",
"state": "PASS"
},
"G12_docs": {
"command": "./scripts/check-docs.sh",
"exit_code": 0,
"log": "docs/evidence/452e9a32bd9e40dba427d4180691c58bab74449e/logs/G12_docs.log",
"state": "PASS"
}
},
"generated_utc": "2026-11-25T14:21:15.414398+00:00",
"markdown_profile": "marqdo.md.v1",
"platform": "linux-x86_64-glibc2.39",
"product": {
"name": "marqdo-view",
"target": "linux-x86_64-glibc2.39",
"version": "0.3.0"
},
"product_range": ">=3.0.0-rc.3,<4.0.0",
"result": "PASS",
"schema": "marqdo.view.acceptance",
"schema_version": 1,
"unverified": [],
"view_binary_sha256": "sha256:93421d3dc83d39e99a547d9e9c34e1a2a69b7f3781016e08c46bf1ff72f0cf31",
"view_commit": "340ecb035fbde0a825c1e5edf1d28b41342d1002",
"view_tool_bundle_digest": "sha256:7fa5e3ae590cd42e29b50f083a39dbb465a4eb114fc9336581a38b6747cd6658",
"view_tool_bundle_digest_method": "sha256 of the canonical SHA256SUMS file bytes in the bundle"
}
+81 -25
View File
@@ -1,34 +1,90 @@
# 验收证据 # 验收证据
本目录保存**由真实命令生成**的验收证据。历史证据使用 `<CLI-SOURCE-SHA>/manifest.json`,工单复验另存于 `issue-2/manifest.json`: 本目录只保存**由真实命令生成**的机器证据。当前基线:
`marqdo 3.0.0-rc.4`(源码 `452e9a32bd9e40dba427d4180691c58bab74449e`)。
`PASS/FAIL/UNVERIFIED` 一律以 manifest 为准;`UNVERIFIED`、`PARTIAL`、`WARN`
不得写成 `PASS`。缺证据即视为未完成,任一 P0 门禁失败/未证明 → 不发布 0.3.0。
- `schema`/`schema_version`:`marqdo.view-conformance` v1(View 自有,非 CLI 协议); ## 目录布局
- `view_source_sha`:生成证据时的 View Git SHA;
- `view_binary_sha256`:发布 bundle 内 `bin/marqdo-view` 摘要;
- `cli_source_sha`:CLI 发布归档记录的源码 SHA;
- `cli_binary_sha256_before/after`:冻结 CLI 在验收前后的 SHA-256,必须相同;
- `tool_protocol`/`analysis_protocol`/`trace_protocol`、`target`、`archive_sha256`;
- `gates`:`scripts/acceptance.sh` 每一步的真实退出状态,包括冻结身份、代码、浏览器、Tool 完整性和卸载;
- `tests`:contract/examples/export/no_exec/security/browser 的 PASS/FAIL/SKIP。
生成方式(不要手写/篡改): - `docs/evidence/<CLI-SOURCE-SHA>/manifest.json`:当前契约的机器验收清单
(当前目录名固定为 `452e9a32bd9e40dba427d4180691c58bab74449e`);
- `docs/evidence/<CLI-SOURCE-SHA>/README.md`:该次证据的说明/附件索引;
- 历史目录(`2c7c4f31e7a388d3fcfa717a77067e696ed13854/`、`issue-2/`、
`issue-3/`、`PR-01..PR-06/`、`0001-pr03/`):0.2.0 旧预发布契约时代的证据,
**仅作历史记录,不能替代 rc.4 门禁**;
- 分 PR 的人工/截图/日志不是协议证据,只在对应 README 中说明。
```bash ## manifest schema:`marqdo.view.acceptance` / `schema_version: 1`
# 输出到 dist/acceptance/manifest.json
MARQDO_BIN=/abs/path/to/frozen/marqdo scripts/acceptance.sh 必填字段(按 issue #5 §0):
```json
{
"schema": "marqdo.view.acceptance",
"schema_version": 1,
"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",
"generated_utc": "<UTC ISO-8601>",
"gates": {
"G01_no_legacy": {"state": "UNVERIFIED", "command": "...", "exit_code": null, "log": ""}
},
"unverified": []
}
``` ```
`manifest.json` 在验收最后一步写入;任一步失败时脚本非零退出且不会声称 PASS。 生成器额外输出(不改变上述语义):
冻结 CLI 的 `--version`/SHA 与发布归档必须一致(`scripts/verify-frozen-cli.sh`),
CI 证据只在 `.github/workflows/ci.yml` 真正运行后才可补入;本仓库当前**未声称**
远端 CI 通过。
分 PR 证据目录(人工/截图/日志,非协议证据): - `product {name, version, target}`、`cli_version`、`contracts {api_revision:1,
analysis:3, observation:1}`、`markdown_profile`、`product_range`;
- `result`:`PASS | PARTIAL | FAIL`;
- `gates.G01…G12`:每项 `{state, command, exit_code, log, note?}`,
`state ∈ {PASS, FAIL, UNVERIFIED}`;
- `unverified`:所有非 PASS 门禁 id 的显式列表;
- `extras`:cargo 测试数、浏览器状态、说明。
- `PR-01/`:Tool v1 安装/分发/篡改拒绝实测; `view_tool_bundle_digest` 的计算方式:bundle 内规范化 `SHA256SUMS` 文件字节的
- `PR-02/`:Reader 结构与 `/api/documents` 只读面; SHA-256(`sha256:` 前缀),字段旁会记录 `view_tool_bundle_digest_method`。
- `PR-03/`:执行层 request/process/controller/events 测试;
- `PR-04/`:SSE 闭环、7 路由、会话安全、真实 Chromium 与真实冻结 CLI run; ## 门禁状态含义
- `PR-05/`:Trace 绑定/标注/stale 与浏览器回归截图;
- `PR-06/`:示例 check/call/run、零执行哨兵、一键验收日志与发布包身份; | 状态 | 含义 |
- `0001-pr03/`:RFC-VIEW-0001 时期的浏览器截图(历史归档)。 |---|---|
| `PASS` | 本环境真实命令 exit 0,且产物/日志与声明一致 |
| `FAIL` | 真实命令非 0 或断言失败;阻塞发布 |
| `UNVERIFIED` | 未运行、无法在本环境判定或缺少测试路径;**不得**读作 PASS;阻塞发布 |
G01–G12 的判定命令与通过判据见 [`docs/ACCEPTANCE.md`](../ACCEPTANCE.md)。
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 中保持
`UNVERIFIED`,不能证明远端 CI 通过。
## 生成方式(不要手写/篡改)
```bash
export MARQDO_BIN=/abs/unpacked/marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu/marqdo
scripts/frozen-beta.sh verify "$MARQDO_BIN"
scripts/acceptance.sh
# → docs/evidence/452e9a32bd9e40dba427d4180691c58bab74449e/manifest.json
# → dist/acceptance/manifest.json(同一内容)
```
`manifest.json` 在验收最后一步写入;任一步 FAIL 时脚本非零退出且不会声称 PASS。
冻结 CLI 的 `--version`/SHA 与发布归档必须一致(`scripts/verify-frozen-cli.sh`)。
`VIEW_EVIDENCE_OUT` 可覆盖主输出路径,但不得用于伪造门禁结果。
## 历史证据声明
0.2.0 时代的 manifest 与 PR 证据使用旧预发布契约与旧 manifest 结构,
其中的 `PASS` 只对其当时的基线有效。它们不得被复制为 0.3.0 证据,
也不得在 README/COMPATIBILITY/CHANGELOG/STATUS/ACCEPTANCE 中作为当前能力证明。
远端 CI 证据只在 `.github/workflows/ci.yml` / `.woodpecker.yml` 真正运行后才可补入;
本仓库当前**未声称**远端 CI 通过。
+9
View File
@@ -0,0 +1,9 @@
# 工单 #3 基线
- View 基线:`dcb9daeaf4e5eefd8c35aa0c843dd8a0eaf7fef5`。
- [Linux x86_64 RC.2 发行包](https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-rc.2)与发行方 SHA-256 清单核对通过。
- 发行 tag:`9149ee40a48fcda692c5c112f66c465487d13dfb`。
- 包 SHA-256:`e32e6426caf023fc813ebdbf5a171ec164ee2ffb843ae5594b8e7b9780f496ea`。
- 二进制 SHA-256:`5caa90b8f6a282aef5bb301443ede6cd3bdcf5f64c88969e6d71cb324b03dc5b`。
发行 CLI 完成示例的 `check --emit`(Analysis v3)和 `call`(Events v1、Trace v2),返回 Float 4.0。View 基线只接收 Analysis v2,无法显示这个项目的执行语义。本文件记录 CLI 可观察的基线,View 的端到端门禁另行验证。
+47
View File
@@ -0,0 +1,47 @@
# 工单 #3 验收
Linux x86_64 使用官方 `marqdo 3.0.0-rc.2` 发行归档及 Chromium
`131.0.6778.33`。View 代码和测试提交、发行包、可执行文件、结果 ZIP、
清单与证据文件的 SHA-256 见 [验收清单](manifest.json)。Core 源码标签
及安装归档校验见 [发行基线](../issue-3-baseline.md)。
| 检查 | 结果 |
|---|---|
| Rust 格式、严格 Clippy、160 项单元与集成回归 | PASS |
| 发行包构建、官方 RC.2 安装独立 Tool、Analysis v3 核对 | PASS |
| 原有 Chromium 四套回归 | PASS |
| 本地图片、跨文档重复标题锚点、离线公式和 390px 布局 | PASS |
| 函数旁显式调用及默认参数、终态前可见 stdout、预览确认与下载 | PASS |
| 打开和导出零运行;两种导出后执行计数仍为 1 | PASS |
| 缺少 CSRF、跨 Origin/会话、过期或活动 Job、篡改、源码/锁/导入/图片变化 | PASS |
| 成功、失败确认、取消、超时、Trace 缺失与纯文本输出 | PASS |
| ZIP 条目与清单哈希、打包失败与客户端断开清理、进程重启 | PASS |
| 关闭服务器后,禁用 JavaScript 和网络,以 `file://` 阅读并打印结果 | PASS |
| 完整外部屏幕阅读器手工走查 | UNVERIFIED |
测试日志见 [Rust 与打包](checks.log)、[HTTP 与 ZIP](http.log)及
[浏览器](browser.log)。浏览器验证用真实发行 CLI。计数包装器审查传给 CLI
的 argv,并在流式验证场景延迟转发终态,以观察真实 stdout 在终态之前出现。
- [函数旁结果](live-result.png)
- [导出预览](export-preview.png)
- [离线正文及媒体](offline-snapshot.png)
- [离线结果](offline-result.png)
- [窄屏阅读](mobile-reader.png)
## 复跑
```bash
export MARQDO_BIN=/absolute/path/to/released/marqdo
cargo fmt --all -- --check
cargo clippy --locked --all-targets -- -D warnings
cargo test --locked
cargo build --locked
./scripts/test-complete-reader.py
(cd tests/browser && npm ci && npx playwright install chromium)
node tests/browser/complete-reader.browser.cjs
```
如已有 Chromium,可通过 `CHROMIUM_BIN` 指定可执行文件。
`MQ_SCREENSHOT_DIR` 可收集浏览器截图,`SNAPSHOT_ZIP` 可保存 HTTP 验收下载文件。
部署前可运行 `scripts/package.sh`,用同一官方 CLI 复验 Tool 安装。
+11
View File
@@ -0,0 +1,11 @@
Chromium 131.0.6778.33
Live media, cross-document anchors, confirmed call, pre-terminal stdout, private download and offline ZIP: PASS
==> browser suite: examples/welcome
browser: PASS
==> browser suite: examples/control-flow
browser: PASS
==> browser suite: examples/function-params.mq.md
browser: PASS
==> browser suite: tests/fixtures/security-project
browser: PASS
browser: PASS (core sha256 5caa90b8f6a282aef5bb301443ede6cd3bdcf5f64c88969e6d71cb324b03dc5b unchanged; screenshots: /tmp/marqdo-view-regression)
+11
View File
@@ -0,0 +1,11 @@
cargo fmt --all -- --check: PASS
cargo clippy --locked --all-targets -- -D warnings: PASS
test result: ok. 65 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.02s
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
test result: ok. 41 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.34s
test result: ok. 43 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 3.23s
test result: ok. 11 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.13s
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
install-smoke: PASS (core sha256 5caa90b8f6a282aef5bb301443ede6cd3bdcf5f64c88969e6d71cb324b03dc5b unchanged)
Installed Tool: verify examples/complete-reader --json emitted Analysis v3, result PASS and executed=false
Draft 2020-12 schema definitions and generated v2 manifest: PASS
Binary file not shown.

After

Width:  |  Height:  |  Size: 147 KiB

+10
View File
@@ -0,0 +1,10 @@
marqdo view export: 2 page(s), 15 file(s) → <临时目录>/pure
manifest: sha256:254974d424a6def3b7f8b45b7511bf73ff85586b85e2bbac32d66113a969320d
executed: false (纯静态导出,未运行任何文档)
snapshot manifest sha256 7fdc11d812a619382068198bb3f3f27b46f9713c7b1f75d7d82c63220cacfbb0
pure and selected export leave execution count at 1; source, lock, dependency and media staleness denied
snapshot manifest sha256 7fdc11d812a619382068198bb3f3f27b46f9713c7b1f75d7d82c63220cacfbb0
active/cancelled export denied, verified failure gated, stdout escaped, missing Trace separate
selected IDs remain isolated, tampering detected, oversized request denied, failed and aborted packages cleaned
run/call count matches four explicit submissions: ['call', 'call', 'call', 'call']
restarted View cannot recover the previous job; timed-out execution is not exportable; private scratch directories are empty
Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

+52
View File
@@ -0,0 +1,52 @@
{
"schema": "marqdo.view-complete-reader-acceptance",
"schema_version": 1,
"date": "2026-11-24",
"view": {
"code_sha": "574036288008c15dea3cc2ca3682dc489ec3f13c",
"test_sha": "748e1cc491492f1f65d2720d750861d059ba4fe3",
"binary_sha256": "183ac19424107950bbfd977e4736c1f8c24c4456b6bd55ede17246ad5fa004d1",
"tool_archive_sha256": "91df6bb0f4c408dae8a0d63a55025fdaa26dcc288ac2c4d722eebb0ad80acead"
},
"core": {
"version": "3.0.0-rc.2",
"tag_sha": "9149ee40a48fcda692c5c112f66c465487d13dfb",
"linux_archive_sha256": "e32e6426caf023fc813ebdbf5a171ec164ee2ffb843ae5594b8e7b9780f496ea",
"binary_sha256": "5caa90b8f6a282aef5bb301443ede6cd3bdcf5f64c88969e6d71cb324b03dc5b"
},
"platform": {
"kernel": "7.0.0-31-generic",
"architecture": "x86_64",
"libc": [
"glibc",
"2.43"
],
"chromium": "131.0.6778.33"
},
"checks": {
"fmt": "PASS",
"clippy": "PASS",
"rust_tests": 160,
"installed_tool": "PASS",
"http_and_zip": "PASS",
"chromium_new": "PASS",
"chromium_existing": "PASS",
"offline_no_js": "PASS",
"snapshot_manifest_schema": "PASS",
"manual_screen_reader": "UNVERIFIED"
},
"snapshot": {
"archive_sha256": "11d0f11828bc1a971e4173943781fcc0fb6bddaecd9df6014af3b3e44de838e7",
"manifest_sha256": "7fdc11d812a619382068198bb3f3f27b46f9713c7b1f75d7d82c63220cacfbb0"
},
"artifacts": {
"browser.log": "2330a995605e0c792a8e73f6eacec2f0018408699d7d9f413afc27b7b5794d86",
"checks.log": "8848f9398bd1eb44fd8aa91183298d85537b06eac79ca1588814ad479b7b9a1a",
"export-preview.png": "2fb98536a6ef1b77e3b96f1d9564ff1e60e7d259f59975944c5326d89590656f",
"http.log": "6a662683268e29116d416f8af75110bba3de55b7bdbb3c2c8bc64ed47abbe57f",
"live-result.png": "c1a843f5e697256d2953a3074318f05a260bbf6624ed61f60920b3ae4e3f5d18",
"mobile-reader.png": "7678a211f82b502321d2da3302ede5a29f4775f48e86faf927d3364a11cf1c49",
"offline-result.png": "b0a5aa3b11480ad0a7914f2cdc81d187577113e37efab716ec9c2a98993760fb",
"offline-snapshot.png": "f18661b2a086e039e00c2292356957c667afb0abd6ce0d44c6d8138072b4b30a"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

+421
View File
@@ -0,0 +1,421 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://git.cflmy.cn/cflmy/marqdo-view/raw/branch/master/docs/schema/export-manifest-v2.schema.json",
"title": "View Static Result Export Manifest v2",
"type": "object",
"properties": {
"schema": {
"const": "marqdo.view-export"
},
"schema_version": {
"const": 2
},
"view": {
"type": "object",
"properties": {
"name": {
"const": "marqdo-view"
},
"version": {
"type": "string"
}
},
"required": [
"name",
"version"
],
"additionalProperties": false
},
"core_version": {
"type": "string"
},
"entry": {
"type": "object",
"properties": {
"relative_path": {
"type": "string",
"pattern": "^(?!/)(?!.*(?:^|/)\\.{1,2}(?:/|$))[^\\\\:\\x00-\\x1f]+$"
},
"file": {
"const": "index.html"
},
"sha256": {
"type": "string",
"pattern": "^[0-9a-f]{64}$"
}
},
"required": [
"relative_path",
"file",
"sha256"
],
"additionalProperties": false
},
"pages": {
"type": "array",
"items": {
"type": "object",
"properties": {
"relative_path": {
"type": "string",
"pattern": "^(?!/)(?!.*(?:^|/)\\.{1,2}(?:/|$))[^\\\\:\\x00-\\x1f]+$"
},
"module_id": {
"type": "string"
},
"source_sha256": {
"type": "string",
"pattern": "^[0-9a-f]{64}$"
},
"source_status": {
"type": "string"
},
"analysis_digest": {
"anyOf": [
{
"type": "string",
"pattern": "^sha256:[0-9a-f]{64}$"
},
{
"type": "null"
}
]
},
"file": {
"type": "string",
"pattern": "^(?!/)(?!.*(?:^|/)\\.{1,2}(?:/|$))[^\\\\:\\x00-\\x1f]+$"
},
"sha256": {
"type": "string",
"pattern": "^[0-9a-f]{64}$"
},
"annotations": {
"type": "boolean"
}
},
"required": [
"relative_path",
"module_id",
"source_sha256",
"source_status",
"analysis_digest",
"file",
"sha256",
"annotations"
],
"additionalProperties": false
}
},
"assets": {
"type": "array",
"items": {
"type": "object",
"properties": {
"path": {
"type": "string",
"pattern": "^(?!/)(?!.*(?:^|/)\\.{1,2}(?:/|$))[^\\\\:\\x00-\\x1f]+$"
},
"sha256": {
"type": "string",
"pattern": "^[0-9a-f]{64}$"
},
"size": {
"type": "integer",
"minimum": 0
}
},
"required": [
"path",
"sha256",
"size"
],
"additionalProperties": false
}
},
"files": {
"type": "array",
"items": {
"type": "object",
"properties": {
"path": {
"type": "string",
"pattern": "^(?!/)(?!.*(?:^|/)\\.{1,2}(?:/|$))[^\\\\:\\x00-\\x1f]+$"
},
"sha256": {
"type": "string",
"pattern": "^[0-9a-f]{64}$"
},
"size": {
"type": "integer",
"minimum": 0
},
"mime": {
"enum": [
"image/png",
"image/jpeg",
"image/gif",
"image/webp",
"image/svg+xml"
]
}
},
"required": [
"path",
"sha256",
"size"
],
"additionalProperties": false
}
},
"scope": {
"const": "document"
},
"source": {
"type": "object",
"properties": {
"project_root_id": {
"type": "string"
},
"document": {
"type": "string",
"pattern": "^(?!/)(?!.*(?:^|/)\\.{1,2}(?:/|$))[^\\\\:\\x00-\\x1f]+$"
},
"module_id": {
"type": "string"
},
"source_sha256": {
"type": "string",
"pattern": "^[0-9a-f]{64}$"
},
"analysis_digest": {
"type": "string",
"pattern": "^sha256:[0-9a-f]{64}$"
},
"lock_digest": {
"anyOf": [
{
"type": "string",
"pattern": "^sha256:[0-9a-f]{64}$"
},
{
"type": "null"
}
]
}
},
"required": [
"project_root_id",
"document",
"module_id",
"source_sha256",
"analysis_digest",
"lock_digest"
],
"additionalProperties": false
},
"execution": {
"type": "object",
"properties": {
"included": {
"const": true
},
"core_run_id": {
"type": "string",
"pattern": "^[A-Za-z0-9_-]{1,128}$"
},
"core_version": {
"type": "string"
},
"target": {
"type": "string"
},
"status": {
"enum": [
"succeeded",
"failed"
]
},
"terminal_at": {
"type": "string",
"format": "date-time"
},
"source_verified": {
"const": true
},
"trace_status": {
"enum": [
"verified",
"invalid",
"unavailable",
"truncated"
]
},
"result_complete": {
"type": "boolean"
},
"output_complete": {
"type": "boolean"
},
"observation_truncated": {
"type": "boolean"
},
"parameters": {
"enum": [
"omitted",
"included"
]
},
"mode": {
"enum": [
"pure",
"project"
]
},
"core_protocol": {
"type": "object",
"properties": {
"analysis": {
"enum": [
2,
3
]
},
"trace": {
"const": 2
},
"events": {
"const": 1
}
},
"required": [
"analysis",
"trace",
"events"
],
"additionalProperties": false
}
},
"required": [
"included",
"core_run_id",
"core_version",
"target",
"status",
"terminal_at",
"source_verified",
"trace_status",
"result_complete",
"output_complete",
"observation_truncated",
"parameters",
"mode",
"core_protocol"
],
"additionalProperties": false
},
"executed_during_export": {
"const": false
},
"requires": {
"type": "object",
"properties": {
"marqdo": {
"type": "string"
},
"api_revision": {
"const": 1
},
"analysis": {
"const": 3
},
"observation": {
"const": 1
},
"markdown_profile": {
"const": "marqdo.md.v1"
}
},
"required": [
"marqdo",
"api_revision",
"analysis",
"observation",
"markdown_profile"
],
"additionalProperties": false
},
"producers": {
"type": "object",
"properties": {
"view": {
"type": "object",
"properties": {
"name": {
"const": "marqdo-view"
},
"version": {
"type": "string"
},
"binary_sha256": {
"type": "string"
}
},
"required": [
"name",
"version",
"binary_sha256"
],
"additionalProperties": false
},
"cli": {
"oneOf": [
{
"type": "null"
},
{
"type": "object",
"properties": {
"version": {
"type": [
"string",
"null"
]
},
"binary_sha256": {
"type": "string"
}
},
"required": [
"version",
"binary_sha256"
],
"additionalProperties": false
}
]
}
},
"required": [
"view",
"cli"
],
"additionalProperties": false
}
},
"required": [
"schema",
"schema_version",
"view",
"producers",
"requires",
"core_version",
"entry",
"pages",
"assets",
"files",
"scope",
"source",
"execution",
"executed_during_export"
],
"additionalProperties": false
}
+218
View File
@@ -0,0 +1,218 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://git.cflmy.cn/cflmy/marqdo-view/raw/branch/master/docs/schema/export-overlay-v1.schema.json",
"title": "View internal renderer result projection v1",
"type": "object",
"properties": {
"source": {
"type": "object",
"properties": {
"project_root_id": {
"type": "string"
},
"document": {
"type": "string",
"pattern": "^(?!/)(?!.*(?:^|/)\\.{1,2}(?:/|$))[^\\\\:\\x00-\\x1f]+$"
},
"module_id": {
"type": "string"
},
"source_sha256": {
"type": "string",
"pattern": "^[0-9a-f]{64}$"
},
"analysis_digest": {
"type": "string",
"pattern": "^sha256:[0-9a-f]{64}$"
},
"lock_digest": {
"anyOf": [
{
"type": "string",
"pattern": "^sha256:[0-9a-f]{64}$"
},
{
"type": "null"
}
]
}
},
"required": [
"project_root_id",
"document",
"module_id",
"source_sha256",
"analysis_digest",
"lock_digest"
],
"additionalProperties": false
},
"execution": {
"type": "object",
"properties": {
"included": {
"const": true
},
"core_version": {
"type": "string"
},
"target": {
"type": "string"
},
"status": {
"enum": [
"succeeded",
"failed"
]
},
"terminal_at": {
"type": "string",
"format": "date-time"
},
"source_verified": {
"const": true
},
"observation_status": {
"enum": [
"verified",
"invalid",
"unavailable",
"truncated",
"stale"
]
},
"result_complete": {
"type": "boolean"
},
"output_complete": {
"type": "boolean"
},
"observation_truncated": {
"type": "boolean"
},
"parameters": {
"enum": [
"omitted",
"included"
]
},
"mode": {
"enum": [
"pure",
"project"
]
},
"capture_level": {
"type": "string"
},
"contracts": {
"type": "object",
"properties": {
"api_revision": {
"const": 1
},
"analysis": {
"const": 3
},
"observation": {
"const": 1
}
},
"required": [
"api_revision",
"analysis",
"observation"
],
"additionalProperties": false
},
"core_run_id": {
"type": "string",
"pattern": "^[A-Za-z0-9_-]{1,128}$"
}
},
"required": [
"included",
"core_run_id",
"core_version",
"target",
"status",
"terminal_at",
"source_verified",
"observation_status",
"capture_level",
"result_complete",
"output_complete",
"observation_truncated",
"parameters",
"mode",
"contracts"
],
"additionalProperties": false
},
"label": {
"type": "string"
},
"value": {
"type": [
"string",
"null"
],
"maxLength": 131072
},
"stdout": {
"type": [
"string",
"null"
],
"maxLength": 131072
},
"stderr": {
"type": [
"string",
"null"
],
"maxLength": 131072
},
"observation_counts": {
"type": [
"object",
"null"
],
"additionalProperties": {
"type": "integer",
"minimum": 0
}
},
"arguments": {
"type": [
"array",
"null"
],
"maxItems": 32,
"items": {
"type": "array",
"prefixItems": [
{
"type": "string"
},
{
"type": "string"
}
],
"items": false,
"minItems": 2
}
}
},
"required": [
"source",
"execution",
"label",
"value",
"stdout",
"stderr",
"observation_counts",
"arguments"
],
"additionalProperties": false
}
+85
View File
@@ -0,0 +1,85 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://git.cflmy.cn/cflmy/marqdo-view/raw/branch/master/docs/schema/export-request-v1.schema.json",
"title": "View Static Export Request v1",
"type": "object",
"properties": {
"schema": {
"const": "marqdo.view-static-export-request"
},
"schema_version": {
"const": 1
},
"run_id": {
"type": "string",
"pattern": "^[A-Za-z0-9_-]{1,128}$"
},
"document": {
"type": "string",
"pattern": "^(?!/)(?!.*(?:^|/)\\.{1,2}(?:/|$))[^\\\\:\\x00-\\x1f]+$",
"maxLength": 1024,
"allOf": [
{
"pattern": "\\.mq\\.md$"
}
]
},
"analysis_digest": {
"type": "string",
"pattern": "^sha256:[0-9a-f]{64}$"
},
"scope": {
"const": "document"
},
"include": {
"type": "object",
"properties": {
"result_value": {
"type": "boolean"
},
"stdout": {
"type": "boolean"
},
"stderr": {
"type": "boolean"
},
"observation_summary": {
"type": "boolean"
},
"arguments": {
"type": "boolean"
}
},
"required": [
"result_value",
"stdout",
"stderr",
"observation_summary",
"arguments"
],
"additionalProperties": false
},
"confirm_sensitive_output": {
"type": "boolean"
},
"confirm_partial": {
"type": "boolean"
},
"client_export_request_id": {
"type": "string",
"pattern": "^[A-Za-z0-9_-]{1,128}$"
}
},
"required": [
"schema",
"schema_version",
"run_id",
"document",
"analysis_digest",
"scope",
"include",
"confirm_sensitive_output",
"client_export_request_id"
],
"additionalProperties": false
}
@@ -0,0 +1,17 @@
# @knowledge 误差说明
## 误差
[返回计算均值](../index.mq.md#计算均值)
![样本记录](../media/result.webp)
## 复核
### 误差
同名标题以稳定的序号区分。
![流程图](../media/diagram.svg)
![状态图](../media/status.gif)
+100
View File
@@ -0,0 +1,100 @@
---
import:
notes: "./docs/explanation.mq.md"
---
# @knowledge 小型统计实验
样本的均值 $\bar{x}$ 可用下式计算:
$$
\bar{x} = \frac{1}{n} \sum_{i=1}^{n} x_i
$$
![样本数据图](media/flow.png)
| 样本 | 数值 |
| :--- | ---: |
| A | 3 |
| B | 5 |
- [x] 记录样本
- [ ] 审查结果
[误差说明](docs/explanation.mq.md#误差-1) · [本页公式](#计算均值)
# @exec 计算
## @exec main
`return 4`
## @exec 计算均值
计算两个样本的均值。
`params(a: Int, b: Int = 5)`
`return (a + b) / 2`
## @exec classify
`params(n: Int)`
**if n < 0**
`return -1`
**else if n == 0**
`return 0`
**else**
`return 1`
**end**
## @exec scan
`n = 0`
**while n < 10**
`n = n + 1`
**if n == 2**
`continue`
**else if n == 4**
`break`
**end**
**end**
`return n`
## @exec fail
`params(divisor: Int)`
`return 3 / divisor`
## @exec write_output
`buffer = memory.new(1, 1)`
`buffer[0] = 52`
`buffer[1] = 10`
`stdout = resource.open("stdio", "stdout", ["write"])`
`resource.write(stdout, buffer, 0, 2)`
`resource.close(stdout)`
`return 4`
+3
View File
@@ -0,0 +1,3 @@
project:
name: complete-reader
version: 0.1.0
+1
View File
@@ -0,0 +1 @@
PNG、WebP、SVG 和 GIF 均为本仓库原创合成测试图,适用仓库的 MIT/Apache-2.0 双许可。
@@ -0,0 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" width="360" height="80" viewBox="0 0 360 80">
<rect x="1" y="1" width="358" height="78" rx="8" fill="#f7f0e5" stroke="#b88a45"/>
<path d="M48 40h264m-12-9 12 9-12 9" fill="none" stroke="#52603a" stroke-width="2"/>
<circle cx="80" cy="40" r="7" fill="#52603a"/>
<circle cx="200" cy="40" r="7" fill="#52603a"/>
</svg>

After

Width:  |  Height:  |  Size: 364 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 488 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 482 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 367 B

+15 -4
View File
@@ -4,7 +4,8 @@
Usage: python3 scripts/acceptance-run.py http://127.0.0.1:PORT/ Usage: python3 scripts/acceptance-run.py http://127.0.0.1:PORT/
Prints a PASS line and exits non-zero on any failure. Never polls: it creates Prints a PASS line and exits non-zero on any failure. Never polls: it creates
one run, observes one SSE stream until the single terminal event, and asserts one run, observes one SSE stream until the single terminal event, and asserts
the verified Trace binding. the verified Observation v1 binding (source analysis digest, contiguous seq,
unique terminal) instead of any retired trace protocol.
""" """
import http.cookiejar import http.cookiejar
import json import json
@@ -74,8 +75,18 @@ with opener.open(events_url, timeout=120) as stream:
assert terminal is not None, "no terminal SSE event" assert terminal is not None, "no terminal SSE event"
assert terminal["state"] == "succeeded", terminal assert terminal["state"] == "succeeded", terminal
assert terminal["result"]["success"] is True, terminal["result"] assert terminal["result"]["success"] is True, terminal["result"]
assert terminal["trace"]["status"] == "verified", terminal.get("trace") assert terminal["result"]["observation_status"] == "verified", terminal["result"]
assert terminal["result"]["observation_protocol"] == 1, terminal["result"]
assert terminal["result"]["observation_truncated"] is False, terminal["result"]
summary = terminal.get("observation_summary") or terminal["result"].get("observation_summary")
assert summary is not None, "missing observation summary"
assert summary.get("status") in ("verified", "ok"), summary
event_count = 0
if isinstance(summary.get("events"), list):
event_count = len(summary["events"])
elif isinstance(summary.get("counts"), dict):
event_count = sum(int(value) for value in summary["counts"].values())
print( print(
"explicit real run: PASS (run_id=%s events=%d)" "explicit real run: PASS (run_id=%s observation=%s events=%d)"
% (accepted["run_id"], len(terminal["trace"]["events"])) % (accepted["run_id"], terminal["result"]["observation_status"], event_count)
) )
+385 -157
View File
@@ -1,15 +1,20 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# RFC-VIEW-0002 §9.4 one-command acceptance. # marqdo-view 0.3.0 one-command acceptance for the rc.4 contract baseline
# (adaptation issue #4, acceptance gates G01-G12 from issue #5, public Analysis
# boundary issue #6).
# #
# Usage: # Usage:
# MARQDO_BIN=/abs/path/to/frozen/marqdo scripts/acceptance.sh # MARQDO_BIN=/abs/path/to/frozen/marqdo scripts/acceptance.sh
# #
# Optional: # Optional:
# VIEW_EVIDENCE_OUT=path override dist/acceptance/manifest.json # VIEW_EVIDENCE_OUT=path primary manifest path
# SKIP_BROWSER=1 skip Chromium suite (recorded as SKIP, not PASS) # (default docs/evidence/<CLI-SOURCE-SHA>/manifest.json)
# SKIP_BROWSER=1 skip the Chromium suite (recorded as SKIP, not PASS)
# #
# The script never modifies or recompiles the frozen CLI; it records its # The script never modifies or recompiles the frozen CLI; it records its
# SHA-256 before and after and fails if it changes. # SHA-256 before and after and fails if it changes. A gate that cannot be
# judged from this environment is recorded as UNVERIFIED with a reason; it is
# never written as PASS.
set -euo pipefail set -euo pipefail
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
@@ -22,33 +27,196 @@ export MARQDO_BIN
"$repo_root/scripts/frozen-beta.sh" verify "$MARQDO_BIN" "$repo_root/scripts/frozen-beta.sh" verify "$MARQDO_BIN"
export MARQDO_FROZEN_BIN="$MARQDO_BIN" export MARQDO_FROZEN_BIN="$MARQDO_BIN"
metadata="$("$repo_root/scripts/frozen-beta.sh" metadata)"
cli_version="$(sed -n 's/^version=//p' <<<"$metadata")"
cli_source_sha="$(sed -n 's/^source_sha=//p' <<<"$metadata")"
cli_binary_sha="$(sed -n 's/^binary_sha=//p' <<<"$metadata")"
cli_archive_sha="$(sed -n 's/^archive_sha=//p' <<<"$metadata")"
work="$repo_root/dist/acceptance" work="$repo_root/dist/acceptance"
rm -rf "$work" rm -rf "$work"
mkdir -p "$work" mkdir -p "$work/logs"
statuses="" declare -A gate_state=() gate_cmd=() gate_exit=() gate_log=() gate_note=()
record() { statuses+="$1=$2"$'\n'; echo "[acceptance] $1: $2"; } gate_ids=(
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
)
run_step() { gate_run() {
local name="$1" local id="$1" label="$2" command="$3"
shift local log="$work/logs/$id.log" status
echo "==> $name" echo "==> [$id] $label"
if "$@"; then set +e
record "$name" PASS bash -c "$command" 2>&1 | tee "$log"
status=${PIPESTATUS[0]}
set -e
gate_cmd[$id]="$command"
gate_exit[$id]="$status"
gate_log[$id]="${log#"$repo_root"/}"
if [[ "$status" -eq 0 ]]; then
gate_state[$id]=PASS
gate_note[$id]=""
else else
record "$name" FAIL gate_state[$id]=FAIL
return 1 gate_note[$id]="command exited $status; see log"
fi fi
return 0
} }
core_before="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)" gate_unverified() {
cli_source_sha="$(cat "$(dirname "$MARQDO_BIN")/SOURCE_SHA")" local id="$1" command="$2" note="$3"
view_source_sha="$(git rev-parse HEAD 2>/dev/null || echo unknown)" echo "==> [$id] UNVERIFIED: $note"
gate_state[$id]=UNVERIFIED
gate_cmd[$id]="$command"
gate_exit[$id]=""
gate_log[$id]=""
gate_note[$id]="$note"
}
fail_now() {
local id="$1" note="$2"
echo "error: [$id] $note" >&2
gate_state[$id]=FAIL
gate_note[$id]="$note"
finish 1
}
finish() {
local requested="${1:-0}" state result unverified=()
for id in "${gate_ids[@]}"; do
if [[ -z "${gate_state[$id]:-}" ]]; then
gate_state[$id]=UNVERIFIED
gate_note[$id]="not reached because an earlier gate failed"
gate_log[$id]=""
gate_exit[$id]=""
fi
[[ "${gate_state[$id]}" == "UNVERIFIED" ]] && unverified+=("$id")
done
result=PASS
for id in "${gate_ids[@]}"; do
[[ "${gate_state[$id]}" == "FAIL" ]] && result=FAIL
done
if [[ "$result" != "FAIL" && ${#unverified[@]} -gt 0 ]]; then
result=PARTIAL
fi
local bundle_sha sums_sha test_count
bundle_sha="$(sha256sum "${bundle:-/nonexistent}/bin/marqdo-view" 2>/dev/null | cut -d' ' -f1 || true)"
sums_sha="$(sha256sum "${bundle:-/nonexistent}/SHA256SUMS" 2>/dev/null | cut -d' ' -f1 || true)"
[[ -n "$bundle_sha" ]] || bundle_sha="unavailable"
[[ -n "$sums_sha" ]] || sums_sha="unavailable"
test_count="${cargo_test_count:-0}"
browser_state="${browser_state:-UNVERIFIED}"
: >"$work/gates.tsv"
for id in "${gate_ids[@]}"; do
printf '%s\t%s\t%s\t%s\t%s\t%s\n' \
"$id" "${gate_state[$id]}" "${gate_exit[$id]:-}" "${gate_cmd[$id]:-}" \
"${gate_log[$id]:-}" "${gate_note[$id]:-}" >>"$work/gates.tsv"
done
: >"$work/unverified.txt"
for id in "${unverified[@]}"; do printf '%s\n' "$id" >>"$work/unverified.txt"; done
local evidence_path="${VIEW_EVIDENCE_OUT:-$repo_root/docs/evidence/$cli_source_sha/manifest.json}"
mkdir -p "$(dirname "$evidence_path")"
# Logs referenced by the manifest must live beside it, not in a git-ignored
# build directory.
local evidence_logs="$(dirname "$evidence_path")/logs"
rm -rf "$evidence_logs"
cp -R "$work/logs" "$evidence_logs" 2>/dev/null || true
mkdir -p "$evidence_logs"
python3 - "$work/gates.tsv" "$work/unverified.txt" "$evidence_path" \
"$work/manifest.json" "$cli_version" "$cli_source_sha" "$cli_binary_sha" \
"$cli_archive_sha" "$bundle_sha" "$sums_sha" "$result" "$test_count" \
"$browser_state" <<'PY_MANIFEST'
import datetime
import json
import pathlib
import subprocess
import sys
(gates_path, unverified_path, evidence_path, dist_path, cli_version,
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()
gates = {}
for line in pathlib.Path(gates_path).read_text().splitlines():
gate_id, state, exit_code, command, log, note = line.split("\t")
entry = {"state": state, "command": command, "exit_code": int(exit_code) if exit_code else None}
if log:
prefix = "dist/acceptance/logs/"
if log.startswith(prefix):
log = f"docs/evidence/{cli_source_sha}/logs/{log[len(prefix):]}"
entry["log"] = log
if note:
entry["note"] = note
gates[gate_id] = entry
unverified = [line for line in pathlib.Path(unverified_path).read_text().splitlines() if line]
try:
view_commit = subprocess.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True, check=True).stdout.strip()
except Exception:
view_commit = "unknown"
tool = json.loads((repo / "tool.json").read_text())
manifest = {
"schema": "marqdo.view.acceptance",
"schema_version": 1,
"product": {"name": "marqdo-view", "version": tool["version"], "target": "linux-x86_64-glibc2.39"},
"view_commit": view_commit,
"view_binary_sha256": "sha256:" + view_binary_sha,
"view_tool_bundle_digest": "sha256:" + bundle_sha,
"view_tool_bundle_digest_method": "sha256 of the canonical SHA256SUMS file bytes in the bundle",
"cli_version": cli_version,
"cli_source_sha": cli_source_sha,
"cli_archive_sha256": "sha256:" + cli_archive_sha,
"cli_binary_sha256": "sha256:" + cli_binary_sha,
"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",
"generated_utc": datetime.datetime.now(datetime.timezone.utc).isoformat(),
"result": result,
"gates": gates,
"unverified": unverified,
"extras": {
"cargo_tests_passed": int(test_count),
"browser": browser_state,
"notes": "Generated from real command exit statuses. UNVERIFIED gates are not release evidence and must never be read as PASS.",
},
}
text = json.dumps(manifest, indent=2, sort_keys=True) + "\n"
pathlib.Path(evidence_path).write_text(text)
pathlib.Path(dist_path).write_text(text)
print("evidence manifest:", evidence_path)
PY_MANIFEST
echo
echo "acceptance: $result"
if [[ ${#unverified[@]} -gt 0 ]]; then
echo "unverified: ${unverified[*]}"
fi
echo "evidence: $evidence_path"
echo "cli: marqdo $cli_version source=$cli_source_sha archive=sha256:$cli_archive_sha"
echo "gate states:"
for id in "${gate_ids[@]}"; do
printf ' %-20s %s\n' "$id" "${gate_state[$id]}"
done
if [[ "$result" == "FAIL" || "$requested" -ne 0 ]]; then
exit 1
fi
exit 0
}
export PATH="${HOME}/.cargo/bin:${PATH}" export PATH="${HOME}/.cargo/bin:${PATH}"
export CARGO_HOME="${CARGO_HOME:-$repo_root/.cargo-home}" export CARGO_HOME="${CARGO_HOME:-$repo_root/.cargo-home}"
# 0. code quality / unit / contract tests core_before="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)"
if [[ "$core_before" != "$cli_binary_sha" ]]; then
echo "error: frozen CLI sha256 $core_before does not match pinned $cli_binary_sha" >&2
exit 1
fi
# A wrong CLI must fail the frozen identity check before any command runs.
check_wrong_cli() { check_wrong_cli() {
mkdir -p "$work/wrong-cli" mkdir -p "$work/wrong-cli"
cp "$(dirname "$MARQDO_BIN")/SOURCE_SHA" "$work/wrong-cli/SOURCE_SHA" cp "$(dirname "$MARQDO_BIN")/SOURCE_SHA" "$work/wrong-cli/SOURCE_SHA"
@@ -63,43 +231,105 @@ FAKE
fi fi
test ! -e "$work/wrong-cli/executed" test ! -e "$work/wrong-cli/executed"
} }
run_step wrong_cli_refused check_wrong_cli if ! check_wrong_cli; then
run_step fmt cargo fmt --all -- --check echo "error: wrong-CLI refusal regression failed" >&2
run_step clippy cargo clippy --locked --all-targets -- -D warnings exit 1
run_step test cargo test --locked fi
run_step build cargo build --release --locked
# 1. controlled Tool bundle + frozen-CLI install smoke # ---------------------------------------------------------------- gates ----
run_step bundle env MARQDO_BIN="$MARQDO_BIN" ./scripts/package.sh 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 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"
cargo_test_count="$(grep -hE 'test result: ok\. [0-9]+ passed' "$work/logs/G02_build.log" | awk '{sum += $4} END {print sum + 0}')"
if [[ "${gate_state[G02_build]}" != "PASS" ]]; then
finish 1
fi
# G03: package, clean archive install and dispatch only through the frozen CLI.
echo "==> [G03_install] package + archive install + tool dispatch"
if ! env MARQDO_BIN="$MARQDO_BIN" ./scripts/package.sh >"$work/logs/G03_package.log" 2>&1; then
gate_state[G03_install]=FAIL
gate_cmd[G03_install]="./scripts/package.sh"
gate_exit[G03_install]=1
gate_log[G03_install]="${work#"$repo_root"/}/logs/G03_package.log"
finish 1
fi
bundle="$repo_root/dist/marqdo-view" bundle="$repo_root/dist/marqdo-view"
read -r version target < <(python3 -c 'import json; p=json.load(open("dist/marqdo-view/RELEASE_INFO.json")); print(p["tool_version"], p["target"])') read -r version target < <(python3 -c 'import json; p=json.load(open("dist/marqdo-view/RELEASE_INFO.json")); print(p["tool_version"], p["target"])')
archive="$repo_root/dist/marqdo-view-$version-$target.tar.gz" dist_archive="$repo_root/dist/marqdo-view-$version-$target.tar.gz"
archive_sha="$(sha256sum "$archive" | cut -d' ' -f1)" archive_sha="$(sha256sum "$dist_archive" | cut -d' ' -f1)"
# 2. clean install from the *archive*, in a moved temporary directory
mkdir -p "$work/extracted" mkdir -p "$work/extracted"
tar -xzf "$archive" -C "$work/extracted" tar -xzf "$dist_archive" -C "$work/extracted"
extracted_bundle="$work/extracted/marqdo-view" extracted_bundle="$work/extracted/marqdo-view"
(cd "$extracted_bundle" && sha256sum -c SHA256SUMS) (cd "$extracted_bundle" && sha256sum -c SHA256SUMS >>"$work/logs/G03_install.log" 2>&1)
tool_home="$work/tool-home" tool_home="$work/tool-home"
mkdir -p "$tool_home" mkdir -p "$tool_home"
export MARQDO_TOOL_HOME="$tool_home" export MARQDO_TOOL_HOME="$tool_home"
export VIEW_USE_INSTALLED_TOOL=1 export VIEW_USE_INSTALLED_TOOL=1
run_step archive_install "$MARQDO_BIN" tool install "$extracted_bundle/tool.json" install_ok=1
check_tool_list() { {
grep -q '^view ' <<<"$("$MARQDO_BIN" tool list)" echo "== bundle digest: sha256:$(sha256sum "$bundle/SHA256SUMS" | cut -d' ' -f1)"
} "$MARQDO_BIN" tool install "$extracted_bundle/tool.json"
check_view_help() { "$MARQDO_BIN" tool list
grep -q 'marqdo-view' <<<"$("$MARQDO_BIN" view --help)" "$MARQDO_BIN" view --help
} MARQDO_BIN="$MARQDO_BIN" ./scripts/install-smoke.sh "$bundle/tool.json"
run_step tool_list check_tool_list } >>"$work/logs/G03_install.log" 2>&1 || install_ok=0
run_step view_help check_view_help if [[ "$install_ok" -eq 1 ]]; then
run_step verify "$MARQDO_BIN" view verify examples/mixed-modes/index.mq.md printf 'x' >>"$tool_home/view/README.md" 2>/dev/null || true
run_step export "$MARQDO_BIN" view export examples/control-flow --out "$work/site" if "$MARQDO_BIN" view --version >"$work/logs/G03_tamper.log" 2>&1; then
run_step examples_check env MARQDO_BIN="$MARQDO_BIN" ./scripts/check-examples.sh install_ok=0
test -f "$work/site/manifest.json" echo "error: tampered installed tool was dispatched" >>"$work/logs/G03_tamper.log"
elif ! grep -q 'bundle hash mismatch' "$work/logs/G03_tamper.log"; then
install_ok=0
echo "error: tamper refusal did not report a bundle hash mismatch" >>"$work/logs/G03_tamper.log"
fi
"$MARQDO_BIN" tool remove view >>"$work/logs/G03_install.log" 2>&1 || install_ok=0
if "$MARQDO_BIN" view --version >>"$work/logs/G03_install.log" 2>&1; then
install_ok=0
echo "error: removed tool still dispatched" >>"$work/logs/G03_install.log"
fi
fi
if [[ "$install_ok" -eq 1 ]]; then
# Reinstall the clean bundle for the remaining gates (the removal test above
# intentionally deregistered the command).
if ! "$MARQDO_BIN" tool install "$extracted_bundle/tool.json" >>"$work/logs/G03_install.log" 2>&1; then
install_ok=0
echo "error: could not reinstall the clean Tool bundle" >>"$work/logs/G03_install.log"
fi
fi
if [[ "$install_ok" -eq 1 ]]; then
gate_state[G03_install]=PASS
else
gate_state[G03_install]=FAIL
fi
gate_cmd[G03_install]="scripts/package.sh && marqdo tool install/list/remove && marqdo view --help && scripts/install-smoke.sh && tamper refusal"
gate_exit[G03_install]=$(( install_ok == 1 ? 0 : 1 ))
gate_log[G03_install]="${work#"$repo_root"/}/logs/G03_install.log"
gate_note[G03_install]="$([[ "$install_ok" -eq 1 ]] && echo "" || echo "see G03_install.log")"
if [[ "$install_ok" -ne 1 ]]; then
finish 1
fi
# Tool dispatch starts View as a child. Keep both in one disposable group. gate_run G04_static "static contract: view verify + Analysis v3 examples" \
"\"$MARQDO_BIN\" view verify examples/mixed-modes/index.mq.md && MARQDO_BIN=\"$MARQDO_BIN\" ./scripts/check-examples.sh"
# G05: live browse + one explicit real run through the installed Tool and SSE.
echo "==> [G05_run] live browse + explicit real run"
run_ok=1
start_server() {
local project="$1" log="$2"
setsid "$MARQDO_BIN" view "$project" --port 0 --no-open >"$log" 2>&1 &
server_pid=$!
local url=""
for _ in $(seq 1 100); do
url="$(grep -o 'http://127.0.0.1:[0-9]*/' "$log" | head -1 || true)"
[[ -n "$url" ]] && break
sleep 0.1
done
printf '%s\n' "$url"
}
server_pid="" server_pid=""
stop_server() { stop_server() {
if [[ -n "$server_pid" ]]; then if [[ -n "$server_pid" ]]; then
@@ -109,133 +339,131 @@ stop_server() {
fi fi
} }
trap stop_server EXIT trap stop_server EXIT
browse_url="$(start_server examples/welcome "$work/browse.log")"
# 3. Live browse smoke (no execution on open)
browse_log="$work/browse.log"
setsid "$MARQDO_BIN" view examples/welcome --port 0 --no-open >"$browse_log" 2>&1 &
server_pid=$!
browse_url=""
for _ in $(seq 1 100); do
browse_url="$(grep -o 'http://127.0.0.1:[0-9]*/' "$browse_log" | head -1 || true)"
[[ -n "$browse_url" ]] && break
sleep 0.1
done
if [[ -n "$browse_url" ]] && curl -sf "${browse_url}api/documents" | grep -q '"schema": "marqdo.view-documents"'; then if [[ -n "$browse_url" ]] && curl -sf "${browse_url}api/documents" | grep -q '"schema": "marqdo.view-documents"'; then
record browse PASS echo "browse: PASS" >>"$work/logs/G05_run.log"
else else
record browse FAIL run_ok=0
cat "$browse_log" >&2 echo "browse: FAIL" >>"$work/logs/G05_run.log"
exit 1 cat "$work/browse.log" >>"$work/logs/G05_run.log" 2>&1 || true
fi fi
stop_server stop_server
run_url="$(start_server examples/control-flow "$work/run-server.log")"
# 4. Explicit real run through the installed tool + CSRF flow if [[ -n "$run_url" ]] && python3 "$repo_root/scripts/acceptance-run.py" "$run_url" >>"$work/logs/G05_run.log" 2>&1; then
run_log="$work/run.log" echo "explicit run: PASS" >>"$work/logs/G05_run.log"
setsid "$MARQDO_BIN" view examples/control-flow --port 0 --no-open >"$run_log" 2>&1 &
server_pid=$!
run_url=""
for _ in $(seq 1 100); do
run_url="$(grep -o 'http://127.0.0.1:[0-9]*/' "$run_log" | head -1 || true)"
[[ -n "$run_url" ]] && break
sleep 0.1
done
if [[ -n "$run_url" ]]; then
if python3 "$repo_root/scripts/acceptance-run.py" "$run_url"
then
record real_run PASS
else
record real_run FAIL
exit 1
fi
else else
record real_run FAIL run_ok=0
cat "$run_log" >&2 echo "explicit run: FAIL" >>"$work/logs/G05_run.log"
exit 1 cat "$work/run-server.log" >>"$work/logs/G05_run.log" 2>&1 || true
fi fi
stop_server stop_server
gate_cmd[G05_run]="installed marqdo view examples/welcome + scripts/acceptance-run.py over SSE"
gate_exit[G05_run]=$(( run_ok == 1 ? 0 : 1 ))
gate_log[G05_run]="${work#"$repo_root"/}/logs/G05_run.log"
if [[ "$run_ok" -eq 1 ]]; then
gate_state[G05_run]=PASS
gate_note[G05_run]=""
else
gate_state[G05_run]=FAIL
gate_note[G05_run]="browse or explicit run failed; see G05_run.log"
finish 1
fi
# 5. project-local verification suites gate_run G06_stream_snapshot "Observation v1 stream/snapshot equivalence + truncation" \
run_step export_suite env MARQDO_BIN="$MARQDO_BIN" ./scripts/test-export.sh "python3 scripts/check-observation.py stream-snapshot"
run_step no_exec_suite env MARQDO_BIN="$MARQDO_BIN" ./scripts/test-no-exec.sh
run_step security_suite ./scripts/test-security.sh gate_run G07_binding_stale "exact Analysis binding + stale-never-success mapping" \
"python3 scripts/check-observation.py binding && cargo test --lib execution::controller::tests::stale_and_incomplete_never_map_to_success && cargo test --test integration execution::source_edit_during_a_run_marks_the_result_stale_and_drops_anchor_ids && cargo test --test contract observation_contract::stale_and_wrong_root_bindings_are_observation_stale"
gate_note[G07_binding_stale]="CLI exact-byte binding probe + controller unit mapping + real run/source-change e2e + wrong-digest stale contract all PASS"
gate_run G08_negative "fail-closed matrix N01-N20: protocol + controller + security" \
"python3 scripts/check-observation.py fail-closed && cargo test --lib execution:: && cargo test --test contract observation_contract:: && cargo test --test contract core_contract:: && cargo test --test contract presentation_states:: && cargo test --test contract no_coupling:: && cargo test --test security"
gate_note[G08_negative]="N01-N11 decoder/contract negatives, N12-N13 controller hard rejection, N14-N15 CLI fail-closed probes, N16 G01 static check, N17 tool_v1 product-range unit test, N18-N20 security suite: all PASS"
gate_run G09_security "security baseline + zero-execution sentinel" \
"env MARQDO_BIN=\"$MARQDO_BIN\" ./scripts/test-no-exec.sh && ./scripts/test-security.sh"
browser_state=UNVERIFIED
if [[ "${SKIP_BROWSER:-0}" == "1" ]]; then if [[ "${SKIP_BROWSER:-0}" == "1" ]]; then
record browser SKIP echo "browser: SKIP (SKIP_BROWSER=1)" >>"$work/logs/browser.log"
else else
run_step browser env MARQDO_BIN="$MARQDO_BIN" ./scripts/test-browser.sh if env MARQDO_BIN="$MARQDO_BIN" ./scripts/test-browser.sh >"$work/logs/browser.log" 2>&1; then
browser_state=PASS
else
browser_state=FAIL
gate_state[G09_security]=FAIL
gate_note[G09_security]="browser suite failed; see browser.log"
fi
fi fi
check_tampered_install() { gate_run G10_export "static export zero-execution + single renderer contract" \
local output "env MARQDO_BIN=\"$MARQDO_BIN\" ./scripts/test-export.sh && cargo test --locked --test contract"
printf 'x' >> "$tool_home/view/README.md" || return 1
if output="$("$MARQDO_BIN" view --version 2>&1)"; then if [[ "${CI:-}" == "true" || "${CI:-}" == "woodpecker" || -n "${WOODPECKER:-}" || -n "${GITHUB_ACTIONS:-}" ]]; then
echo "error: tampered Tool installation was dispatched" >&2 gate_state[G11_evidence_ci]=PASS
return 1 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}")
else:
print(f"FAIL\tWoodpecker pipeline #{number} is {state} for {commit}")
raise SystemExit(0)
print(f"UNVERIFIED\tno Woodpecker pipeline 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 fi
grep -q 'bundle hash mismatch' <<<"$output" if [[ -z "${gate_state[G11_evidence_ci]:-}" ]]; then
} gate_unverified G11_evidence_ci "$ci_cmd" "$ci_note"
run_step tool_tamper_refused check_tampered_install fi
run_step tool_remove "$MARQDO_BIN" tool remove view fi
# Leave the isolated tool home clean.
"$MARQDO_BIN" tool remove view >>"$work/logs/G10_export.log" 2>&1 || true
# 6. frozen core must be byte-identical
core_after="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)" core_after="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)"
if [[ "$core_before" != "$core_after" ]]; then if [[ "$core_before" != "$core_after" ]]; then
record core_sha FAIL
echo "error: frozen core binary changed during acceptance" >&2 echo "error: frozen core binary changed during acceptance" >&2
exit 1 gate_state[G03_install]=FAIL
gate_note[G03_install]="frozen CLI SHA changed during acceptance"
finish 1
fi fi
record core_sha PASS
view_binary_sha="$(sha256sum "$bundle/bin/marqdo-view" | cut -d' ' -f1)" finish 0
evidence_path="${VIEW_EVIDENCE_OUT:-$work/manifest.json}"
mkdir -p "$(dirname "$evidence_path")"
python3 - "$evidence_path" "$statuses" "$view_source_sha" "$view_binary_sha" \
"$cli_source_sha" "$core_before" "$core_after" "$target" "$archive_sha" <<'PY_EVIDENCE'
import datetime
import json
import pathlib
import sys
(path, gates, view_source_sha, view_binary_sha, cli_source_sha,
core_before, core_after, target, archive_sha) = sys.argv[1:]
path = pathlib.Path(path)
statuses = dict(line.split("=", 1) for line in gates.splitlines())
manifest = {
"schema": "marqdo.view-conformance",
"schema_version": 1,
"view_source_sha": view_source_sha,
"view_binary_sha256": view_binary_sha,
"cli_source_sha": cli_source_sha,
"cli_binary_sha256_before": core_before,
"cli_binary_sha256_after": core_after,
"tool_protocol": 1,
"analysis_protocol": 2,
"trace_protocol": 2,
"target": target,
"archive_sha256": archive_sha,
"generated_at_utc": datetime.datetime.now(datetime.timezone.utc).isoformat(),
"tests": {
"contract": statuses.get("test", "FAIL"),
"examples": statuses.get("examples_check", "FAIL"),
"browser": statuses.get("browser", "SKIP"),
"export": statuses.get("export_suite", "FAIL"),
"no_exec": statuses.get("no_exec_suite", "FAIL"),
"security": statuses.get("security_suite", "FAIL"),
},
"gates": statuses,
"commands": {
"script": "scripts/acceptance.sh",
"notes": "Generated from real command exit statuses; install/verify/export/run use the frozen CLI archive copied to an isolated tool home.",
},
}
path.write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n")
print("evidence manifest:", path)
PY_EVIDENCE
echo
if [[ "${SKIP_BROWSER:-0}" == "1" ]]; then
echo "acceptance: PARTIAL (browser skipped)"
else
echo "acceptance: PASS"
fi
echo "evidence: $evidence_path"
echo "archive sha256: $archive_sha"
+89
View File
@@ -0,0 +1,89 @@
#!/usr/bin/env bash
# G12 (issue #5): current documentation must describe the rc.4 contracts as the
# only current capability. Historical CHANGELOG entries may name retired
# interfaces only under an explicit `## History` heading.
#
# Checked files:
# 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.4 contract baseline.
#
# Usage: scripts/check-docs.sh
set -euo pipefail
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$repo_root"
fail=0
hit() {
printf 'FAIL[%s] %s\n' "$1" "$2"
fail=1
}
legacy_pattern='Analysis v2|Trace v2|Execution Events|--trace-file|--event-stream|PROTOCOL_ANALYSIS|PROTOCOL_TRACE|TOOL_PROTOCOL|3\.0\.0-beta|>=3\.0\.0-rc\.2'
run_json_pattern='run[^.。\n]{0,20}--json|call[^.。\n]{0,20}--json|--json[^.。\n]{0,20}run|--json[^.。\n]{0,20}call'
# ------------------------------------------------------------- baseline ----
for file in README.md COMPATIBILITY.md docs/STATUS.md; do
[[ -f "$file" ]] || { hit "missing doc" "$file"; continue; }
grep -q '0\.3\.0' "$file" || hit "version drift" "$file: does not state View 0.3.0"
done
for file in README.md COMPATIBILITY.md docs/STATUS.md docs/ACCEPTANCE.md; do
[[ -f "$file" ]] || { hit "missing doc" "$file"; continue; }
while IFS=: read -r line text; do
[[ -n "$line" ]] && hit "legacy contract as current capability" "$file:$line: $text"
done < <(grep -nE "$legacy_pattern" "$file" || true)
while IFS=: read -r line text; do
[[ -n "$line" ]] && hit "retired run --json as current output" "$file:$line: $text"
done < <(grep -nE "$run_json_pattern" "$file" || true)
done
grep -qE 'Analysis[^A-Za-z0-9]+3' COMPATIBILITY.md || hit "contract drift" "COMPATIBILITY.md: no current Analysis 3 row"
grep -qE 'Observation[^A-Za-z0-9]+1' COMPATIBILITY.md || hit "contract drift" "COMPATIBILITY.md: no current Observation 1 row"
grep -qE 'api_revision[^A-Za-z0-9]+1|API revision[^A-Za-z0-9]+1' COMPATIBILITY.md \
|| hit "contract drift" "COMPATIBILITY.md: no current Tool api_revision 1 row"
grep -q '>=3.0.0-rc.3,<4.0.0' COMPATIBILITY.md || hit "product range drift" "COMPATIBILITY.md: expected >=3.0.0-rc.3,<4.0.0"
# ------------------------------------------------------------- CHANGELOG ---
if [[ ! -f CHANGELOG.md ]]; then
hit "missing doc" "CHANGELOG.md"
else
history_line="$(grep -nE '^##[[:space:]]+(History|历史)' CHANGELOG.md | head -1 | cut -d: -f1 || true)"
if [[ -z "$history_line" ]]; then
if grep -qE "$legacy_pattern" CHANGELOG.md; then
hit "CHANGELOG history" "CHANGELOG.md: retired interfaces appear without an explicit '## History' heading"
fi
else
# Only the current (pre-history) part may be scanned for legacy claims.
while IFS=: read -r line text; do
[[ -n "$line" ]] && hit "legacy contract as current CHANGELOG entry" "CHANGELOG.md:$line: $text"
done < <(head -n "$((history_line - 1))" CHANGELOG.md | grep -nE "$legacy_pattern" || true)
while IFS=: read -r line text; do
[[ -n "$line" ]] && hit "retired run --json in current CHANGELOG entry" "CHANGELOG.md:$line: $text"
done < <(head -n "$((history_line - 1))" CHANGELOG.md | grep -nE "$run_json_pattern" || true)
if ! head -n "$((history_line - 1))" CHANGELOG.md | grep -q '0\.3\.0'; then
hit "CHANGELOG current entry" "CHANGELOG.md: no 0.3.0 entry before '## History'"
fi
fi
fi
# --------------------------------------------------------------- report ----
if [[ "$fail" -ne 0 ]]; then
cat >&2 <<'EOF'
check-docs: FAIL
Update the current docs to the rc.4 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.4.
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.4 baseline; CHANGELOG history is explicit)"
+63 -41
View File
@@ -1,7 +1,8 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# RFC-VIEW-0002 §13.3/§13.4: prove the five 3.0 example documents against the # Prove the five 3.0 example documents against the frozen released CLI using
# frozen released CLI. Never rebuilds the Core; runs in a copied temp project so # the current public contracts: one `check --emit` Analysis v3 source and one
# the repository examples are never modified. # Observation v1 sequence per `run`/`call`. Never rebuilds the Core; runs in a
# copied temp project so the repository examples are never modified.
# #
# Usage: MARQDO_BIN=/abs/path/marqdo scripts/check-examples.sh # Usage: MARQDO_BIN=/abs/path/marqdo scripts/check-examples.sh
set -euo pipefail set -euo pipefail
@@ -10,7 +11,8 @@ repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$repo_root" cd "$repo_root"
: "${MARQDO_BIN:?set MARQDO_BIN to the frozen marqdo binary}" : "${MARQDO_BIN:?set MARQDO_BIN to the frozen marqdo binary}"
core_sha_before="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)" core="${MARQDO_BIN}"
core_sha_before="$(sha256sum "$core" | cut -d' ' -f1)"
work="$repo_root/dist/examples-check" work="$repo_root/dist/examples-check"
rm -rf "$work" rm -rf "$work"
@@ -21,71 +23,91 @@ cp examples/view.json "$work/"
cd "$work" cd "$work"
echo "==> check all five example documents (no execution)" 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 for file in welcome.mq.md branch-loop.mq.md function-params.mq.md knowledge-only.mq.md unsafe-side-effect.mq.md; do
if ! "$MARQDO_BIN" check "$file" --emit "analysis-$file.json" --json > "check-$file.json"; then if ! "$core" check "$file" --emit "analysis-$file.json" --json > "check-$file.json"; then
echo "error: frozen CLI refused $file" >&2 echo "error: frozen CLI refused $file" >&2
cat "check-$file.json" >&2 cat "check-$file.json" >&2
exit 1 exit 1
fi fi
test -s "analysis-$file.json" test -s "analysis-$file.json"
done done
python3 - <<'PY'
echo "==> call function-params.double(n=5) -> 10" import json
call_json="$("$MARQDO_BIN" call function-params.mq.md double --arg n=5 --mode pure --json --trace-file call.trace.json)" for name in ("welcome", "branch-loop", "function-params", "knowledge-only", "unsafe-side-effect"):
python3 - "$call_json" <<'PY' artifact = json.load(open(f"analysis-{name}.mq.md.json"))
import json, sys assert artifact["schema"] == "marqdo.analysis", artifact["schema"]
data = json.loads(sys.argv[1]) assert artifact["schema_version"] == 3, artifact["schema_version"]
assert data["success"] is True, data assert artifact["modules"] and artifact["modules"][0]["source"], name
assert data["value"] == {"type": "int", "decimal": "10"}, data["value"] assert artifact["modules"][0]["document"], name
print("call double(5): PASS (Int 10)") assert artifact["project"]["entry_module_id"], name
print("Analysis v3: PASS (schema_version 3, exact source/document/entry present)")
PY PY
echo "==> run branch-loop main -> Int 0 with loop/return trace" echo "==> call function-params.double(n=5) -> 10 via Observation v1"
run_json="$("$MARQDO_BIN" run branch-loop.mq.md --mode pure --json --trace-file run.trace.json)" "$core" call function-params.mq.md double --arg n=5 --mode pure --output json > call.json
python3 - "$run_json" "run.trace.json" <<'PY' python3 - <<'PY'
import json, sys import json
data = json.loads(sys.argv[1]) snapshot = json.load(open("call.json"))
assert data["success"] is True, data assert snapshot["schema"] == "marqdo.observation" and snapshot["schema_version"] == 1
assert data["value"] == {"type": "int", "decimal": "0"}, data["value"] assert snapshot["run"]["status"] == "ok", snapshot["run"]
trace = json.load(open(sys.argv[2])) terminal = snapshot["events"][-1]
kinds = {event["kind"] for event in trace["events"]} assert terminal["kind"] == "run.completed", terminal
assert terminal["payload"]["value"] == {"type": "int", "decimal": "10"}, terminal["payload"]
print("call double(5): PASS (Observation v1, Int 10)")
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'
import json
snapshot = json.load(open("run.json"))
assert snapshot["run"]["status"] == "ok", snapshot["run"]
terminal = snapshot["events"][-1]
assert terminal["kind"] == "run.completed", terminal
assert terminal["payload"]["value"] == {"type": "int", "decimal": "0"}, terminal["payload"]
kinds = [event["kind"] for event in snapshot["events"]]
assert "loop.iteration" in kinds and "return" in kinds, kinds assert "loop.iteration" in kinds and "return" in kinds, kinds
print("run branch-loop: PASS (value 0, events: %s)" % ",".join(sorted(kinds))) seqs = [event["seq"] for event in snapshot["events"]]
assert seqs == list(range(len(seqs))), seqs
assert len({event["run_id"] for event in snapshot["events"]}) == 1
print("run branch-loop: PASS (Int 0, contiguous seq, kinds: %s)" % ",".join(kinds))
PY PY
echo "==> knowledge-only has no main (truthful failure, no fallback)" echo "==> knowledge-only has no main (truthful rejection, no fallback)"
set +e set +e
"$MARQDO_BIN" run knowledge-only.mq.md --mode pure --json > knowledge.json 2>&1 "$core" run knowledge-only.mq.md --mode pure --output json > knowledge.json 2>/dev/null
status=$? status=$?
set -e set -e
test "$status" -ne 0 test "$status" -ne 0
python3 - knowledge.json <<'PY' python3 - <<'PY'
import json, sys import json
data = json.load(open(sys.argv[1])) snapshot = json.load(open("knowledge.json"))
assert data["success"] is False, data terminal = snapshot["events"][-1]
assert data["code"] == "sem.no_entry_function", data assert terminal["kind"] == "run.rejected", terminal
assert terminal["payload"]["error"]["code"] == "sem.no_entry_function", terminal["payload"]
print("knowledge-only: PASS (explicit sem.no_entry_function)") print("knowledge-only: PASS (explicit sem.no_entry_function)")
PY PY
echo "==> unsafe-side-effect writes nothing in pure mode" echo "==> unsafe-side-effect writes nothing in pure mode"
set +e set +e
"$MARQDO_BIN" run unsafe-side-effect.mq.md --mode pure --json > unsafe-pure.json 2>&1 "$core" run unsafe-side-effect.mq.md --mode pure --output json > unsafe-pure.json 2>/dev/null
status=$? status=$?
set -e set -e
test "$status" -ne 0 test "$status" -ne 0
test ! -e out/view-sentinel.txt test ! -e out/view-sentinel.txt
python3 - unsafe-pure.json <<'PY' python3 - <<'PY'
import json, sys import json
data = json.load(open(sys.argv[1])) snapshot = json.load(open("unsafe-pure.json"))
assert data["success"] is False, data terminal = snapshot["events"][-1]
assert data["error"]["code"] == "permission.denied", data["error"] assert terminal["kind"] == "run.failed", terminal
assert terminal["payload"]["error"]["code"] == "permission.denied", terminal["payload"]
print("unsafe-side-effect pure: PASS (permission.denied, no file)") print("unsafe-side-effect pure: PASS (permission.denied, no file)")
PY PY
echo "==> unsafe-side-effect writes only with explicit project grants" echo "==> unsafe-side-effect writes only with explicit project grants"
"$MARQDO_BIN" run unsafe-side-effect.mq.md --mode project \ "$core" run unsafe-side-effect.mq.md --mode project \
--allow-write out --allow-write 'out/**' --json --trace-file unsafe.trace.json >/dev/null --allow-write out --allow-write 'out/**' --output json >/dev/null
test -f out/view-sentinel.txt test -f out/view-sentinel.txt
python3 - <<'PY' python3 - <<'PY'
content = open("out/view-sentinel.txt", "rb").read() content = open("out/view-sentinel.txt", "rb").read()
@@ -94,6 +116,6 @@ print("unsafe-side-effect project+grants: PASS (sentinel written explicitly)")
PY PY
rm -rf out rm -rf out
core_sha_after="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)" core_sha_after="$(sha256sum "$core" | cut -d' ' -f1)"
test "$core_sha_before" = "$core_sha_after" test "$core_sha_before" = "$core_sha_after"
echo "examples: PASS (frozen CLI sha256 $core_sha_before unchanged)" echo "examples: PASS (frozen CLI sha256 $core_sha_before unchanged)"
+169
View File
@@ -0,0 +1,169 @@
#!/usr/bin/env bash
# G01 (issue #5 §4): fail if the current tree still contains retired public
# contracts, retired run/call argv, legacy Tool negotiation or dual-state
# compatibility shims.
#
# Scope:
# * src/ one decoder, one validator, no version branch;
# * tool.json CLI Tool revision 1 only (no `compatibility`);
# * current contract docs README/COMPATIBILITY/STATUS/ACCEPTANCE/
# CONFORMANCE/architecture/current audit/ADR-0012.
#
# Historical records are exempt by design and are never rewritten:
# docs/evidence/** (except README), docs/decisions/0001..0011,
# docs/architecture/RFC-VIEW-0001*, RFC-VIEW-0002.md, docs/audits/legacy-*,
# docs/audits/protocol-conformance.md, CHANGELOG.md (history is validated by
# scripts/check-docs.sh instead).
#
# Usage: scripts/check-no-legacy.sh
# Exit: 0 = 0 hits; 1 = at least one retired reference (actionable output).
set -euo pipefail
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$repo_root"
fail=0
hit() {
printf 'FAIL[%s] %s\n' "$1" "$2"
fail=1
}
# ---------------------------------------------------------------- src/ ------
src_files() {
find src -type f \( -name '*.rs' -o -name '*.js' -o -name '*.css' \) -print0
}
# Negative unit tests may name a retired flag to assert it is never emitted.
# Everything from the conventional `#[cfg(test)]` attribute to EOF is test code
# and is not a production compatibility path, so scans skip it.
scan_src_pattern() {
local label="$1" pattern="$2" file line text
while IFS= read -r -d '' file; do
while IFS=: read -r line text; do
[[ -n "$line" ]] && hit "$label" "$file:$line: $text"
done < <(awk -v pat="$pattern" -v file="$file" '
/^[[:space:]]*#\[cfg\(test\)\]/ { intests = 1 }
intests { next }
$0 ~ pat { print FNR ":" $0 }
' "$file" || true)
done < <(src_files)
}
scan_src_pattern "legacy protocol module/name" 'analysis_v2|trace_v2|Trace v2|Execution Events'
scan_src_pattern "retired run/call flag" '--trace-file|--event-stream|trace_max|trace_path|trace_bytes'
scan_src_pattern "legacy Tool negotiation/migration" 'compatibility|record_version:[[:space:]]*1|PROTOCOL_ANALYSIS|PROTOCOL_TRACE|TOOL_PROTOCOL'
scan_src_pattern "dual-state/legacy branch" 'Option<Legacy|enum Either|legacy_mode|map_v1'
# Version branches belong to protocol modules only; the reader never sees them.
while IFS= read -r -d '' file; do
while IFS=: read -r line text; do
[[ -n "$line" ]] && hit "reader branches on schema_version" "$file:$line: $text"
done < <(awk '
/^[[:space:]]*#\[cfg\(test\)\]/ { intests = 1 }
intests { next }
/schema_version/ { print FNR ":" $0 }
' "$file" || true)
done < <(find src/reader -type f -name '*.rs' -print0 2>/dev/null || true)
# `fallback` is legitimate only as a comment phrase ("never decoded through a
# fallback") or for the unrelated OS-random fallback helper. Flag real code.
while IFS= read -r -d '' file; do
while IFS=: read -r line text; do
[[ -z "$line" ]] && continue
code="${text%%//*}"
[[ "$code" == *fallback* ]] || continue
case "$code" in
*fallback_counter*) ;;
*) hit "protocol fallback branch" "$file:$line: $text" ;;
esac
done < <(awk '
/^[[:space:]]*#\[cfg\(test\)\]/ { intests = 1 }
intests { next }
/fallback/ { print FNR ":" $0 }
' "$file" || true)
done < <(src_files)
# Retired `run`/`call --json` argv: the only accepted `--json` is the `check`
# diagnostic summary. Heuristic: find the enclosing Rust function; argv
# builders for check-like commands are the only permitted owners.
while IFS= read -r -d '' file; do
while IFS=: read -r line_no text; do
[[ -z "$line_no" ]] && continue
case "$text" in
//*|///*) continue ;;
esac
fn="$(awk -v target="$line_no" '
/^[[:space:]]*(pub[[:space:]]+)?(async[[:space:]]+)?fn[[:space:]]+[A-Za-z0-9_]+/ {
s=$0; sub(/^[[:space:]]*(pub[[:space:]]+)?(async[[:space:]]+)?fn[[:space:]]+/, "", s); sub(/[^A-Za-z0-9_].*/, "", s); current=s
}
NR==target { print current; exit }
' "$file")"
case "$fn" in
*check*|*diagnostic*|*analysis*) ;;
*) hit "retired run/call --json argv" "$file:$line_no: $text (enclosing fn: ${fn:-<top-level>})" ;;
esac
done < <(awk '
/^[[:space:]]*#\[cfg\(test\)\]/ { intests = 1 }
intests { next }
/--json/ { print FNR ":" $0 }
' "$file" || true)
done < <(src_files)
# ------------------------------------------------------------- tool.json ----
if grep -qE '"compatibility"' tool.json; then
while IFS=: read -r line text; do
hit "tool.json compatibility field" "tool.json:$line: $text"
done < <(grep -nE '"compatibility"' tool.json)
fi
if grep -qE 'record_version|PROTOCOL_ANALYSIS|PROTOCOL_TRACE|TOOL_PROTOCOL' tool.json; then
while IFS=: read -r line text; do
hit "legacy tool metadata" "tool.json:$line: $text"
done < <(grep -nE 'record_version|PROTOCOL_ANALYSIS|PROTOCOL_TRACE|TOOL_PROTOCOL' tool.json)
fi
# -------------------------------------------------------- current docs ------
current_docs=(
README.md
COMPATIBILITY.md
docs/STATUS.md
docs/ACCEPTANCE.md
docs/CONFORMANCE.md
docs/audits/protocol-contract-0002.md
docs/architecture/observation-v1-and-analysis-v3.md
docs/decisions/0012-rc4-current-contracts.md
docs/design/complete-reader.md
docs/design/state-matrix.md
docs/design/visual-tokens.md
docs/evidence/README.md
)
doc_pattern='Analysis v2|Trace v2|Execution Events|--trace-file|--event-stream|PROTOCOL_ANALYSIS|PROTOCOL_TRACE|TOOL_PROTOCOL|3\.0\.0-beta|>=3\.0\.0-rc\.2'
run_json_pattern='run[^.。\n]{0,20}--json|call[^.。\n]{0,20}--json|--json[^.。\n]{0,20}run|--json[^.。\n]{0,20}call'
for doc in "${current_docs[@]}"; do
if [[ ! -f "$doc" ]]; then
hit "missing current doc" "$doc"
continue
fi
while IFS=: read -r line text; do
[[ -n "$line" ]] && hit "legacy contract in current doc" "$doc:$line: $text"
done < <(grep -nE "$doc_pattern" "$doc" || true)
while IFS=: read -r line text; do
[[ -n "$line" ]] && hit "retired run --json in current doc" "$doc:$line: $text"
done < <(grep -nE "$run_json_pattern" "$doc" || true)
done
if [[ "$fail" -ne 0 ]]; then
cat >&2 <<'EOF'
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
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),
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)"
+261
View File
@@ -0,0 +1,261 @@
#!/usr/bin/env python3
"""Machine checks for the current observation/analysis contracts (G06/G07/G08).
These probes use only the frozen CLI's public interface and assert the exact
contract marqdo-view 0.3.0 consumes. They do not run the View binary; View-side
regressions are covered by the cargo test suite owned by the migration.
Usage:
MARQDO_BIN=/abs/path/marqdo python3 scripts/check-observation.py stream-snapshot
MARQDO_BIN=/abs/path/marqdo python3 scripts/check-observation.py binding
MARQDO_BIN=/abs/path/marqdo python3 scripts/check-observation.py fail-closed
"""
import hashlib
import json
import os
import pathlib
import shutil
import subprocess
import sys
import tempfile
ROOT = pathlib.Path(__file__).resolve().parents[1]
BIN = pathlib.Path(os.environ.get("MARQDO_BIN", "")).resolve()
def fail(message):
print(f"observation probe: FAIL: {message}", file=sys.stderr)
sys.exit(1)
def run(args, cwd, expect=0):
result = subprocess.run([str(BIN), *args], cwd=cwd, capture_output=True, text=True)
if result.returncode != expect:
fail(f"{' '.join(args)} exited {result.returncode}, expected {expect}\n{result.stderr}")
return result
def sha256_prefixed(data):
return "sha256:" + hashlib.sha256(data).hexdigest()
def workspace():
dist = ROOT / "dist"
dist.mkdir(exist_ok=True)
directory = tempfile.TemporaryDirectory(prefix="observation-contract-", dir=dist)
root = pathlib.Path(directory.name)
for source in (
"examples/function-params.mq.md",
"examples/branch-loop.mq.md",
"examples/knowledge-only.mq.md",
):
shutil.copy(ROOT / source, root / pathlib.Path(source).name)
return directory, root
def load_snapshot(path):
snapshot = json.loads(pathlib.Path(path).read_text())
if snapshot.get("schema") != "marqdo.observation" or snapshot.get("schema_version") != 1:
fail(f"not an Observation v1 snapshot: {path}")
events = snapshot["events"]
run_id = snapshot["run"]["id"]
if [event["seq"] for event in events] != list(range(len(events))):
fail("snapshot seq is not zero-based contiguous")
if any(event["run_id"] != run_id for event in events):
fail("snapshot mixes run_id values")
return snapshot, events
def stream_snapshot():
directory, root = workspace()
with directory:
stream = run(
["call", "function-params.mq.md", "double", "--arg", "n=5", "--mode", "pure",
"--output", "jsonl", "--observation-file", "obs.json"],
root,
).stdout
lines = [json.loads(line) for line in stream.splitlines() if line.strip()]
snapshot, events = load_snapshot(root / "obs.json")
if lines != events:
fail("JSONL stream and atomic snapshot disagree for the same execution")
if snapshot["run"]["status"] != "ok":
fail(f"unexpected run.status {snapshot['run']['status']}")
if events[-1]["kind"] != "run.completed":
fail("terminal event is not run.completed")
if events[-1]["payload"]["value"] != {"type": "int", "decimal": "10"}:
fail("call result is not Int 10")
print("stream/snapshot equivalence: PASS (%d events, one run_id, contiguous seq, one terminal)" % len(events))
truncated_out = run(
["run", "branch-loop.mq.md", "--mode", "pure", "--observe-max-events", "2",
"--output", "jsonl", "--observation-file", "truncated.json"],
root,
).stdout
truncated_lines = [json.loads(line) for line in truncated_out.splitlines() if line.strip()]
truncated_snapshot, truncated_events = load_snapshot(root / "truncated.json")
if truncated_lines != truncated_events:
fail("truncated stream and snapshot disagree")
truncated = truncated_snapshot["capture"]["truncated"]
if not truncated or truncated.get("reason") != "event_budget":
fail("missing observation.truncated capture metadata")
if truncated_events[-1]["kind"] != "run.completed":
fail("truncated run has no truthful terminal")
print("observation truncation: PASS (capture.truncated=%s, terminal=%s)"
% (truncated.get("reason"), truncated_events[-1]["kind"]))
def span_ok(span, length):
return (
isinstance(span, dict)
and isinstance(span.get("start"), int)
and isinstance(span.get("end"), int)
and 0 <= span["start"] <= span["end"] <= length
)
def binding():
directory, root = workspace()
with directory:
run(["check", "function-params.mq.md", "--emit", "analysis.json", "--json"], root)
analysis_bytes = (root / "analysis.json").read_bytes()
analysis = json.loads(analysis_bytes)
if analysis.get("schema") != "marqdo.analysis" or analysis.get("schema_version") != 3:
fail("check --emit did not produce Analysis revision 3")
expected_digest = sha256_prefixed(analysis_bytes)
module = analysis["modules"][0]
source = module["source"].encode("utf-8")
if module["source_digest"] != hashlib.sha256(source).hexdigest():
fail("module.source_digest does not hash the exact module.source bytes")
run(
["call", "function-params.mq.md", "double", "--arg", "n=5", "--mode", "pure",
"--output", "jsonl", "--observation-file", "obs.json"],
root,
)
snapshot, events = load_snapshot(root / "obs.json")
started = next((event for event in events if event["kind"] == "run.started"), None)
if started is None:
fail("no run.started event")
observed = started["payload"]["source"]
if observed.get("analysis_digest") != expected_digest:
fail("run.started analysis_digest does not bind the exact check --emit bytes")
if observed.get("root_id") != analysis["project"]["root_id"]:
fail("run.started root_id does not match Analysis project.root_id")
if snapshot["run"]["source"] != observed:
fail("snapshot run.source disagrees with run.started source")
module_ids = {candidate["id"] for candidate in analysis["modules"]}
for event in events:
payload = event["payload"]
if payload.get("module_id") is not None and payload["module_id"] not in module_ids:
fail(f"event {event['seq']} references unknown module_id")
span = payload.get("span")
if span is not None and not span_ok(span, len(source)):
fail(f"event {event['seq']} span is outside the exact source bytes")
# A source edit must invalidate the binding: a new check emits a different digest.
original = (root / "function-params.mq.md").read_bytes()
(root / "function-params.mq.md").write_bytes(original + b"\nsource changed\n")
result = subprocess.run(
[str(BIN), "check", "function-params.mq.md", "--emit", "analysis-edited.json", "--json"],
cwd=root, capture_output=True, text=True,
)
(root / "function-params.mq.md").write_bytes(original)
if result.returncode == 0:
edited = (root / "analysis-edited.json").read_bytes()
if sha256_prefixed(edited) == expected_digest:
fail("source edit did not change the Analysis digest")
print("exact Analysis binding: PASS (digest=%s, root/module/span checks, source edit invalidates)" % expected_digest)
def fail_closed():
directory, root = workspace()
with directory:
cases = [
(["run", "branch-loop.mq.md", "--mode", "pure", "--json"], "retired --json"),
(["run", "branch-loop.mq.md", "--mode", "pure", "--trace-file", "x.json"], "retired --trace-file"),
(["run", "branch-loop.mq.md", "--mode", "pure", "--event-stream", "jsonl"], "retired --event-stream"),
]
for args, label in cases:
result = subprocess.run([str(BIN), *args], cwd=root, capture_output=True, text=True)
if result.returncode != 2:
fail(f"{label}: expected exit 2, got {result.returncode}")
print(f"fail-closed {label}: PASS (exit 2, no fallback retry)")
strict = subprocess.run(
[str(BIN), "run", "branch-loop.mq.md", "--mode", "strict", "--output", "jsonl"],
cwd=root, capture_output=True, text=True,
)
if strict.returncode != 2 or "strict.unsupported_grant" not in strict.stderr:
fail(f"strict + jsonl: expected exit 2 strict.unsupported_grant, got {strict.returncode}: {strict.stderr}")
print("fail-closed strict live destination: PASS (exit 2, strict.unsupported_grant)")
# Retired manifest fixture: used only to prove the current CLI rejects it.
old = root / "old-tool"
(old / "bin").mkdir(parents=True)
(old / "bin" / "probe").write_text("#!/usr/bin/env bash\nexit 0\n")
os.chmod(old / "bin" / "probe", 0o755)
(old / "tool.json").write_text(json.dumps({
"schema": "marqdo.cli-tool",
"schema_version": 1,
"name": "old-probe",
"version": "0.2.0",
"command": "old-probe",
"entrypoint": "bin/probe",
"compatibility": {"schema": "retired-fixture", "versions": ["fixture-only"]},
}))
env = {**os.environ, "MARQDO_TOOL_HOME": str(root / "tool-home")}
legacy = subprocess.run(
[str(BIN), "tool", "install", str(old / "tool.json")],
cwd=root, capture_output=True, text=True, env=env,
)
if legacy.returncode == 0 or "compatibility" not in legacy.stderr:
fail(f"retired tool.json was not rejected: {legacy.returncode} {legacy.stderr}")
print("fail-closed retired tool.json: PASS (unknown field `compatibility`, no migrator)")
# Retired install record (record_version 1): dispatching the tool must
# fail with a remove+reinstall instruction; there is no migrator.
record_home = root / "record-home"
record_dir = record_home / "view"
record_dir.mkdir(parents=True)
(record_dir / "record.json").write_text(json.dumps({
"record_version": 1,
"command": "view",
"name": "marqdo-view",
"version": "0.2.0",
"entrypoint": "bin/marqdo-view",
"bundle": [],
"bundle_sha256": "0" * 64,
"source": "retired-fixture",
"schema_version": 1,
"requires": {"api_revision": 1},
}))
retired_env = {
**os.environ,
"MARQDO_TOOL_HOME": str(record_home),
"MARQDO_BIN": str(BIN),
}
retired = subprocess.run(
[str(BIN), "view", "--version"],
cwd=root, capture_output=True, text=True, env=retired_env,
)
message = retired.stderr + retired.stdout
if retired.returncode == 0 or "reinstall" not in message:
fail(f"retired record_version 1 was not rejected: {retired.returncode} {message}")
print("fail-closed retired record_version 1: PASS (dispatch refused, remove+reinstall hint)")
def main():
if not BIN.is_file() or not os.access(BIN, os.X_OK):
fail("set MARQDO_BIN to the unpacked frozen marqdo binary")
if len(sys.argv) != 2:
fail(__doc__)
mode = sys.argv[1]
if mode == "stream-snapshot":
stream_snapshot()
elif mode == "binding":
binding()
elif mode == "fail-closed":
fail_closed()
else:
fail(f"unknown mode {mode}")
if __name__ == "__main__":
main()
+23 -6
View File
@@ -1,11 +1,16 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Identity of the released CLI used by the RFC-VIEW-0002 acceptance gate. # 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.4 (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 set -euo pipefail
version=3.0.0-beta.1 version=3.0.0-rc.4
source_sha=2c7c4f31e7a388d3fcfa717a77067e696ed13854 source_sha=452e9a32bd9e40dba427d4180691c58bab74449e
binary_sha=062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f binary_sha=a7306962689c635445a59043971ea2eb09298e01feeee81f0ba07b1f3e10306e
archive_sha=507e4cd358f75f517433935ce90d5fc2eb5cecda4f19121a68b136c83b15f317 archive_sha=9c3f166b5e5b8840d39d10019074e4e1c42432fc23e26c69670e64fdcf4e15d8
artifact="marqdo-$version-x86_64-unknown-linux-gnu" artifact="marqdo-$version-x86_64-unknown-linux-gnu"
root="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" root="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
@@ -24,8 +29,20 @@ verify() {
fi fi
} }
if [[ "${1:-}" == "metadata" && $# -eq 1 ]]; then
case "$1" in
metadata)
printf 'version=%s\n' "$version"
printf 'source_sha=%s\n' "$source_sha"
printf 'binary_sha=%s\n' "$binary_sha"
printf 'archive_sha=%s\n' "$archive_sha"
printf 'artifact=%s\n' "$artifact"
exit 0
;;
esac
fi
if [[ $# != 2 ]]; then if [[ $# != 2 ]]; then
echo "usage: $0 fetch EMPTY_DIRECTORY | $0 verify /absolute/path/to/marqdo" >&2 echo "usage: $0 fetch EMPTY_DIRECTORY | $0 verify /absolute/path/to/marqdo | $0 metadata" >&2
exit 2 exit 2
fi fi
case "$1" in case "$1" in
+22 -9
View File
@@ -1,5 +1,10 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Regenerate committed Analysis v2 goldens from the frozen CLI release binary. # Regenerate committed Analysis v3 / Observation v1 goldens from the frozen CLI
# release binary.
#
# The current public contracts have exactly one static source (`check --emit`
# Analysis v3) and one runtime sequence (Observation v1, either `--output jsonl`
# or the atomic `--observation-file` snapshot of the same execution).
# #
# Usage: MARQDO_BIN=/abs/path/marqdo scripts/gen-golden.sh # Usage: MARQDO_BIN=/abs/path/marqdo scripts/gen-golden.sh
set -euo pipefail set -euo pipefail
@@ -14,21 +19,29 @@ if [[ ! -x "$MARQDO_BIN" ]]; then
fi fi
echo "golden core sha256: $(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)" echo "golden core sha256: $(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)"
out="tests/golden/analysis-v2" out="tests/golden/analysis-v3"
mkdir -p "$out" mkdir -p "$out"
"$MARQDO_BIN" check examples/mixed-modes/index.mq.md --emit "$out/mixed-modes.json" "$MARQDO_BIN" check examples/mixed-modes/index.mq.md --emit "$out/mixed-modes.json"
"$MARQDO_BIN" check examples/control-flow/index.mq.md --emit "$out/control-flow.json" "$MARQDO_BIN" check examples/control-flow/index.mq.md --emit "$out/control-flow.json"
"$MARQDO_BIN" check examples/tables-math/index.mq.md --emit "$out/tables-math.json" "$MARQDO_BIN" check examples/tables-math/index.mq.md --emit "$out/tables-math.json"
"$MARQDO_BIN" check examples/welcome/00-welcome.mq.md --emit "$out/welcome.json" "$MARQDO_BIN" check examples/welcome/00-welcome.mq.md --emit "$out/welcome.json"
# Trace v2 goldens come from the same frozen binary (pure mode, no grants). "$MARQDO_BIN" check examples/unicode-spans/index.mq.md --emit "$out/unicode-spans.json"
out_trace="tests/golden/trace-v2" "$MARQDO_BIN" check examples/unicode-spans/crlf.mq.md --emit "$out/unicode-spans-crlf.json"
mkdir -p "$out_trace"
# Observation v1 goldens come from the same frozen binary (pure mode, no grants).
out_obs="tests/golden/observation-v1"
mkdir -p "$out_obs"
( cd examples/control-flow \ ( cd examples/control-flow \
&& "$MARQDO_BIN" run index.mq.md --mode pure --json --trace-file "$repo_root/$out_trace/control-flow.trace.json" > "$repo_root/$out_trace/control-flow.run.json" ) && "$MARQDO_BIN" run index.mq.md --mode pure --output jsonl --observation-file "$repo_root/$out_obs/control-flow.snapshot.json" \
> "$repo_root/$out_obs/control-flow.jsonl" )
( cd examples/control-flow \ ( cd examples/control-flow \
&& "$MARQDO_BIN" run index.mq.md --mode pure --json --trace-max-events 5 --trace-file "$repo_root/$out_trace/control-flow.truncated.trace.json" > "$repo_root/$out_trace/control-flow.truncated.run.json" ) && "$MARQDO_BIN" run index.mq.md --mode pure --observe-max-events 5 \
--output jsonl --observation-file "$repo_root/$out_obs/control-flow.truncated.snapshot.json" \
> "$repo_root/$out_obs/control-flow.truncated.jsonl" )
if ( cd examples/mixed-modes \ if ( cd examples/mixed-modes \
&& "$MARQDO_BIN" run index.mq.md --mode pure --json --trace-file "$repo_root/$out_trace/mixed-modes.arity.trace.json" > "$repo_root/$out_trace/mixed-modes.arity.run.json" ); then && "$MARQDO_BIN" run index.mq.md --mode pure --output jsonl \
--observation-file "$repo_root/$out_obs/mixed-modes.arity.snapshot.json" \
> "$repo_root/$out_obs/mixed-modes.arity.jsonl" 2>/dev/null ); then
echo "error: mixed-modes without params unexpectedly ran" >&2 echo "error: mixed-modes without params unexpectedly ran" >&2
exit 1 exit 1
fi fi
@@ -37,4 +50,4 @@ if "$MARQDO_BIN" check examples/diagnostics/index.mq.md --json >/dev/null 2>&1;
echo "error: examples/diagnostics unexpectedly passed check" >&2 echo "error: examples/diagnostics unexpectedly passed check" >&2
exit 1 exit 1
fi fi
echo "goldens: PASS" echo "goldens: PASS (Analysis v3 + Observation v1 stream/snapshot)"
+48 -2
View File
@@ -2,6 +2,10 @@
# Install the built bundle with a frozen marqdo CLI into an isolated tool home, # Install the built bundle with a frozen marqdo CLI into an isolated tool home,
# then prove the command is served by this program (not by the Core). # then prove the command is served by this program (not by the Core).
# #
# The frozen CLI is the current Tool revision 1 baseline: it injects
# MARQDO_API_REVISION=1 and MARQDO_BIN only, with no legacy
# MARQDO_PROTOCOL_* negotiation variables.
#
# Usage: MARQDO_BIN=/abs/path/marqdo scripts/install-smoke.sh [tool.json] # Usage: MARQDO_BIN=/abs/path/marqdo scripts/install-smoke.sh [tool.json]
set -euo pipefail set -euo pipefail
@@ -16,6 +20,19 @@ if [[ ! -x "$MARQDO_BIN" ]]; then
fi fi
before="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)" before="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)"
# The packaged manifest must declare the current exact contracts.
python3 - "$manifest" <<'PY'
import json
import sys
tool = json.load(open(sys.argv[1]))
assert tool["schema"] == "marqdo.cli-tool", tool
assert tool["schema_version"] == 1, tool
assert "compatibility" not in tool, "retired compatibility field present"
assert tool["requires"] == {"api_revision": 1, "analysis": 3, "observation": 1}, tool["requires"]
print("manifest: PASS (revision 1 requires api_revision=1 analysis=3 observation=1)")
PY
mkdir -p "$repo_root/dist" mkdir -p "$repo_root/dist"
tool_home="$(mktemp -d "$repo_root/dist/smoke-tool-home.XXXXXX")" tool_home="$(mktemp -d "$repo_root/dist/smoke-tool-home.XXXXXX")"
cleanup() { cleanup() {
@@ -25,7 +42,7 @@ trap cleanup EXIT
export MARQDO_TOOL_HOME="$tool_home" export MARQDO_TOOL_HOME="$tool_home"
"$MARQDO_BIN" tool install "$manifest" >/dev/null "$MARQDO_BIN" tool install "$manifest" >/dev/null
"$MARQDO_BIN" tool list | grep -q 'view' "$MARQDO_BIN" tool list | grep -q '^view '
help="$("$MARQDO_BIN" view --help)" help="$("$MARQDO_BIN" view --help)"
grep -q 'marqdo-view' <<<"$help" grep -q 'marqdo-view' <<<"$help"
grep -q 'export' <<<"$help" grep -q 'export' <<<"$help"
@@ -33,10 +50,39 @@ grep -q 'verify' <<<"$help"
version="$("$MARQDO_BIN" view --version)" version="$("$MARQDO_BIN" view --version)"
grep -q 'marqdo-view' <<<"$version" grep -q 'marqdo-view' <<<"$version"
# Prove the current dispatch environment contract: the CLI injects
# MARQDO_API_REVISION=1 (and MARQDO_BIN), never the retired negotiation vars.
probe_dir="$tool_home/probe"
mkdir -p "$probe_dir/bin"
cat >"$probe_dir/bin/api-probe" <<'PROBE'
#!/usr/bin/env bash
printf 'MARQDO_API_REVISION=%s\n' "${MARQDO_API_REVISION:-<unset>}"
printf 'MARQDO_BIN=%s\n' "${MARQDO_BIN:-<unset>}"
printf 'retired=%s\n' "${MARQDO_PROTOCOL_ANALYSIS:-}${MARQDO_PROTOCOL_TRACE:-}${MARQDO_TOOL_PROTOCOL:-}"
PROBE
chmod 755 "$probe_dir/bin/api-probe"
cat >"$probe_dir/tool.json" <<'PROBE_JSON'
{
"schema": "marqdo.cli-tool",
"schema_version": 1,
"name": "api-probe",
"version": "0.0.1",
"command": "api-probe",
"entrypoint": "bin/api-probe",
"requires": {"api_revision": 1}
}
PROBE_JSON
"$MARQDO_BIN" tool install "$probe_dir/tool.json" >/dev/null
probe="$("$MARQDO_BIN" api-probe)"
grep -qx 'MARQDO_API_REVISION=1' <<<"$probe"
grep -q '^MARQDO_BIN=/' <<<"$probe"
grep -qx 'retired=' <<<"$probe"
"$MARQDO_BIN" tool remove api-probe >/dev/null
after="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)" after="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)"
if [[ "$before" != "$after" ]]; then if [[ "$before" != "$after" ]]; then
echo "error: frozen core binary changed during install smoke test" >&2 echo "error: frozen core binary changed during install smoke test" >&2
exit 1 exit 1
fi fi
echo "install-smoke: PASS (core sha256 $before unchanged, tool home $tool_home)" echo "install-smoke: PASS (view installed/dispatched, api_revision 1 injected, core sha256 $before unchanged, tool home $tool_home)"
+20 -8
View File
@@ -1,13 +1,16 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Build and assemble the Tool Protocol v1 release bundle. # Build and assemble the CLI Tool revision 1 release bundle for marqdo-view 0.3.0.
# #
# Produces: # Produces:
# dist/marqdo-view/ stable bundle path (RFC §18) # dist/marqdo-view/ stable bundle path
# dist/marqdo-view-<version>-<target>.tar.gz (+ .sha256) # dist/marqdo-view-<version>-<target>.tar.gz (+ .sha256)
# #
# The bundle contains only the runtime binary, the manifest and the legal / # The bundle contains only the runtime binary, the manifest and the legal /
# compatibility files. CSS/JS/images are compiled into the binary (ADR-0002), # release-note files. CSS/JS/images are compiled into the binary (ADR-0002),
# so there is exactly one asset source for Live and Export. # so there is exactly one asset source for Live and Export.
#
# The current public contracts are exact: api_revision 1, Analysis 3 and
# Observation 1. There is no version negotiation and no `compatibility` field.
set -euo pipefail set -euo pipefail
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
@@ -66,6 +69,12 @@ import sys
bundle = pathlib.Path(sys.argv[1]) bundle = pathlib.Path(sys.argv[1])
version, target, source_sha = sys.argv[2], sys.argv[3], sys.argv[4] version, target, source_sha = sys.argv[2], sys.argv[3], sys.argv[4]
tool = json.loads((bundle / 'tool.json').read_text())
requires = tool.get('requires') or {}
if 'compatibility' in tool:
raise SystemExit('tool.json must not contain a compatibility field')
if requires != {'api_revision': 1, 'analysis': 3, 'observation': 1}:
raise SystemExit('tool.json requires must be exactly api_revision 1 / analysis 3 / observation 1')
files = [] files = []
for path in sorted(bundle.rglob('*')): for path in sorted(bundle.rglob('*')):
if not path.is_file(): if not path.is_file():
@@ -87,12 +96,15 @@ info = {
'command': 'view', 'command': 'view',
'target': target, 'target': target,
'source_sha': source_sha, 'source_sha': source_sha,
'compatibility': { 'requires': {
'marqdo': '>=3.0.0-beta.1,<4.0.0', 'api_revision': 1,
'analysis': [2], 'analysis': 3,
'trace': [2], 'observation': 1,
'tool_protocol': 1, },
'release': {
'product_range': '>=3.0.0-rc.3,<4.0.0',
'markdown_profile': 'marqdo.md.v1', 'markdown_profile': 'marqdo.md.v1',
'platform': 'linux-x86_64-glibc2.39',
}, },
'files': files, 'files': files,
} }
+2 -1
View File
@@ -1,5 +1,6 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Browser acceptance for the Live reader: real Chromium, real frozen core. # 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).
# #
# Usage: # Usage:
# MARQDO_BIN=/abs/path/marqdo scripts/test-browser.sh # MARQDO_BIN=/abs/path/marqdo scripts/test-browser.sh
+308
View File
@@ -0,0 +1,308 @@
#!/usr/bin/env python3
"""HTTP and ZIP acceptance against the frozen rc.4 release binary.
The View consumes Observation v1 (`--output jsonl` / `--observation-file`);
there is no trace file or legacy JSON run envelope.
"""
import hashlib
import http.cookiejar
import io
import json
import os
from pathlib import Path, PurePosixPath
import re
import shutil
import socket
import struct
import subprocess
import tempfile
import time
import urllib.error
import urllib.request
import zipfile
ROOT = Path(__file__).resolve().parents[1]
CORE = Path(os.environ["MARQDO_BIN"]).resolve(strict=True)
VIEW = Path(os.environ.get("VIEW_BIN", ROOT / "target/debug/marqdo-view")).resolve(strict=True)
def sha(data):
return hashlib.sha256(data).hexdigest()
def session(base):
browser = urllib.request.build_opener(
urllib.request.ProxyHandler({}),
urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()),
)
html = browser.open(base, timeout=10).read().decode()
token = re.search(r'name="mq-csrf-token" content="([a-f0-9]+)"', html)[1]
digest = re.search(r'data-analysis-digest="([^"]+)"', html)[1]
return browser, token, digest, html
def post(browser, base, route, token, body, status=200, origin=None):
headers = {"Content-Type": "application/json", "Origin": origin or base}
if token is not None:
headers["X-View-CSRF"] = token
request = urllib.request.Request(base + route, json.dumps(body).encode(), headers)
try:
with browser.open(request, timeout=20) as response:
assert response.status == status, (route, response.status, status)
return response.read(), response.headers
except urllib.error.HTTPError as error:
assert error.code == status, (route, error.code, status, error.read())
return error.read(), error.headers
def verify_zip(payload, destination, expected_digest):
with zipfile.ZipFile(io.BytesIO(payload)) as archive:
names = archive.namelist()
assert len(names) == len(set(names))
for item in archive.infolist():
path = PurePosixPath(item.filename)
assert not path.is_absolute() and ".." not in path.parts
assert item.compress_type == zipfile.ZIP_STORED and item.file_size <= 16 * 1024 ** 2
raw_manifest = archive.read("manifest.json")
assert sha(raw_manifest) == expected_digest
manifest = json.loads(raw_manifest)
assert manifest["schema_version"] == 2 and not manifest["executed_during_export"]
assert manifest["execution"]["source_verified"] and manifest["execution"]["status"] == "succeeded"
assert manifest["execution"]["parameters"] == "omitted"
assert manifest["source"]["document"] == "index.mq.md"
assert manifest["execution"]["contracts"] == {"api_revision": 1, "analysis": 3, "observation": 1}
for entry in manifest["files"] + manifest["assets"]:
data = archive.read(entry["path"])
assert sha(data) == entry["sha256"] and len(data) == entry["size"]
assert not any(name.endswith(".js") for name in names)
html = archive.read("index.html").decode()
assert "<math" in html and "<script" not in html and 'data-action="call-function"' not in html
assert "本次执行快照" in html and "Int(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 '<script' not in other
if destination:
Path(destination).write_bytes(payload)
print("snapshot manifest sha256", sha(archive.read("manifest.json")))
def check(root):
project = root / "project"
shutil.copytree(ROOT / "examples/complete-reader", project)
attack_text = b"<script>bad()</script><img onerror=bad()>"
lines = ["", "## @exec write_markup", "", f"`buffer = memory.new(1, {len(attack_text)})`", ""]
for index, byte in enumerate(attack_text):
lines.extend([f"`buffer[{index}] = {byte}`", ""])
lines.extend(['`out = resource.open("stdio", "stdout", ["write"])`', "",
f"`resource.write(out, buffer, 0, {len(attack_text)})`", "",
"`resource.close(out)`", "", "`return 1`", ""])
with (project / "index.mq.md").open("a") as source:
source.write("\n".join(lines))
scratch = root / "scratch"
scratch.mkdir()
count = root / "runs"
wrapper = root / "core"
wrapper.write_text(
"#!/usr/bin/env python3\n"
"import os, subprocess, sys, time\n"
f"core, count = {str(CORE)!r}, {str(count)!r}\n"
"if sys.argv[1] in ('run', 'call'):\n"
" assert sys.argv[sys.argv.index('--output') + 1] == 'jsonl' and '--observation-file' in sys.argv\n"
" assert '--json' not in sys.argv and '--trace-file' not in sys.argv\n"
" with open(count, 'a') as f: f.write(sys.argv[1]+'\\n')\n"
" if sys.argv[1] == 'call' and sys.argv[3] == 'write_markup':\n"
" result = subprocess.run([core, *sys.argv[1:]], check=False)\n"
" os.unlink(sys.argv[sys.argv.index('--observation-file') + 1])\n"
" sys.exit(result.returncode)\n"
" if sys.argv[1] == 'call' and sys.argv[3] == 'scan': time.sleep(2)\n"
"os.execv(core, [core, *sys.argv[1:]])\n"
)
wrapper.chmod(0o700)
env = {**os.environ, "TMPDIR": str(scratch)}
args = [str(VIEW), "--marqdo-bin", str(wrapper)]
with subprocess.Popen(
[*args, str(project), "--port", "0", "--no-open"],
stderr=subprocess.PIPE,
text=True,
env=env,
) as server:
try:
base = server.stderr.readline().split()[-1].rstrip("/")
browser, token, digest, html = session(base)
assert not count.exists()
assert "<math" in html and 'alt="样本数据图"' in html
media = re.search(r'src="(/media/[^"]+)" alt="样本数据图"', html)[1]
with browser.open(base + media, timeout=10) as response:
data = response.read()
assert response.headers.get_content_type() == "image/png"
assert sha(data) in media
try:
urllib.request.build_opener(urllib.request.ProxyHandler({})).open(base + media, timeout=10)
except urllib.error.HTTPError as error:
assert error.code == 401
else:
raise AssertionError("unauthenticated project media was accessible")
original = {path: sha(path.read_bytes()) for path in project.rglob("*") if path.is_file()}
def submit(function, request_id, parameters=None):
body = {
"document": "index.mq.md",
"target": {"kind": "function", "function_id": f"root:complete-reader@0.1.0::index.mq.md::计算.{function}"},
"parameters": parameters or [],
"analysis_digest": digest,
"client_request_id": request_id,
}
payload, _ = post(browser, base, "/api/runs", token, body, 202)
return json.loads(payload)
def observe(accepted):
with browser.open(base + accepted["events_url"], timeout=20) as response:
events = [json.loads(line[6:]) for line in response.read().decode().splitlines() if line.startswith("data: ")]
return accepted["run_id"], events[-1]
run_id, terminal = observe(submit("write_output", "one"))
assert terminal["state"] == "succeeded" and terminal["result"]["stdout"] == "4\n", terminal
assert terminal["result"]["observation_status"] == "verified"
assert count.read_text().splitlines() == ["call"]
selection = {
"schema": "marqdo.view-static-export-request",
"schema_version": 1,
"run_id": run_id,
"document": "index.mq.md",
"analysis_digest": digest,
"scope": "document",
"include": {"result_value": True, "stdout": True, "stderr": False, "arguments": False, "observation_summary": True},
"confirm_sensitive_output": True,
"client_export_request_id": "zip-one",
}
post(browser, base, "/api/exports", None, selection, 403)
post(browser, base, "/api/exports", token, selection, 403, "https://example.invalid")
other, other_token, _, _ = session(base)
post(other, base, "/api/exports", other_token, selection, 404)
post(browser, base, "/api/exports", token, {**selection, "schema_version": 2}, 400)
post(browser, base, "/api/exports", token, {**selection, "confirm_sensitive_output": False}, 400)
post(browser, base, "/api/exports", token, {**selection, "run_id": "unknown"}, 404)
payload, headers = post(browser, base, "/api/exports", token, selection)
assert headers.get_content_type() == "application/zip" and "attachment" in headers["Content-Disposition"]
assert headers["Cache-Control"] == "no-store" and headers["X-Content-Type-Options"] == "nosniff"
verify_zip(payload, os.environ.get("SNAPSHOT_ZIP"), headers["X-Marqdo-Manifest-SHA256"])
manifest_digest = headers["X-Marqdo-Manifest-SHA256"]
with zipfile.ZipFile(io.BytesIO(payload)) as archive:
manifest = json.loads(archive.read("manifest.json"))
assert sha(archive.read("manifest.json") + b" ") != manifest_digest
for entry in manifest["files"] + manifest["assets"]:
assert sha(archive.read(entry["path"]) + b" ") != entry["sha256"]
post(browser, base, "/api/exports", token, {**selection, "unknown": "x" * 8192}, 429)
auth = next(handler.cookiejar for handler in browser.handlers if hasattr(handler, "cookiejar"))
cookies = "; ".join(f"{cookie.name}={cookie.value}" for cookie in auth)
body = json.dumps(selection).encode()
host, port = base.removeprefix("http://").rsplit(":", 1)
request = (f"POST /api/exports HTTP/1.1\r\nHost: {host}:{port}\r\n"
f"Origin: {base}\r\nX-View-CSRF: {token}\r\nCookie: {cookies}\r\n"
f"Content-Type: application/json\r\nContent-Length: {len(body)}\r\n\r\n").encode()
with socket.create_connection((host, int(port)), timeout=10) as abandoned:
abandoned.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 4096)
abandoned.sendall(request + body)
assert abandoned.recv(16).startswith(b"HTTP/1.1 200")
abandoned.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
deadline = time.monotonic() + 5
while list(scratch.iterdir()) and time.monotonic() < deadline:
time.sleep(.01)
assert not list(scratch.iterdir()), list(scratch.iterdir())
forbidden_entry = project / "bad:archive-name.mq.md"
forbidden_entry.write_text("# @knowledge Archive path fixture\n")
post(browser, base, "/api/exports", token, selection, 500)
forbidden_entry.unlink()
assert not list(scratch.iterdir()), list(scratch.iterdir())
subprocess.run([*args, "export", str(project), "--out", str(root / "pure")], check=True, env=env)
assert "本次执行快照" not in (root / "pure/index.html").read_text()
assert count.read_text().splitlines() == ["call"]
assert original == {path: sha(path.read_bytes()) for path in project.rglob("*") if path.is_file()}
source = project / "index.mq.md"
original_source = source.read_bytes()
source.write_bytes(original_source + b"\nsource changed\n")
post(browser, base, "/api/exports", token, selection, 409)
source.write_bytes(original_source)
image = project / "media/flow.png"
original_image = image.read_bytes()
image.unlink()
image.symlink_to(root / "external.png")
(root / "external.png").write_bytes(original_image)
post(browser, base, "/api/exports", token, selection, 409)
image.unlink()
image.write_bytes(original_image)
dependency = project / "docs/explanation.mq.md"
dependency_bytes = dependency.read_bytes()
dependency.write_bytes(dependency_bytes + b"\nDependency changed.\n")
post(browser, base, "/api/exports", token, selection, 409)
dependency.write_bytes(dependency_bytes)
lock = project / "marqdo.lock"
assert not lock.exists()
lock.write_text("changed lock bytes")
post(browser, base, "/api/exports", token, selection, 409)
lock.unlink()
assert count.read_text().splitlines() == ["call"]
print("pure and selected export leave execution count at 1; source, lock, dependency and media staleness denied")
pending = submit("scan", "cancelled")
pending_selection = {**selection, "run_id": pending["run_id"]}
post(browser, base, "/api/exports", token, pending_selection, 409)
bare_cancel = urllib.request.Request(base + pending["cancel_url"], b"", {
"Origin": base, "X-View-CSRF": token
}, method="POST")
with browser.open(bare_cancel, timeout=10) as response:
assert response.status in (200, 202)
_, cancelled = observe(pending)
assert cancelled["state"] == "cancelled", cancelled
post(browser, base, "/api/exports", token, pending_selection, 409)
failed_id, failed = observe(submit("fail", "failed", [{"name": "divisor", "expression": "0"}]))
assert failed["state"] == "failed", failed
failed_selection = {**selection, "run_id": failed_id}
post(browser, base, "/api/exports", token, failed_selection, 400)
failed_zip, _ = post(browser, base, "/api/exports", token, {**failed_selection, "confirm_partial": True})
with zipfile.ZipFile(io.BytesIO(failed_zip)) as archive:
assert json.loads(archive.read("manifest.json"))["execution"]["status"] == "failed"
text_id, text = observe(submit("write_markup", "markup"))
assert text["state"] == "succeeded" and text["result"]["observation_status"] == "unavailable", text
assert text["result"]["stdout"] == attack_text.decode()
text_zip, _ = post(browser, base, "/api/exports", token, {**selection, "run_id": text_id})
with zipfile.ZipFile(io.BytesIO(text_zip)) as archive:
html = archive.read("index.html").decode()
assert "<script>" not in html and "&lt;script&gt;bad()" in html
assert json.loads(archive.read("manifest.json"))["execution"]["observation_status"] == "unavailable"
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("selected IDs remain isolated, tampering detected, oversized request denied, failed and aborted packages cleaned")
calls = count.read_text().splitlines()
assert calls == ["call"] * 4, calls
print("run/call count matches four explicit submissions:", calls)
finally:
server.terminate()
server.wait(timeout=5)
with subprocess.Popen(
[*args, str(project), "--port", "0", "--no-open", "--run-timeout", "1"],
stderr=subprocess.PIPE, text=True, env=env,
) as restarted:
try:
base = restarted.stderr.readline().split()[-1].rstrip("/")
browser, token, digest, _ = session(base)
post(browser, base, "/api/exports", token, selection, 404)
timed_id, timed = observe(submit("scan", "timeout"))
assert timed["state"] == "timed_out", timed
post(browser, base, "/api/exports", token, {**selection, "run_id": timed_id}, 409)
finally:
restarted.terminate()
restarted.wait(timeout=5)
assert not list(scratch.iterdir()), list(scratch.iterdir())
print("restarted View cannot recover the previous job; timed-out execution is not exportable; private scratch directories are empty")
if __name__ == "__main__":
with tempfile.TemporaryDirectory(prefix="marqdo-view-acceptance-") as directory:
check(Path(directory))
+3 -2
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Contract-focused gate: formatting, lints, all tests, Tool v1 install smoke, # Contract-focused gate: formatting, lints, all tests, CLI Tool revision 1
# static verify and static export against the frozen core. No browser. # install smoke, static verify and static export against the frozen core.
# No browser. Current contracts: Analysis revision 3, Observation revision 1.
# #
# Usage: MARQDO_BIN=/abs/path/marqdo scripts/test-contract.sh # Usage: MARQDO_BIN=/abs/path/marqdo scripts/test-contract.sh
set -euo pipefail set -euo pipefail
+1
View File
@@ -1,5 +1,6 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Static export acceptance: pure read-only, offline assets, safe paths. # Static export acceptance: pure read-only, offline assets, safe paths.
# One renderer for Live and Export; no execution, no network.
# #
# Usage: MARQDO_BIN=/abs/path/marqdo scripts/test-export.sh # Usage: MARQDO_BIN=/abs/path/marqdo scripts/test-export.sh
set -euo pipefail set -euo pipefail
+2 -2
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# RFC-VIEW-0002 §13.4 / §6 / §10.3: opening, searching, switching and exporting # Opening, searching, switching and exporting must never execute a document
# must never execute a document. Uses the unsafe-side-effect fixture and checks # (zero-execution baseline, current rc.4 contracts). Uses the unsafe-side-effect fixture and checks
# source/lock hashes plus the absence of any write sentinel around the whole # source/lock hashes plus the absence of any write sentinel around the whole
# read-only operation set. # read-only operation set.
# #
+1 -1
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Prove a frozen marqdo release binary is byte-identical before and after a # Prove a frozen marqdo release binary is byte-identical before and after a
# command sequence (RFC-VIEW-0002 §2 / §9.4 / §10.2). # command sequence (issue #4/#5 release evidence).
# #
# Usage: # Usage:
# scripts/verify-frozen-cli.sh /abs/path/marqdo [-- EXPECTED_SHA256] -- CMD [ARGS...] # scripts/verify-frozen-cli.sh /abs/path/marqdo [-- EXPECTED_SHA256] -- CMD [ARGS...]
+2 -2
View File
@@ -12,8 +12,8 @@ use std::path::PathBuf;
#[command( #[command(
name = "marqdo-view", name = "marqdo-view",
version, version,
about = "Read .mq.md documents as documents: static Analysis v2, optional explicit run Trace v2", about = "Read .mq.md documents as documents: static Analysis v3, optional explicit Observation v1",
long_about = "Marqdo View renders the original Markdown and attaches verified Analysis v2 facts. \ long_about = "Marqdo View renders the original Markdown and attaches verified Analysis v3 facts. \
Running is never implicit: it requires an explicit user action. \ Running is never implicit: it requires an explicit user action. \
Export is always a pure read-only operation.", Export is always a pure read-only operation.",
disable_help_subcommand = true, disable_help_subcommand = true,
+165 -248
View File
@@ -1,9 +1,11 @@
//! The only way View talks to the frozen CLI. //! The only way View talks to the frozen CLI.
//! //!
//! Invariants (RFC-VIEW-0001 §4.2, §10.3, §14.1): //! Invariants:
//! * absolute `MARQDO_BIN`, argv arrays, never `sh -c`, never shell strings; //! * absolute `MARQDO_BIN`, argv arrays, never `sh -c`, never shell strings;
//! * `check --emit` is the only static channel; `run --trace-file --json` the //! * `check --emit` is the only static channel; `run`/`call --output jsonl`
//! only dynamic one; private Core IR dumps are never used; //! (optionally with `--observation-file`) is the only dynamic channel, and
//! both dynamic destinations come from the same execution;
//! * private Core IR dumps, second parsers and protocol probing are never used;
//! * stdout/stderr/exit status are handled separately; a stderr JSON blob is //! * stdout/stderr/exit status are handled separately; a stderr JSON blob is
//! never promoted to a successful Analysis; //! never promoted to a successful Analysis;
//! * temporary artifacts live in a private 0700 directory and are removed on //! * temporary artifacts live in a private 0700 directory and are removed on
@@ -24,14 +26,18 @@ pub const DEFAULT_RUN_TIMEOUT: Duration = Duration::from_secs(120);
/// Default View-level wall clock cap for one Core `check`. /// Default View-level wall clock cap for one Core `check`.
pub const DEFAULT_CHECK_TIMEOUT: Duration = Duration::from_secs(120); pub const DEFAULT_CHECK_TIMEOUT: Duration = Duration::from_secs(120);
const ENV_MARQDO_BIN: &str = "MARQDO_BIN"; /// Bounded observation budget sent on every explicit run. The protocol
/// expresses exhaustion through `observation.truncated`; View never silently
/// drops or amplifies events itself.
pub const DEFAULT_OBSERVE_MAX_EVENTS: u64 = 10_000;
pub const DEFAULT_OBSERVE_MAX_BYTES: u64 = 4_194_304;
pub const DEFAULT_OBSERVE_MAX_VALUE_BYTES: u64 = 256;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")] #[serde(rename_all = "lowercase")]
pub enum SandboxMode { pub enum SandboxMode {
Pure, Pure,
Project, Project,
Strict,
} }
impl SandboxMode { impl SandboxMode {
@@ -39,7 +45,6 @@ impl SandboxMode {
match self { match self {
SandboxMode::Pure => "pure", SandboxMode::Pure => "pure",
SandboxMode::Project => "project", SandboxMode::Project => "project",
SandboxMode::Strict => "strict",
} }
} }
} }
@@ -59,7 +64,7 @@ pub struct Grants {
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default)]
pub struct CheckOptions { pub struct CheckOptions {
/// `--refs` also validates Markdown link targets; it is a stricter check /// `--refs` also validates Markdown link targets; it is a stricter check
/// and may fail where plain syntax succeeds. /// and its artifact must never be used as the Observation binding input.
pub refs: bool, pub refs: bool,
pub timeout: Option<Duration>, pub timeout: Option<Duration>,
} }
@@ -73,8 +78,14 @@ pub struct RunOptions {
pub max_output: Option<u64>, pub max_output: Option<u64>,
pub timeout_seconds: Option<u64>, pub timeout_seconds: Option<u64>,
pub view_timeout: Option<Duration>, pub view_timeout: Option<Duration>,
pub trace_max_events: Option<u64>, pub observe_max_events: u64,
pub trace_max_bytes: Option<u64>, pub observe_max_bytes: u64,
pub observe_max_value_bytes: u64,
/// Explicit value selection. Empty by default: View never requests values
/// unless the user opts in (and Text additionally needs a second consent).
pub observe_variables: Vec<String>,
pub observe_parameters: Vec<String>,
pub observe_text_values: bool,
} }
impl Default for RunOptions { impl Default for RunOptions {
@@ -87,8 +98,12 @@ impl Default for RunOptions {
max_output: None, max_output: None,
timeout_seconds: None, timeout_seconds: None,
view_timeout: Some(DEFAULT_RUN_TIMEOUT), view_timeout: Some(DEFAULT_RUN_TIMEOUT),
trace_max_events: None, observe_max_events: DEFAULT_OBSERVE_MAX_EVENTS,
trace_max_bytes: None, observe_max_bytes: DEFAULT_OBSERVE_MAX_BYTES,
observe_max_value_bytes: DEFAULT_OBSERVE_MAX_VALUE_BYTES,
observe_variables: Vec::new(),
observe_parameters: Vec::new(),
observe_text_values: false,
} }
} }
} }
@@ -99,13 +114,13 @@ pub struct CheckOutput {
pub analysis_bytes: Vec<u8>, pub analysis_bytes: Vec<u8>,
/// Lowercase hex SHA-256 of `analysis_bytes`. /// Lowercase hex SHA-256 of `analysis_bytes`.
pub analysis_sha256: String, pub analysis_sha256: String,
/// Prefixed digest (`sha256:...`) for comparison with Trace v2. /// Prefixed digest (`sha256:...`) used by the Observation binding.
pub analysis_digest: String, pub analysis_digest: String,
pub stdout: String, pub stdout: String,
pub stderr: String, pub stderr: String,
} }
/// One compile diagnostic from `check --json`, normalized so no absolute /// One check diagnostic from `check --json`, normalized so no absolute
/// machine path can leak into pages, exports or logs. /// machine path can leak into pages, exports or logs.
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RawCheckDiagnostic { pub struct RawCheckDiagnostic {
@@ -126,7 +141,7 @@ pub struct RawCheckDiagnostic {
} }
/// Result of one `check` invocation. A failed check is **not** an I/O error: /// Result of one `check` invocation. A failed check is **not** an I/O error:
/// the prose stays readable and diagnostics must be shown (RFC §12.3). /// the prose stays readable and diagnostics must be shown.
#[derive(Debug)] #[derive(Debug)]
pub struct CheckResponse { pub struct CheckResponse {
pub success: bool, pub success: bool,
@@ -136,123 +151,39 @@ pub struct CheckResponse {
pub stderr: String, pub stderr: String,
} }
#[derive(Debug)] pub use crate::scratch::ScratchDir;
pub struct RunOutput {
/// Exactly one JSON document emitted on stdout by the Core.
pub json: serde_json::Value,
pub stdout: String,
pub stderr: String,
pub exit_code: i32,
/// Raw Trace v2 bytes when the Core wrote them (even for a failed run).
pub trace_bytes: Option<Vec<u8>>,
pub trace_sha256: Option<String>,
}
/// A private temporary directory for Core artifacts. /// The public client for one frozen core binary.
pub struct ScratchDir {
path: PathBuf,
}
impl ScratchDir {
pub fn create(label: &str) -> ViewResult<Self> {
let base = std::env::temp_dir();
let unique = format!(
"marqdo-view-{}-{}-{}",
std::process::id(),
unique_counter(),
sanitize_label(label)
);
let path = base.join(unique);
std::fs::create_dir_all(&path)
.map_err(|err| ViewError::io(&format!("create scratch {}", path.display()), err))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700))
.map_err(|err| ViewError::io(&format!("chmod scratch {}", path.display()), err))?;
}
Ok(Self { path })
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn file(&self, name: &str) -> PathBuf {
self.path.join(name)
}
}
impl Drop for ScratchDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
fn unique_counter() -> u64 {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos() as u64)
.unwrap_or(0);
seq ^ nanos.rotate_left(17)
}
fn sanitize_label(label: &str) -> String {
label
.chars()
.map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '-' })
.take(32)
.collect()
}
/// Negotiated public-client for one frozen core binary.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct CoreClient { pub struct CoreClient {
bin: PathBuf, bin: PathBuf,
protocol_env: ProtocolEnv, api_revision: Option<String>,
}
#[derive(Debug, Clone, Default)]
struct ProtocolEnv {
tool: Option<String>,
analysis: Option<String>,
trace: Option<String>,
} }
impl CoreClient { impl CoreClient {
/// Build a client from `--marqdo-bin` (development) or `MARQDO_BIN` /// Build a client from `--marqdo-bin` (development) or `MARQDO_BIN`
/// (installed Tool Protocol). Never guesses a `PATH` binary: a wrong /// (installed Tool). Never guesses a `PATH` binary: a wrong version must
/// version must fail loudly, not silently. /// fail loudly, not silently.
pub fn from_env(explicit: Option<&Path>) -> ViewResult<Self> { pub fn from_env(explicit: Option<&Path>) -> ViewResult<Self> {
let bin = locate_bin(explicit)?; let bin = locate_bin(explicit)?;
Self::with_bin(bin) Self::with_bin(bin)
} }
/// Construct from an explicit binary path, still reading any negotiated /// Construct from an explicit binary path, still reading the injected API
/// protocol environment. Useful for `--marqdo-bin` and integration tests; /// revision expectation. Useful for `--marqdo-bin` and integration tests.
/// production dispatch should prefer [`CoreClient::from_env`].
pub fn with_bin(bin: impl Into<PathBuf>) -> ViewResult<Self> { pub fn with_bin(bin: impl Into<PathBuf>) -> ViewResult<Self> {
let bin = validate_bin(&bin.into(), "core binary")?; let bin = validate_bin(&bin.into(), "core binary")?;
Ok(Self { let api_revision = std::env::var(tool_v1::ENV_MARQDO_API_REVISION).ok();
bin, tool_v1::validate_api_revision_env(api_revision.as_deref())?;
protocol_env: ProtocolEnv { Ok(Self { bin, api_revision })
tool: std::env::var(tool_v1::ENV_TOOL_PROTOCOL).ok(),
analysis: std::env::var(tool_v1::ENV_PROTOCOL_ANALYSIS).ok(),
trace: std::env::var(tool_v1::ENV_PROTOCOL_TRACE).ok(),
},
})
} }
/// Test-only constructor with an explicit binary and no environment /// Test-only constructor with no injected environment expectation.
/// negotiation input.
#[cfg(test)] #[cfg(test)]
pub fn for_test(bin: impl Into<PathBuf>) -> Self { pub fn for_test(bin: impl Into<PathBuf>) -> Self {
Self { Self {
bin: bin.into(), bin: bin.into(),
protocol_env: ProtocolEnv::default(), api_revision: None,
} }
} }
@@ -260,15 +191,15 @@ impl CoreClient {
&self.bin &self.bin
} }
/// Run `--version`, validate the product range and any negotiated protocol pub fn api_revision(&self) -> Option<&str> {
/// environment variables. A missing Development-mode env is allowed; an self.api_revision.as_deref()
/// unknown major is a hard error. }
/// Run `--version`, validate the product range and the injected API
/// revision. A missing Development-mode environment is allowed; an
/// unknown revision is a hard error.
pub fn negotiate(&self) -> ViewResult<CoreVersion> { pub fn negotiate(&self) -> ViewResult<CoreVersion> {
tool_v1::negotiate_protocol_env( tool_v1::validate_api_revision_env(self.api_revision.as_deref())?;
self.protocol_env.tool.as_deref(),
self.protocol_env.analysis.as_deref(),
self.protocol_env.trace.as_deref(),
)?;
let output = self.execute( let output = self.execute(
&[OsString::from("--version")], &[OsString::from("--version")],
&std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")), &std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
@@ -288,7 +219,7 @@ impl CoreClient {
if !tool_v1::product_is_compatible(&version.version) { if !tool_v1::product_is_compatible(&version.version) {
return Err(ViewError::ProtocolIncompatible { return Err(ViewError::ProtocolIncompatible {
detail: format!( detail: format!(
"core {} is outside the supported range {}", "core {} is outside the supported range {}; install the current rc.3+ core",
version.version, version.version,
tool_v1::PRODUCT_RANGE tool_v1::PRODUCT_RANGE
), ),
@@ -297,9 +228,11 @@ impl CoreClient {
Ok(version) Ok(version)
} }
/// `check --json --emit`. On success the exact Analysis v2 bytes are /// `check --json --emit`. `--json` only selects the diagnostic summary on
/// returned; on failure the structured diagnostics are returned without /// stdout; it does not change the emitted Analysis bytes. On success the
/// any absolute path. Only spawn/timeout/IO failures are hard errors. /// exact Analysis bytes are returned; on failure the structured
/// diagnostics are returned without any absolute path. Only
/// spawn/timeout/IO failures are hard errors.
pub fn check( pub fn check(
&self, &self,
project: &Project, project: &Project,
@@ -376,62 +309,6 @@ impl CoreClient {
}) })
} }
/// `run --trace-file --json`, only after an explicit user confirmation in
/// the calling layer. Returns the CLI JSON document and raw Trace bytes.
pub fn run(
&self,
project: &Project,
relative: &SafeRelativePath,
options: &RunOptions,
) -> ViewResult<RunOutput> {
let entry = project.absolute_for(relative)?;
let scratch = ScratchDir::create("run")?;
let trace_path = scratch.file("trace.json");
let args = build_run_args(&entry, &trace_path, options);
let output = self.execute(
&args,
project.root(),
options.view_timeout.unwrap_or(DEFAULT_RUN_TIMEOUT),
)?;
let json: serde_json::Value =
serde_json::from_slice(&output.stdout_bytes).map_err(|err| ViewError::Io {
detail: format!(
"`marqdo run --json` did not emit exactly one JSON document: {err}; stderr: {}",
summarize_stderr(&output.stderr)
),
})?;
if !json.is_object() {
return Err(ViewError::Io {
detail: "`marqdo run --json` emitted a non-object JSON document".to_string(),
});
}
let trace_bytes = match std::fs::read(&trace_path) {
Ok(bytes) => {
if bytes.is_empty() {
None
} else {
Some(bytes)
}
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => None,
Err(err) => {
return Err(ViewError::io(
&format!("read trace {}", trace_path.display()),
err,
))
}
};
Ok(RunOutput {
json,
stdout: output.stdout,
stderr: output.stderr,
exit_code: output.exit_code,
trace_sha256: trace_bytes.as_deref().map(sha256_hex),
trace_bytes,
})
}
/// Spawn the core through the single process adapter with an explicit /// Spawn the core through the single process adapter with an explicit
/// argv, private cwd, bounded capture and a wall-clock cap. /// argv, private cwd, bounded capture and a wall-clock cap.
fn execute(&self, args: &[OsString], cwd: &Path, timeout: Duration) -> ViewResult<ExecOutput> { fn execute(&self, args: &[OsString], cwd: &Path, timeout: Duration) -> ViewResult<ExecOutput> {
@@ -466,24 +343,48 @@ struct ExecOutput {
stderr: String, stderr: String,
} }
/// Build the base `check` arguments. The caller appends `--emit <path>` and /// Build the base `check` arguments. The caller appends `--json`,
/// optionally `--refs`; this function exists so the argv shape is unit-testable. /// `--emit <path>` and optionally `--refs`; this function exists so the argv
/// shape is unit-testable and cannot drift to a retired flag.
fn build_check_args(entry: &Path) -> Vec<OsString> { fn build_check_args(entry: &Path) -> Vec<OsString> {
vec![OsString::from("check"), entry.as_os_str().to_os_string()] vec![OsString::from("check"), entry.as_os_str().to_os_string()]
} }
/// Common explicit flags shared by `run` and `call`. Budgets are always sent /// Common explicit flags shared by `run` and `call`.
/// explicitly by the execution controller (RFC-VIEW-0002 §6.7). fn append_common_args(args: &mut Vec<OsString>, observation_file: &Path, options: &RunOptions) {
fn append_common_args(args: &mut Vec<OsString>, trace_path: &Path, options: &RunOptions) {
fn push_pair(args: &mut Vec<OsString>, flag: &str, value: &str) { fn push_pair(args: &mut Vec<OsString>, flag: &str, value: &str) {
args.push(OsString::from(flag)); args.push(OsString::from(flag));
args.push(OsString::from(value)); args.push(OsString::from(value));
} }
args.push(OsString::from("--mode")); args.push(OsString::from("--mode"));
args.push(OsString::from(options.mode.as_str())); args.push(OsString::from(options.mode.as_str()));
args.push(OsString::from("--json")); push_pair(args, "--output", "jsonl");
args.push(OsString::from("--trace-file")); args.push(OsString::from("--observation-file"));
args.push(trace_path.as_os_str().to_os_string()); args.push(observation_file.as_os_str().to_os_string());
push_pair(
args,
"--observe-max-events",
&options.observe_max_events.to_string(),
);
push_pair(
args,
"--observe-max-bytes",
&options.observe_max_bytes.to_string(),
);
push_pair(
args,
"--observe-max-value-bytes",
&options.observe_max_value_bytes.to_string(),
);
for name in &options.observe_variables {
push_pair(args, "--observe-variable", name);
}
for name in &options.observe_parameters {
push_pair(args, "--observe-parameter", name);
}
if options.observe_text_values {
args.push(OsString::from("--observe-text-values"));
}
for glob in &options.grants.allow_read { for glob in &options.grants.allow_read {
push_pair(args, "--allow-read", glob); push_pair(args, "--allow-read", glob);
} }
@@ -514,18 +415,16 @@ fn append_common_args(args: &mut Vec<OsString>, trace_path: &Path, options: &Run
if let Some(timeout) = options.timeout_seconds { if let Some(timeout) = options.timeout_seconds {
push_pair(args, "--timeout", &timeout.to_string()); push_pair(args, "--timeout", &timeout.to_string());
} }
if let Some(max_events) = options.trace_max_events {
push_pair(args, "--trace-max-events", &max_events.to_string());
}
if let Some(max_bytes) = options.trace_max_bytes {
push_pair(args, "--trace-max-bytes", &max_bytes.to_string());
}
} }
/// Build `run` arguments from an already user-approved request. /// Build `run` arguments from an already user-approved request.
pub fn build_run_args(entry: &Path, trace_path: &Path, options: &RunOptions) -> Vec<OsString> { pub fn build_run_args(
entry: &Path,
observation_file: &Path,
options: &RunOptions,
) -> Vec<OsString> {
let mut args = vec![OsString::from("run"), entry.as_os_str().to_os_string()]; let mut args = vec![OsString::from("run"), entry.as_os_str().to_os_string()];
append_common_args(&mut args, trace_path, options); append_common_args(&mut args, observation_file, options);
args args
} }
@@ -535,7 +434,7 @@ pub fn build_call_args(
entry: &Path, entry: &Path,
function: &str, function: &str,
arguments: &[(String, String)], arguments: &[(String, String)],
trace_path: &Path, observation_file: &Path,
options: &RunOptions, options: &RunOptions,
) -> Vec<OsString> { ) -> Vec<OsString> {
let mut args = vec![ let mut args = vec![
@@ -547,7 +446,7 @@ pub fn build_call_args(
args.push(OsString::from("--arg")); args.push(OsString::from("--arg"));
args.push(OsString::from(format!("{name}={expression}"))); args.push(OsString::from(format!("{name}={expression}")));
} }
append_common_args(&mut args, trace_path, options); append_common_args(&mut args, observation_file, options);
args args
} }
@@ -555,18 +454,19 @@ fn locate_bin(explicit: Option<&Path>) -> ViewResult<PathBuf> {
if let Some(path) = explicit { if let Some(path) = explicit {
return validate_bin(path, "--marqdo-bin"); return validate_bin(path, "--marqdo-bin");
} }
if let Some(raw) = std::env::var_os(ENV_MARQDO_BIN) { if let Some(raw) = std::env::var_os(tool_v1::ENV_MARQDO_BIN) {
if raw.is_empty() { if raw.is_empty() {
return Err(ViewError::CoreMissing { return Err(ViewError::CoreMissing {
detail: format!("{ENV_MARQDO_BIN} is set but empty"), detail: format!("{} is set but empty", tool_v1::ENV_MARQDO_BIN),
}); });
} }
return validate_bin(Path::new(&raw), ENV_MARQDO_BIN); return validate_bin(Path::new(&raw), tool_v1::ENV_MARQDO_BIN);
} }
Err(ViewError::CoreMissing { Err(ViewError::CoreMissing {
detail: format!( detail: format!(
"{ENV_MARQDO_BIN} is not set. Install this tool with `marqdo tool install <bundle>/tool.json`, \ "{} is not set. Install this tool with `marqdo tool install <bundle>/tool.json`, \
or pass --marqdo-bin <path> when running marqdo-view directly." or pass --marqdo-bin <path> when running marqdo-view directly.",
tool_v1::ENV_MARQDO_BIN
), ),
}) })
} }
@@ -595,25 +495,12 @@ fn validate_bin(path: &Path, origin: &str) -> ViewResult<PathBuf> {
Ok(canonical) Ok(canonical)
} }
fn summarize_stderr(stderr: &str) -> String {
let trimmed = stderr.trim();
if trimmed.is_empty() {
"(no stderr)".to_string()
} else {
let mut text: String = trimmed.chars().take(1200).collect();
if trimmed.chars().count() > 1200 {
text.push('…');
}
text
}
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// `marqdo view verify`: static Analysis/source binding check. Never executes. // `marqdo view verify`: static Analysis/source binding check. Never executes.
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
use crate::cli::{RuntimeOpts, VerifyArgs}; use crate::cli::{RuntimeOpts, VerifyArgs};
use crate::protocol::analysis_v2; use crate::protocol::analysis_v3;
pub fn verify_command(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32> { pub fn verify_command(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32> {
let path = args let path = args
@@ -627,7 +514,6 @@ pub fn verify_command(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32>
let source = String::from_utf8(source_bytes).map_err(|err| ViewError::Io { let source = String::from_utf8(source_bytes).map_err(|err| ViewError::Io {
detail: format!("{entry} is not valid UTF-8: {err}"), detail: format!("{entry} is not valid UTF-8: {err}"),
})?; })?;
let source_index = crate::reader::source::SourceIndex::new(&source);
let client = CoreClient::from_env(opts.marqdo_bin.as_deref())?; let client = CoreClient::from_env(opts.marqdo_bin.as_deref())?;
let core_version = client.negotiate()?; let core_version = client.negotiate()?;
@@ -677,12 +563,8 @@ pub fn verify_command(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32>
}) })
} }
}; };
let verified = analysis_v2::verify_analysis( let verified =
&check.analysis_bytes, analysis_v3::verify_analysis(&check.analysis_bytes, entry.as_str(), Some(&source))?;
&source,
&source_index,
entry.as_str(),
)?;
let projection = &verified.projection; let projection = &verified.projection;
if args.json { if args.json {
@@ -693,22 +575,31 @@ pub fn verify_command(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32>
"core": { "core": {
"version": core_version.version.to_string(), "version": core_version.version.to_string(),
"supported_range": tool_v1::PRODUCT_RANGE, "supported_range": tool_v1::PRODUCT_RANGE,
"api_revision": tool_v1::API_REVISION,
}, },
"analysis": { "analysis": {
"schema": "marqdo.analysis", "schema": "marqdo.analysis",
"schema_version": tool_v1::ANALYSIS_PROTOCOL, "schema_version": projection.schema_version,
"digest": projection.analysis_digest, "digest": projection.analysis_digest,
"producer_version": projection.producer_version, "producer_version": projection.producer_version,
"markdown_profile": projection.markdown_profile, "markdown_profile": projection.markdown_profile,
"functions": projection.functions.len(), "functions": projection.functions.len(),
"units": projection.units.len(), "units": projection.units.len(),
"references": projection.references.len(),
"diagnostics": projection.diagnostics.len(), "diagnostics": projection.diagnostics.len(),
"requires": {
"analysis": tool_v1::ANALYSIS_REVISION,
"observation": tool_v1::OBSERVATION_REVISION,
},
}, },
"project": { "project": {
"root_id": projection.project_root_id, "root_id": projection.project_root_id,
"identity_kind": projection.identity_kind, "identity_kind": projection.identity_kind,
"entry_module_id": projection.entry_module_id,
"lock_digest": projection.lock_digest, "lock_digest": projection.lock_digest,
"manifest_digest": projection.manifest_digest,
"stdlib_version": projection.stdlib_version, "stdlib_version": projection.stdlib_version,
"extensions": projection.extensions.len(),
}, },
"document": { "document": {
"relative_path": entry.as_str(), "relative_path": entry.as_str(),
@@ -726,9 +617,10 @@ pub fn verify_command(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32>
); );
} else { } else {
println!( println!(
"core: marqdo {} (supported {})", "core: marqdo {} (supported {}, api revision {})",
core_version.version, core_version.version,
tool_v1::PRODUCT_RANGE tool_v1::PRODUCT_RANGE,
tool_v1::API_REVISION
); );
println!( println!(
"project: {} ({})", "project: {} ({})",
@@ -736,9 +628,11 @@ pub fn verify_command(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32>
); );
println!("document: {entry}"); println!("document: {entry}");
println!( println!(
"analysis: schema=marqdo.analysis v2 modules={} functions={} digest={}", "analysis: schema=marqdo.analysis v{} modules={} functions={} references={} digest={}",
projection.schema_version,
projection.modules.len(), projection.modules.len(),
projection.functions.len(), projection.functions.len(),
projection.references.len(),
projection.analysis_digest projection.analysis_digest
); );
println!("source digest: match"); println!("source digest: match");
@@ -751,40 +645,70 @@ pub fn verify_command(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32>
mod tests { mod tests {
use super::*; use super::*;
fn text(args: &[OsString]) -> Vec<String> {
args.iter()
.map(|arg| arg.to_string_lossy().to_string())
.collect()
}
#[test] #[test]
fn run_args_are_explicit_argv_never_shell() { fn run_args_use_the_current_observation_flags_only() {
let args = build_run_args( let args = build_run_args(
Path::new("/p/index.mq.md"), Path::new("/p/index.mq.md"),
Path::new("/t/trace.json"), Path::new("/t/observation.json"),
&RunOptions { &RunOptions {
mode: SandboxMode::Pure, mode: SandboxMode::Project,
grants: Grants { grants: Grants {
allow_read: vec!["data/**".into()], allow_read: vec!["data/**".into()],
allow_net: vec!["example.com".into()], allow_net: vec!["example.com".into()],
..Default::default() ..Default::default()
}, },
fuel: Some(1000), fuel: Some(1000),
trace_max_events: Some(20), observe_max_events: 20,
..Default::default() ..Default::default()
}, },
); );
let text: Vec<String> = args let text = text(&args);
.iter()
.map(|arg| arg.to_string_lossy().to_string())
.collect();
assert_eq!(text[0], "run"); assert_eq!(text[0], "run");
assert_eq!(text[1], "/p/index.mq.md"); assert_eq!(text[1], "/p/index.mq.md");
assert!(text.contains(&"pure".to_string())); assert!(text.contains(&"project".to_string()));
assert!(text.contains(&"--json".to_string())); assert!(text.contains(&"--output".to_string()));
assert!(text.contains(&"--trace-file".to_string())); assert!(text.contains(&"jsonl".to_string()));
assert!(text.contains(&"--observation-file".to_string()));
assert!(text.contains(&"--observe-max-events".to_string()));
assert!(text.contains(&"--observe-max-bytes".to_string()));
assert!(text.contains(&"--observe-max-value-bytes".to_string()));
assert!(text.contains(&"data/**".to_string())); assert!(text.contains(&"data/**".to_string()));
assert!(text.contains(&"example.com".to_string())); assert!(text.contains(&"example.com".to_string()));
assert!(text.contains(&"1000".to_string())); // Retired flags and any shell fragment must never appear.
assert!(text.contains(&"20".to_string())); for retired in [
// No token is a shell fragment: every argument is a separate value. "--json",
"--trace-file",
"--event-stream",
"--trace-max-events",
"--trace-max-bytes",
] {
assert!(
!text.contains(&retired.to_string()),
"retired flag {retired}"
);
}
assert!(!text assert!(!text
.iter() .iter()
.any(|t| t.contains(';') || t.contains('|') || t.contains('&'))); .any(|token| token.contains(';') || token.contains('|') || token.contains('&')));
}
#[test]
fn run_defaults_do_not_request_values() {
let args = build_run_args(
Path::new("/p/index.mq.md"),
Path::new("/t/observation.json"),
&RunOptions::default(),
);
let text = text(&args);
assert!(!text.iter().any(|token| token == "--observe-variable"));
assert!(!text.iter().any(|token| token == "--observe-parameter"));
assert!(!text.iter().any(|token| token == "--observe-text-values"));
} }
#[test] #[test]
@@ -816,11 +740,4 @@ mod tests {
drop(scratch); drop(scratch);
assert!(!path.exists()); assert!(!path.exists());
} }
#[test]
fn stderr_summary_is_bounded() {
let text = summarize_stderr(&"x".repeat(5000));
assert!(text.chars().count() <= 1201);
assert_eq!(summarize_stderr(" "), "(no stderr)");
}
} }
+119 -31
View File
@@ -17,55 +17,124 @@ pub enum ExitClass {
#[derive(Debug)] #[derive(Debug)]
pub enum ViewError { pub enum ViewError {
/// `MARQDO_BIN` unset, missing, or not executable. /// `MARQDO_BIN` unset, missing, or not executable.
CoreMissing { detail: String }, CoreMissing {
detail: String,
},
/// Tool/Analysis/Trace protocol or product range mismatch. /// Tool/Analysis/Trace protocol or product range mismatch.
ProtocolIncompatible { detail: String }, ProtocolIncompatible {
detail: String,
},
/// Core `check` failed; prose stays readable but semantics are unusable. /// Core `check` failed; prose stays readable but semantics are unusable.
AnalysisFailed { detail: String }, AnalysisFailed {
detail: String,
},
/// Analysis `source_digest` does not match the current source bytes. /// Analysis `source_digest` does not match the current source bytes.
SourceMismatch { expected: String, actual: String }, SourceMismatch {
expected: String,
actual: String,
},
/// A Core byte span is out of range or not on a UTF-8 boundary. /// A Core byte span is out of range or not on a UTF-8 boundary.
SourceSpanInvalid { detail: String }, SourceSpanInvalid {
/// Trace does not bind to the current Analysis bytes. detail: String,
TraceStale { detail: String }, },
/// Observation v1 is malformed, mixed, out of order or violates the
/// selected observation policy.
ObservationInvalid {
detail: String,
},
/// Observation does not bind to the current Analysis bytes/source.
ObservationStale {
detail: String,
},
/// The CLI rejected an option combination before starting (exit code 2).
CoreOptionRejected {
detail: String,
},
/// The user did not confirm, or the requested mode/grants are not allowed. /// The user did not confirm, or the requested mode/grants are not allowed.
RunDenied { detail: String }, RunDenied {
detail: String,
},
/// Path escapes the allowed project root or is otherwise forbidden. /// Path escapes the allowed project root or is otherwise forbidden.
PathForbidden { detail: String }, PathForbidden {
detail: String,
},
/// Refused a bind address that is not explicitly allowed. /// Refused a bind address that is not explicitly allowed.
BindDenied { detail: String }, BindDenied {
detail: String,
},
/// Embedded asset digest mismatch (build/package integrity). /// Embedded asset digest mismatch (build/package integrity).
AssetIntegrity { detail: String }, AssetIntegrity {
detail: String,
},
/// Export target is unsafe or the write failed. /// Export target is unsafe or the write failed.
ExportFailed { detail: String }, ExportFailed {
detail: String,
},
ExportInvalid {
detail: String,
},
ExportUnavailable {
detail: String,
},
ExportSourceChanged {
detail: String,
},
/// A configured resource limit was exceeded. /// A configured resource limit was exceeded.
ResourceLimit { detail: String }, ResourceLimit {
detail: String,
},
/// Core subprocess could not be spawned. /// Core subprocess could not be spawned.
CoreSpawn { detail: String }, CoreSpawn {
detail: String,
},
/// The submitted run request failed schema/target/parameter validation. /// The submitted run request failed schema/target/parameter validation.
RunInvalid { detail: String }, RunInvalid {
detail: String,
},
/// The entry document has no resolvable `main`; View never substitutes one. /// The entry document has no resolvable `main`; View never substitutes one.
NoEntryFunction { detail: String }, NoEntryFunction {
detail: String,
},
/// A page/SSE/POST requires a valid local session cookie. /// A page/SSE/POST requires a valid local session cookie.
SessionRequired { detail: String }, SessionRequired {
detail: String,
},
/// Another explicit run is already active; View allows one at a time. /// Another explicit run is already active; View allows one at a time.
RunBusy { detail: String }, RunBusy {
detail: String,
},
/// The same client request id was reused with a different payload. /// The same client request id was reused with a different payload.
RunConflict { detail: String }, RunConflict {
detail: String,
},
/// The requested run id is unknown, expired or belongs to another session. /// The requested run id is unknown, expired or belongs to another session.
RunNotFound { detail: String }, RunNotFound {
detail: String,
},
/// Bounded capture of CLI stdout/stderr/JSON/trace exceeded the budget. /// Bounded capture of CLI stdout/stderr/JSON/trace exceeded the budget.
OutputLimit { detail: String }, OutputLimit {
/// The CLI exited but its `--json` document was missing or invalid. detail: String,
CoreProtocol { detail: String }, },
/// The CLI exited but its Observation v1 stream was missing or invalid.
CoreProtocol {
detail: String,
},
/// More than two concurrent SSE observers for one job. /// More than two concurrent SSE observers for one job.
SseBusy { detail: String }, SseBusy {
detail: String,
},
/// Core subprocess exceeded the View-level timeout and was killed. /// Core subprocess exceeded the View-level timeout and was killed.
CoreTimeout { detail: String }, CoreTimeout {
detail: String,
},
/// Local file system / HTTP I/O failure. /// Local file system / HTTP I/O failure.
Io { detail: String }, Io {
detail: String,
},
/// Feature intentionally not implemented in this build (honest status). /// Feature intentionally not implemented in this build (honest status).
Unsupported { detail: String }, Unsupported {
detail: String,
},
} }
impl ViewError { impl ViewError {
@@ -76,12 +145,17 @@ impl ViewError {
ViewError::AnalysisFailed { .. } => "view.analysis_failed", ViewError::AnalysisFailed { .. } => "view.analysis_failed",
ViewError::SourceMismatch { .. } => "view.source_mismatch", ViewError::SourceMismatch { .. } => "view.source_mismatch",
ViewError::SourceSpanInvalid { .. } => "view.source_span_invalid", ViewError::SourceSpanInvalid { .. } => "view.source_span_invalid",
ViewError::TraceStale { .. } => "view.trace_stale", ViewError::ObservationInvalid { .. } => "view.observation_invalid",
ViewError::ObservationStale { .. } => "view.observation_stale",
ViewError::CoreOptionRejected { .. } => "view.core_option_rejected",
ViewError::RunDenied { .. } => "view.run_denied", ViewError::RunDenied { .. } => "view.run_denied",
ViewError::PathForbidden { .. } => "view.path_forbidden", ViewError::PathForbidden { .. } => "view.path_forbidden",
ViewError::BindDenied { .. } => "view.bind_denied", ViewError::BindDenied { .. } => "view.bind_denied",
ViewError::AssetIntegrity { .. } => "view.asset_integrity", ViewError::AssetIntegrity { .. } => "view.asset_integrity",
ViewError::ExportFailed { .. } => "view.export_failed", ViewError::ExportFailed { .. } => "view.export_failed",
ViewError::ExportInvalid { .. } => "view.export_invalid",
ViewError::ExportUnavailable { .. } => "view.export_unavailable",
ViewError::ExportSourceChanged { .. } => "view.export_source_changed",
ViewError::ResourceLimit { .. } => "view.resource_limit", ViewError::ResourceLimit { .. } => "view.resource_limit",
ViewError::CoreSpawn { .. } => "view.core_spawn", ViewError::CoreSpawn { .. } => "view.core_spawn",
ViewError::CoreTimeout { .. } => "view.core_timeout", ViewError::CoreTimeout { .. } => "view.core_timeout",
@@ -107,6 +181,8 @@ impl ViewError {
| ViewError::PathForbidden { .. } | ViewError::PathForbidden { .. }
| ViewError::BindDenied { .. } | ViewError::BindDenied { .. }
| ViewError::SourceSpanInvalid { .. } | ViewError::SourceSpanInvalid { .. }
| ViewError::ObservationInvalid { .. }
| ViewError::CoreOptionRejected { .. }
| ViewError::Unsupported { .. } | ViewError::Unsupported { .. }
| ViewError::RunInvalid { .. } | ViewError::RunInvalid { .. }
| ViewError::NoEntryFunction { .. } | ViewError::NoEntryFunction { .. }
@@ -145,12 +221,19 @@ impl ViewError {
"view.analysis_failed" => "Core 静态检查失败;正文仍可阅读,语义标注已撤销。", "view.analysis_failed" => "Core 静态检查失败;正文仍可阅读,语义标注已撤销。",
"view.source_mismatch" => "当前源码与 Analysis 字节摘要不一致。", "view.source_mismatch" => "当前源码与 Analysis 字节摘要不一致。",
"view.source_span_invalid" => "语义位置超出源码或不在 UTF-8 边界。", "view.source_span_invalid" => "语义位置超出源码或不在 UTF-8 边界。",
"view.trace_stale" => "运行结果与当前 Analysis 不匹配,已标记为过期。", "view.observation_invalid" => "运行观察事件无效或不符合当前协议,已拒绝展示。",
"view.observation_stale" => "运行结果与当前 Analysis 不匹配,已标记为过期。",
"view.core_option_rejected" => {
"冻结核心在启动前拒绝了该选项组合( exit 2 );View 不会去掉参数重试。"
}
"view.run_denied" => "运行请求未获授权或被拒绝。", "view.run_denied" => "运行请求未获授权或被拒绝。",
"view.path_forbidden" => "请求的路径超出允许的项目根目录。", "view.path_forbidden" => "请求的路径超出允许的项目根目录。",
"view.bind_denied" => "拒绝绑定该网络地址。", "view.bind_denied" => "拒绝绑定该网络地址。",
"view.asset_integrity" => "内嵌资源摘要不一致。", "view.asset_integrity" => "内嵌资源摘要不一致。",
"view.export_failed" => "静态导出失败(输出目录不安全或写入失败)。", "view.export_failed" => "静态导出失败(输出目录不安全或写入失败)。",
"view.export_invalid" => "导出范围或隐私确认无效。",
"view.export_unavailable" => "本次执行尚无可导出的已验证终态。",
"view.export_source_changed" => "文档、依赖或图片已变更。请刷新并重新运行后再导出。",
"view.resource_limit" => "超过配置的资源上限。", "view.resource_limit" => "超过配置的资源上限。",
"view.core_spawn" => "无法启动冻结核心。", "view.core_spawn" => "无法启动冻结核心。",
"view.core_timeout" => "冻结核心执行超时,已终止。", "view.core_timeout" => "冻结核心执行超时,已终止。",
@@ -160,7 +243,7 @@ impl ViewError {
"view.run_busy" => "已有一次运行正在进行;本版本每个 View 服务只允许一个任务。", "view.run_busy" => "已有一次运行正在进行;本版本每个 View 服务只允许一个任务。",
"view.run_conflict" => "同一客户端请求 ID 携带了不同内容,拒绝执行。", "view.run_conflict" => "同一客户端请求 ID 携带了不同内容,拒绝执行。",
"view.run_not_found" => "运行任务不存在、已过期或不属于当前会话。", "view.run_not_found" => "运行任务不存在、已过期或不属于当前会话。",
"view.core_protocol" => "冻结核心退出但未给出合法的 --json 结果。", "view.core_protocol" => "冻结核心退出但未给出合法的 Observation v1 事件流。",
"view.sse_busy" => "该运行任务的 SSE 观察连接超过上限,请稍后重试。", "view.sse_busy" => "该运行任务的 SSE 观察连接超过上限,请稍后重试。",
"view.output_limit" => "执行输出超过 View 的接收上限,已停止接收。", "view.output_limit" => "执行输出超过 View 的接收上限,已停止接收。",
"view.io" => "本地 I/O 失败。", "view.io" => "本地 I/O 失败。",
@@ -198,12 +281,17 @@ impl ViewError {
| ViewError::ProtocolIncompatible { detail } | ViewError::ProtocolIncompatible { detail }
| ViewError::AnalysisFailed { detail } | ViewError::AnalysisFailed { detail }
| ViewError::SourceSpanInvalid { detail } | ViewError::SourceSpanInvalid { detail }
| ViewError::TraceStale { detail } | ViewError::ObservationInvalid { detail }
| ViewError::ObservationStale { detail }
| ViewError::CoreOptionRejected { detail }
| ViewError::RunDenied { detail } | ViewError::RunDenied { detail }
| ViewError::PathForbidden { detail } | ViewError::PathForbidden { detail }
| ViewError::BindDenied { detail } | ViewError::BindDenied { detail }
| ViewError::AssetIntegrity { detail } | ViewError::AssetIntegrity { detail }
| ViewError::ExportFailed { detail } | ViewError::ExportFailed { detail }
| ViewError::ExportInvalid { detail }
| ViewError::ExportUnavailable { detail }
| ViewError::ExportSourceChanged { detail }
| ViewError::ResourceLimit { detail } | ViewError::ResourceLimit { detail }
| ViewError::CoreSpawn { detail } | ViewError::CoreSpawn { detail }
| ViewError::CoreTimeout { detail } | ViewError::CoreTimeout { detail }
File diff suppressed because it is too large. Load diff
+49 -12
View File
@@ -1,8 +1,9 @@
//! View-owned run event log and SSE frames (`marqdo.view-run-events` v1). //! View-owned run event log and SSE frames (`marqdo.view-run-events` v1).
//! //!
//! This is View's own protocol, not a CLI protocol (RFC-VIEW-0002 §6.4). It //! This is View's own protocol, not a CLI protocol (RFC-VIEW-0002 §6.4). It
//! only carries four event types and a bounded, sequenced replay buffer; it is //! only carries View lifecycle frames plus already-normalized Observation v1
//! not an event bus and never carries token streams or per-instruction values. //! values and a bounded, sequenced replay buffer; it is not an event bus and
//! never carries token streams or per-instruction values.
use std::collections::VecDeque; use std::collections::VecDeque;
use std::sync::mpsc::{self, Receiver, SyncSender, TrySendError}; use std::sync::mpsc::{self, Receiver, SyncSender, TrySendError};
@@ -26,6 +27,7 @@ pub enum RunState {
Cancelled, Cancelled,
TimedOut, TimedOut,
Unavailable, Unavailable,
Incomplete,
} }
impl RunState { impl RunState {
@@ -39,6 +41,7 @@ impl RunState {
RunState::Cancelled => "cancelled", RunState::Cancelled => "cancelled",
RunState::TimedOut => "timed_out", RunState::TimedOut => "timed_out",
RunState::Unavailable => "unavailable", RunState::Unavailable => "unavailable",
RunState::Incomplete => "incomplete",
} }
} }
@@ -52,6 +55,7 @@ impl RunState {
RunState::Cancelled => "已取消", RunState::Cancelled => "已取消",
RunState::TimedOut => "超时", RunState::TimedOut => "超时",
RunState::Unavailable => "不可用", RunState::Unavailable => "不可用",
RunState::Incomplete => "观察未完成",
} }
} }
@@ -63,6 +67,7 @@ impl RunState {
| RunState::Cancelled | RunState::Cancelled
| RunState::TimedOut | RunState::TimedOut
| RunState::Unavailable | RunState::Unavailable
| RunState::Incomplete
) )
} }
} }
@@ -73,6 +78,7 @@ pub enum EventKind {
Complete, Complete,
Error, Error,
Snapshot, Snapshot,
Observation,
} }
impl EventKind { impl EventKind {
@@ -82,6 +88,7 @@ impl EventKind {
EventKind::Complete => "run.complete", EventKind::Complete => "run.complete",
EventKind::Error => "run.error", EventKind::Error => "run.error",
EventKind::Snapshot => "run.snapshot", EventKind::Snapshot => "run.snapshot",
EventKind::Observation => "run.observation",
} }
} }
} }
@@ -94,10 +101,11 @@ pub struct RunEvent {
pub at: String, pub at: String,
/// Safe parsed CLI result summary (never raw HTML/innerHTML material). /// Safe parsed CLI result summary (never raw HTML/innerHTML material).
pub result: Option<serde_json::Value>, pub result: Option<serde_json::Value>,
/// Verified Trace v2 summary, only after digest/binding checks. /// Verified Observation v1 summary, only after digest/binding checks.
pub trace: Option<serde_json::Value>, pub observation_summary: Option<serde_json::Value>,
/// `{code, message}` for terminal failures. /// `{code, message}` for terminal failures.
pub error: Option<serde_json::Value>, pub error: Option<serde_json::Value>,
pub observation: Option<serde_json::Value>,
} }
impl RunEvent { impl RunEvent {
@@ -113,12 +121,15 @@ impl RunEvent {
if let Some(result) = &self.result { if let Some(result) = &self.result {
data["result"] = result.clone(); data["result"] = result.clone();
} }
if let Some(trace) = &self.trace { if let Some(summary) = &self.observation_summary {
data["trace"] = trace.clone(); data["observation_summary"] = summary.clone();
} }
if let Some(error) = &self.error { if let Some(error) = &self.error {
data["error"] = error.clone(); data["error"] = error.clone();
} }
if let Some(observation) = &self.observation {
data["observation"] = observation.clone();
}
data data
} }
@@ -178,8 +189,9 @@ impl EventLog {
state, state,
at: utc_now(), at: utc_now(),
result: None, result: None,
trace: None, observation_summary: None,
error: None, error: None,
observation: None,
}; };
self.next_seq += 1; self.next_seq += 1;
self.last_state = state; self.last_state = state;
@@ -213,14 +225,20 @@ impl EventLog {
self.record(event) self.record(event)
} }
pub fn publish_observation(&mut self, observation: serde_json::Value) {
let mut event = self.next_event(EventKind::Observation, self.last_state);
event.observation = Some(observation);
self.record(event);
}
pub fn publish_complete( pub fn publish_complete(
&mut self, &mut self,
result: serde_json::Value, result: serde_json::Value,
trace: Option<serde_json::Value>, observation_summary: Option<serde_json::Value>,
) -> RunEvent { ) -> RunEvent {
let mut event = self.next_event(EventKind::Complete, RunState::Succeeded); let mut event = self.next_event(EventKind::Complete, RunState::Succeeded);
event.result = Some(result); event.result = Some(result);
event.trace = trace; event.observation_summary = observation_summary;
self.record(event) self.record(event)
} }
@@ -230,7 +248,7 @@ impl EventLog {
code: &str, code: &str,
message: &str, message: &str,
result: Option<serde_json::Value>, result: Option<serde_json::Value>,
trace: Option<serde_json::Value>, observation_summary: Option<serde_json::Value>,
) -> RunEvent { ) -> RunEvent {
let mut event = self.next_event(EventKind::Error, state); let mut event = self.next_event(EventKind::Error, state);
event.error = Some(serde_json::json!({ event.error = Some(serde_json::json!({
@@ -238,7 +256,7 @@ impl EventLog {
"message": message, "message": message,
})); }));
event.result = result; event.result = result;
event.trace = trace; event.observation_summary = observation_summary;
self.record(event) self.record(event)
} }
@@ -274,8 +292,9 @@ impl EventLog {
state: self.last_state, state: self.last_state,
at: utc_now(), at: utc_now(),
result: None, result: None,
trace: None, observation_summary: None,
error: None, error: None,
observation: None,
} }
} }
@@ -412,6 +431,24 @@ mod tests {
assert!(subscription.replay[0].result.is_some()); assert!(subscription.replay[0].result.is_some());
} }
#[test]
fn terminal_frame_carries_observation_summary_not_trace() {
let mut log = EventLog::new();
log.publish_observation(serde_json::json!({
"kind": "stdout.chunk",
"seq": 13,
"run_id": "core-run",
}));
let event = log.publish_complete(
serde_json::json!({"success": true}),
Some(serde_json::json!({"status": "verified"})),
);
let data = event.data("run-1");
assert!(data.get("trace").is_none());
assert_eq!(data["observation_summary"]["status"], "verified");
assert_eq!(data["result"]["success"], true);
}
#[test] #[test]
fn utc_formatting_is_stable() { fn utc_formatting_is_stable() {
assert_eq!(format_utc(0), "1970-01-01T00:00:00Z"); assert_eq!(format_utc(0), "1970-01-01T00:00:00Z");
+199
View File
@@ -0,0 +1,199 @@
//! A bounded projection retained only inside an existing terminal Job.
//!
//! The overlay is bound to the verified Observation v1 terminal (run id, state,
//! capture level, truncation) and to the exact pre-run Analysis bytes; it never
//! re-parses the CLI JSON and never widens the value consent the user gave.
use crate::execution::events::RunState;
use crate::execution::request::ExecutionPlan;
use crate::protocol::observation_v1::{EventCounts, RunProjection};
use crate::reader::assemble::StaticDocument;
use serde_json::{json, Value};
use std::collections::BTreeMap;
const MAX_TEXT: usize = 128 * 1024;
#[derive(Debug)]
pub struct TerminalExportCandidate {
pub document: String,
pub function_id: String,
pub label: String,
pub project_root_id: String,
pub module_id: String,
pub analysis_digest: String,
/// Analysis revision carried by the exact pre-run artifact (3).
pub analysis_version: u32,
pub source_sha256: String,
pub lock_digest: String,
pub media: BTreeMap<String, String>,
/// Observation v1 run id (`run.id`/`run_id`).
pub observation_run_id: String,
pub core_version: String,
pub mode: String,
pub terminal_at: String,
pub state: RunState,
pub value: Option<String>,
pub value_is_public_scalar: bool,
pub stdout: String,
pub stderr: String,
pub arguments: Vec<(String, String)>,
pub observation_status: String,
pub observation_counts: Option<BTreeMap<String, u64>>,
pub capture_level: String,
pub output_complete: bool,
pub result_complete: bool,
pub observation_truncated: bool,
}
impl TerminalExportCandidate {
pub(super) fn from_terminal(
state: RunState,
plan: &ExecutionPlan,
document: &StaticDocument,
result: &Value,
observation: Option<&RunProjection>,
) -> Option<Self> {
if !matches!(state, RunState::Succeeded | RunState::Failed) {
return None;
}
let observation = observation?;
if !observation.source_verified
|| result.get("source_verified").and_then(Value::as_bool) != Some(true)
{
return None;
}
let observation_status = result.get("observation_status").and_then(Value::as_str)?;
if !matches!(observation_status, "verified" | "truncated") {
return None;
}
let projection = &document.verified.projection;
let function = projection
.functions
.iter()
.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.
let (value, value_complete, value_is_public_scalar) =
match observation.result_value.as_ref() {
Some(run) if public_scalar_type(&run.ty) => {
let (text, complete) = bounded_text(Some(run.display.as_str()));
(Some(text), complete, true)
}
Some(_) => (None, false, false),
None => (None, true, false),
};
let observation_truncated = observation.truncated.is_some();
let observation_counts = Some(counts_map(&observation.counts));
Some(Self {
document: plan.document.to_string(),
function_id: function.id.clone(),
label: function.local_name.clone(),
project_root_id: projection.project_root_id.clone(),
module_id: projection.module_id.clone(),
analysis_digest: document.analysis_digest.clone(),
analysis_version: projection.schema_version,
source_sha256: document.source_sha256.clone(),
lock_digest: projection.lock_digest.clone(),
media: document.media_digests.clone(),
observation_run_id: observation.run_id.clone(),
core_version: projection.producer_version.clone(),
mode: plan.mode.as_str().to_string(),
terminal_at: crate::execution::events::utc_now(),
state,
value,
value_is_public_scalar,
stdout,
stderr,
arguments: plan.arguments.clone(),
observation_status: observation_status.to_string(),
observation_counts,
capture_level: observation.capture_level.clone(),
output_complete: result["output_complete"].as_bool() == Some(true)
&& stdout_complete
&& stderr_complete,
result_complete: state == RunState::Succeeded
&& !observation_truncated
&& value_complete,
observation_truncated,
})
}
pub(super) fn preview(&self) -> Value {
json!({
"label": self.label,
"value_bytes": self.value.as_ref().map(String::len),
"value": self.value,
"value_is_public_scalar": self.value_is_public_scalar,
"stdout_bytes": self.stdout.len(),
"stderr_bytes": self.stderr.len(),
"arguments_count": self.arguments.len(),
"observation_summary": self.observation_counts.is_some(),
"observation_status": self.observation_status,
"capture_level": self.capture_level,
"observation_truncated": self.observation_truncated,
"output_complete": self.output_complete,
"result_complete": self.result_complete,
})
}
}
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<String, u64> {
[
("total", counts.total()),
("call_enter", counts.call_enter),
("call_exit", counts.call_exit),
("branch_eval", counts.branch_eval),
("loop_iteration", counts.loop_iteration),
("control_break", counts.control_break),
("control_continue", counts.control_continue),
("return", counts.return_events),
("effect", counts.effect),
("other", counts.other),
]
.into_iter()
.map(|(kind, count)| (kind.to_string(), count as u64))
.collect()
}
fn bounded_text(value: Option<&str>) -> (String, bool) {
let Some(text) = value else {
return (String::new(), true);
};
let mut end = text.len().min(MAX_TEXT);
while !text.is_char_boundary(end) {
end -= 1;
}
(text[..end].to_string(), end == text.len())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn public_scalar_types_exclude_text_and_containers() {
for accepted in ["Int", "float", "Bool", "Unit", "none"] {
assert!(public_scalar_type(accepted), "{accepted}");
}
for rejected in ["Text", "List", "Map", "Table", "Memory", "Resource"] {
assert!(!public_scalar_type(rejected), "{rejected}");
}
}
#[test]
fn bounded_text_never_splits_utf8() {
let text = "é".repeat(MAX_TEXT);
let (bounded, complete) = bounded_text(Some(&text));
assert!(bounded.is_char_boundary(bounded.len()));
assert!(!complete);
}
}
+2 -1
View File
@@ -7,9 +7,10 @@
//! - `request`: schema/target/parameter/mode/grant validation //! - `request`: schema/target/parameter/mode/grant validation
//! - `process`: the one cancellable Core process adapter with bounded capture //! - `process`: the one cancellable Core process adapter with bounded capture
//! - `events`: bounded, sequenced View-owned run events and SSE frames //! - `events`: bounded, sequenced View-owned run events and SSE frames
//! - `controller`: single-job lifecycle, dedupe, cancel, Trace binding //! - `controller`: single-job lifecycle, dedupe, cancel, Observation v1 binding
pub mod controller; pub mod controller;
pub mod events; pub mod events;
pub mod export_candidate;
pub mod process; pub mod process;
pub mod request; pub mod request;
+17 -4
View File
@@ -85,7 +85,15 @@ pub fn run_bounded(
budget: &ProcessBudget, budget: &ProcessBudget,
cancel: Option<Arc<AtomicBool>>, cancel: Option<Arc<AtomicBool>>,
) -> ViewResult<ProcessOutcome> { ) -> ViewResult<ProcessOutcome> {
run_bounded_with_hook(bin, args, cwd, budget, cancel, Box::new(|| {})) run_bounded_with_hook(bin, args, cwd, budget, cancel, ProcessHooks::default())
}
type StdoutReader = Box<dyn FnOnce(std::process::ChildStdout) -> Captured + Send>;
#[derive(Default)]
pub struct ProcessHooks {
pub on_spawn: Option<Box<dyn FnOnce() + Send>>,
pub stdout: Option<StdoutReader>,
} }
/// Same as [`run_bounded`], with a hook invoked exactly once **after** the /// Same as [`run_bounded`], with a hook invoked exactly once **after** the
@@ -96,7 +104,7 @@ pub fn run_bounded_with_hook(
cwd: &Path, cwd: &Path,
budget: &ProcessBudget, budget: &ProcessBudget,
cancel: Option<Arc<AtomicBool>>, cancel: Option<Arc<AtomicBool>>,
on_spawn: Box<dyn FnOnce() + Send>, hooks: ProcessHooks,
) -> ViewResult<ProcessOutcome> { ) -> ViewResult<ProcessOutcome> {
let started = Instant::now(); let started = Instant::now();
let mut command = Command::new(bin); let mut command = Command::new(bin);
@@ -122,12 +130,17 @@ pub fn run_bounded_with_hook(
let mut child = command.spawn().map_err(|err| ViewError::CoreSpawn { let mut child = command.spawn().map_err(|err| ViewError::CoreSpawn {
detail: format!("spawn {}: {err}", bin.display()), detail: format!("spawn {}: {err}", bin.display()),
})?; })?;
on_spawn(); if let Some(on_spawn) = hooks.on_spawn {
on_spawn();
}
let stdout = child.stdout.take().expect("piped stdout"); let stdout = child.stdout.take().expect("piped stdout");
let stderr = child.stderr.take().expect("piped stderr"); let stderr = child.stderr.take().expect("piped stderr");
let stdout_cap = budget.max_stdout; let stdout_cap = budget.max_stdout;
let stderr_cap = budget.max_stderr; let stderr_cap = budget.max_stderr;
let stdout_thread = std::thread::spawn(move || read_bounded(stdout, stdout_cap)); let stdout_thread = std::thread::spawn(move || match hooks.stdout {
Some(read_stdout) => read_stdout(stdout),
None => read_bounded(stdout, stdout_cap),
});
let stderr_thread = std::thread::spawn(move || read_bounded(stderr, stderr_cap)); let stderr_thread = std::thread::spawn(move || read_bounded(stderr, stderr_cap));
let deadline = started + budget.wall_clock; let deadline = started + budget.wall_clock;
+128 -56
View File
@@ -1,14 +1,14 @@
//! Validation of the two-phase explicit run request (RFC-VIEW-0002 §6.3). //! Validation of the two-phase explicit run request (RFC-VIEW-0002 §6.3).
//! //!
//! The browser never sends a command: it sends a document, a target selected //! The browser never sends a command: it sends a document, a target selected
//! from Analysis v2, constant parameter expressions, the exact Analysis digest //! from Analysis v3, constant parameter expressions, the exact Analysis digest
//! it rendered, a mode and (for project mode) explicit fs globs. Everything is //! it rendered, a mode and (for project mode) explicit fs globs. Everything is
//! re-validated here and finally by the Core itself; the client cannot inject //! re-validated here and finally by the Core itself; the client cannot inject
//! cwd, flags, a binary path or shell text. //! cwd, flags, a binary path or shell text.
use crate::core_client::Grants; use crate::core_client::Grants;
use crate::error::{ViewError, ViewResult}; use crate::error::{ViewError, ViewResult};
use crate::protocol::analysis_v2::SemanticProjection; use crate::protocol::analysis_v3::SemanticProjection;
use crate::reader::source::SafeRelativePath; use crate::reader::source::SafeRelativePath;
use serde::Deserialize; use serde::Deserialize;
@@ -111,6 +111,7 @@ pub enum ExecutionTarget {
pub struct ExecutionPlan { pub struct ExecutionPlan {
pub document: SafeRelativePath, pub document: SafeRelativePath,
pub target: ExecutionTarget, pub target: ExecutionTarget,
pub function_id: String,
pub arguments: Vec<(String, String)>, pub arguments: Vec<(String, String)>,
pub mode: RunMode, pub mode: RunMode,
pub grants: Grants, pub grants: Grants,
@@ -122,17 +123,17 @@ impl ValidatedRequest {
/// Resolve the target and parameter names against the verified entry-module /// Resolve the target and parameter names against the verified entry-module
/// Analysis. Never accepts a dependency-module function id (RFC §6.3). /// Analysis. Never accepts a dependency-module function id (RFC §6.3).
pub fn plan_against(self, projection: &SemanticProjection) -> ViewResult<ExecutionPlan> { pub fn plan_against(self, projection: &SemanticProjection) -> ViewResult<ExecutionPlan> {
let target = match &self.target { let (target, function_id) = match &self.target {
RunTarget::Entry => { RunTarget::Entry => {
if resolve_main(projection).is_none() { let Some(function) = resolve_main(projection) else {
return Err(ViewError::NoEntryFunction { return Err(ViewError::NoEntryFunction {
detail: format!( detail: format!(
"{} 没有可调用的 main;请从函数面板选择一个 H2 Exec 函数", "{} 没有可调用的 main;请从函数面板选择一个 H2 Exec 函数",
self.document self.document
), ),
}); });
} };
ExecutionTarget::Entry (ExecutionTarget::Entry, function.id.clone())
} }
RunTarget::Function { function_id } => { RunTarget::Function { function_id } => {
let function = projection let function = projection
@@ -153,12 +154,16 @@ impl ValidatedRequest {
}; };
let label = canonical; let label = canonical;
validate_parameters(&self.parameters, projection, &function.id)?; validate_parameters(&self.parameters, projection, &function.id)?;
ExecutionTarget::Function { cli_name, label } (
ExecutionTarget::Function { cli_name, label },
function.id.clone(),
)
} }
}; };
Ok(ExecutionPlan { Ok(ExecutionPlan {
document: self.document, document: self.document,
target, target,
function_id,
arguments: self arguments: self
.parameters .parameters
.into_iter() .into_iter()
@@ -201,7 +206,7 @@ pub fn validate_request(body: &[u8]) -> ViewResult<ValidatedRequest> {
|| function_id.chars().any(|ch| ch.is_control() || ch == '\0') || function_id.chars().any(|ch| ch.is_control() || ch == '\0')
{ {
return Err(ViewError::RunInvalid { return Err(ViewError::RunInvalid {
detail: "function_id 必须来自 Analysis v2 且长度为 1..=512".to_string(), detail: "function_id 必须来自 Analysis 且长度为 1..=512".to_string(),
}); });
} }
} }
@@ -364,17 +369,21 @@ fn validate_glob(glob: &str) -> ViewResult<()> {
/// Resolve `main` exactly like the frozen CLI does for `run`: canonical name /// Resolve `main` exactly like the frozen CLI does for `run`: canonical name
/// first, then a unique local name. No fallback to any other function. /// first, then a unique local name. No fallback to any other function.
fn resolve_main(projection: &SemanticProjection) -> Option<(String, String)> { fn resolve_main(
if let Some(function) = projection.functions.iter().find(|function| { projection: &SemanticProjection,
canonical_name(&function.id, &projection.module_id) == "main" ) -> Option<&crate::protocol::analysis_v3::SemanticFunction> {
|| function.local_name == "main" projection
}) { .functions
return Some(( .iter()
canonical_name(&function.id, &projection.module_id), .find(|function| canonical_name(&function.id, &projection.module_id) == "main")
function.local_name.clone(), .or_else(|| {
)); let mut candidates = projection
} .functions
None .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 { fn unique_local_name(projection: &SemanticProjection, local_name: &str, id: &str) -> bool {
@@ -392,7 +401,7 @@ fn unique_local_name(projection: &SemanticProjection, local_name: &str, id: &str
canonical == local_name canonical == local_name
} }
/// Analysis v2 function ids are `<module id>::<canonical name>`. /// Analysis v3 function ids are `<module id>::<canonical name>`.
pub fn canonical_name(function_id: &str, module_id: &str) -> String { pub fn canonical_name(function_id: &str, module_id: &str) -> String {
function_id function_id
.strip_prefix(&format!("{module_id}::")) .strip_prefix(&format!("{module_id}::"))
@@ -447,44 +456,107 @@ mod tests {
use super::*; use super::*;
fn projection() -> SemanticProjection { fn projection() -> SemanticProjection {
use crate::protocol::analysis_v3::{
DocumentNode, FunctionParam, FunctionSignature, ModuleSummary, SemanticFunction,
};
use crate::reader::source::{sha256_hex, SourceSpan};
let module_id = "root:t@0.1.0::index.mq.md";
let source = "x".repeat(200); let source = "x".repeat(200);
let digest = crate::reader::source::sha256_hex(source.as_bytes()); let source_digest = sha256_hex(source.as_bytes());
let analysis = serde_json::json!({ SemanticProjection {
"schema": "marqdo.analysis", schema_version: 3,
"schema_version": 2, analysis_sha256: "a".repeat(64),
"producer": {"name": "marqdo", "version": "3.0.0-beta.1", "markdown_profile": "marqdo.md.v1"}, analysis_digest: format!("sha256:{}", "a".repeat(64)),
"project": {"root_id": "root:t@0.1.0", "identity_kind": "manifest", "lock_digest": "", "stdlib": null}, producer_version: "3.0.0-rc.4".to_string(),
"modules": [{ markdown_profile: "marqdo.md.v1".to_string(),
"id": "root:t@0.1.0::index.mq.md", project_root_id: "root:t@0.1.0".to_string(),
"package_instance_id": "root:t@0.1.0", identity_kind: "manifest".to_string(),
"relative_path": "index.mq.md", entry_module_id: module_id.to_string(),
"source_digest": digest, lock_digest: String::new(),
"units": [], manifest_digest: String::new(),
"functions": [ stdlib_version: None,
{"id": "root:t@0.1.0::index.mq.md::main", "unit_id": "u1", "local_name": "main", stdlib_digest: None,
"namespace": null, "span": {"start": 0, "end": 10}, "heading_span": {"start": 0, "end": 10}, stdlib_instance_id: None,
"signature": {"kind": "inferred", "params": []}, "body": [], "effects": ["unknown"]}, extensions: Vec::new(),
{"id": "root:t@0.1.0::index.mq.md::N.f", "unit_id": "u2", "local_name": "f", module_id: module_id.to_string(),
"namespace": "N", "span": {"start": 20, "end": 30}, "heading_span": {"start": 20, "end": 30}, package_instance_id: "root:t@0.1.0".to_string(),
"signature": {"kind": "explicit", "params": [ relative_path: "index.mq.md".to_string(),
{"name": "n", "required": true, "type": "Int", "default": null, "span": null} source_digest: source_digest.clone(),
]}, "body": [], "effects": ["unknown"]} source: source.clone(),
], document: DocumentNode {
"imports": [], "references": [], "calls": [], "resources": [] kind: "document".to_string(),
span: SourceSpan::new(0, source.len() as u64),
children: Vec::new(),
literal: None,
level: None,
setext: None,
ordered: None,
start: None,
tight: None,
task: None,
ticks: None,
fenced: None,
info: None,
display: None,
url: None,
title: None,
alignments: None,
header: None,
tag: None,
},
anchors: Vec::new(),
units: Vec::new(),
functions: vec![
SemanticFunction {
id: format!("{module_id}::main"),
unit_id: "u1".to_string(),
local_name: "main".to_string(),
namespace: None,
span: SourceSpan::new(0, 10),
heading_span: SourceSpan::new(0, 10),
signature: FunctionSignature {
kind: "inferred".to_string(),
params: Vec::new(),
},
effects: vec!["unknown".to_string()],
statements: Vec::new(),
},
SemanticFunction {
id: format!("{module_id}::N.f"),
unit_id: "u2".to_string(),
local_name: "f".to_string(),
namespace: Some("N".to_string()),
span: SourceSpan::new(20, 30),
heading_span: SourceSpan::new(20, 30),
signature: FunctionSignature {
kind: "explicit".to_string(),
params: vec![FunctionParam {
name: "n".to_string(),
ty: Some("Int".to_string()),
required: true,
default: None,
span: SourceSpan::new(24, 25),
}],
},
effects: vec!["unknown".to_string()],
statements: Vec::new(),
},
],
resources: Vec::new(),
imports: Vec::new(),
references: Vec::new(),
calls: Vec::new(),
diagnostics: Vec::new(),
warnings: Vec::new(),
modules: vec![ModuleSummary {
id: module_id.to_string(),
package_instance_id: "root:t@0.1.0".to_string(),
relative_path: "index.mq.md".to_string(),
source_digest,
source,
}], }],
"diagnostics": [] }
})
.to_string();
let source = "x".repeat(200);
let index = crate::reader::source::SourceIndex::new(&source);
crate::protocol::analysis_v2::verify_analysis(
analysis.to_string().as_bytes(),
&source,
&index,
"index.mq.md",
)
.map(|verified| verified.projection)
.unwrap_or_else(|err| panic!("fixture analysis must verify: {err}"))
} }
#[test] #[test]
+275 -133
View File
@@ -8,9 +8,12 @@ use crate::error::{ViewError, ViewResult};
use crate::reader::assemble::DocumentService; use crate::reader::assemble::DocumentService;
use crate::reader::assets::AssetBundle; use crate::reader::assets::AssetBundle;
use crate::reader::render::ReaderRenderer; use crate::reader::render::ReaderRenderer;
use crate::reader::snapshot::ExportResultOverlay;
use crate::reader::source::sha256_hex; use crate::reader::source::sha256_hex;
use crate::reader::source::SafeRelativePath; use crate::reader::source::SafeRelativePath;
use crate::scratch::ScratchDir;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::Arc;
const MANIFEST_SCHEMA: &str = "marqdo.view-export"; const MANIFEST_SCHEMA: &str = "marqdo.view-export";
@@ -29,8 +32,6 @@ pub struct ExportSummary {
} }
pub fn export(context: &DocumentService, options: &ExportOptions) -> ViewResult<ExportSummary> { pub fn export(context: &DocumentService, options: &ExportOptions) -> ViewResult<ExportSummary> {
let bundle = AssetBundle::get();
let renderer = ReaderRenderer::new();
let root = context.project().root().to_path_buf(); let root = context.project().root().to_path_buf();
let out = absolute_export_target(&options.out)?; let out = absolute_export_target(&options.out)?;
if out.starts_with(&root) { if out.starts_with(&root) {
@@ -44,149 +45,290 @@ pub fn export(context: &DocumentService, options: &ExportOptions) -> ViewResult<
} }
validate_existing_target(&out)?; validate_existing_target(&out)?;
let documents = context.project().list_documents()?;
if documents.is_empty() {
return Err(ViewError::ExportFailed {
detail: "项目内没有 .mq.md 文档可导出".to_string(),
});
}
let entry = context.project().entry().relative.clone();
let staging = staging_dir(&out)?; let staging = staging_dir(&out)?;
let result = (|| {
let result = (|| -> ViewResult<ExportSummary> { let entry = context.load(&context.project().entry().relative)?;
let assets_dir = staging.join("assets"); let site = build_site(context, &entry, &staging, !options.no_annotations, None)?;
let pages_dir = staging.join("pages");
std::fs::create_dir_all(&assets_dir)
.map_err(|err| ViewError::io(&format!("create {}", assets_dir.display()), err))?;
std::fs::create_dir_all(&pages_dir)
.map_err(|err| ViewError::io(&format!("create {}", pages_dir.display()), err))?;
// Assets: the exact same bytes Live serves.
let mut asset_manifest = Vec::new();
for asset in bundle.all() {
let name = if asset.extension == "css" && asset.name == "reader" {
bundle.hashed_css_name()
} else {
asset.hashed_name()
};
let bytes = if asset.extension == "css" && asset.name == "reader" {
bundle.css_bytes().to_vec()
} else {
asset.bytes.to_vec()
};
std::fs::write(assets_dir.join(&name), &bytes)
.map_err(|err| ViewError::io(&format!("write asset {name}"), err))?;
asset_manifest.push(serde_json::json!({
"path": format!("assets/{name}"),
"sha256": sha256_hex(&bytes),
"size": bytes.len(),
}));
}
let mut pages = Vec::new();
let mut file_manifest: Vec<serde_json::Value> = Vec::new();
for relative in &documents {
let model = context.load(relative)?;
let depth = relative.as_str().split('/').count();
let context =
crate::reader::render::RenderContext::static_export(depth, !options.no_annotations);
let page = renderer.render(&model, &context);
let page_path = pages_dir.join(format!("{}.html", relative.as_str()));
if let Some(parent) = page_path.parent() {
std::fs::create_dir_all(parent)
.map_err(|err| ViewError::io(&format!("create {}", parent.display()), err))?;
}
std::fs::write(&page_path, page.html.as_bytes())
.map_err(|err| ViewError::io(&format!("write {}", page_path.display()), err))?;
let page_sha = sha256_hex(page.html.as_bytes());
let page_rel = format!("pages/{}.html", relative.as_str());
file_manifest.push(serde_json::json!({
"path": page_rel,
"sha256": page_sha,
"size": page.html.len(),
}));
pages.push(serde_json::json!({
"relative_path": relative.as_str(),
"module_id": model.document.identity.module_id,
"source_sha256": sha256_hex(model.document.source.as_bytes()),
"source_status": model.source_status.data_value(),
"analysis_digest": model.semantic.as_ref().map(|semantic| semantic.analysis_digest.clone()),
"file": page_rel,
"sha256": page_sha,
"annotations": !options.no_annotations,
}));
}
// index.html is the same renderer output with site-root depth.
let entry_model = context.load(&entry)?;
let entry_context =
crate::reader::render::RenderContext::static_export(0, !options.no_annotations);
let index_page = renderer.render(&entry_model, &entry_context);
let index_path = staging.join("index.html");
std::fs::write(&index_path, index_page.html.as_bytes())
.map_err(|err| ViewError::io(&format!("write {}", index_path.display()), err))?;
let index_sha = sha256_hex(index_page.html.as_bytes());
file_manifest.push(serde_json::json!({
"path": "index.html",
"sha256": index_sha,
"size": index_page.html.len(),
}));
file_manifest.sort_by(|a, b| {
a["path"]
.as_str()
.unwrap_or("")
.cmp(b["path"].as_str().unwrap_or(""))
});
let manifest = serde_json::json!({
"schema": MANIFEST_SCHEMA,
"schema_version": 1,
"view": {
"name": "marqdo-view",
"version": env!("CARGO_PKG_VERSION"),
},
"compatibility": {
"marqdo": crate::protocol::tool_v1::PRODUCT_RANGE,
"tool_protocol": crate::protocol::tool_v1::TOOL_PROTOCOL,
"analysis": crate::protocol::tool_v1::ANALYSIS_PROTOCOL,
"trace": crate::protocol::tool_v1::TRACE_PROTOCOL,
"markdown_profile": "marqdo.md.v1",
},
"core_version": entry_model.core_version,
"entry": {
"relative_path": entry.as_str(),
"file": "index.html",
"sha256": index_sha,
},
"pages": pages,
"assets": asset_manifest,
"files": file_manifest,
"executed": false,
"note": "Static export only; reading or exporting never executes the document.",
});
let manifest_bytes =
serde_json::to_vec_pretty(&manifest).map_err(|err| ViewError::ExportFailed {
detail: format!("serialize export manifest: {err}"),
})?;
let manifest_path = staging.join("manifest.json");
std::fs::write(&manifest_path, &manifest_bytes)
.map_err(|err| ViewError::io(&format!("write {}", manifest_path.display()), err))?;
publish(&staging, &out)?; publish(&staging, &out)?;
Ok(ExportSummary { Ok(ExportSummary {
out, out,
pages: documents.len(), pages: site.pages,
files: file_manifest.len() + asset_manifest.len() + 1, files: site.entries.len(),
manifest_sha256: sha256_hex(&manifest_bytes), manifest_sha256: site.manifest_sha256,
}) })
})(); })();
if result.is_err() { if result.is_err() {
let _ = std::fs::remove_dir_all(&staging); let _ = std::fs::remove_dir_all(&staging);
} }
result result
} }
struct Site {
pages: usize,
entries: Vec<String>,
manifest_sha256: String,
}
struct SiteWriter<'a> {
root: &'a Path,
entries: std::collections::BTreeSet<String>,
remaining_bytes: usize,
}
impl SiteWriter<'_> {
fn write(&mut self, relative: &str, bytes: &[u8]) -> ViewResult<serde_json::Value> {
if relative.contains([':', '\\'])
|| SafeRelativePath::parse(relative).is_err()
|| relative
.split('/')
.any(|part| part.is_empty() || part == ".")
{
return Err(ViewError::ExportFailed {
detail: "unsafe static asset path".into(),
});
}
if self.entries.insert(relative.to_string()) {
self.remaining_bytes =
self.remaining_bytes
.checked_sub(bytes.len())
.ok_or_else(|| ViewError::ResourceLimit {
detail: "static package size limit exceeded".into(),
})?;
if self.entries.len() > 6_000 {
return Err(ViewError::ResourceLimit {
detail: "static package file limit exceeded".into(),
});
}
let path = self.root.join(relative);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)
.map_err(|err| ViewError::io("create static package directory", err))?;
}
std::fs::write(path, bytes)
.map_err(|err| ViewError::io("write static package file", err))?;
}
Ok(serde_json::json!({"path": relative, "sha256": sha256_hex(bytes), "size": bytes.len()}))
}
}
fn build_site(
context: &DocumentService,
entry_model: &crate::reader::model::PresentationModel,
staging: &Path,
annotations: bool,
overlay: Option<Arc<ExportResultOverlay>>,
) -> ViewResult<Site> {
let documents = context.project().list_documents()?;
let entry = SafeRelativePath::parse(&entry_model.document.identity.relative_path)?;
if !documents.contains(&entry) {
return Err(ViewError::ExportFailed {
detail: "entry document is missing".into(),
});
}
let mut writer = SiteWriter {
root: staging,
entries: Default::default(),
remaining_bytes: 96 * 1024 * 1024,
};
let bundle = AssetBundle::get();
let renderer = ReaderRenderer::new();
let mut assets = Vec::new();
for asset in bundle.all() {
if overlay.is_some() && asset.extension == "js" {
continue;
}
let (name, bytes) = if asset.name == "reader" && asset.extension == "css" {
(bundle.hashed_css_name(), bundle.css_bytes())
} else {
(asset.hashed_name(), asset.bytes)
};
assets.push(writer.write(&format!("assets/{name}"), bytes)?);
}
let mut pages = Vec::new();
let mut files = Vec::new();
let mut media_files = std::collections::BTreeMap::new();
for relative in &documents {
let loaded;
let model = if *relative == entry {
entry_model
} else {
loaded = context.load(relative)?;
&loaded
};
for media in model.media.values() {
let path = format!("media/{}", media.filename());
if let std::collections::btree_map::Entry::Vacant(entry) = media_files.entry(path) {
let mut record = writer.write(entry.key(), &media.bytes)?;
record["mime"] = serde_json::json!(media.mime);
entry.insert(record);
}
}
let depth = relative.as_str().split('/').count();
let mut settings = crate::reader::render::RenderContext::static_export(depth, annotations);
settings.snapshot_package = overlay.is_some();
settings.overlay = if *relative == entry {
overlay.clone()
} else {
None
};
let page = renderer.render(model, &settings);
let path = 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(),
"module_id": model.document.identity.module_id,
"source_sha256": sha256_hex(model.document.source.as_bytes()),
"source_status": model.source_status.data_value(),
"analysis_digest": model.semantic.as_ref().map(|semantic| &semantic.analysis_digest),
"file": path,
"sha256": file["sha256"],
"annotations": annotations,
}));
files.push(file);
}
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,
"schema_version": 1,
"view": {
"name": "marqdo-view",
"version": env!("CARGO_PKG_VERSION"),
"binary_sha256": current_view_sha256(),
},
"producers": {
"view": {
"name": "marqdo-view",
"version": env!("CARGO_PKG_VERSION"),
"binary_sha256": current_view_sha256(),
},
"cli": match context.core() {
Some(core) => serde_json::json!({
"version": entry_model.core_version,
"binary_sha256": sha256_file(core.bin()),
}),
None => serde_json::Value::Null,
},
},
"requires": {
"marqdo": crate::protocol::tool_v1::PRODUCT_RANGE,
"api_revision": crate::protocol::tool_v1::API_REVISION,
"analysis": crate::protocol::tool_v1::ANALYSIS_REVISION,
"observation": crate::protocol::tool_v1::OBSERVATION_REVISION,
"markdown_profile": "marqdo.md.v1",
},
"core_version": entry_model.core_version,
"entry": {"relative_path": entry.as_str(), "file": "index.html", "sha256": index_sha},
"pages": pages,
"assets": assets,
"files": files,
"executed": false,
"note": "Static export only; reading or exporting never executes the document.",
});
if let Some(overlay) = overlay {
manifest["schema_version"] = serde_json::json!(2);
manifest["source"] = serde_json::json!(overlay.source);
manifest["execution"] = serde_json::json!(overlay.execution);
manifest["scope"] = serde_json::json!("document");
manifest["executed_during_export"] = serde_json::json!(false);
if let Some(fields) = manifest.as_object_mut() {
fields.remove("executed");
fields.remove("note");
}
}
let manifest_bytes =
serde_json::to_vec_pretty(&manifest).map_err(|err| ViewError::ExportFailed {
detail: format!("serialize export manifest: {err}"),
})?;
writer.write("manifest.json", &manifest_bytes)?;
Ok(Site {
pages: documents.len(),
entries: writer.entries.into_iter().collect(),
manifest_sha256: sha256_hex(&manifest_bytes),
})
}
/// Lowercase hex SHA-256 of the running View executable, used to bind the
/// exported manifest to the exact producer binary. Never a machine path.
fn current_view_sha256() -> String {
let Ok(exe) = std::env::current_exe() else {
return "unavailable".to_string();
};
sha256_file(&exe)
}
fn sha256_file(path: &std::path::Path) -> String {
match std::fs::read(path) {
Ok(bytes) => sha256_hex(&bytes),
Err(_) => "unavailable".to_string(),
}
}
pub struct SnapshotArchive {
pub file: std::fs::File,
pub len: usize,
pub manifest_sha256: String,
_scratch: ScratchDir,
}
pub fn snapshot(
context: &DocumentService,
model: &crate::reader::model::PresentationModel,
overlay: ExportResultOverlay,
) -> ViewResult<SnapshotArchive> {
let temp = std::env::temp_dir()
.canonicalize()
.map_err(|err| ViewError::io("resolve temporary location", err))?;
if temp.starts_with(context.project().root()) {
return Err(ViewError::ExportFailed {
detail: "temporary location is inside the project".into(),
});
}
let scratch = ScratchDir::create("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 path = scratch.file("snapshot.zip");
let archive =
std::fs::File::create(&path).map_err(|err| ViewError::io("create snapshot ZIP", err))?;
let mut archive = zip::ZipWriter::new(archive);
let zip_error = |err: zip::result::ZipError| ViewError::ExportFailed {
detail: format!("package snapshot ZIP: {err}"),
};
let options = zip::write::SimpleFileOptions::default()
.compression_method(zip::CompressionMethod::Stored)
.unix_permissions(0o644);
for name in site.entries {
archive.start_file(&name, options).map_err(zip_error)?;
let mut file = std::fs::File::open(staging.join(name))
.map_err(|err| ViewError::io("open static snapshot file", err))?;
std::io::copy(&mut file, &mut archive)
.map_err(|err| ViewError::io("write snapshot file into ZIP", err))?;
}
archive.finish().map_err(zip_error)?;
let file = std::fs::File::open(path).map_err(|err| ViewError::io("open snapshot ZIP", err))?;
let len = file
.metadata()
.map_err(|err| ViewError::io("stat snapshot ZIP", err))?
.len() as usize;
Ok(SnapshotArchive {
file,
len,
manifest_sha256: site.manifest_sha256,
_scratch: scratch,
})
}
fn absolute_export_target(raw: &Path) -> ViewResult<PathBuf> { fn absolute_export_target(raw: &Path) -> ViewResult<PathBuf> {
let absolute = if raw.is_absolute() { let absolute = if raw.is_absolute() {
raw.to_path_buf() raw.to_path_buf()
+191
View File
@@ -0,0 +1,191 @@
//! Validate the selected session result against a freshly loaded document.
//! The output is an owned reader projection, independent of the job.
use crate::{
execution::{events::RunState, export_candidate::TerminalExportCandidate},
protocol::tool_v1,
reader::{
assemble::DocumentService,
media,
model::PresentationModel,
snapshot::{ExportResultOverlay, SnapshotContracts, SnapshotExecution, SnapshotSource},
source::{sha256_hex, SafeRelativePath},
},
ViewError, ViewResult,
};
use serde::Deserialize;
pub const MAX_EXPORT_REQUEST: usize = 8 * 1024;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ExportSelection {
schema: String,
schema_version: u32,
pub run_id: String,
document: String,
analysis_digest: String,
scope: Scope,
include: Include,
confirm_sensitive_output: bool,
#[serde(default)]
confirm_partial: bool,
client_export_request_id: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
enum Scope {
Document,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Include {
result_value: bool,
stdout: bool,
stderr: bool,
observation_summary: bool,
arguments: bool,
}
impl ExportSelection {
pub fn parse(body: &[u8]) -> ViewResult<Self> {
let invalid = || ViewError::ExportInvalid {
detail: "invalid v1 static export request".into(),
};
let selection: Self = serde_json::from_slice(body).map_err(|_| invalid())?;
let valid_token = |value: &str| {
!value.is_empty()
&& value.len() <= 128
&& value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
};
let path = SafeRelativePath::parse(&selection.document).map_err(|_| invalid())?;
let digest = selection
.analysis_digest
.strip_prefix("sha256:")
.ok_or_else(invalid)?;
if selection.schema != "marqdo.view-static-export-request"
|| selection.schema_version != 1
|| !matches!(selection.scope, Scope::Document)
|| selection.document.len() > 1024
|| path.as_str() != selection.document
|| !selection.document.ends_with(".mq.md")
|| digest.len() != 64
|| !digest
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
|| !valid_token(&selection.run_id)
|| !valid_token(&selection.client_export_request_id)
{
return Err(invalid());
}
Ok(selection)
}
pub fn prepare(
&self,
service: &DocumentService,
candidate: &TerminalExportCandidate,
) -> ViewResult<(PresentationModel, ExportResultOverlay)> {
let changed = || ViewError::ExportSourceChanged {
detail: "selected execution no longer matches the document".into(),
};
let invalid = || ViewError::ExportInvalid {
detail: "missing confirmation for selected fields or partial result".into(),
};
if self.document != candidate.document || self.analysis_digest != candidate.analysis_digest
{
return Err(changed());
}
if (self.include.stdout
|| self.include.stderr
|| self.include.arguments
|| self.include.result_value
&& candidate.value.is_some()
&& !candidate.value_is_public_scalar)
&& !self.confirm_sensitive_output
{
return Err(invalid());
}
if (candidate.state != RunState::Succeeded
|| !candidate.output_complete
|| !candidate.result_complete
|| candidate.observation_truncated
|| candidate.observation_status == "truncated")
&& !self.confirm_partial
{
return Err(invalid());
}
let document = SafeRelativePath::parse(&self.document)?;
let model = service.load(&document).map_err(|_| changed())?;
let analysis = model.semantic.as_ref().ok_or_else(changed)?;
if analysis.analysis_digest != candidate.analysis_digest
|| analysis.schema_version != candidate.analysis_version
|| analysis.project_root_id != candidate.project_root_id
|| analysis.module_id != candidate.module_id
|| analysis.lock_digest != candidate.lock_digest
|| sha256_hex(model.document.source.as_bytes()) != candidate.source_sha256
|| media::digests(&model.media) != candidate.media
|| !analysis
.functions
.iter()
.any(|function| function.id == candidate.function_id)
{
return Err(changed());
}
let overlay = ExportResultOverlay {
source: SnapshotSource {
project_root_id: candidate.project_root_id.clone(),
document: candidate.document.clone(),
module_id: candidate.module_id.clone(),
source_sha256: candidate.source_sha256.clone(),
analysis_digest: candidate.analysis_digest.clone(),
lock_digest: (!candidate.lock_digest.is_empty())
.then(|| candidate.lock_digest.clone()),
},
execution: SnapshotExecution {
included: true,
core_run_id: candidate.observation_run_id.clone(),
target: candidate.function_id.clone(),
core_version: candidate.core_version.clone(),
status: candidate.state.data_value(),
terminal_at: candidate.terminal_at.clone(),
source_verified: true,
observation_status: candidate.observation_status.clone(),
capture_level: candidate.capture_level.clone(),
result_complete: candidate.result_complete,
output_complete: candidate.output_complete,
observation_truncated: candidate.observation_truncated,
parameters: if self.include.arguments {
"included"
} else {
"omitted"
},
mode: candidate.mode.clone(),
contracts: SnapshotContracts {
api_revision: tool_v1::API_REVISION,
analysis: candidate.analysis_version,
observation: tool_v1::OBSERVATION_REVISION,
},
},
label: candidate.label.clone(),
value: self
.include
.result_value
.then(|| candidate.value.clone())
.flatten(),
stdout: self.include.stdout.then(|| candidate.stdout.clone()),
stderr: self.include.stderr.then(|| candidate.stderr.clone()),
observation_counts: self
.include
.observation_summary
.then(|| candidate.observation_counts.clone())
.flatten(),
arguments: self.include.arguments.then(|| candidate.arguments.clone()),
};
Ok((model, overlay))
}
}
+2
View File
@@ -12,8 +12,10 @@ pub mod core_client;
pub mod error; pub mod error;
pub mod execution; pub mod execution;
pub mod export; pub mod export;
pub mod export_result;
pub mod protocol; pub mod protocol;
pub mod reader; pub mod reader;
mod scratch;
pub mod server; pub mod server;
pub use cli::Cli; pub use cli::Cli;
-940
View File
@@ -1,940 +0,0 @@
//! Analysis v2 validation and static semantic projection.
//!
//! This module is the only consumer of the public Analysis JSON. It verifies
//! protocol identity first, then projects functions/units/statements/diagnostics
//! into View-owned types with **validated** source spans. A span that is out of
//! range or not on a UTF-8 boundary is dropped with an explicit View warning
//! instead of being pointed at nearby text (RFC-VIEW-0001 §4.3, §8.2).
use crate::error::{ViewError, ViewResult};
use crate::reader::source::{sha256_hex, sha256_prefixed, SourceIndex, SourceSpan};
use serde::Deserialize;
use serde_json::Value;
/// Stable DOM identity for one source-bound annotation, local to this document
/// and run. It is not a cross-edit identity.
pub fn source_id(module_id: &str, span: SourceSpan, kind: &str) -> String {
let material = format!("{module_id}\0{}:{}:{}", span.start, span.end, kind);
sha256_hex(material.as_bytes())[..16].to_string()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnitKind {
Root,
Namespace,
Function,
Knowledge,
Section,
Other,
}
#[derive(Debug, Clone)]
pub struct SemanticUnit {
pub id: String,
pub name: String,
pub level: u8,
pub kind: UnitKind,
pub function: Option<String>,
pub span: SourceSpan,
}
#[derive(Debug, Clone)]
pub struct FunctionParam {
pub name: String,
pub ty: String,
pub required: bool,
pub default: Option<String>,
pub span: Option<SourceSpan>,
}
#[derive(Debug, Clone)]
pub struct FunctionSignature {
pub kind: String,
pub params: Vec<FunctionParam>,
}
#[derive(Debug, Clone)]
pub struct SemanticFunction {
pub id: String,
pub unit_id: String,
pub local_name: String,
pub namespace: Option<String>,
pub span: SourceSpan,
pub heading_span: SourceSpan,
pub signature: FunctionSignature,
pub effects: Vec<String>,
pub statements: Vec<SemanticStatement>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StatementKind {
Assign,
Expression,
Branch,
Loop,
Return,
Other,
}
impl StatementKind {
pub fn label(&self) -> &'static str {
match self {
StatementKind::Assign => "赋值",
StatementKind::Expression => "表达式",
StatementKind::Branch => "条件分支",
StatementKind::Loop => "循环",
StatementKind::Return => "返回",
StatementKind::Other => "语句",
}
}
pub fn data_value(&self) -> &'static str {
match self {
StatementKind::Assign => "assign",
StatementKind::Expression => "expression",
StatementKind::Branch => "branch",
StatementKind::Loop => "loop",
StatementKind::Return => "return",
StatementKind::Other => "other",
}
}
}
#[derive(Debug, Clone)]
pub struct SemanticStatement {
pub kind: StatementKind,
/// Header span for control flow, payload span for simple statements.
pub span: SourceSpan,
/// For `if` arms and `while` conditions: the condition text span as the
/// compiler recorded it.
pub condition_span: Option<SourceSpan>,
pub arms: Vec<SemanticArm>,
pub body: Vec<SemanticStatement>,
/// Target name for assignments (local name or `index` form), for static
/// outline display only. Never a runtime value.
pub target: Option<String>,
}
#[derive(Debug, Clone)]
pub struct SemanticArm {
pub span: Option<SourceSpan>,
pub condition_span: Option<SourceSpan>,
pub body: Vec<SemanticStatement>,
}
impl SemanticFunction {
/// Depth-first statement walk in source order.
pub fn flattened_statements(&self) -> Vec<&SemanticStatement> {
let mut out = Vec::new();
for statement in &self.statements {
collect_statements(statement, &mut out);
}
out
}
}
fn collect_statements<'a>(statement: &'a SemanticStatement, out: &mut Vec<&'a SemanticStatement>) {
out.push(statement);
for arm in &statement.arms {
for child in &arm.body {
collect_statements(child, out);
}
}
for child in &statement.body {
collect_statements(child, out);
}
}
#[derive(Debug, Clone)]
pub struct StaticResource {
pub id: String,
pub kind: String,
pub span: SourceSpan,
pub content_digest: String,
pub language: Option<String>,
pub display: bool,
}
#[derive(Debug, Clone)]
pub struct StaticImport {
pub alias: String,
pub target: String,
pub resolved: Option<String>,
pub span: SourceSpan,
}
#[derive(Debug, Clone)]
pub struct StaticReference {
pub url: String,
pub span: SourceSpan,
pub state: String,
pub target_module: Option<String>,
pub target_unit: Option<String>,
}
#[derive(Debug, Clone)]
pub struct StaticCall {
pub state: String,
pub target: Option<String>,
pub function: Option<String>,
pub span: SourceSpan,
}
#[derive(Debug, Clone)]
pub struct CoreDiagnostic {
pub module: Option<String>,
pub relative_path: Option<String>,
pub span: Option<SourceSpan>,
pub line: Option<u64>,
pub column: Option<u64>,
pub severity: String,
pub code: String,
pub message: String,
pub hints: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct ViewWarning {
pub code: String,
pub message: String,
pub span: Option<SourceSpan>,
}
#[derive(Debug, Clone)]
pub struct ModuleSummary {
pub id: String,
pub package_instance_id: String,
pub relative_path: String,
pub source_digest: String,
}
#[derive(Debug, Clone)]
pub struct SemanticProjection {
pub analysis_sha256: String,
pub analysis_digest: String,
pub producer_version: String,
pub markdown_profile: String,
pub project_root_id: String,
pub identity_kind: String,
pub lock_digest: String,
pub stdlib_version: Option<String>,
pub module_id: String,
pub package_instance_id: String,
pub relative_path: String,
pub source_digest: String,
pub units: Vec<SemanticUnit>,
pub functions: Vec<SemanticFunction>,
pub resources: Vec<StaticResource>,
pub imports: Vec<StaticImport>,
pub references: Vec<StaticReference>,
pub calls: Vec<StaticCall>,
pub diagnostics: Vec<CoreDiagnostic>,
pub warnings: Vec<ViewWarning>,
pub modules: Vec<ModuleSummary>,
}
#[derive(Debug)]
pub struct VerifiedAnalysis {
pub projection: SemanticProjection,
}
impl SemanticProjection {
pub fn unit_for_heading(&self, span: SourceSpan, level: u8) -> Option<&SemanticUnit> {
self.units
.iter()
.filter(|unit| unit.level == level && unit.span.contains(span))
.min_by_key(|unit| unit.span.len())
}
pub fn function_by_heading(&self, span: SourceSpan) -> Option<&SemanticFunction> {
self.functions
.iter()
.find(|function| function.heading_span == span)
.or_else(|| {
self.functions
.iter()
.find(|function| function.span.contains(span))
})
}
/// All statements of all functions, flattened in deterministic order.
pub fn all_statements(&self) -> Vec<(&SemanticFunction, &SemanticStatement)> {
let mut out = Vec::new();
for function in &self.functions {
for statement in function.flattened_statements() {
out.push((function, statement));
}
}
out
}
/// The innermost statement whose span is contained in `inline_span`.
pub fn statement_for_inline(
&self,
inline_span: SourceSpan,
) -> Option<(&SemanticFunction, &SemanticStatement)> {
self.all_statements()
.into_iter()
.filter(|(_, statement)| {
statement.span.start >= inline_span.start
&& statement.span.end <= inline_span.end
&& !statement.span.is_empty()
})
.max_by_key(|(_, statement)| statement.span.start)
}
pub fn resource_for_span(&self, span: SourceSpan) -> Option<&StaticResource> {
self.resources
.iter()
.find(|resource| resource.span == span || resource.span.contains(span))
}
pub fn reference_for_span(&self, span: SourceSpan) -> Option<&StaticReference> {
self.references
.iter()
.find(|reference| reference.span == span || reference.span.contains(span))
}
}
// ---------------------------------------------------------------------------
// Raw protocol types (additive fields are tolerated and ignored).
// ---------------------------------------------------------------------------
#[derive(Debug, Deserialize)]
struct RawAnalysis {
schema: String,
schema_version: u32,
producer: RawProducer,
project: RawProject,
modules: Vec<RawModule>,
#[serde(default)]
diagnostics: Vec<RawDiagnostic>,
}
#[derive(Debug, Deserialize)]
struct RawProducer {
#[serde(default)]
name: String,
#[serde(default)]
version: String,
#[serde(default)]
markdown_profile: String,
}
#[derive(Debug, Deserialize)]
struct RawProject {
#[serde(default)]
root_id: String,
#[serde(default)]
identity_kind: String,
#[serde(default)]
lock_digest: String,
#[serde(default)]
stdlib: Option<RawStdlib>,
}
#[derive(Debug, Deserialize)]
struct RawStdlib {
#[serde(default)]
version: String,
}
#[derive(Debug, Deserialize)]
struct RawModule {
#[serde(default)]
id: String,
#[serde(default)]
package_instance_id: String,
#[serde(default)]
relative_path: String,
#[serde(default)]
source_digest: String,
#[serde(default)]
units: Vec<RawUnit>,
#[serde(default)]
functions: Vec<RawFunction>,
#[serde(default)]
imports: Vec<RawImport>,
#[serde(default)]
references: Vec<RawReference>,
#[serde(default)]
calls: Vec<RawCall>,
#[serde(default)]
resources: Vec<RawResource>,
}
#[derive(Debug, Deserialize)]
struct RawUnit {
#[serde(default)]
id: String,
#[serde(default)]
name: String,
#[serde(default)]
level: u8,
#[serde(default)]
kind: String,
#[serde(default)]
function: Option<String>,
#[serde(default)]
span: Option<SourceSpan>,
}
#[derive(Debug, Deserialize)]
struct RawFunction {
#[serde(default)]
id: String,
#[serde(default)]
unit_id: String,
#[serde(default)]
local_name: String,
#[serde(default)]
namespace: Option<String>,
#[serde(default)]
span: Option<SourceSpan>,
#[serde(default)]
heading_span: Option<SourceSpan>,
#[serde(default)]
signature: Option<RawSignature>,
#[serde(default)]
effects: Vec<String>,
#[serde(default)]
body: Vec<RawStatement>,
}
#[derive(Debug, Deserialize)]
struct RawSignature {
#[serde(default)]
kind: String,
#[serde(default)]
params: Vec<RawParam>,
}
#[derive(Debug, Deserialize)]
struct RawParam {
#[serde(default)]
name: String,
#[serde(default, rename = "type")]
ty: Option<String>,
#[serde(default)]
required: bool,
#[serde(default)]
default: Option<Value>,
#[serde(default)]
span: Option<SourceSpan>,
}
#[derive(Debug, Deserialize)]
struct RawStatement {
#[serde(default)]
kind: String,
#[serde(default)]
span: Option<SourceSpan>,
#[serde(default)]
condition_span: Option<SourceSpan>,
#[serde(default)]
arms: Vec<RawArm>,
#[serde(default)]
body: Vec<RawStatement>,
#[serde(default)]
target: Option<Value>,
}
#[derive(Debug, Deserialize)]
struct RawArm {
#[serde(default)]
span: Option<SourceSpan>,
#[serde(default)]
condition_span: Option<SourceSpan>,
#[serde(default)]
body: Vec<RawStatement>,
}
#[derive(Debug, Deserialize)]
struct RawResource {
#[serde(default)]
id: String,
#[serde(default)]
kind: String,
#[serde(default)]
span: Option<SourceSpan>,
#[serde(default)]
content_digest: String,
#[serde(default)]
language: Option<String>,
#[serde(default)]
display: bool,
}
#[derive(Debug, Deserialize)]
struct RawImport {
#[serde(default)]
alias: String,
#[serde(default)]
target: String,
#[serde(default)]
resolved: Option<String>,
#[serde(default)]
span: Option<SourceSpan>,
}
#[derive(Debug, Deserialize)]
struct RawReference {
#[serde(default)]
url: String,
#[serde(default)]
state: String,
#[serde(default)]
target_module: Option<String>,
#[serde(default)]
target_unit: Option<String>,
#[serde(default)]
span: Option<SourceSpan>,
}
#[derive(Debug, Deserialize)]
struct RawCall {
#[serde(default)]
state: String,
#[serde(default)]
target: Option<String>,
#[serde(default)]
function: Option<String>,
#[serde(default)]
span: Option<SourceSpan>,
}
#[derive(Debug, Deserialize)]
struct RawDiagnostic {
#[serde(default)]
module: Option<String>,
#[serde(default)]
relative_path: Option<String>,
#[serde(default)]
span: Option<SourceSpan>,
#[serde(default)]
line: Option<u64>,
#[serde(default)]
column: Option<u64>,
#[serde(default)]
severity: String,
#[serde(default)]
code: String,
#[serde(default)]
message: String,
#[serde(default)]
hints: Vec<String>,
}
// ---------------------------------------------------------------------------
// Validation
// ---------------------------------------------------------------------------
/// Verify Analysis bytes against the exact source and project the static facts.
///
/// Rejects protocol incompatibility and source-digest mismatch as errors; drops
/// individual invalid spans as warnings so the prose stays readable.
pub fn verify_analysis(
analysis_bytes: &[u8],
source: &str,
source_index: &SourceIndex,
expected_relative_path: &str,
) -> ViewResult<VerifiedAnalysis> {
let raw: RawAnalysis =
serde_json::from_slice(analysis_bytes).map_err(|err| ViewError::AnalysisFailed {
detail: format!("Analysis v2 is not valid JSON: {err}"),
})?;
if raw.schema != "marqdo.analysis" {
return Err(ViewError::ProtocolIncompatible {
detail: format!("unexpected Analysis schema {:?}", raw.schema),
});
}
if raw.schema_version != crate::protocol::tool_v1::ANALYSIS_PROTOCOL {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"Analysis schema_version {} is not supported (View implements v{})",
raw.schema_version,
crate::protocol::tool_v1::ANALYSIS_PROTOCOL
),
});
}
if raw.producer.name != "marqdo" {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"Analysis producer.name {:?} is not `marqdo`",
raw.producer.name
),
});
}
if raw.producer.markdown_profile != "marqdo.md.v1" {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"unexpected Markdown profile {:?}; this View targets marqdo.md.v1",
raw.producer.markdown_profile
),
});
}
if raw.project.root_id.is_empty() {
return Err(ViewError::AnalysisFailed {
detail: "Analysis project.root_id is empty".to_string(),
});
}
let actual_digest = sha256_hex(source.as_bytes());
let module = raw
.modules
.iter()
.find(|module| module.relative_path == expected_relative_path)
.ok_or_else(|| ViewError::AnalysisFailed {
detail: format!("Analysis has no module for {expected_relative_path}"),
})?;
if module.source_digest != actual_digest {
return Err(ViewError::SourceMismatch {
expected: module.source_digest.clone(),
actual: actual_digest,
});
}
let mut warnings = Vec::new();
let mut valid_span = |span: Option<SourceSpan>, what: &str| -> Option<SourceSpan> {
let span = span?;
if source_index.validate_span_bytes(source.as_bytes(), span) {
Some(span)
} else {
warnings.push(ViewWarning {
code: "view.source_span_invalid".to_string(),
message: format!("{what} 的字节区间超出源码或不在 UTF-8 边界,已跳过该标注"),
span: Some(span),
});
None
}
};
let units: Vec<SemanticUnit> = module
.units
.iter()
.filter_map(|unit| {
let span = valid_span(unit.span, "语义单元")?;
Some(SemanticUnit {
id: unit.id.clone(),
name: unit.name.clone(),
level: unit.level,
kind: match unit.kind.as_str() {
"root" => UnitKind::Root,
"namespace" => UnitKind::Namespace,
"function" => UnitKind::Function,
"knowledge" => UnitKind::Knowledge,
"section" => UnitKind::Section,
_ => UnitKind::Other,
},
function: unit.function.clone(),
span,
})
})
.collect();
let functions: Vec<SemanticFunction> = module
.functions
.iter()
.filter_map(|function| {
let span = valid_span(function.span, "函数范围")?;
let heading_span = valid_span(function.heading_span, "函数标题")?;
let statements = function
.body
.iter()
.filter_map(|statement| convert_statement(statement, &mut valid_span))
.collect();
Some(SemanticFunction {
id: function.id.clone(),
unit_id: function.unit_id.clone(),
local_name: function.local_name.clone(),
namespace: function.namespace.clone(),
span,
heading_span,
signature: FunctionSignature {
kind: function
.signature
.as_ref()
.map(|signature| signature.kind.clone())
.unwrap_or_default(),
params: function
.signature
.as_ref()
.map(|signature| {
signature
.params
.iter()
.map(|param| FunctionParam {
name: param.name.clone(),
ty: param.ty.clone().unwrap_or_default(),
required: param.required,
default: param.default.as_ref().map(compact_value),
span: param.span.filter(|span| {
source_index.validate_span_bytes(source.as_bytes(), *span)
}),
})
.collect()
})
.unwrap_or_default(),
},
effects: function.effects.clone(),
statements,
})
})
.collect();
let resources: Vec<StaticResource> = module
.resources
.iter()
.filter(|resource| matches!(resource.kind.as_str(), "formula" | "code"))
.filter_map(|resource| {
let span = valid_span(resource.span, "资源")?;
Some(StaticResource {
id: resource.id.clone(),
kind: resource.kind.clone(),
span,
content_digest: resource.content_digest.clone(),
language: resource.language.clone(),
display: resource.display,
})
})
.collect();
let imports: Vec<StaticImport> = module
.imports
.iter()
.filter_map(|import| {
Some(StaticImport {
alias: import.alias.clone(),
target: import.target.clone(),
resolved: import.resolved.clone(),
span: valid_span(import.span, "导入声明")?,
})
})
.collect();
let references: Vec<StaticReference> = module
.references
.iter()
.filter_map(|reference| {
Some(StaticReference {
url: reference.url.clone(),
state: reference.state.clone(),
target_module: reference.target_module.clone(),
target_unit: reference.target_unit.clone(),
span: valid_span(reference.span, "Markdown 引用")?,
})
})
.collect();
let calls: Vec<StaticCall> = module
.calls
.iter()
.filter_map(|call| {
Some(StaticCall {
state: call.state.clone(),
target: call.target.clone(),
function: call.function.clone(),
span: valid_span(call.span, "调用点")?,
})
})
.collect();
let diagnostics: Vec<CoreDiagnostic> = raw
.diagnostics
.iter()
.map(|diagnostic| {
let span = diagnostic
.span
.filter(|span| source_index.validate_span_bytes(source.as_bytes(), *span));
CoreDiagnostic {
module: diagnostic.module.clone(),
relative_path: diagnostic.relative_path.clone(),
span,
line: diagnostic.line,
column: diagnostic.column,
severity: if diagnostic.severity.is_empty() {
"error".to_string()
} else {
diagnostic.severity.clone()
},
code: diagnostic.code.clone(),
message: diagnostic.message.clone(),
hints: diagnostic.hints.clone(),
}
})
.collect();
let modules = raw
.modules
.iter()
.map(|module| ModuleSummary {
id: module.id.clone(),
package_instance_id: module.package_instance_id.clone(),
relative_path: module.relative_path.clone(),
source_digest: module.source_digest.clone(),
})
.collect();
Ok(VerifiedAnalysis {
projection: SemanticProjection {
analysis_sha256: sha256_hex(analysis_bytes),
analysis_digest: sha256_prefixed(analysis_bytes),
producer_version: raw.producer.version.clone(),
markdown_profile: raw.producer.markdown_profile.clone(),
project_root_id: raw.project.root_id.clone(),
identity_kind: raw.project.identity_kind.clone(),
lock_digest: raw.project.lock_digest.clone(),
stdlib_version: raw.project.stdlib.as_ref().map(|s| s.version.clone()),
module_id: module.id.clone(),
package_instance_id: module.package_instance_id.clone(),
relative_path: module.relative_path.clone(),
source_digest: module.source_digest.clone(),
units,
functions,
resources,
imports,
references,
calls,
diagnostics,
warnings,
modules,
},
})
}
fn convert_statement(
raw: &RawStatement,
valid_span: &mut impl FnMut(Option<SourceSpan>, &str) -> Option<SourceSpan>,
) -> Option<SemanticStatement> {
let span = valid_span(raw.span, "语句")?;
let kind = match raw.kind.as_str() {
"assign" => StatementKind::Assign,
"expression" => StatementKind::Expression,
"branch" => StatementKind::Branch,
"loop" => StatementKind::Loop,
"return" => StatementKind::Return,
_ => StatementKind::Other,
};
let body = raw
.body
.iter()
.filter_map(|child| convert_statement(child, valid_span))
.collect();
let arms = raw
.arms
.iter()
.map(|arm| SemanticArm {
span: valid_span(arm.span, "分支臂"),
condition_span: valid_span(arm.condition_span, "分支条件"),
body: arm
.body
.iter()
.filter_map(|child| convert_statement(child, valid_span))
.collect(),
})
.collect();
Some(SemanticStatement {
kind,
span,
condition_span: valid_span(raw.condition_span, "控制条件"),
arms,
body,
target: raw.target.as_ref().and_then(assignment_target_label),
})
}
fn assignment_target_label(target: &Value) -> Option<String> {
match target {
Value::String(name) => Some(name.clone()),
Value::Object(map) => {
if map.get("kind").and_then(Value::as_str) == Some("index") {
Some("索引赋值".to_string())
} else {
None
}
}
_ => None,
}
}
fn compact_value(value: &Value) -> String {
match value {
Value::String(text) => text.clone(),
other => {
let text = other.to_string();
if text.chars().count() > 40 {
format!("{}…", text.chars().take(40).collect::<String>())
} else {
text
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn analysis(schema_version: u32, digest: &str) -> Vec<u8> {
serde_json::json!({
"schema": "marqdo.analysis",
"schema_version": schema_version,
"producer": {"name": "marqdo", "version": "3.0.0-beta.1", "markdown_profile": "marqdo.md.v1"},
"project": {"root_id": "root:t@0.1.0", "identity_kind": "manifest", "lock_digest": "", "stdlib": null},
"modules": [{
"id": "root:t@0.1.0::index.mq.md",
"package_instance_id": "root:t@0.1.0",
"relative_path": "index.mq.md",
"source_digest": digest,
"units": [],
"functions": [],
"imports": [],
"references": [],
"calls": [],
"resources": []
}],
"diagnostics": []
})
.to_string()
.into_bytes()
}
#[test]
fn rejects_unknown_schema_major_and_profile() {
let source = "# hi\n";
let index = SourceIndex::new(source);
let digest = sha256_hex(source.as_bytes());
let err =
verify_analysis(&analysis(3, &digest), source, &index, "index.mq.md").unwrap_err();
assert_eq!(err.code(), "view.protocol_incompatible");
}
#[test]
fn rejects_digest_mismatch() {
let source = "# hi\n";
let index = SourceIndex::new(source);
let err = verify_analysis(&analysis(2, &"0".repeat(64)), source, &index, "index.mq.md")
.unwrap_err();
assert_eq!(err.code(), "view.source_mismatch");
}
#[test]
fn projects_valid_analysis() {
let source = "# hi\n";
let index = SourceIndex::new(source);
let digest = sha256_hex(source.as_bytes());
let verified =
verify_analysis(&analysis(2, &digest), source, &index, "index.mq.md").unwrap();
assert_eq!(verified.projection.project_root_id, "root:t@0.1.0");
assert_eq!(verified.projection.relative_path, "index.mq.md");
}
#[test]
fn source_id_is_deterministic_and_bounded() {
let span = SourceSpan::new(1, 5);
let id = source_id("mod", span, "statement");
assert_eq!(id.len(), 16);
assert_eq!(id, source_id("mod", span, "statement"));
assert_ne!(id, source_id("mod", span, "resource"));
}
}
File diff suppressed because it is too large. Load diff
+7 -3
View File
@@ -1,8 +1,12 @@
//! Public protocol adapters consumed by View. //! Public protocol adapters consumed by View.
//! //!
//! These modules are a **consumer** of the published CLI formats, never a //! These modules are a **consumer** of the published CLI formats, never a
//! second publisher or implementation of them (RFC-VIEW-0002 §5.3). //! second publisher or implementation of them. Each public boundary has
//! exactly one current decoder and one domain projection:
//! Analysis v3 (`marqdo.analysis`) and Observation v1 (`marqdo.observation`).
//! Retired formats are rejected, never decoded through a fallback.
pub mod analysis_v2; pub mod analysis_v3;
pub mod observation_v1;
pub mod tool_v1; pub mod tool_v1;
pub mod trace_v2; pub mod value_wire_v1;
File diff suppressed because it is too large. Load diff
+60 -83
View File
@@ -1,27 +1,30 @@
//! Product/protocol version negotiation with the frozen CLI. //! Current CLI Tool protocol constants (revision 1) and product identity.
//! //!
//! Version axes are independent (RFC-VIEW-0001 §4): product SemVer, //! A CLI Tool declares exact contract revisions in `tool.json`
//! Analysis major, Trace major and Tool protocol. We never infer one from //! (`requires.api_revision`, optional `analysis`/`observation`). There is no
//! another and never silently fall back to a latest-looking JSON. //! negotiation: the installed registration injects only `MARQDO_BIN` and
//! `MARQDO_API_REVISION`, and a mismatch is a hard, actionable error.
use crate::error::{ViewError, ViewResult}; use crate::error::{ViewError, ViewResult};
use semver::Version; use semver::Version;
/// Product range this View build targets. Must match `tool.json`. /// Product range this View build consumes. The rc.3 contract family is the
pub const PRODUCT_RANGE: &str = ">=3.0.0-beta.1,<4.0.0"; /// first public pre-release with Observation v1 and Tool revision 1.
pub const PRODUCT_RANGE: &str = ">=3.0.0-rc.3,<4.0.0";
/// Lowest compatible product version (inclusive). /// Lowest compatible product version (inclusive).
pub const MIN_PRODUCT: &str = "3.0.0-beta.1"; pub const MIN_PRODUCT: &str = "3.0.0-rc.3";
pub const TOOL_PROTOCOL: u32 = 1; /// CLI Tool API revision implemented by this View build.
pub const ANALYSIS_PROTOCOL: u32 = 2; pub const API_REVISION: u32 = 1;
pub const TRACE_PROTOCOL: u32 = 2; /// Public Analysis revision consumed by this View build.
pub const ANALYSIS_REVISION: u32 = 3;
/// Public Observation revision consumed by this View build.
pub const OBSERVATION_REVISION: u32 = 1;
/// Environment variables injected by CLI Tool Protocol v1. /// Environment variables injected by the CLI Tool registration.
pub const ENV_MARQDO_BIN: &str = "MARQDO_BIN"; pub const ENV_MARQDO_BIN: &str = "MARQDO_BIN";
pub const ENV_TOOL_PROTOCOL: &str = "MARQDO_TOOL_PROTOCOL"; pub const ENV_MARQDO_API_REVISION: &str = "MARQDO_API_REVISION";
pub const ENV_PROTOCOL_ANALYSIS: &str = "MARQDO_PROTOCOL_ANALYSIS";
pub const ENV_PROTOCOL_TRACE: &str = "MARQDO_PROTOCOL_TRACE";
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct CoreVersion { pub struct CoreVersion {
@@ -30,7 +33,7 @@ pub struct CoreVersion {
pub raw: String, pub raw: String,
} }
/// Parse the output of `marqdo --version` (`marqdo 3.0.0-beta.1`). /// Parse the output of `marqdo --version` (`marqdo 3.0.0-rc.4`).
pub fn parse_version_output(output: &str) -> ViewResult<CoreVersion> { pub fn parse_version_output(output: &str) -> ViewResult<CoreVersion> {
let line = output let line = output
.lines() .lines()
@@ -54,96 +57,70 @@ pub fn parse_version_output(output: &str) -> ViewResult<CoreVersion> {
}) })
} }
/// True when `version` is inside the product range without relying on /// True when `version` is inside the supported product range.
/// prerelease quirks of `semver::VersionReq`: any 3.x at or above the first
/// beta is accepted, so a later `3.1.0-beta.1` keeps working.
pub fn product_is_compatible(version: &Version) -> bool { pub fn product_is_compatible(version: &Version) -> bool {
let min = Version::parse(MIN_PRODUCT).expect("MIN_PRODUCT is valid SemVer"); let min = Version::parse(MIN_PRODUCT).expect("MIN_PRODUCT is valid SemVer");
version.major == 3 && version >= &min version.major == 3 && version >= &min
} }
/// Validate the negotiated environment for Tool Protocol v1. /// Validate the CLI-injected API revision, if present.
/// ///
/// Absence of `MARQDO_PROTOCOL_*` is allowed for a directly-run development /// Absence is allowed for a directly-run development binary (`--marqdo-bin`);
/// binary (`--marqdo-bin`), but presence of an unknown major is a hard error. /// a present-but-different revision is a hard error. The value is only a
pub fn negotiate_protocol_env( /// static expectation check, never a negotiation input.
tool_protocol: Option<&str>, pub fn validate_api_revision_env(raw: Option<&str>) -> ViewResult<()> {
analysis_protocol: Option<&str>, let Some(raw) = raw else {
trace_protocol: Option<&str>, return Ok(());
) -> ViewResult<()> { };
if let Some(raw) = tool_protocol { let value: u32 = raw
let value = parse_env_u32(ENV_TOOL_PROTOCOL, raw)?; .trim()
if value != TOOL_PROTOCOL { .parse()
return Err(ViewError::ProtocolIncompatible { .map_err(|_| ViewError::ProtocolIncompatible {
detail: format!( detail: format!("{ENV_MARQDO_API_REVISION}={raw:?} is not a positive integer"),
"{ENV_TOOL_PROTOCOL}={value} is not supported (this View implements protocol {TOOL_PROTOCOL})" })?;
), if value != API_REVISION {
}); return Err(ViewError::ProtocolIncompatible {
} detail: format!(
} "{ENV_MARQDO_API_REVISION}={value} is not supported; this View implements CLI Tool \
if let Some(raw) = analysis_protocol { API revision {API_REVISION}. Reinstall the rebuilt Tool bundle."
let value = parse_env_u32(ENV_PROTOCOL_ANALYSIS, raw)?; ),
if value != ANALYSIS_PROTOCOL { });
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"{ENV_PROTOCOL_ANALYSIS}={value} is not supported (this View requires Analysis v{ANALYSIS_PROTOCOL})"
),
});
}
}
if let Some(raw) = trace_protocol {
let value = parse_env_u32(ENV_PROTOCOL_TRACE, raw)?;
if value != TRACE_PROTOCOL {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"{ENV_PROTOCOL_TRACE}={value} is not supported (this View requires Trace v{TRACE_PROTOCOL})"
),
});
}
} }
Ok(()) Ok(())
} }
fn parse_env_u32(name: &str, raw: &str) -> ViewResult<u32> {
raw.trim()
.parse::<u32>()
.map_err(|_| ViewError::ProtocolIncompatible {
detail: format!("{name}={raw:?} is not a positive integer protocol version"),
})
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
#[test] #[test]
fn parses_official_version_line() { fn parses_official_version_line() {
let version = parse_version_output("marqdo 3.0.0-beta.1\n").unwrap(); let version = parse_version_output("marqdo 3.0.0-rc.4\n").unwrap();
assert_eq!(version.version.to_string(), "3.0.0-beta.1"); assert_eq!(version.version.to_string(), "3.0.0-rc.4");
assert!(product_is_compatible(&version.version)); assert!(product_is_compatible(&version.version));
} }
#[test] #[test]
fn rejects_stable_only_reinterpretation() { fn rejects_retired_and_future_product_lines() {
// 2.9.1 is the old product line and must never be accepted. for accepted in ["3.0.0-rc.3", "3.0.0-rc.4", "3.0.0", "3.1.0-beta.1"] {
let old = Version::parse("2.9.1").unwrap(); assert!(
assert!(!product_is_compatible(&old)); product_is_compatible(&Version::parse(accepted).unwrap()),
// A future major is rejected too. "{accepted} must be accepted"
assert!(!product_is_compatible(&Version::parse("4.0.0").unwrap())); );
// Later prereleases in the 3.x line remain compatible. }
assert!(product_is_compatible( for rejected in ["2.9.1", "3.0.0-beta.1", "3.0.0-rc.2", "4.0.0"] {
&Version::parse("3.1.0-beta.1").unwrap() assert!(
)); !product_is_compatible(&Version::parse(rejected).unwrap()),
assert!(product_is_compatible(&Version::parse("3.0.0").unwrap())); "{rejected} must be rejected"
);
}
} }
#[test] #[test]
fn negotiates_known_protocols_only() { fn api_revision_is_an_exact_expectation() {
assert!(negotiate_protocol_env(Some("1"), Some("2"), Some("2")).is_ok()); assert!(validate_api_revision_env(None).is_ok());
assert!(negotiate_protocol_env(None, None, None).is_ok()); assert!(validate_api_revision_env(Some("1")).is_ok());
assert!(negotiate_protocol_env(Some("2"), None, None).is_err()); assert!(validate_api_revision_env(Some("2")).is_err());
assert!(negotiate_protocol_env(None, Some("1"), None).is_err()); assert!(validate_api_revision_env(Some("one")).is_err());
assert!(negotiate_protocol_env(None, None, Some("3")).is_err());
assert!(negotiate_protocol_env(None, Some("two"), None).is_err());
} }
} }
Loaded 100 of 159 files, more files were not shown because too many files have changed in this diff. Show more