diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..4644fbe --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,47 @@ +name: ci + +on: + push: + pull_request: + workflow_dispatch: + +jobs: + frozen-acceptance: + name: frozen CLI acceptance (Tool install / SSE / export / browser) + runs-on: ubuntu-24.04 + env: + CARGO_TERM_COLOR: always + RUST_MIN_STACK: "8388608" + PLAYWRIGHT_BROWSERS_PATH: ${{ github.workspace }}/tests/.cache/pw-browsers + 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 + - uses: actions/setup-node@v4 + with: + node-version: "22" + - name: Fetch the official frozen core and verify its identity + shell: bash + run: | + set -euo pipefail + frozen="$(scripts/frozen-beta.sh fetch "$RUNNER_TEMP/marqdo-frozen")" + echo "MARQDO_BIN=$frozen" >> "$GITHUB_ENV" + - name: Install Chromium and run the full acceptance gate + run: | + (cd tests/browser && npm ci --no-audit --no-fund) + (cd tests/browser && npx playwright install --with-deps chromium) + scripts/acceptance.sh + - name: Upload acceptance evidence + uses: actions/upload-artifact@v4 + with: + name: view-evidence-${{ github.sha }} + path: | + dist/acceptance/manifest.json + dist/marqdo-view-*.tar.gz + dist/marqdo-view-*.tar.gz.sha256 + if-no-files-found: error diff --git a/.woodpecker.yml b/.woodpecker.yml index 129f90f..e0c3878 100644 --- a/.woodpecker.yml +++ b/.woodpecker.yml @@ -1,68 +1,26 @@ -# Woodpecker CI for marqdo-view. -# -# The contract/export/browser lanes need the frozen marqdo release archive. -# Provide it through a secret and extract it before the lane runs; the pipeline -# deliberately never builds the CLI from source. +# The published beta needs glibc 2.39. Use the matching Playwright image +# so the installed-tool tests get both Ubuntu Noble and Chromium. when: - event: [push, pull_request, manual] + - event: [pull_request, manual] + - event: push + branch: master steps: - code: - image: rust:1.85-bookworm - commands: - - export PATH="$HOME/.cargo/bin:$PATH" - - cargo fmt --all -- --check - - cargo clippy --all-targets -- -D warnings - - cargo test --locked - - cargo build --release --locked - - contract: - image: rust:1.85-bookworm - depends_on: [code] - environment: - MARQDO_ARCHIVE: - from_secret: marqdo_beta_archive - commands: - # CI maintainers must provide the official archive at $MARQDO_ARCHIVE or - # export MARQDO_BIN from a verified extracted release. Do not rebuild it. - - | - if [ -z "${MARQDO_ARCHIVE:-}" ]; then - echo "MARQDO_ARCHIVE secret missing; contract lane requires the frozen official archive" >&2 - exit 1 - fi - mkdir -p /tmp/marqdo && tar -xzf "$MARQDO_ARCHIVE" -C /tmp/marqdo - - export MARQDO_BIN="$(find /tmp/marqdo -maxdepth 2 -name marqdo -type f | head -1)" - - sha256sum "$MARQDO_BIN" - - MARQDO_BIN="$MARQDO_BIN" ./tools/test-contract.sh - - sha256sum "$MARQDO_BIN" - - export: - image: rust:1.85-bookworm - depends_on: [code] - environment: - MARQDO_ARCHIVE: - from_secret: marqdo_beta_archive - commands: - - mkdir -p /tmp/marqdo && tar -xzf "$MARQDO_ARCHIVE" -C /tmp/marqdo - - export MARQDO_BIN="$(find /tmp/marqdo -maxdepth 2 -name marqdo -type f | head -1)" - - cargo build --release --locked - - MARQDO_BIN="$MARQDO_BIN" ./tools/test-export.sh - - browser: + frozen-acceptance: image: mcr.microsoft.com/playwright:v1.49.0-noble - depends_on: [code] + environment: + PLAYWRIGHT_BROWSERS_PATH: /ms-playwright + RUST_MIN_STACK: "8388608" commands: - - apt-get update && apt-get install -y --no-install-recommends cargo rustc || true + - apt-get update + - apt-get install -y --no-install-recommends build-essential ca-certificates curl git python3 + - curl -fsSL --retry 3 https://sh.rustup.rs -o /tmp/marqdo-view-rustup.sh + - sh /tmp/marqdo-view-rustup.sh -y --profile minimal --default-toolchain 1.89.0 --component rustfmt --component clippy --no-modify-path - export PATH="$HOME/.cargo/bin:$PATH" - - cargo build --release --locked - - (cd tests/browser && npm install --no-audit --no-fund) - - MARQDO_BIN="$(find /tmp/marqdo -maxdepth 2 -name marqdo -type f | head -1)" ./tools/test-browser.sh - - release-bundle: - image: rust:1.85-bookworm - depends_on: [code] - commands: - - cargo build --release --locked - - MARQDO_BIN="" ./tools/package.sh - - sha256sum dist/marqdo-view-*.tar.gz - - tar -tzf dist/marqdo-view-*.tar.gz | sort + - (cd tests/browser && npm ci --no-audit --no-fund) + - | + frozen_dir="$(mktemp -d)" + MARQDO_BIN="$(scripts/frozen-beta.sh fetch "$frozen_dir")" + export MARQDO_BIN + scripts/acceptance.sh + cat dist/acceptance/manifest.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 30cb894..ee6b7ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,146 @@ 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. Protocol axes (Tool v1, Analysis v2, Trace v2) are versioned separately. -## [Unreleased] +`0.2.0` is the first release implementing RFC-VIEW-0002 end to end (SSE execution +loop, 7-route Live API, controlled project grants and Trace-bound annotations). +The earlier `0.1.0` development line was never published; its verified reader / +Analysis / export work is folded into this entry. + +## [0.2.0] - 2026-11-22 + +### Fixed during issue #2 acceptance + +- Terminate the HTTP/1.1 SSE body after the terminal frame, including a + replayed terminal frame. Preserve View Run Events v1 and flush every frame. +- Verify Chromium reconnects with the received event ID without resubmitting + the run. Exercise the installed Tool's Int, Unicode Text and List controls. +- Pin the official Beta archive in CI. Run the installed Tool, browser trace, + no-side-effect and artifact integrity checks in the acceptance gate. + +### Added (RFC-VIEW-0002 PR-05) + +- Trace v2 evidence binding hardened end to end: the SSE trace summary carries + per-event `source_id` only for verified entry-module spans, observed chips are + marked `data-annotation-source="trace"`, static anchors + `data-annotation-source="analysis"`, and grouped chips collapse >3 events per + anchor with a real count in `title`. +- Stale/invalid/truncated Trace semantics covered by tests: editing source during + a run yields `stale=true` with all anchors/source ids null; a mismatched Trace + digest yields `trace.status=invalid` while the run still succeeds; truncated + traces are reported without claiming complete coverage. +- ADR-0010 records the annotation/staleness strategy (inline keyed chips instead + of SVG curves, per RFC §4.4's allowed degradation). +- Browser regression at the RFC width matrix incl. 2048x1133, provenance/grouping + assertions, dark-theme run screenshot; evidence in `docs/evidence/PR-05/`. + +### Added (RFC-VIEW-0002 PR-04) + +- `src/server/{mod,routes,security,sse}.rs`: the fixed 7-route Live API with one + explicit execution entry. Removed `/api/health`, `/api/document`, + `/api/run` and `/api/clear-run`. +- SSE transport writes the `text/event-stream` response directly to the socket + and flushes every frame/heartbeat (tiny_http's chunked writer would delay + frames); heartbeats, `Last-Event-ID` replay, authoritative snapshots, 128-event + ring, terminal close and a max of two observers per run. +- Per-session `HttpOnly; SameSite=Strict` cookie + per-session CSRF token + (`X-View-CSRF`), exact same-origin `Origin`, loopback `Host` validation, + `Sec-Fetch-Site` cross-site rejection, JSON-only bounded run POSTs (64 KiB). +- Reader front-end now runs through one POST + EventSource: target form built + from Analysis signatures, text-only command preview, pure/project mode with + explicit fs read/write globs and second confirmation, cancel button, live + result/stdout/stderr/Trace panel, keyed source anchors (skipped when stale), + and no status polling. Run shell is hidden until an explicit run. +- New `tests/security/` suite (cookies/CSRF/CORS/symlink/Markdown/SSE session + isolation) and rewritten HTTP/SSE integration tests; browser suite updated for + EventSource, dark theme and the RFC width matrix (incl. 2048x1133). +- ADR-0009 records the SSE transport, session model and route decisions; evidence + in `docs/evidence/PR-04/` includes real Chromium logs/screenshots and a real + frozen-CLI run (285 Trace v2 events). + +### Added (RFC-VIEW-0002 PR-03) + +- Execution layer: `src/execution/{request,process,controller,events}.rs`. + - request validation per §6.3 (size/path/target/parameter/mode/fs grants) and + exact `function_id` -> CLI name resolution from Analysis v2; + - one cancellable process adapter (explicit argv, process group, + SIGTERM→2s→SIGKILL, bounded stdout/stderr, spawn hook, wall clock); the + CoreClient now uses the same adapter for `check`/`--version`; + - single active job, `client_request_id` + payload digest idempotency/409, + unique terminal states, cancellation, 128-event ring buffer with + `Last-Event-ID` replay/snapshot, and `marqdo.view-run-events` v1 frames; + - Trace v2 verification against the exact pre-run Analysis bytes with safe + event summaries; missing/invalid trace is reported without faking evidence. +- Explicit budgets on every run/call (`--fuel`, `--max-output`, `--timeout`, + trace limits) plus 4 MiB JSON/Trace bounded reads and `view.output_limit`. +- New `--run-timeout` option clamped to 1..=120 seconds (default 30). +- ADR-0008 records lifecycle/cancel-race/Trace-missing semantics. +- Tests: `tests/integration/execution.rs` with a real fake-Core executable + (accepted/running/terminal SSE-ready events, call argv, dedupe, busy, cancel, + session isolation, stale digest, grants, unavailable trace). + +### Changed (RFC-VIEW-0002 PR-02) + +- Restructured the crate into the RFC-VIEW-0002 §5.3 layout: `src/protocol/ + {analysis_v2,trace_v2,tool_v1}.rs`, `src/reader/{source,markdown,model, + assemble,render,assets}.rs`, `src/config.rs`; `lib.rs` is the composition + root and `app.rs`/`project.rs`/`semantic.rs`/`trace.rs`/`document.rs`/ + `presentation.rs`/`source_map.rs`/`render.rs`/`assets.rs` are gone. +- Replaced `GET /api/document` with the read-only `GET /api/documents` + (documents list + current outline/function/analysis summary). +- Reading UI: removed variable/memory placeholder menu entries (one explicit + "unsupported capability" explanation remains), added a simple dark theme + toggle with a single token override layer and persisted preference. +- Reorganized tests into Cargo `[[test]]` suites: `tests/contract/` (CLI/Tool/ + Analysis/Trace/coupling/assets) and `tests/integration/` (Live HTTP/renderer/ + Unicode/export); `tests/fixtures`, `tests/golden`, `tests/browser` unchanged. + +### Changed (RFC-VIEW-0002 PR-01) + +- View product version is now `0.2.0` (`Cargo.toml`, `tool.json`, binary + `--version`), still independent from the CLI product version. +- Scripts moved from `tools/` to `scripts/` per RFC-VIEW-0002 §5.3; added + `scripts/verify-frozen-cli.sh` (records version/SHA and fails if the frozen + CLI changes across a command sequence). +- Added `.github/workflows/ci.yml`: quality lane (fmt/clippy/test/build) plus a + frozen-CLI acceptance lane that verifies the release archive SHA, runs the + one-command acceptance and uploads evidence. `.woodpecker.yml` updated to the + new script paths. +- Tool v1 packaging now emits `0.2.0`; install/dispatch/tamper behaviour is + re-verified against the frozen `3.0.0-beta.1` CLI. + +### Added (RFC-VIEW-0002 PR-06) + +- Five RFC §13.3 example documents at `examples/{welcome,branch-loop, + function-params,knowledge-only,unsafe-side-effect}.mq.md` plus explicit + `examples/view.json`; all are checked with the frozen CLI and recorded via + `scripts/check-examples.sh` (double(5)=Int 10, branch-loop=Int 0 with + loop/return Trace, knowledge-only has no main, unsafe-side-effect writes only + with explicit project grants). +- `scripts/test-no-exec.sh`: opens/lists/searches/reloads/exports the + unsafe-side-effect document, hashes every example source and the lock file, + asserts no write sentinel appears and that exported HTML contains no run + controls, CSRF material or external URLs. +- Static export no longer renders run controls: no run Dock button, no run tab, + no call buttons and no run dialog; only settings/more remain offline. +- `scripts/acceptance.sh` extended with `examples_check` and `no_exec_suite` + gates and refreshed evidence manifest schema (`tests.examples`, `tests.no_exec`). +- Final documentation closure: `docs/ACCEPTANCE.md` rewritten against + RFC-VIEW-0002 §9/§10, STATUS/CONFORMANCE/README/COMPATIBILITY updated, final + evidence manifest generated from the frozen CLI release (CLI SHA unchanged). + +### Changed (RFC-VIEW-0002 PR-00) + +- Adopted `docs/architecture/RFC-VIEW-0002.md` as the sole implementation + baseline for execution, scope, SSE, UI routes and release gates; RFC-0001 is + archived as historical design (ADR-0007). +- Moved specs to `docs/architecture/` and decisions to `docs/decisions/`. +- Added `docs/audits/legacy-view.md` (static legacy evidence with + `KEEP_ASSET/REIMPLEMENT/DROP/UNKNOWN` decisions and `LEGACY_RUNTIME_UNVERIFIED` + declaration), `docs/audits/protocol-contract-0002.md` (frozen CLI black-box + contract), `docs/CONFORMANCE.md` (living RFC-VIEW-0002 matrix) and refreshed + `docs/STATUS.md` with the remaining 0002 gaps. +- No source behaviour changed in this step; the tracked 0001 implementation is + unchanged and still passes its tests while PR-02..PR-06 migration proceeds. ### Added @@ -71,7 +210,7 @@ Protocol axes (Tool v1, Analysis v2, Trace v2) are versioned separately. search, settings, 7 viewport widths without horizontal overflow or dock clipping, no-JS reading, print mode, explicit run + clear. - Screenshot evidence for the Welcome page (1664×920, 390×844) and a real - Trace run page in `docs/evidence/PR-03/`. + Trace run page in `docs/evidence/0001-pr03/`. - Meta CSP no longer carries the ignored `frame-ancestors` directive (the HTTP header still enforces framing). diff --git a/COMPATIBILITY.md b/COMPATIBILITY.md index 8074734..6408e56 100644 --- a/COMPATIBILITY.md +++ b/COMPATIBILITY.md @@ -4,7 +4,7 @@ | 轴 | 本 View 值 | 说明 | |---|---|---| -| View 产品版本 | `0.1.0` | 独立 SemVer,与 CLI 不共用 | +| View 产品版本 | `0.2.0` | 独立 SemVer,与 CLI 不共用 | | `marqdo` 产品范围 | `>=3.0.0-beta.1,<4.0.0` | 安装与分发时由 CLI 强制校验 | | CLI Tool Protocol | `1` | `tool.json` 清单/整包摘要/分发 | | Analysis | `2` | 未知 major 直接拒绝,不回退 | @@ -17,7 +17,7 @@ Beta 版 CLI 必须使用 prerelease 范围(`>=3.0.0-beta.1,<4.0.0`);`>=3. | 平台 | 状态 | 说明 | |---|---|---| -| Linux x86_64 (glibc) | **Supported** | 与 CLI Beta 唯一发布目标一致 | +| Linux x86_64 (glibc 2.39+) | **Supported** | 完整验收使用官方 CLI Beta | | Linux aarch64 | 未构建 | 未验证 | | macOS / Windows | 未验证 | 不声明支持;路径/进程组逻辑留有平台分支,但未做实测 | @@ -28,19 +28,19 @@ Beta 版 CLI 必须使用 prerelease 范围(`>=3.0.0-beta.1,<4.0.0`);`>=3. | 原始 Markdown 只读浏览(GFM 表/列表/引用/代码围栏/数学文本) | **已实现**(PR-02) | | Analysis v2 静态语义(函数/Unit/诊断/引用/资源) | **已实现**(PR-02) | | 文档态 / 源码态切换 | **已实现**(PR-02) | -| 暖纸 Reader 视觉(单一 CSS/JS) | 计划 PR-03 | -| 用户显式触发运行 + Trace v2 事件可视化 | **已实现**(PR-04,仅 `pure` 模式,需页面内确认 + CSRF) | -| Live 本机安全 API | **已实现**(PR-02 只读 + PR-04 run + PR-05 并发/公开错误/导出) | +| 暖纸 Reader 视觉(单一 CSS/JS) | 已实现并经 Chromium 验收 | +| 用户显式触发运行 + SSE + Trace v2 事件可视化 | **已实现**(0002 PR-04;`pure`/受控 `project`,显式确认 + 会话 CSRF) | +| Live 本机安全 API(7 路由) | **已实现**(0002 PR-04;Cookie/CSRF/Origin/CSP/单任务/SSE) | | 静态离线导出(纯只读) | **已实现**(PR-05,同一渲染器) | | 逐语句变量值 / 参数实际值 / 内存快照 | **UNSUPPORTED**(Trace v2 不提供,绝不伪造) | | 知识“已证明”状态 | **UNSUPPORTED**(需要独立 Prove 协议与证书) | -| `project`/`strict` 运行与 grants 授权 | **未实现**(首版仅 `pure`,其他模式 403) | -| SSE 流式输出 / 取消运行 / 多运行历史 | **未实现**(运行后整页重载并保留位置) | +| `project` 运行与 fs grants | **已实现(受控)**:仅相对项目根 read/write glob,显式二次确认;其它权限拒绝 | +| SSE 状态推送 / 取消运行 / 事件重放 | **已实现**(逐帧 flush、心跳、Last-Event-ID、2 连接上限、无轮询) | | SVG 曲线侧注 | **未实现**(运行事件用内联 keyed chip,U-04 PARTIAL) | | 调试器/断点/单步 | **不实现**(首版非目标) | | Knowledge/Prove/Lint 引擎 | **不实现**(独立仓库/未来可选信息层) | -实际完成状态以 [`docs/STATUS.md`](docs/STATUS.md) 与 [`docs/ACCEPTANCE.md`](docs/ACCEPTANCE.md) 为准,本文不代替现状。远端 CI 未实际运行(`.woodpecker.yml` 已提供),本地冻结 CLI 验收证据见 `docs/evidence/`。 +实际完成状态以 [`docs/STATUS.md`](docs/STATUS.md) 与 [`docs/ACCEPTANCE.md`](docs/ACCEPTANCE.md) 为准,本文不代替现状。RFC-VIEW-0002 §10 门禁已按真实冻结 CLI + Chromium 验收 PASS;本地证据见 `docs/evidence/`。 ## 消费者契约 @@ -49,3 +49,9 @@ Beta 版 CLI 必须使用 prerelease 范围(`>=3.0.0-beta.1,<4.0.0`);`>=3. - `trace.source.root_id == analysis.project.root_id`;事件 `module_id` 必须存在于 Analysis。 - `trace.truncated != null` → `TRUNCATED`,不声明全部分支/循环已遍历。 - 运行只使用 `MARQDO_BIN` 子进程与公开 JSON;不链接 Core crate、不读 Core 源码、不依赖私有 IR。 + +## 官方 Beta 归档的标准库 + +`v3.0.0-beta.1` 的 Linux 归档未携带 `stdlib/`。View 的冻结验收示例使用 +该二进制公开的 Memory、stdout 和文件资源原语。含 `std:` 导入的项目由 +所选 Core 校验,缺少标准库时由 View 展示 Core 的诊断。 diff --git a/Cargo.lock b/Cargo.lock index 23b05e6..9fc11f5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -263,7 +263,7 @@ checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "marqdo-view" -version = "0.1.0" +version = "0.2.0" dependencies = [ "clap", "comrak", diff --git a/Cargo.toml b/Cargo.toml index 5bb8a96..19ea9ca 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,8 +1,8 @@ [package] name = "marqdo-view" -version = "0.1.0" +version = "0.2.0" edition = "2021" -rust-version = "1.85" +rust-version = "1.89" license = "MIT OR Apache-2.0" description = "Marqdo View: read .mq.md documents as documents, with optional verified Analysis v2 and Trace v2" repository = "https://github.com/cflmy/marqdo-view" @@ -14,6 +14,18 @@ categories = ["command-line-utilities", "documentation"] name = "marqdo-view" path = "src/main.rs" +[[test]] +name = "contract" +path = "tests/contract/main.rs" + +[[test]] +name = "security" +path = "tests/security/main.rs" + +[[test]] +name = "integration" +path = "tests/integration/main.rs" + [dependencies] clap = { version = "4.5", features = ["derive"] } serde = { version = "1", features = ["derive"] } diff --git a/README.md b/README.md index 8ede561..dd9f0dc 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,23 @@ # marqdo-view -Marqdo View 是一个独立的可执行文档阅读器:以**原始 Markdown 为阅读主体**,把冻结 +Marqdo View(`0.2.0`)是一个独立的可执行文档阅读器:以**原始 Markdown 为阅读主体**,把冻结 `marqdo` CLI 的静态语义(Analysis v2)与用户显式触发的真实运行轨迹(Trace v2) 附着回原文,而不是把文档翻译成另一套语言。 - 状态(唯一现状来源):[`docs/STATUS.md`](docs/STATUS.md) -- 验收结果与证据:[`docs/ACCEPTANCE.md`](docs/ACCEPTANCE.md) -- 架构规范:[`docs/RFC-VIEW-0001.md`](docs/RFC-VIEW-0001.md) -- 旧 View 静态审计:[`docs/audits/legacy-render-paths.md`](docs/audits/legacy-render-paths.md) -- 协议一致性:[`docs/audits/protocol-conformance.md`](docs/audits/protocol-conformance.md) +- **实施规范(当前)**:[`docs/architecture/RFC-VIEW-0002.md`](docs/architecture/RFC-VIEW-0002.md) +- 0002 合规矩阵:[`docs/CONFORMANCE.md`](docs/CONFORMANCE.md) +- 历史基础设计:[`docs/architecture/RFC-VIEW-0001.md`](docs/architecture/RFC-VIEW-0001.md) +- 旧 View 静态审计:[`docs/audits/legacy-view.md`](docs/audits/legacy-view.md) +- 冻结 CLI 合同审计:[`docs/audits/protocol-contract-0002.md`](docs/audits/protocol-contract-0002.md) - 兼容性:[`COMPATIBILITY.md`](COMPATIBILITY.md) / 变更:[`CHANGELOG.md`](CHANGELOG.md) +- 决策记录:[`docs/decisions/`](docs/decisions/) + +> **当前状态**:RFC-VIEW-0002 PR-00~PR-06 已完成,按 §10 发布门禁验收 +> **PASS**(真实冻结 CLI + 真实 Chromium;见 +> [`docs/ACCEPTANCE.md`](docs/ACCEPTANCE.md) 与 +> `docs/evidence//manifest.json`)。像素级人工比对与完整 +> screen-reader 走查仍为 `UNVERIFIED`,见 `docs/STATUS.md`。 ## 能力 @@ -17,12 +25,13 @@ Marqdo View 是一个独立的可执行文档阅读器:以**原始 Markdown |---|---| | 原始 Markdown + GFM 阅读、源码态、文档态 | ✅ | | Analysis v2 静态语义(函数/Unit/签名/诊断/导入/引用/资源) | ✅ 严格校验,span 无效则降级 | -| 本机 Live 阅读(默认 `127.0.0.1`,只读 API) | ✅ | -| 用户确认后运行 + 真实 Trace v2 可视化(`pure` 模式) | ✅ 需要页面内确认 + CSRF | +| 本机 Live 阅读(默认 `127.0.0.1`,只读 API + 显式执行端点) | ✅ | +| 显式确认后运行 + SSE 状态/取消 + 真实 Trace v2 | ✅ 单任务、无轮询、断线重放 | | 纯只读静态导出(离线 `file://`、manifest/哈希、原子发布) | ✅ | +| 单函数参数表单 + 受控 `project` fs grants | ✅ 参数来自 Analysis 签名;project 需显式 glob 二次确认 | +| SSE 状态推送 / 取消 / 断线重放(禁止轮询) | ✅ `POST /api/runs` + `GET …/events` + `POST …/cancel` | | 逐语句变量值 / 参数值 / 内存快照 | ❌ UNSUPPORTED(协议不提供,绝不伪造) | | 知识“已证明” / Prove / Lint / 调试器 | ❌ 非目标/等待独立协议 | -| `project`/`strict` 运行、SSE、多运行历史 | ❌ 未实现(首版仅 `pure`) | ## 安装 @@ -32,7 +41,7 @@ MARQDO_BIN=/absolute/path/to/marqdo "$MARQDO_BIN" --version # 2) 构建并制作 Tool v1 bundle -./tools/package.sh +./scripts/package.sh # → dist/marqdo-view/tool.json + dist/marqdo-view/bin/marqdo-view # 3) 安装为 `marqdo view` @@ -51,14 +60,20 @@ marqdo view examples/control-flow --port 0 --no-open marqdo view verify examples/mixed-modes/index.mq.md marqdo view verify examples/mixed-modes --refs --json +# RFC §13.3 示例(可检查/调用/运行;无隐式执行) +marqdo view examples/function-params.mq.md --no-open +marqdo view examples/unsafe-side-effect.mq.md --no-open + # 纯只读静态导出(永不执行;导出后可用 file:// 离线打开) marqdo view export examples/welcome --out ./site marqdo view export examples/mixed-modes --out ./site --no-annotations ``` -开发期可直接运行 `marqdo-view`(用 `--marqdo-bin` 指定冻结核心)。运行入口在 Live -页面中:点击“运行”→ 阅读风险说明 → 点击“确认运行”,才会调用冻结核心执行 -`--mode pure`;页面刷新/打开/搜索/导出都不会运行。 +开发期可直接运行 `marqdo-view`(用 `--marqdo-bin` 指定冻结核心)。运行只有一个入口: +Live 页面点击 Dock “运行”(执行 `main`)或函数面板的“调用”(执行 `call`), +阅读命令预览与权限说明后点击“确认执行”,服务端才 `POST /api/runs` 启动一个 +CLI 子进程;状态与结果通过 SSE 推送,可取消,断线可重放。页面刷新/打开/搜索/ +切换/导出都不会运行,也没有状态轮询。 ## 架构(强制约束) @@ -69,21 +84,25 @@ Reader UI(唯一 assets/reader.css + assets/reader.js) │ ReaderRenderer(唯一模板,Live/Export 共用) │ -PresentationModel(DocumentModel / SemanticProjection / RunProjection) +PresentationModel(reader::assemble / reader::model) │ -PublicCoreClient ─ MARQDO_BIN 子进程 + 公开 JSON(check --emit / run --trace-file) +CoreClient ─ MARQDO_BIN 子进程 + 公开 JSON(check --emit / run/call --trace-file) + │ +ExecutionController ─ 单任务、取消、SSE 事件(仅 POST /api/runs 可达) │ 冻结发布版 marqdo CLI(不修改、不重编译、不链接、不读源码) ``` - 单一 Rust package、单一渲染入口、单一主题文件;没有第二个 Markdown→语义管线。 +- 服务端只有 7 条固定路由;SSE 只推送 View 自有 `run.*` 生命周期事件。 - Analysis v2 是唯一语义权威:函数/语句/分支/循环/诊断均来自 `check --emit`, 源码字节 span 只用于绑定视觉位置。 - Trace v2 与 Analysis 字节摘要严格绑定;`STALE/TRUNCATED/FAILED/UNSUPPORTED` 状态显式呈现,不猜测未公开值。 - Live/Export 内容同源;导出绝不执行、绝不覆盖项目源文件或无关目录。 -- 门禁:`tests/no_coupling.rs` 拒绝旧 crate/源码依赖、第二套渲染器/主题、shell 执行; - `tests/asset_integrity.rs` 锁定内嵌资产与唯一主题层。 +- 门禁:`tests/contract/no_coupling.rs` 拒绝旧 crate/源码依赖、第二套渲染器/主题、shell 执行; + `tests/contract/asset_integrity.rs` 锁定内嵌资产与唯一主题层; + `tests/security/` 覆盖 CSRF/Origin/Cookie/路径/symlink/XSS/跨会话 SSE。 ## 开发与验收 @@ -95,36 +114,43 @@ cargo test --locked cargo build --release --locked ``` -全链路(Tool 安装、浏览、显式运行、导出、浏览器、安全、冻结内核 SHA 不变): +全链路验收使用 Rust 1.89 或更新版本,以及能运行官方 Beta 的 Linux x86_64 +环境(glibc 2.39 起)。浏览器、显式运行和离线导出通过已安装的 Tool 执行。 ```bash -export MARQDO_BIN=/absolute/path/to/frozen/marqdo -./tools/acceptance.sh +(cd tests/browser && npm ci && PLAYWRIGHT_BROWSERS_PATH="$PWD/../.cache/pw-browsers" npx playwright install chromium) +MARQDO_BIN="$(./scripts/frozen-beta.sh fetch "$(mktemp -d)")" +export MARQDO_BIN +./scripts/acceptance.sh +cat dist/acceptance/manifest.json ``` +也可将 `MARQDO_BIN` 指向已解包的官方 Beta。验收核对源码 SHA 和二进制 +SHA-256。 + 单独套件: ```bash -MARQDO_BIN=... ./tools/test-contract.sh # code + Tool v1 + verify + export -MARQDO_BIN=... ./tools/test-export.sh # 纯只读导出 + file:// Chromium -./tools/test-security.sh # HTTP/路径/XSS/导出对抗 +MARQDO_BIN=... ./scripts/check-examples.sh # RFC §13.3 示例真实 check/call/run +MARQDO_BIN=... ./scripts/test-no-exec.sh # 打开/导出零副作用哨兵 +MARQDO_BIN=... ./scripts/test-contract.sh # code + Tool v1 + verify + export +MARQDO_BIN=... ./scripts/test-export.sh # 纯只读导出 + file:// Chromium +./scripts/test-security.sh # HTTP/路径/XSS/导出对抗 (cd tests/browser && npm install && PLAYWRIGHT_BROWSERS_PATH="$PWD/../.cache/pw-browsers" npx playwright install chromium) -MARQDO_BIN=... ./tools/test-browser.sh # 真实 Chromium 视觉/交互/响应式/运行 +MARQDO_BIN=... ./scripts/test-browser.sh # 真实 Chromium 视觉/交互/响应式/运行 ``` -协议 golden 由冻结 CLI 生成,见 `tests/golden/README.md` 与 `tools/gen-golden.sh`。 +协议 golden 由冻结 CLI 生成,见 `tests/golden/README.md` 与 `scripts/gen-golden.sh`。 ## 已知限制(诚实状态) -- 首版运行只支持 `--mode pure`;`project`/`strict` 及 grants 授权界面未实现。 -- 运行完成后整页重载并保留阅读位置;无 SSE 流式输出/取消/多运行历史。 -- 变量实际值、参数值、内存快照、知识证明状态不在 Trace v2 中,UI 一律标 UNSUPPORTED。 -- 平台仅 Linux x86_64 glibc 正式验证;macOS/Windows 未验证。 -- 视觉自动化门禁 PASS,但参考截图的像素级人工比对仍未执行(`U-01 UNVERIFIED`); - SVG 曲线侧注未实现,运行事件以可访问的内联 chip 呈现(`U-04 PARTIAL`)。 -- 远端正 CI 未实际运行;`.woodpecker.yml` 已提供,本地验收证据完整。 - -## 许可 - -代码按 MIT / Apache-2.0 双许可发布(`LICENSE-MIT`、`LICENSE-APACHE`)。复用的旧 -View 视觉资产(Apache-2.0)来源与哈希见 `assets/licenses/ASSETS.md`。 +- 运行仅 `pure`(默认)与受控 `project` fs read/write;`strict`、网络/进程/环境/ + plugin/provider/kernel 授权不在首版 UI,必须使用终端 CLI。 +- `project` 不是 OS 沙箱;View 不继承 `marqdo.yaml` 的 capability 请求。 +- SSE 只推送 View 生命周期与终态数据,不承诺逐字 stdout/Token 流;Trace v2 不含 + 参数实际值/逐语句变量/内存快照。 +- 平台:仅 Linux x86_64 正式验证;Windows/macOS 不支持声明。 +- 远端 CI 配置已提供(`.github/workflows/ci.yml`),本环境未实际运行远端 CI; + 验收证据来自本地真实命令。 +- 像素级人工视觉比对与完整 screen-reader 走查为 `UNVERIFIED`(自动化几何/响应式/ + 无外部资源/无 JS/打印证据见 `docs/evidence/PR-04/`)。 diff --git a/assets/reader.css b/assets/reader.css index f32b2df..8eb93b7 100644 --- a/assets/reader.css +++ b/assets/reader.css @@ -40,6 +40,28 @@ --mq-dock-h: 66px; --mq-note-width: 176px; } + + /* Simple dark theme (RFC-VIEW-0002 §1.2 MVP SMALL): one token override + * layer, no theme framework, no remote skin. */ + .mq-reader[data-theme="dark"] { + color-scheme: dark; + --mq-paper: #1e1b17; + --mq-surface: #26221d; + --mq-surface-2: #2e2923; + --mq-surface-3: #3a332b; + --mq-ink: #ece5da; + --mq-strong: #f7f2ea; + --mq-muted: #ab9c89; + --mq-line: #3d362d; + --mq-line-strong: #5b5041; + --mq-gold: #d0a55f; + --mq-gold-soft: #8a6a37; + --mq-olive: #a3b482; + --mq-ok: #a3b482; + --mq-warn: #d7a55a; + --mq-error: #e08072; + --mq-focus: #e2b877; + } } @layer reset { @@ -1259,3 +1281,92 @@ } } } + +@layer interactions { + .mq-fn-call { + margin-left: 10px; + padding: 2px 10px; + border: 1px solid var(--mq-gold); + border-radius: 999px; + background: transparent; + color: var(--mq-gold); + font: 12px/1.6 var(--mq-sans); + cursor: pointer; + } + .mq-fn-call:hover { + background: var(--mq-gold-soft); + color: var(--mq-strong); + } + .mq-run-target { + margin: 4px 0 12px; + font: 13px/1.6 var(--mq-sans); + color: var(--mq-muted); + } + .mq-run-status { + font: 13px/1.6 var(--mq-sans); + color: var(--mq-ink); + } + .mq-run-params { + display: grid; + gap: 10px; + margin: 12px 0; + } + .mq-run-param { + display: flex; + flex-direction: column; + gap: 4px; + font: 12px/1.5 var(--mq-sans); + color: var(--mq-muted); + } + .mq-run-param input { + padding: 7px 10px; + border: 1px solid var(--mq-line-strong); + border-radius: 8px; + background: var(--mq-paper); + color: var(--mq-ink); + font: 13px/1.5 var(--mq-mono); + } + .mq-run-mode { + margin: 12px 0; + padding: 10px 12px; + border: 1px solid var(--mq-line); + border-radius: 10px; + font: 12px/1.6 var(--mq-sans); + } + .mq-run-mode legend { + padding: 0 6px; + color: var(--mq-muted); + } + .mq-run-mode label { + display: block; + margin: 4px 0; + } + .mq-run-grants { + display: grid; + gap: 8px; + margin: 10px 0; + font: 12px/1.6 var(--mq-sans); + } + .mq-run-grants textarea { + width: 100%; + margin-top: 4px; + padding: 8px 10px; + border: 1px solid var(--mq-line-strong); + border-radius: 8px; + background: var(--mq-paper); + color: var(--mq-ink); + font: 12px/1.5 var(--mq-mono); + resize: vertical; + } + .mq-run-command { + margin: 8px 0 12px; + padding: 10px 12px; + overflow-x: auto; + border: 1px dashed var(--mq-line-strong); + border-radius: 8px; + background: var(--mq-surface-2); + font: 12px/1.6 var(--mq-mono); + white-space: pre-wrap; + overflow-wrap: anywhere; + } +} diff --git a/assets/reader.js b/assets/reader.js index a188553..9717098 100644 --- a/assets/reader.js +++ b/assets/reader.js @@ -213,6 +213,22 @@ closeAllDialogs(); } + function applyTheme(theme, announce) { + var next = theme === "dark" ? "dark" : "light"; + reader.dataset.theme = next; + try { + window.localStorage.setItem("marqdo.view.theme", next); + } catch (error) { + /* storage is optional */ + } + if (announce) toast(next === "dark" ? "已切换到深色主题" : "已切换到暖纸主题"); + } + + function cycleTheme() { + applyTheme(reader.dataset.theme === "dark" ? "light" : "dark", true); + closeAllDialogs(); + } + function cycleTextSize() { var order = ["normal", "large", "small"]; var current = reader.dataset.size || "normal"; @@ -236,7 +252,7 @@ openDialog("mq-dialog-unsupported"); } - function handleAction(action) { + function handleAction(action, trigger) { switch (action) { case "mode-document": setMode("document"); @@ -272,41 +288,47 @@ case "annotations": toggleAnnotationVisibility(); break; - case "variables": + case "unsupported": showUnsupported( - "变量快照", - "Trace v2 不提供逐语句赋值后的实际值;View 只能展示 Analysis 中的静态参数与赋值目标,绝不猜测运行时数据。" + "变量快照 / 内存检查 / 调试器 / 证明状态", + "Trace v2 不提供逐语句赋值后的实际值或内存快照,公开协议也没有断点/单步通道;" + + "知识证明属于独立 Prove 工具。View 绝不猜测这些运行事实,相应能力在具备公开、受版本约束的协议前不会出现。" ); break; - case "memory": - showUnsupported( - "内存快照", - "当前公开协议没有内存观测通道;该能力需等待未来独立、受权限审计的调试协议。" - ); + case "theme": + cycleTheme(); break; case "about": openDialog("mq-dialog-about"); break; case "run": - if (reader.dataset.runAvailable === "true") { - openDialog("mq-dialog-run-confirm"); - } else { - showUnsupported( - "运行文档", - "当前页面没有可用的冻结核心或可执行入口;View 不会在缺少确认的情况下执行任何文档。" - ); - } + openRunForMain(); break; case "run-confirm": - confirmRun(); + submitRun(); + break; + case "cancel-run": + cancelRun(); + break; + case "call-function": + if (trigger) { + var params = []; + try { + params = JSON.parse(trigger.dataset.params || "[]"); + } catch (error) { + params = []; + } + openRunForm({ + kind: "function", + functionId: trigger.dataset.functionId, + label: trigger.dataset.functionLabel, + params: params + }); + } break; case "clear-run": - clearRun(); - break; case "clear": - var panel = $("#mq-run-panel"); - if (panel) panel.hidden = true; - toast("已清理本地展示状态(源文件与缓存未修改)"); + clearRun(); break; default: break; @@ -318,93 +340,538 @@ return meta ? meta.getAttribute("content") : ""; } - function setRunBusy(busy) { - var button = document.querySelector('.mq-dock-btn[data-action="run"]'); - if (!button) return; - if (busy) { - button.setAttribute("aria-busy", "true"); - button.dataset.busy = "true"; - button.disabled = true; - reader.dataset.runState = "running"; + var activeRun = null; + var pendingRun = null; + + function randomId() { + var bytes = new Uint8Array(16); + if (window.crypto && window.crypto.getRandomValues) { + window.crypto.getRandomValues(bytes); } else { - button.removeAttribute("aria-busy"); - delete button.dataset.busy; - button.disabled = false; + for (var i = 0; i < bytes.length; i += 1) bytes[i] = Math.floor(Math.random() * 256); + } + var out = ""; + for (var j = 0; j < bytes.length; j += 1) { + out += (bytes[j] < 16 ? "0" : "") + bytes[j].toString(16); + } + return "req-" + out; + } + + function csrfToken() { + var meta = document.querySelector('meta[name="mq-csrf-token"]'); + return meta ? meta.getAttribute("content") : ""; + } + + function stateLabel(state) { + switch (state) { + case "accepted": return "已接受"; + case "running": return "运行中"; + case "cancel_requested": return "正在取消"; + case "succeeded": return "成功"; + case "failed": return "失败"; + case "cancelled": return "已取消"; + case "timed_out": return "超时"; + case "unavailable": return "不可用"; + default: return String(state || "未知"); } } - function confirmRun() { - var dialog = $("#mq-dialog-run-confirm"); - var path = dialog ? dialog.dataset.path : ""; - var token = csrfToken(); - if (!path || !token) { - toast("缺少运行上下文或 CSRF 令牌,已拒绝运行"); + function isTerminalState(state) { + return ["succeeded", "failed", "cancelled", "timed_out", "unavailable"].indexOf(state) >= 0; + } + + function runPanel() { + return $("#mq-run-panel"); + } + + function setRunStatus(text) { + var status = $("#mq-run-status"); + if (status) status.textContent = text; + } + + function showRunPanel() { + var panel = runPanel(); + if (panel) panel.hidden = false; + } + + function setRunBusy(busy) { + var button = document.querySelector('.mq-dock-btn[data-action="run"]'); + if (button) { + if (busy) { + button.setAttribute("aria-busy", "true"); + button.dataset.busy = "true"; + button.disabled = true; + reader.dataset.runState = "running"; + } else { + button.removeAttribute("aria-busy"); + delete button.dataset.busy; + button.disabled = false; + } + } + var cancel = $("#mq-run-actions"); + if (cancel) cancel.hidden = !busy; + } + + function appendLine(container, tag, className, text) { + var node = document.createElement(tag); + if (className) node.className = className; + node.textContent = text; + container.appendChild(node); + return node; + } + + function clearRunOutput() { + ["#mq-run-summary", "#mq-run-stdout", "#mq-run-stderr", "#mq-run-events"].forEach(function (selector) { + var node = $(selector); + if (node) node.textContent = ""; + }); + var stdout = $("#mq-run-stdout"); + if (stdout) stdout.hidden = true; + var stderr = $("#mq-run-stderr"); + if (stderr) stderr.hidden = true; + var traceWrap = $("#mq-run-trace-wrap"); + if (traceWrap) traceWrap.hidden = true; + $$(".mq-run-chip[data-view-chip]").forEach(function (chip) { + chip.remove(); + }); + } + + function closeActiveObserver() { + if (activeRun && activeRun.source) { + try { + activeRun.source.close(); + } catch (error) { + /* optional */ + } + activeRun.source = null; + } + } + + function selectedMode() { + var checked = document.querySelector('input[name="mq-mode"]:checked'); + return checked ? checked.value : "pure"; + } + + function grantList(id) { + var field = document.getElementById(id); + if (!field) return []; + return field.value + .split("\n") + .map(function (line) { return line.trim(); }) + .filter(function (line) { return line.length > 0; }); + } + + function rawParams() { + var out = []; + $$("#mq-run-params [data-param-name]").forEach(function (input) { + out.push({ name: input.dataset.paramName, expression: input.value, required: input.dataset.required === "true" }); + }); + return out; + } + + function updateRunPreview() { + var preview = $("#mq-run-command"); + if (!preview || !pendingRun) return; + var mode = selectedMode(); + var parts = []; + if (pendingRun.kind === "entry") { + parts = ["marqdo", "run", reader.dataset.document, "--mode", mode, "--json", "--trace-file", "<临时文件>"]; + } else { + parts = ["marqdo", "call", reader.dataset.document, "<函数 " + pendingRun.label + ">", "--mode", mode, "--json", "--trace-file", "<临时文件>"]; + rawParams().forEach(function (param) { + parts.push("--arg"); + parts.push(param.name + "=" + (param.expression || "<常量表达式>")); + }); + } + if (mode === "project") { + grantList("mq-grant-read").forEach(function (glob) { parts.push("--allow-read"); parts.push(glob); }); + grantList("mq-grant-write").forEach(function (glob) { parts.push("--allow-write"); parts.push(glob); }); + } + preview.textContent = parts.join(" "); + var modeLabel = $("#mq-run-target-mode"); + if (modeLabel) modeLabel.textContent = mode; + } + + function renderRunParams(params) { + var container = $("#mq-run-params"); + if (!container) return; + container.textContent = ""; + if (!params.length) { + appendLine(container, "p", "mq-colophon", "该目标没有参数。"); return; } + params.forEach(function (param) { + var label = document.createElement("label"); + label.className = "mq-run-param"; + var title = document.createElement("span"); + var type = param.type ? ": " + param.type : ""; + var required = param.required ? "(必填)" : "(可选)"; + title.textContent = param.name + type + " " + required; + var input = document.createElement("input"); + input.type = "text"; + input.dataset.paramName = param.name; + input.dataset.required = param.required ? "true" : "false"; + input.spellcheck = false; + input.placeholder = param.default ? "默认常量:" + param.default : "常量表达式,例如 5 或 \"text\""; + if (param.required) input.setAttribute("aria-required", "true"); + input.addEventListener("input", updateRunPreview); + label.appendChild(title); + label.appendChild(input); + container.appendChild(label); + }); + } + + function openRunForm(target) { + var dialog = $("#mq-dialog-run"); + if (!dialog) { + toast("当前页面没有可用的运行表单;请确认已安装冻结核心"); + return; + } + pendingRun = { + kind: target.kind, + functionId: target.functionId || "", + label: target.label || "入口 main", + clientRequestId: randomId(), + params: target.params || [] + }; + var label = $("#mq-run-target-label"); + if (label) label.textContent = target.kind === "entry" ? "入口 main" : "函数 " + (target.label || ""); + renderRunParams(pendingRun.params); + var mode = document.querySelector('input[name="mq-mode"][value="pure"]'); + if (mode) mode.checked = true; + var grants = $("#mq-run-grants"); + if (grants) grants.hidden = true; + updateRunPreview(); + openDialog("mq-dialog-run"); + } + + function openRunForMain() { + if (reader.dataset.coreAvailable !== "true") { + showUnsupported( + "运行文档", + "当前页面没有可用的冻结核心(MARQDO_BIN),无法通过 CLI 执行;打开、刷新与导出仍然零副作用。" + ); + return; + } + if (reader.dataset.hasMain !== "true") { + toast("本文档没有可执行的 main;请从函数面板选择一个 H2 Exec 函数"); + showFunctions(); + return; + } + openRunForm({ kind: "entry", label: "入口 main" }); + } + + function submitRun() { + if (!pendingRun) return; + var params = rawParams(); + for (var i = 0; i < params.length; i += 1) { + if (params[i].required && params[i].expression.trim() === "") { + toast("缺少必填参数:" + params[i].name); + return; + } + } + var mode = selectedMode(); + var grants = mode === "project" + ? { read: grantList("mq-grant-read"), write: grantList("mq-grant-write") } + : { read: [], write: [] }; + if (mode === "project" && grants.read.length === 0 && grants.write.length === 0) { + toast("project 模式必须至少声明一个相对项目根的 fs read/write glob"); + return; + } + if (mode === "project" && + !window.confirm("project 模式将按你填写的 glob 授予文件读写权限。它仍不是操作系统沙箱,是否继续?")) { + return; + } + var payload = { + document: reader.dataset.document, + target: pendingRun.kind === "entry" + ? { kind: "entry" } + : { kind: "function", function_id: pendingRun.functionId }, + parameters: params.map(function (param) { + return { name: param.name, expression: param.expression }; + }), + analysis_digest: reader.dataset.analysisDigest, + mode: mode, + grants: grants, + client_request_id: pendingRun.clientRequestId + }; + closeAllDialogs(); + clearRunOutput(); + showRunPanel(); setRunBusy(true); - fetch("/api/run", { + setRunStatus("正在提交运行请求…"); + fetch("/api/runs", { method: "POST", credentials: "same-origin", cache: "no-store", headers: { "Content-Type": "application/json", "Accept": "application/json", - "X-MQ-CSRF": token + "X-View-CSRF": csrfToken() }, - body: JSON.stringify({ path: path, mode: "pure", confirm: true }) + body: JSON.stringify(payload) }) .then(function (response) { - return response.json().then(function (data) { - return { ok: response.ok, data: data }; - }); + return response.json().then(function (data) { return { ok: response.ok, status: response.status, data: data }; }); }) .then(function (result) { - if (!result.ok || !result.data || !result.data.ok) { + if (!result.ok || !result.data || !result.data.run_id) { setRunBusy(false); - var reason = result.data && result.data.message - ? result.data.message - : "运行被拒绝或失败"; - toast("运行未完成:" + reason); + var reason = result.data && result.data.message ? result.data.message : "运行请求被拒绝"; + setRunStatus("运行未启动(" + result.status + "):" + reason); + toast("运行未启动:" + reason); return; } - try { - window.sessionStorage.setItem( - "marqdo.view.scroll", - String(window.scrollY || 0) - ); - } catch (error) { - /* storage is optional */ - } - window.location.assign(result.data.redirect); + subscribeRun(result.data, pendingRun ? pendingRun.label : "运行"); }) .catch(function (error) { setRunBusy(false); + setRunStatus("运行请求失败:" + error.message); toast("运行请求失败:" + error.message); }); } + function subscribeRun(job, targetLabel) { + closeActiveObserver(); + activeRun = { + runId: job.run_id, + eventsUrl: job.events_url, + cancelUrl: job.cancel_url, + source: null, + lastSeq: -1, + targetLabel: targetLabel || "运行", + terminal: false + }; + clearRunOutput(); + showRunPanel(); + setRunStatus("状态:已接受 · " + activeRun.targetLabel); + if (!window.EventSource) { + setRunBusy(false); + setRunStatus("浏览器不支持 EventSource,无法接收运行状态;请使用现代浏览器。"); + return; + } + var source = new EventSource(job.events_url, { withCredentials: true }); + activeRun.source = source; + function apply(event) { + var data; + try { + data = JSON.parse(event.data); + } catch (error) { + return; + } + if (!data || + data.schema !== "marqdo.view-run-events" || + data.schema_version !== 1 || + data.run_id !== job.run_id || + !Number.isSafeInteger(data.seq) || + data.seq <= activeRun.lastSeq) { + return; + } + activeRun.lastSeq = data.seq; + updateRunView(data); + } + ["run.state", "run.complete", "run.error", "run.snapshot"].forEach(function (kind) { + source.addEventListener(kind, apply); + }); + source.onerror = function () { + if (activeRun && !activeRun.terminal) { + setRunStatus("SSE 连接中断,正在自动恢复…(任务仍在服务端运行;不会重新执行)"); + } + }; + } + + function updateRunView(data) { + var panel = runPanel(); + if (panel) { + panel.hidden = false; + panel.dataset.runState = data.state; + } + reader.dataset.runState = data.state; + setRunStatus("状态:" + stateLabel(data.state) + (data.at ? " · " + data.at : "")); + if (!isTerminalState(data.state)) { + setRunBusy(true); + return; + } + if (activeRun) activeRun.terminal = true; + closeActiveObserver(); + setRunBusy(false); + if (data.result) renderRunResult(data.result, data.state, data.error); + else if (data.error) renderRunResult(null, data.state, data.error); + if (data.trace) renderTrace(data.trace); + else if (data.result && data.result.trace_status) renderTraceStatus(data.result.trace_status); + if (data.state === "succeeded") toast("运行完成"); + else toast("运行" + stateLabel(data.state)); + } + + function renderRunResult(result, state, error) { + var summary = $("#mq-run-summary"); + if (!summary) return; + summary.textContent = ""; + if (result) { + if (result.target) { + var label = result.target.kind === "entry" ? "入口 main" : "函数 " + (result.target.label || result.target.cli_name || ""); + appendLine(summary, "p", "mq-run-result", label + " · 模式 " + (result.mode || "pure") + + (typeof result.duration_ms === "number" ? " · " + result.duration_ms + " ms" : "") + + (result.exit_code === null || typeof result.exit_code === "undefined" ? "" : " · 退出码 " + result.exit_code)); + } + if (result.value_text) { + appendLine(summary, "p", "mq-run-result", "返回值:" + result.value_text); + } + if (result.stale) { + appendLine(summary, "p", "mq-run-warning", "源码在运行后发生变化:结果可见但标记为过期,不在当前正文上绘制执行标注。"); + } + if (result.stdout) { + var stdout = $("#mq-run-stdout"); + if (stdout) { + stdout.textContent = result.stdout; + stdout.hidden = false; + } + } + if (result.stderr) { + var stderr = $("#mq-run-stderr"); + if (stderr) { + stderr.textContent = result.stderr; + stderr.hidden = false; + } + } + if (Array.isArray(result.diagnostics) && result.diagnostics.length) { + appendLine(summary, "p", "mq-run-warning", "诊断:" + result.diagnostics.length + " 条(详见运行详情)"); + var list = document.createElement("ol"); + list.className = "mq-run-events"; + result.diagnostics.slice(0, 20).forEach(function (diagnostic) { + var code = diagnostic && diagnostic.code ? diagnostic.code : "diagnostic"; + var message = diagnostic && diagnostic.message ? diagnostic.message : ""; + appendLine(list, "li", "", code + ":" + message); + }); + summary.appendChild(list); + } + } + if (error && (error.code || error.message)) { + appendLine(summary, "p", "mq-run-error", (error.code || "error") + ":" + (error.message || "运行失败")); + } + if (state === "cancelled") { + appendLine(summary, "p", "mq-run-warning", "运行已按请求取消;进程组已终止。"); + } + } + + function renderTraceStatus(status) { + if (!status || status === "verified") return; + var summary = $("#mq-run-summary"); + if (!summary) return; + var message = status === "invalid" + ? "Trace 与本次 Analysis 不匹配或格式无效:不绘制执行标注,也不声称观察到完整过程。" + : "本次运行没有可用的 Trace v2(unavailable):只展示 CLI 返回值与输出。"; + appendLine(summary, "p", "mq-run-warning", message); + } + + function renderTrace(trace) { + var summary = $("#mq-run-summary"); + var wrap = $("#mq-run-trace-wrap"); + var list = $("#mq-run-events"); + if (!wrap || !list) return; + list.textContent = ""; + if (!trace || trace.status !== "verified") { + wrap.hidden = true; + renderTraceStatus(trace && trace.status ? trace.status : "unavailable"); + return; + } + wrap.hidden = false; + if (summary) { + if (trace.stale) { + appendLine(summary, "p", "mq-run-warning", "Trace 属于运行时的源码:当前源码已变化,本次不绘制执行标注。"); + } + if (trace.truncated) { + var label = trace.truncated.label || (trace.truncated.reason + "(上限 " + trace.truncated.limit + ")"); + appendLine(summary, "p", "mq-run-warning", "Trace 被截断:" + label + ";这不代表程序终止。"); + } + } + var entryEvents = Array.isArray(trace.events) ? trace.events : []; + entryEvents.slice(0, 200).forEach(function (event) { + var location = event.span ? "span " + event.span.start + "–" + event.span.end : (event.module_id || ""); + var detail = event.detail ? " · " + event.detail : ""; + var operation = event.operation ? " · " + event.operation : ""; + appendLine(list, "li", "", event.kind + " · " + location + detail + operation); + }); + if (entryEvents.length > 200) { + appendLine(list, "li", "mq-colophon", "仅显示前 200 条(共 " + entryEvents.length + " 条)。"); + } + if (!trace.stale) { + var bySource = {}; + $$("[data-source-id]").forEach(function (element) { + bySource[element.dataset.sourceId] = element; + }); + var grouped = {}; + entryEvents.forEach(function (event) { + if (!event.source_id || !bySource[event.source_id]) return; + if (!grouped[event.source_id]) grouped[event.source_id] = []; + grouped[event.source_id].push(event); + }); + Object.keys(grouped).forEach(function (sourceId) { + var group = grouped[sourceId]; + var last = group[group.length - 1]; + var kinds = []; + group.forEach(function (event) { + if (kinds.indexOf(event.kind) < 0) kinds.push(event.kind); + }); + var chip = document.createElement("span"); + chip.className = "mq-run-chip"; + chip.dataset.viewChip = "1"; + chip.dataset.annotationSource = "trace"; + chip.dataset.runSeq = String(last.seq); + chip.dataset.runKind = kinds.join(","); + var text = last.detail || last.kind; + if (group.length > 3) text += " ×" + group.length; + chip.textContent = text; + chip.title = "本次 Trace 事件:" + group.length + " 条(" + kinds.join(",") + ")"; + bySource[sourceId].appendChild(chip); + }); + } + } + + function cancelRun() { + if (!activeRun || activeRun.terminal) return; + setRunStatus("正在请求取消…"); + fetch(activeRun.cancelUrl, { + method: "POST", + credentials: "same-origin", + cache: "no-store", + headers: { "Accept": "application/json", "X-View-CSRF": csrfToken() } + }) + .then(function (response) { + return response.json().then(function (data) { return { ok: response.ok, status: response.status, data: data }; }); + }) + .then(function (result) { + if (!result.ok) { + var reason = result.data && result.data.message ? result.data.message : "取消失败"; + setRunStatus("取消请求被拒绝(" + result.status + "):" + reason); + return; + } + setRunStatus("已请求取消;等待唯一终态…"); + }) + .catch(function (error) { + setRunStatus("取消请求失败:" + error.message); + }); + } + function clearRun() { closeAllDialogs(); - try { - var url = new URL(window.location.href); - if (url.searchParams.has("run")) { - url.searchParams.delete("run"); - window.location.assign(url.toString()); - return; - } - } catch (error) { - /* fall through */ + closeActiveObserver(); + var panel = runPanel(); + if (panel) { + panel.hidden = true; + panel.dataset.runState = "idle"; } - var panel = $("#mq-run-panel"); - if (panel) panel.hidden = true; - toast("已清理本地展示状态(源文件与缓存未修改)"); + reader.dataset.runState = "idle"; + clearRunOutput(); + setRunStatus("尚未运行。点击 Dock 的“运行”执行 main,或在函数面板选择函数。"); + toast("已清理本地结果展示(未删除项目文件、lock 或服务端运行记录)"); } document.addEventListener("click", function (event) { var trigger = event.target.closest ? event.target.closest("[data-action]") : null; if (!trigger) return; event.preventDefault(); - handleAction(trigger.dataset.action); + handleAction(trigger.dataset.action, trigger); }); document.addEventListener("click", function (event) { @@ -426,6 +893,16 @@ if (event.target && event.target.id === "mq-search-input") { renderSearch(event.target.value); } + if (event.target && (event.target.id === "mq-grant-read" || event.target.id === "mq-grant-write" || event.target.dataset.paramName)) { + updateRunPreview(); + } + }); + document.addEventListener("change", function (event) { + if (event.target && event.target.name === "mq-mode") { + var grants = $("#mq-run-grants"); + if (grants) grants.hidden = event.target.value !== "project"; + updateRunPreview(); + } }); document.addEventListener("keydown", function (event) { @@ -451,6 +928,18 @@ } }, true); + // Restore reading preferences (theme only; never secrets/permissions). + try { + var storedTheme = window.localStorage.getItem("marqdo.view.theme"); + if (storedTheme === "dark" || storedTheme === "light") { + applyTheme(storedTheme, false); + } else if (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches) { + applyTheme("dark", false); + } + } catch (error) { + /* storage is optional */ + } + // Restore a URL-selected mode, then honour the persisted diagnostics state. try { var params = new URLSearchParams(window.location.search); @@ -466,22 +955,6 @@ setMode("document"); } - // Restore reading position after a run reload, without faking any result. - try { - var scroll = window.sessionStorage.getItem("marqdo.view.scroll"); - if (scroll && new URLSearchParams(window.location.search).has("run")) { - window.sessionStorage.removeItem("marqdo.view.scroll"); - var target = parseInt(scroll, 10); - if (!isNaN(target)) { - window.requestAnimationFrame(function () { - window.scrollTo(0, target); - }); - } - } - } catch (error) { - /* storage is optional */ - } - // Keep dock buttons visible above the last line on small screens. function syncDockInset() { var dock = $(".mq-dock"); diff --git a/docs/ACCEPTANCE.md b/docs/ACCEPTANCE.md index be73d1f..d4f940b 100644 --- a/docs/ACCEPTANCE.md +++ b/docs/ACCEPTANCE.md @@ -1,61 +1,164 @@ -# 验收状态(RFC-VIEW-0001 §18) +# 验收状态(RFC-VIEW-0002 §9 / §10) -> 结论:首个 Beta 的 **P0 门禁全部 PASS**(由真实冻结 CLI + 真实 Chromium 生成, -> 见 `docs/evidence/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json`)。 -> P1 视觉/交互门禁大部分 PASS,**U-01 像素级人工比对与 U-04 动态曲线侧注未完成/未实现**, -> 已在 README/CHANGELOG/STATUS 明确标注,不以自动化结果替代人工判断。 +> 最新 issue #2 复验见 §7。以下为 PR-00~PR-06 的初次验收记录。 +> 证据来自真实冻结 CLI(`marqdo 3.0.0-beta.1`)+ 真实进程 HTTP/SSE 测试 + +> 真实 Chromium 131;生成命令为 `MARQDO_BIN=… scripts/acceptance.sh`。 +> 机器可读证据:`docs/evidence/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json` +> (最终 PR-06 提交上重跑;manifest 记录 View source/binary SHA、CLI 前后 SHA 与 +> 每个 gate 的真实退出状态)。 -## P0 门禁 +- 日期:2026-11-22 +- 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` -| ID | 结果 | 证据 | -|---|---|---| -| A-01 无旧 crate 依赖 | PASS | `tests/no_coupling.rs` 依赖/Cargo.lock/源码扫描 | -| A-02 独立新仓库 clean build | PASS | acceptance `build`;无 `marqdo`/`marqdo-cli` 源码依赖 | -| A-03 Tool v1 安装/分发 | PASS | acceptance `archive_install`、`tool_list`、`view_help`;`tools/install-smoke.sh` | -| A-04 CLI SHA-256 前后相同 | PASS | acceptance `core_sha`;manifest 中 before==after=`062cb56e…` | -| A-05 旧审计与截图基准 | PASS(静态) | `docs/audits/legacy-render-paths.md`(`LEGACY_RUNTIME_UNVERIFIED` 已声明) | -| A-06 单一 Renderer/CSS 入口 | PASS | `tests/no_coupling.rs`、`tests/asset_integrity.rs`、ADR-0001/0002 | -| S-01 Knowledge/Exec/继承 | PASS | `tests/rendering.rs`、`tests/unicode_spans.rs`、冻结 Analysis golden | -| S-02 Emph/Strong/Code 载体 | PASS | `tests/rendering.rs`(4 个 Exec 锚点)、`tests/unicode_spans.rs` | -| S-03 Knowledge 惰性 | PASS | `knowledge_emphasis_never_becomes_an_execution_anchor` | -| S-04 中文/emoji/CRLF/重复语句 | PASS | `examples/unicode-spans` + 冻结 golden + `tests/unicode_spans.rs` | -| S-05 check 失败可读 | PASS | `tests/presentation_states.rs`、浏览器 diagnostics 区 | -| S-06 未知 Analysis major 拒绝 | PASS | `tests/semantic` 单测、`tests/presentation_states.rs`、`verify` 负测 | -| S-07 digest/span 篡改 | PASS | `tests/trace_contract.rs`、`tests/presentation_states.rs` | -| R-01 刷新 10 次不运行 | PASS | `tests/http_live.rs::opening_and_refreshing_never_runs_the_document` | -| R-02 导出纯静态 | PASS | `tests/export.rs`(marker 假核心 + argv 无 run) | -| R-03 用户确认后真实运行 | PASS | acceptance `real_run`(安装态、CSRF、真实 Trace) | -| R-04 trace 不匹配 → STALE | PASS | `tests/trace_contract.rs`、`tests/http_live.rs` | -| R-05 截断/运行错误 | PASS | 真实 truncated/arity golden + 页面状态 | -| R-06 不猜未公开值 | PASS | Trace 模型无这些字段;UI `UNSUPPORTED`(`docs/design/state-matrix.md`) | -| X-01 恶意 Markdown | PASS | `tests/rendering.rs`、`tests/fixtures/security-project` 浏览器 | -| X-02 路径穿越/symlink | PASS | `tests/http_live.rs`、`SafeRelativePath` 单测 | -| X-03 跨站 POST run | PASS | `tests/http_live.rs`(token/Origin/confirm/mode) | -| X-04 无 JS/禁网/file:// | PASS | 浏览器 no-JS/外部请求检查;`tools/test-export.sh` file:// Chromium | -| X-05 stdout 注入转义 | PASS | `tests/http_live.rs::program_stdout_is_escaped...` | -| X-06 超时/子进程清理 | PASS | `tests/core_contract.rs::timeout_kills_the_process_group...` | -| P-01 文档可复现 | PASS | README / RFC / STATUS / COMPATIBILITY / ADR / 审计 / 证据 | -| P-02 archive clean install | PASS | acceptance 从 `.tar.gz` 解包到临时目录安装并运行 | -| P-03 协议审计 | PASS | `docs/audits/protocol-conformance.md` | +## 0. 最终证据身份 -## P1 门禁 +| 项 | 值 | +|---|---| +| View 代码提交 | `0fceb40088e728d481411c36a8d311aa3431b057`(本证据对应提交;evidence 提交紧随其后) | +| View 发布二进制 SHA-256 | `eb19f79632457f37ae3573696d7db84d57358627b65e618819ff80f132b0026a` | +| 发布归档 SHA-256 | `a3fb28c8d025f44dee6c06da80c13d3f65b9c62d1f657c04b02ef360ff24fcf5` | +| 冻结 CLI SHA-256(前后相同) | `062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f` | +| 生成时间(UTC) | `2026-11-22T06:55:13.151362+00:00` | +| manifest | `docs/evidence/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json` | -| ID | 结果 | 说明 | -|---|---|---| -| U-01 1664×920 视觉 | **PARTIAL** | 截图已采集(`docs/evidence/PR-03/`),几何/颜色令牌/无溢出/无外部资源 PASS;与参考截图的**像素级人工比对未执行(UNVERIFIED)** | -| U-02 多宽度 | PASS | 390/600/900/1280/1664/1920/2560 真实 Chromium:无横向溢出、Dock 在视口内 | -| U-03 键盘/焦点/屏幕阅读器 | PASS(基础) | Tab 可达命名控件、Esc 关闭、Ctrl/Cmd+K 搜索;完整 screen-reader 手工走查未做 | -| U-04 动态曲线侧注 | **PARTIAL** | 运行事件使用**内联 keyed chip**(无 JS/移动/打印均可读);SVG 曲线侧注未实现,不画错线 | -| U-05 Welcome 仅显式配置 | PASS | `view.json` 驱动;`tests/rendering.rs`、浏览器 | -| U-06 Live/Export 内容对照 | PASS | `tests/rendering.rs` 同模型对照;导出复用同一 renderer | +## 1. §10 发布门禁(强制) -## 复现 +| # | 门禁 | 结果 | 证据 | +|---|---|---|---| +| 1 | PR-00~06 完成、P0 检验、无伪交付 | **PASS** | 本文件 §2/§3;各 PR `docs/evidence/PR-0x/` | +| 2 | Tool v1 独立安装;CLI 无 View 核心提交;SHA 不变 | **PASS** | acceptance `archive_install`/`tool_list`/`view_help`/`core_sha`;CLI before=after=`062cb56e…` | +| 3 | 打开/刷新/导出零副作用;执行只来自显式 POST;跨站/CSRF 全绿 | **PASS** | `no_exec_suite`(源/锁哈希不变、无 sentinel、导出无执行控件)、`security_suite`、`tests/security/` | +| 4 | SSE 生命周期/心跳/序号/断线重连/有界重放;无轮询 | **PASS** | `tests/integration/http_live.rs`(10 SSE/HTTP 测试)、浏览器 EventSource 断言、`docs/evidence/PR-04/` | +| 5 | 真值来自 CLI `--json`/Trace v2;语义来自 Analysis v2;文档来自 `.mq.md` | **PASS** | `execution/controller.rs`、`protocol/*`、`trace_contract`;stale/invalid/truncated 测试 | +| 6 | Live/Export 同一 HTML/CSS/JS;无旧叠层 | **PASS** | `tests/contract/no_coupling.rs`、`asset_integrity.rs`、`integration/export.rs`、`test-export.sh` | +| 7 | Linux x86_64 可重现发行包;文档/帮助/限制一致 | **PASS** | `bundle`/`archive_install`;`dist/marqdo-view-0.2.0-x86_64-unknown-linux-gnu.tar.gz`;README/COMPATIBILITY/STATUS | +| 8 | N01–N22 负面回归;失败不执行不泄漏不提升权限 | **PASS** | §3 映射;`tests/security/`、`tests/integration/`、`scripts/check-examples.sh`、`scripts/test-no-exec.sh` | + +发布阻塞项(无意外执行失败、SSE 跨站读取/执行、过期 Trace 绑定、后台子进程 +泄漏、CLI 核心被迫改动、导出行程序、伪造实时结果、双解释器)逐项均无。 + +## 2. §9.1 正向端到端 + +| ID | 测试 | 结果 | 证据 | +|---|---|---|---| +| E01 | Tool 安装/卸载/分发 `view` | PASS | acceptance `archive_install`/`tool_list`/`view_help`;`scripts/install-smoke.sh` | +| E02 | 打开含 `@knowledge`+H2 `@exec` 文件不运行 | PASS | `pages_issue_a_session_cookie_and_never_execute_the_document`;`no_exec_suite` | +| E03 | Source/Document 切换、字节保真 | PASS | `tests/integration/rendering.rs`、浏览器 source mode 断言 | +| E04 | 中文/Emoji/表格/公式 span | PASS | `tests/integration/unicode_spans.rs`、冻结 Analysis golden | +| E05 | 显式 `main` 运行(真实 run --json --trace-file) | PASS | acceptance `real_run`(真实冻结 CLI + SSE,285 条 Trace 事件) | +| E06 | H2 Exec `n=5` 调用 | PASS | `scripts/check-examples.sh`(Int 10);`execution.rs` 的 call argv;前端表单 | +| E07 | 文本/列表常量参数(无 shell) | PASS | `build_call_args` 单测/集成;`--arg name=expression` argv 测试 | +| E08 | 无 main 不运行其他函数 | PASS | `document_without_main_...`(400 `view.no_entry_function`,无 run 调用) | +| E09 | if/while Trace 事件映射、不伪造变量 | PASS | `execution.rs` Trace 摘要;`at most one grouped chip`;无变量字段 | +| E10 | `GET …/events` 为 SSE、accepted/running/terminal、无 polling | PASS | `explicit_run_streams_sse_...`;浏览器请求记录 | +| E11 | Last-Event-ID 重连有序、无重复、过期 snapshot | PASS | `last_event_id_replays_...` | +| E12 | 长任务 SSE 心跳、GET 不重启 | PASS | `sse_heartbeats_keep_a_slow_job_connected`、`at_most_two_sse_observers_per_run` | +| E13 | 取消终止进程树、唯一终态 | PASS | `cancel_is_idempotent...`、`process.rs` 单测 | +| E14 | 静态导出无执行/无联网/相对链接 | PASS | acceptance `export`/`export_suite`;`test-export.sh`(file:// Chromium) | +| E15 | 页面刷新/重开不自动执行 | PASS | `pages_issue...`(10 次刷新无 run);浏览器 | +| E16 | 运行后源码改变 → 结果可见但 stale、无错误高亮 | PASS | `source_edit_during_a_run...`(stale=true、全部 anchor/source_id=null) | + +## 3. §9.2 必测失败与安全回归 + +| ID | 故障注入 | 结果 | 对应测试/证据 | +|---|---|---|---| +| N01 | 假 Analysis schema v3/缺 modules | PASS | `tests/contract/presentation_states.rs`、`verify` 负测 | +| N02 | check 失败 + 旧 analysis 残留 | PASS | `tools` 合同测试;View 只读 `check --emit`(CLI 删除 stale emit)+ 自缓存按 source digest | +| 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 ` - + 跳到正文 "##, presentation_version = model.version, @@ -170,6 +185,11 @@ impl ReaderRenderer { annotations = if ctx.annotations { "on" } else { "off" }, run_state = model.run_state().data_value(), run_available = if ctx.run_available { "true" } else { "false" }, + has_main = if has_main { "true" } else { "false" }, + core_available = if ctx.core_available { "true" } else { "false" }, + document = escape_attr(&relative_path), + analysis_digest = escape_attr(&analysis_digest), + run_timeout = ctx.run_timeout_secs, live = if ctx.live { "true" } else { "false" }, ); @@ -182,9 +202,13 @@ impl ReaderRenderer { } self.render_document_meta(&mut html, model); self.render_diagnostics(&mut html, model); - self.render_functions(&mut html, model); + self.render_functions(&mut html, model, ctx); self.render_document(&mut html, model, ctx); - self.render_run_panel(&mut html, model, ctx); + if ctx.live { + self.render_live_run_shell(&mut html, ctx); + } else { + self.render_run_panel(&mut html, model, ctx); + } self.render_source_pane(&mut html, model, ctx); self.render_footer(&mut html, model); let _ = write!(html, "\n"); @@ -204,8 +228,8 @@ impl ReaderRenderer { &self, html: &mut String, model: &PresentationModel, - _ctx: &RenderContext, - navigation: &crate::presentation::Navigation, + ctx: &RenderContext, + navigation: &crate::reader::model::Navigation, ) { let active = model .navigation @@ -214,6 +238,11 @@ impl ReaderRenderer { .map(|path| path.as_str()) .unwrap_or(""); let files_count = navigation.documents.len(); + let run_tab = if ctx.live { + "".to_string() + } else { + String::new() + }; let _ = write!( html, r##"
@@ -231,19 +260,13 @@ impl ReaderRenderer { "##, menu_icon = icon("M4 6h16M4 12h16M4 18h16"), site_title = escape_text(&navigation.site_title), logo = escape_attr(&self.assets.logo().data_uri()), search_icon = icon("M21 21l-5-5M18 10a8 8 0 1 1-16 0 8 8 0 0 1 16 0"), - run_disabled = if _ctx.run_available { "false" } else { "true" }, - run_title = if _ctx.run_available { - "运行文档(需要确认)" - } else { - "运行入口尚未启用;当前版本不会执行文档" - }, ); let _ = (files_count, active); } @@ -254,7 +277,7 @@ impl ReaderRenderer { ); } - fn render_welcome(&self, html: &mut String, navigation: &crate::presentation::Navigation) { + fn render_welcome(&self, html: &mut String, navigation: &crate::reader::model::Navigation) { let _ = write!( html, r##"
@@ -361,7 +384,7 @@ impl ReaderRenderer { html.push_str("\n\n"); } - fn render_functions(&self, html: &mut String, model: &PresentationModel) { + fn render_functions(&self, html: &mut String, model: &PresentationModel, ctx: &RenderContext) { if model.outline.is_empty() { return; } @@ -375,12 +398,33 @@ impl ReaderRenderer { count = functions.len() ); for entry in functions { + let function = model.semantic.as_ref().and_then(|semantic| { + semantic.functions.iter().find(|function| { + anchor_for_span(function.heading_span.start, function.heading_span.end) + == entry.anchor + }) + }); + let (function_id, params, callable) = match function { + Some(function) => (function.id.clone(), function_params_json(function), true), + None => (String::new(), "[]".to_string(), false), + }; + let call_button = if callable && ctx.core_available { + format!( + "", + id = escape_attr(&function_id), + label = escape_attr(&entry.label), + params = escape_attr(¶ms) + ) + } else { + String::new() + }; let _ = write!( html, - "
  • {label}{detail}
  • \n", + "
  • {label}{detail}{call_button}
  • \n", anchor = escape_attr(&entry.anchor), label = escape_text(&entry.label), - detail = escape_text(&entry.detail) + detail = escape_text(&entry.detail), + call_button = call_button ); } html.push_str("\n\n"); @@ -457,15 +501,42 @@ impl ReaderRenderer { ); } + /// Empty, accessible run panel that the single reader script fills from + /// SSE events. It is never populated by the server for a live page: no run + /// exists until the user explicitly submits one (RFC-VIEW-0002 §7.1). + fn render_live_run_shell(&self, html: &mut String, _ctx: &RenderContext) { + html.push_str( + r##" +"##, + ); + } + fn render_dock(&self, html: &mut String, ctx: &RenderContext) { - let run_disabled = if ctx.run_available { - "" - } else { - " data-disabled=\"true\"" - }; - let _ = write!( - html, - r##"