Merge pull request '完成 RFC-VIEW-0002 并验收交互式 View' (#1) from rfc-view-0002 into master
ci/woodpecker/push/woodpecker Pipeline was successful
No files matched your search
@@ -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
|
||||||
@@ -1,68 +1,26 @@
|
|||||||
# Woodpecker CI for marqdo-view.
|
# The published beta needs glibc 2.39. Use the matching Playwright image
|
||||||
#
|
# so the installed-tool tests get both Ubuntu Noble and Chromium.
|
||||||
# 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.
|
|
||||||
when:
|
when:
|
||||||
event: [push, pull_request, manual]
|
- event: [pull_request, manual]
|
||||||
|
- event: push
|
||||||
|
branch: master
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
code:
|
frozen-acceptance:
|
||||||
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:
|
|
||||||
image: mcr.microsoft.com/playwright:v1.49.0-noble
|
image: mcr.microsoft.com/playwright:v1.49.0-noble
|
||||||
depends_on: [code]
|
environment:
|
||||||
|
PLAYWRIGHT_BROWSERS_PATH: /ms-playwright
|
||||||
|
RUST_MIN_STACK: "8388608"
|
||||||
commands:
|
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"
|
- export PATH="$HOME/.cargo/bin:$PATH"
|
||||||
- cargo build --release --locked
|
- (cd tests/browser && npm ci --no-audit --no-fund)
|
||||||
- (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
|
frozen_dir="$(mktemp -d)"
|
||||||
|
MARQDO_BIN="$(scripts/frozen-beta.sh fetch "$frozen_dir")"
|
||||||
release-bundle:
|
export MARQDO_BIN
|
||||||
image: rust:1.85-bookworm
|
scripts/acceptance.sh
|
||||||
depends_on: [code]
|
cat dist/acceptance/manifest.json
|
||||||
commands:
|
|
||||||
- cargo build --release --locked
|
|
||||||
- MARQDO_BIN="" ./tools/package.sh
|
|
||||||
- sha256sum dist/marqdo-view-*.tar.gz
|
|
||||||
- tar -tzf dist/marqdo-view-*.tar.gz | sort
|
|
||||||
@@ -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.
|
Keep a Changelog and the project uses SemVer for the View product version.
|
||||||
Protocol axes (Tool v1, Analysis v2, Trace v2) are versioned separately.
|
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
|
### 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
|
search, settings, 7 viewport widths without horizontal overflow or dock
|
||||||
clipping, no-JS reading, print mode, explicit run + clear.
|
clipping, no-JS reading, print mode, explicit run + clear.
|
||||||
- Screenshot evidence for the Welcome page (1664×920, 390×844) and a real
|
- 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
|
- Meta CSP no longer carries the ignored `frame-ancestors` directive (the HTTP
|
||||||
header still enforces framing).
|
header still enforces framing).
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
| 轴 | 本 View 值 | 说明 |
|
| 轴 | 本 View 值 | 说明 |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| View 产品版本 | `0.1.0` | 独立 SemVer,与 CLI 不共用 |
|
| View 产品版本 | `0.2.0` | 独立 SemVer,与 CLI 不共用 |
|
||||||
| `marqdo` 产品范围 | `>=3.0.0-beta.1,<4.0.0` | 安装与分发时由 CLI 强制校验 |
|
| `marqdo` 产品范围 | `>=3.0.0-beta.1,<4.0.0` | 安装与分发时由 CLI 强制校验 |
|
||||||
| CLI Tool Protocol | `1` | `tool.json` 清单/整包摘要/分发 |
|
| CLI Tool Protocol | `1` | `tool.json` 清单/整包摘要/分发 |
|
||||||
| Analysis | `2` | 未知 major 直接拒绝,不回退 |
|
| 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 | 未构建 | 未验证 |
|
| Linux aarch64 | 未构建 | 未验证 |
|
||||||
| macOS / Windows | 未验证 | 不声明支持;路径/进程组逻辑留有平台分支,但未做实测 |
|
| macOS / Windows | 未验证 | 不声明支持;路径/进程组逻辑留有平台分支,但未做实测 |
|
||||||
|
|
||||||
@@ -28,19 +28,19 @@ Beta 版 CLI 必须使用 prerelease 范围(`>=3.0.0-beta.1,<4.0.0`);`>=3.
|
|||||||
| 原始 Markdown 只读浏览(GFM 表/列表/引用/代码围栏/数学文本) | **已实现**(PR-02) |
|
| 原始 Markdown 只读浏览(GFM 表/列表/引用/代码围栏/数学文本) | **已实现**(PR-02) |
|
||||||
| Analysis v2 静态语义(函数/Unit/诊断/引用/资源) | **已实现**(PR-02) |
|
| Analysis v2 静态语义(函数/Unit/诊断/引用/资源) | **已实现**(PR-02) |
|
||||||
| 文档态 / 源码态切换 | **已实现**(PR-02) |
|
| 文档态 / 源码态切换 | **已实现**(PR-02) |
|
||||||
| 暖纸 Reader 视觉(单一 CSS/JS) | 计划 PR-03 |
|
| 暖纸 Reader 视觉(单一 CSS/JS) | 已实现并经 Chromium 验收 |
|
||||||
| 用户显式触发运行 + Trace v2 事件可视化 | **已实现**(PR-04,仅 `pure` 模式,需页面内确认 + CSRF) |
|
| 用户显式触发运行 + SSE + Trace v2 事件可视化 | **已实现**(0002 PR-04;`pure`/受控 `project`,显式确认 + 会话 CSRF) |
|
||||||
| Live 本机安全 API | **已实现**(PR-02 只读 + PR-04 run + PR-05 并发/公开错误/导出) |
|
| Live 本机安全 API(7 路由) | **已实现**(0002 PR-04;Cookie/CSRF/Origin/CSP/单任务/SSE) |
|
||||||
| 静态离线导出(纯只读) | **已实现**(PR-05,同一渲染器) |
|
| 静态离线导出(纯只读) | **已实现**(PR-05,同一渲染器) |
|
||||||
| 逐语句变量值 / 参数实际值 / 内存快照 | **UNSUPPORTED**(Trace v2 不提供,绝不伪造) |
|
| 逐语句变量值 / 参数实际值 / 内存快照 | **UNSUPPORTED**(Trace v2 不提供,绝不伪造) |
|
||||||
| 知识“已证明”状态 | **UNSUPPORTED**(需要独立 Prove 协议与证书) |
|
| 知识“已证明”状态 | **UNSUPPORTED**(需要独立 Prove 协议与证书) |
|
||||||
| `project`/`strict` 运行与 grants 授权 | **未实现**(首版仅 `pure`,其他模式 403) |
|
| `project` 运行与 fs grants | **已实现(受控)**:仅相对项目根 read/write glob,显式二次确认;其它权限拒绝 |
|
||||||
| SSE 流式输出 / 取消运行 / 多运行历史 | **未实现**(运行后整页重载并保留位置) |
|
| SSE 状态推送 / 取消运行 / 事件重放 | **已实现**(逐帧 flush、心跳、Last-Event-ID、2 连接上限、无轮询) |
|
||||||
| SVG 曲线侧注 | **未实现**(运行事件用内联 keyed chip,U-04 PARTIAL) |
|
| SVG 曲线侧注 | **未实现**(运行事件用内联 keyed chip,U-04 PARTIAL) |
|
||||||
| 调试器/断点/单步 | **不实现**(首版非目标) |
|
| 调试器/断点/单步 | **不实现**(首版非目标) |
|
||||||
| Knowledge/Prove/Lint 引擎 | **不实现**(独立仓库/未来可选信息层) |
|
| 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.source.root_id == analysis.project.root_id`;事件 `module_id` 必须存在于 Analysis。
|
||||||
- `trace.truncated != null` → `TRUNCATED`,不声明全部分支/循环已遍历。
|
- `trace.truncated != null` → `TRUNCATED`,不声明全部分支/循环已遍历。
|
||||||
- 运行只使用 `MARQDO_BIN` 子进程与公开 JSON;不链接 Core crate、不读 Core 源码、不依赖私有 IR。
|
- 运行只使用 `MARQDO_BIN` 子进程与公开 JSON;不链接 Core crate、不读 Core 源码、不依赖私有 IR。
|
||||||
|
|
||||||
|
## 官方 Beta 归档的标准库
|
||||||
|
|
||||||
|
`v3.0.0-beta.1` 的 Linux 归档未携带 `stdlib/`。View 的冻结验收示例使用
|
||||||
|
该二进制公开的 Memory、stdout 和文件资源原语。含 `std:` 导入的项目由
|
||||||
|
所选 Core 校验,缺少标准库时由 View 展示 Core 的诊断。
|
||||||
@@ -263,7 +263,7 @@ checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "marqdo-view"
|
name = "marqdo-view"
|
||||||
version = "0.1.0"
|
version = "0.2.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"clap",
|
"clap",
|
||||||
"comrak",
|
"comrak",
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "marqdo-view"
|
name = "marqdo-view"
|
||||||
version = "0.1.0"
|
version = "0.2.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
rust-version = "1.85"
|
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 v2 and Trace v2"
|
||||||
repository = "https://github.com/cflmy/marqdo-view"
|
repository = "https://github.com/cflmy/marqdo-view"
|
||||||
@@ -14,6 +14,18 @@ categories = ["command-line-utilities", "documentation"]
|
|||||||
name = "marqdo-view"
|
name = "marqdo-view"
|
||||||
path = "src/main.rs"
|
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]
|
[dependencies]
|
||||||
clap = { version = "4.5", features = ["derive"] }
|
clap = { version = "4.5", features = ["derive"] }
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
|||||||
@@ -1,15 +1,23 @@
|
|||||||
# marqdo-view
|
# marqdo-view
|
||||||
|
|
||||||
Marqdo View 是一个独立的可执行文档阅读器:以**原始 Markdown 为阅读主体**,把冻结
|
Marqdo View(`0.2.0`)是一个独立的可执行文档阅读器:以**原始 Markdown 为阅读主体**,把冻结
|
||||||
`marqdo` CLI 的静态语义(Analysis v2)与用户显式触发的真实运行轨迹(Trace v2)
|
`marqdo` CLI 的静态语义(Analysis v2)与用户显式触发的真实运行轨迹(Trace v2)
|
||||||
附着回原文,而不是把文档翻译成另一套语言。
|
附着回原文,而不是把文档翻译成另一套语言。
|
||||||
|
|
||||||
- 状态(唯一现状来源):[`docs/STATUS.md`](docs/STATUS.md)
|
- 状态(唯一现状来源):[`docs/STATUS.md`](docs/STATUS.md)
|
||||||
- 验收结果与证据:[`docs/ACCEPTANCE.md`](docs/ACCEPTANCE.md)
|
- **实施规范(当前)**:[`docs/architecture/RFC-VIEW-0002.md`](docs/architecture/RFC-VIEW-0002.md)
|
||||||
- 架构规范:[`docs/RFC-VIEW-0001.md`](docs/RFC-VIEW-0001.md)
|
- 0002 合规矩阵:[`docs/CONFORMANCE.md`](docs/CONFORMANCE.md)
|
||||||
- 旧 View 静态审计:[`docs/audits/legacy-render-paths.md`](docs/audits/legacy-render-paths.md)
|
- 历史基础设计:[`docs/architecture/RFC-VIEW-0001.md`](docs/architecture/RFC-VIEW-0001.md)
|
||||||
- 协议一致性:[`docs/audits/protocol-conformance.md`](docs/audits/protocol-conformance.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)
|
- 兼容性:[`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/<CLI-SHA>/manifest.json`)。像素级人工比对与完整
|
||||||
|
> screen-reader 走查仍为 `UNVERIFIED`,见 `docs/STATUS.md`。
|
||||||
|
|
||||||
## 能力
|
## 能力
|
||||||
|
|
||||||
@@ -17,12 +25,13 @@ Marqdo View 是一个独立的可执行文档阅读器:以**原始 Markdown
|
|||||||
|---|---|
|
|---|---|
|
||||||
| 原始 Markdown + GFM 阅读、源码态、文档态 | ✅ |
|
| 原始 Markdown + GFM 阅读、源码态、文档态 | ✅ |
|
||||||
| Analysis v2 静态语义(函数/Unit/签名/诊断/导入/引用/资源) | ✅ 严格校验,span 无效则降级 |
|
| Analysis v2 静态语义(函数/Unit/签名/诊断/导入/引用/资源) | ✅ 严格校验,span 无效则降级 |
|
||||||
| 本机 Live 阅读(默认 `127.0.0.1`,只读 API) | ✅ |
|
| 本机 Live 阅读(默认 `127.0.0.1`,只读 API + 显式执行端点) | ✅ |
|
||||||
| 用户确认后运行 + 真实 Trace v2 可视化(`pure` 模式) | ✅ 需要页面内确认 + CSRF |
|
| 显式确认后运行 + SSE 状态/取消 + 真实 Trace v2 | ✅ 单任务、无轮询、断线重放 |
|
||||||
| 纯只读静态导出(离线 `file://`、manifest/哈希、原子发布) | ✅ |
|
| 纯只读静态导出(离线 `file://`、manifest/哈希、原子发布) | ✅ |
|
||||||
|
| 单函数参数表单 + 受控 `project` fs grants | ✅ 参数来自 Analysis 签名;project 需显式 glob 二次确认 |
|
||||||
|
| SSE 状态推送 / 取消 / 断线重放(禁止轮询) | ✅ `POST /api/runs` + `GET …/events` + `POST …/cancel` |
|
||||||
| 逐语句变量值 / 参数值 / 内存快照 | ❌ UNSUPPORTED(协议不提供,绝不伪造) |
|
| 逐语句变量值 / 参数值 / 内存快照 | ❌ UNSUPPORTED(协议不提供,绝不伪造) |
|
||||||
| 知识“已证明” / Prove / Lint / 调试器 | ❌ 非目标/等待独立协议 |
|
| 知识“已证明” / Prove / Lint / 调试器 | ❌ 非目标/等待独立协议 |
|
||||||
| `project`/`strict` 运行、SSE、多运行历史 | ❌ 未实现(首版仅 `pure`) |
|
|
||||||
|
|
||||||
## 安装
|
## 安装
|
||||||
|
|
||||||
@@ -32,7 +41,7 @@ MARQDO_BIN=/absolute/path/to/marqdo
|
|||||||
"$MARQDO_BIN" --version
|
"$MARQDO_BIN" --version
|
||||||
|
|
||||||
# 2) 构建并制作 Tool v1 bundle
|
# 2) 构建并制作 Tool v1 bundle
|
||||||
./tools/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`
|
||||||
@@ -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/index.mq.md
|
||||||
marqdo view verify examples/mixed-modes --refs --json
|
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:// 离线打开)
|
# 纯只读静态导出(永不执行;导出后可用 file:// 离线打开)
|
||||||
marqdo view export examples/welcome --out ./site
|
marqdo view export examples/welcome --out ./site
|
||||||
marqdo view export examples/mixed-modes --out ./site --no-annotations
|
marqdo view export examples/mixed-modes --out ./site --no-annotations
|
||||||
```
|
```
|
||||||
|
|
||||||
开发期可直接运行 `marqdo-view`(用 `--marqdo-bin` 指定冻结核心)。运行入口在 Live
|
开发期可直接运行 `marqdo-view`(用 `--marqdo-bin` 指定冻结核心)。运行只有一个入口:
|
||||||
页面中:点击“运行”→ 阅读风险说明 → 点击“确认运行”,才会调用冻结核心执行
|
Live 页面点击 Dock “运行”(执行 `main`)或函数面板的“调用”(执行 `call`),
|
||||||
`--mode pure`;页面刷新/打开/搜索/导出都不会运行。
|
阅读命令预览与权限说明后点击“确认执行”,服务端才 `POST /api/runs` 启动一个
|
||||||
|
CLI 子进程;状态与结果通过 SSE 推送,可取消,断线可重放。页面刷新/打开/搜索/
|
||||||
|
切换/导出都不会运行,也没有状态轮询。
|
||||||
|
|
||||||
## 架构(强制约束)
|
## 架构(强制约束)
|
||||||
|
|
||||||
@@ -69,21 +84,25 @@ Reader UI(唯一 assets/reader.css + assets/reader.js)
|
|||||||
│
|
│
|
||||||
ReaderRenderer(唯一模板,Live/Export 共用)
|
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(不修改、不重编译、不链接、不读源码)
|
冻结发布版 marqdo CLI(不修改、不重编译、不链接、不读源码)
|
||||||
```
|
```
|
||||||
|
|
||||||
- 单一 Rust package、单一渲染入口、单一主题文件;没有第二个 Markdown→语义管线。
|
- 单一 Rust package、单一渲染入口、单一主题文件;没有第二个 Markdown→语义管线。
|
||||||
|
- 服务端只有 7 条固定路由;SSE 只推送 View 自有 `run.*` 生命周期事件。
|
||||||
- Analysis v2 是唯一语义权威:函数/语句/分支/循环/诊断均来自 `check --emit`,
|
- Analysis v2 是唯一语义权威:函数/语句/分支/循环/诊断均来自 `check --emit`,
|
||||||
源码字节 span 只用于绑定视觉位置。
|
源码字节 span 只用于绑定视觉位置。
|
||||||
- Trace v2 与 Analysis 字节摘要严格绑定;`STALE/TRUNCATED/FAILED/UNSUPPORTED`
|
- Trace v2 与 Analysis 字节摘要严格绑定;`STALE/TRUNCATED/FAILED/UNSUPPORTED`
|
||||||
状态显式呈现,不猜测未公开值。
|
状态显式呈现,不猜测未公开值。
|
||||||
- Live/Export 内容同源;导出绝不执行、绝不覆盖项目源文件或无关目录。
|
- Live/Export 内容同源;导出绝不执行、绝不覆盖项目源文件或无关目录。
|
||||||
- 门禁:`tests/no_coupling.rs` 拒绝旧 crate/源码依赖、第二套渲染器/主题、shell 执行;
|
- 门禁:`tests/contract/no_coupling.rs` 拒绝旧 crate/源码依赖、第二套渲染器/主题、shell 执行;
|
||||||
`tests/asset_integrity.rs` 锁定内嵌资产与唯一主题层。
|
`tests/contract/asset_integrity.rs` 锁定内嵌资产与唯一主题层;
|
||||||
|
`tests/security/` 覆盖 CSRF/Origin/Cookie/路径/symlink/XSS/跨会话 SSE。
|
||||||
|
|
||||||
## 开发与验收
|
## 开发与验收
|
||||||
|
|
||||||
@@ -95,36 +114,43 @@ cargo test --locked
|
|||||||
cargo build --release --locked
|
cargo build --release --locked
|
||||||
```
|
```
|
||||||
|
|
||||||
全链路(Tool 安装、浏览、显式运行、导出、浏览器、安全、冻结内核 SHA 不变):
|
全链路验收使用 Rust 1.89 或更新版本,以及能运行官方 Beta 的 Linux x86_64
|
||||||
|
环境(glibc 2.39 起)。浏览器、显式运行和离线导出通过已安装的 Tool 执行。
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
export MARQDO_BIN=/absolute/path/to/frozen/marqdo
|
(cd tests/browser && npm ci && PLAYWRIGHT_BROWSERS_PATH="$PWD/../.cache/pw-browsers" npx playwright install chromium)
|
||||||
./tools/acceptance.sh
|
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
|
```bash
|
||||||
MARQDO_BIN=... ./tools/test-contract.sh # code + Tool v1 + verify + export
|
MARQDO_BIN=... ./scripts/check-examples.sh # RFC §13.3 示例真实 check/call/run
|
||||||
MARQDO_BIN=... ./tools/test-export.sh # 纯只读导出 + file:// Chromium
|
MARQDO_BIN=... ./scripts/test-no-exec.sh # 打开/导出零副作用哨兵
|
||||||
./tools/test-security.sh # HTTP/路径/XSS/导出对抗
|
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)
|
(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 授权界面未实现。
|
- 运行仅 `pure`(默认)与受控 `project` fs read/write;`strict`、网络/进程/环境/
|
||||||
- 运行完成后整页重载并保留阅读位置;无 SSE 流式输出/取消/多运行历史。
|
plugin/provider/kernel 授权不在首版 UI,必须使用终端 CLI。
|
||||||
- 变量实际值、参数值、内存快照、知识证明状态不在 Trace v2 中,UI 一律标 UNSUPPORTED。
|
- `project` 不是 OS 沙箱;View 不继承 `marqdo.yaml` 的 capability 请求。
|
||||||
- 平台仅 Linux x86_64 glibc 正式验证;macOS/Windows 未验证。
|
- SSE 只推送 View 生命周期与终态数据,不承诺逐字 stdout/Token 流;Trace v2 不含
|
||||||
- 视觉自动化门禁 PASS,但参考截图的像素级人工比对仍未执行(`U-01 UNVERIFIED`);
|
参数实际值/逐语句变量/内存快照。
|
||||||
SVG 曲线侧注未实现,运行事件以可访问的内联 chip 呈现(`U-04 PARTIAL`)。
|
- 平台:仅 Linux x86_64 正式验证;Windows/macOS 不支持声明。
|
||||||
- 远端正 CI 未实际运行;`.woodpecker.yml` 已提供,本地验收证据完整。
|
- 远端 CI 配置已提供(`.github/workflows/ci.yml`),本环境未实际运行远端 CI;
|
||||||
|
验收证据来自本地真实命令。
|
||||||
## 许可
|
- 像素级人工视觉比对与完整 screen-reader 走查为 `UNVERIFIED`(自动化几何/响应式/
|
||||||
|
无外部资源/无 JS/打印证据见 `docs/evidence/PR-04/`)。
|
||||||
代码按 MIT / Apache-2.0 双许可发布(`LICENSE-MIT`、`LICENSE-APACHE`)。复用的旧
|
|
||||||
View 视觉资产(Apache-2.0)来源与哈希见 `assets/licenses/ASSETS.md`。
|
|
||||||
@@ -40,6 +40,28 @@
|
|||||||
--mq-dock-h: 66px;
|
--mq-dock-h: 66px;
|
||||||
--mq-note-width: 176px;
|
--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 {
|
@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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -213,6 +213,22 @@
|
|||||||
closeAllDialogs();
|
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() {
|
function cycleTextSize() {
|
||||||
var order = ["normal", "large", "small"];
|
var order = ["normal", "large", "small"];
|
||||||
var current = reader.dataset.size || "normal";
|
var current = reader.dataset.size || "normal";
|
||||||
@@ -236,7 +252,7 @@
|
|||||||
openDialog("mq-dialog-unsupported");
|
openDialog("mq-dialog-unsupported");
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleAction(action) {
|
function handleAction(action, trigger) {
|
||||||
switch (action) {
|
switch (action) {
|
||||||
case "mode-document":
|
case "mode-document":
|
||||||
setMode("document");
|
setMode("document");
|
||||||
@@ -272,41 +288,47 @@
|
|||||||
case "annotations":
|
case "annotations":
|
||||||
toggleAnnotationVisibility();
|
toggleAnnotationVisibility();
|
||||||
break;
|
break;
|
||||||
case "variables":
|
case "unsupported":
|
||||||
showUnsupported(
|
showUnsupported(
|
||||||
"变量快照",
|
"变量快照 / 内存检查 / 调试器 / 证明状态",
|
||||||
"Trace v2 不提供逐语句赋值后的实际值;View 只能展示 Analysis 中的静态参数与赋值目标,绝不猜测运行时数据。"
|
"Trace v2 不提供逐语句赋值后的实际值或内存快照,公开协议也没有断点/单步通道;" +
|
||||||
|
"知识证明属于独立 Prove 工具。View 绝不猜测这些运行事实,相应能力在具备公开、受版本约束的协议前不会出现。"
|
||||||
);
|
);
|
||||||
break;
|
break;
|
||||||
case "memory":
|
case "theme":
|
||||||
showUnsupported(
|
cycleTheme();
|
||||||
"内存快照",
|
|
||||||
"当前公开协议没有内存观测通道;该能力需等待未来独立、受权限审计的调试协议。"
|
|
||||||
);
|
|
||||||
break;
|
break;
|
||||||
case "about":
|
case "about":
|
||||||
openDialog("mq-dialog-about");
|
openDialog("mq-dialog-about");
|
||||||
break;
|
break;
|
||||||
case "run":
|
case "run":
|
||||||
if (reader.dataset.runAvailable === "true") {
|
openRunForMain();
|
||||||
openDialog("mq-dialog-run-confirm");
|
|
||||||
} else {
|
|
||||||
showUnsupported(
|
|
||||||
"运行文档",
|
|
||||||
"当前页面没有可用的冻结核心或可执行入口;View 不会在缺少确认的情况下执行任何文档。"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
break;
|
break;
|
||||||
case "run-confirm":
|
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;
|
break;
|
||||||
case "clear-run":
|
case "clear-run":
|
||||||
clearRun();
|
|
||||||
break;
|
|
||||||
case "clear":
|
case "clear":
|
||||||
var panel = $("#mq-run-panel");
|
clearRun();
|
||||||
if (panel) panel.hidden = true;
|
|
||||||
toast("已清理本地展示状态(源文件与缓存未修改)");
|
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
@@ -318,93 +340,538 @@
|
|||||||
return meta ? meta.getAttribute("content") : "";
|
return meta ? meta.getAttribute("content") : "";
|
||||||
}
|
}
|
||||||
|
|
||||||
function setRunBusy(busy) {
|
var activeRun = null;
|
||||||
var button = document.querySelector('.mq-dock-btn[data-action="run"]');
|
var pendingRun = null;
|
||||||
if (!button) return;
|
|
||||||
if (busy) {
|
function randomId() {
|
||||||
button.setAttribute("aria-busy", "true");
|
var bytes = new Uint8Array(16);
|
||||||
button.dataset.busy = "true";
|
if (window.crypto && window.crypto.getRandomValues) {
|
||||||
button.disabled = true;
|
window.crypto.getRandomValues(bytes);
|
||||||
reader.dataset.runState = "running";
|
|
||||||
} else {
|
} else {
|
||||||
button.removeAttribute("aria-busy");
|
for (var i = 0; i < bytes.length; i += 1) bytes[i] = Math.floor(Math.random() * 256);
|
||||||
delete button.dataset.busy;
|
}
|
||||||
button.disabled = false;
|
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() {
|
function isTerminalState(state) {
|
||||||
var dialog = $("#mq-dialog-run-confirm");
|
return ["succeeded", "failed", "cancelled", "timed_out", "unavailable"].indexOf(state) >= 0;
|
||||||
var path = dialog ? dialog.dataset.path : "";
|
}
|
||||||
var token = csrfToken();
|
|
||||||
if (!path || !token) {
|
function runPanel() {
|
||||||
toast("缺少运行上下文或 CSRF 令牌,已拒绝运行");
|
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;
|
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);
|
setRunBusy(true);
|
||||||
fetch("/api/run", {
|
setRunStatus("正在提交运行请求…");
|
||||||
|
fetch("/api/runs", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
credentials: "same-origin",
|
credentials: "same-origin",
|
||||||
cache: "no-store",
|
cache: "no-store",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
"Accept": "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) {
|
.then(function (response) {
|
||||||
return response.json().then(function (data) {
|
return response.json().then(function (data) { return { ok: response.ok, status: response.status, data: data }; });
|
||||||
return { ok: response.ok, data: data };
|
|
||||||
});
|
|
||||||
})
|
})
|
||||||
.then(function (result) {
|
.then(function (result) {
|
||||||
if (!result.ok || !result.data || !result.data.ok) {
|
if (!result.ok || !result.data || !result.data.run_id) {
|
||||||
setRunBusy(false);
|
setRunBusy(false);
|
||||||
var reason = result.data && result.data.message
|
var reason = result.data && result.data.message ? result.data.message : "运行请求被拒绝";
|
||||||
? result.data.message
|
setRunStatus("运行未启动(" + result.status + "):" + reason);
|
||||||
: "运行被拒绝或失败";
|
toast("运行未启动:" + reason);
|
||||||
toast("运行未完成:" + reason);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
subscribeRun(result.data, pendingRun ? pendingRun.label : "运行");
|
||||||
window.sessionStorage.setItem(
|
|
||||||
"marqdo.view.scroll",
|
|
||||||
String(window.scrollY || 0)
|
|
||||||
);
|
|
||||||
} catch (error) {
|
|
||||||
/* storage is optional */
|
|
||||||
}
|
|
||||||
window.location.assign(result.data.redirect);
|
|
||||||
})
|
})
|
||||||
.catch(function (error) {
|
.catch(function (error) {
|
||||||
setRunBusy(false);
|
setRunBusy(false);
|
||||||
|
setRunStatus("运行请求失败:" + error.message);
|
||||||
toast("运行请求失败:" + 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() {
|
function clearRun() {
|
||||||
closeAllDialogs();
|
closeAllDialogs();
|
||||||
try {
|
closeActiveObserver();
|
||||||
var url = new URL(window.location.href);
|
var panel = runPanel();
|
||||||
if (url.searchParams.has("run")) {
|
if (panel) {
|
||||||
url.searchParams.delete("run");
|
panel.hidden = true;
|
||||||
window.location.assign(url.toString());
|
panel.dataset.runState = "idle";
|
||||||
return;
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
/* fall through */
|
|
||||||
}
|
}
|
||||||
var panel = $("#mq-run-panel");
|
reader.dataset.runState = "idle";
|
||||||
if (panel) panel.hidden = true;
|
clearRunOutput();
|
||||||
toast("已清理本地展示状态(源文件与缓存未修改)");
|
setRunStatus("尚未运行。点击 Dock 的“运行”执行 main,或在函数面板选择函数。");
|
||||||
|
toast("已清理本地结果展示(未删除项目文件、lock 或服务端运行记录)");
|
||||||
}
|
}
|
||||||
|
|
||||||
document.addEventListener("click", function (event) {
|
document.addEventListener("click", function (event) {
|
||||||
var trigger = event.target.closest ? event.target.closest("[data-action]") : null;
|
var trigger = event.target.closest ? event.target.closest("[data-action]") : null;
|
||||||
if (!trigger) return;
|
if (!trigger) return;
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
handleAction(trigger.dataset.action);
|
handleAction(trigger.dataset.action, trigger);
|
||||||
});
|
});
|
||||||
|
|
||||||
document.addEventListener("click", function (event) {
|
document.addEventListener("click", function (event) {
|
||||||
@@ -426,6 +893,16 @@
|
|||||||
if (event.target && event.target.id === "mq-search-input") {
|
if (event.target && event.target.id === "mq-search-input") {
|
||||||
renderSearch(event.target.value);
|
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) {
|
document.addEventListener("keydown", function (event) {
|
||||||
@@ -451,6 +928,18 @@
|
|||||||
}
|
}
|
||||||
}, true);
|
}, 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.
|
// Restore a URL-selected mode, then honour the persisted diagnostics state.
|
||||||
try {
|
try {
|
||||||
var params = new URLSearchParams(window.location.search);
|
var params = new URLSearchParams(window.location.search);
|
||||||
@@ -466,22 +955,6 @@
|
|||||||
setMode("document");
|
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.
|
// Keep dock buttons visible above the last line on small screens.
|
||||||
function syncDockInset() {
|
function syncDockInset() {
|
||||||
var dock = $(".mq-dock");
|
var dock = $(".mq-dock");
|
||||||
|
|||||||
@@ -1,61 +1,164 @@
|
|||||||
# 验收状态(RFC-VIEW-0001 §18)
|
# 验收状态(RFC-VIEW-0002 §9 / §10)
|
||||||
|
|
||||||
> 结论:首个 Beta 的 **P0 门禁全部 PASS**(由真实冻结 CLI + 真实 Chromium 生成,
|
> 最新 issue #2 复验见 §7。以下为 PR-00~PR-06 的初次验收记录。
|
||||||
> 见 `docs/evidence/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json`)。
|
> 证据来自真实冻结 CLI(`marqdo 3.0.0-beta.1`)+ 真实进程 HTTP/SSE 测试 +
|
||||||
> P1 视觉/交互门禁大部分 PASS,**U-01 像素级人工比对与 U-04 动态曲线侧注未完成/未实现**,
|
> 真实 Chromium 131;生成命令为 `MARQDO_BIN=… scripts/acceptance.sh`。
|
||||||
> 已在 README/CHANGELOG/STATUS 明确标注,不以自动化结果替代人工判断。
|
> 机器可读证据:`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 | 结果 | 证据 |
|
## 0. 最终证据身份
|
||||||
|---|---|---|
|
|
||||||
| 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` |
|
|
||||||
|
|
||||||
## 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 | 结果 | 说明 |
|
## 1. §10 发布门禁(强制)
|
||||||
|---|---|---|
|
|
||||||
| 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 | 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 `<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. 复现
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
export MARQDO_BIN=/abs/path/to/frozen/marqdo-3.0.0-beta.1
|
export MARQDO_BIN=/abs/path/to/frozen/marqdo-3.0.0-beta.1
|
||||||
tools/acceptance.sh
|
scripts/verify-frozen-cli.sh "$MARQDO_BIN" -- "$MARQDO_BIN" --version
|
||||||
|
scripts/acceptance.sh
|
||||||
cat docs/evidence/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json
|
cat docs/evidence/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json
|
||||||
```
|
```
|
||||||
|
|
||||||
CI 配置见 `.woodpecker.yml`;本环境未实际运行远端 CI,因此 `CI URL` 仍为
|
单项:
|
||||||
**UNVERIFIED**(证据来自本地可复现命令,不冒称 CI 通过)。
|
|
||||||
|
```bash
|
||||||
|
cargo test --locked --offline # unit + contract + integration + security
|
||||||
|
MARQDO_BIN=... scripts/check-examples.sh # RFC §13.3 fixtures
|
||||||
|
MARQDO_BIN=... scripts/test-no-exec.sh # §13.4 零副作用
|
||||||
|
MARQDO_BIN=... scripts/test-export.sh # 离线导出
|
||||||
|
MARQDO_BIN=... scripts/test-browser.sh # 真实 Chromium
|
||||||
|
```
|
||||||
|
|
||||||
|
## 6. 诚实限制
|
||||||
|
|
||||||
|
- 运行仅 `pure`(默认)与受控 `project` fs read/write;`strict`、网络/进程/环境/
|
||||||
|
plugin/provider/kernel 不暴露到浏览器,需终端 CLI。
|
||||||
|
- `project` 不是 OS 沙箱;View 不把项目 capability 声明自动提升为授权。
|
||||||
|
- SSE 不承诺逐字 stdout/Token 流;Trace v2 不含参数实际值/逐语句变量/内存快照。
|
||||||
|
- 平台:Linux x86_64 正式;Windows/macOS 不支持声明。
|
||||||
|
- `.github/workflows/ci.yml` 已提供,但**远端 CI 未在本环境实际运行**;上述证据
|
||||||
|
均来自本地可复现命令与真实进程/浏览器。
|
||||||
|
|
||||||
|
|
||||||
|
## 7. Issue #2 复验(2026-11-22)
|
||||||
|
|
||||||
|
实现提交 `34de5a34d9cd8488ae4d753aff7d27b9c95379f3` 使用 Gitea 官方
|
||||||
|
`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` 获取发行资产并调用相同的验收入口。
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
# RFC-VIEW-0002 合规矩阵(CONFORMANCE)
|
||||||
|
|
||||||
|
> 活文档:每完成一个 PR 更新。状态值:
|
||||||
|
> `PASS`(本仓库实现 + 可复现证据)、`PARTIAL`(部分实现/证据待补)、
|
||||||
|
> `PENDING`(未开始)、`N/A`(0002 明确非目标/删除项)。
|
||||||
|
> 证据列写测试/脚本文档;不得以视觉相似代替测试。
|
||||||
|
|
||||||
|
最后更新:2026-11-22(PR-00~PR-06 完成)
|
||||||
|
|
||||||
|
## 1. §0 核心不可妥协条件
|
||||||
|
|
||||||
|
| # | 条款 | 状态 | 实现位置 / 证据 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| M1 | 独立构建/测试/打包/安装;不改/不重编译 CLI;无私有 crate/Git/path 依赖 | PASS(0001 基线) | `Cargo.toml`、`tests/contract/no_coupling.rs`、`scripts/acceptance.sh`(SHA 前后一致) |
|
||||||
|
| M2 | 语言真相=Analysis v2;运行真相=`run/call --json`+Trace v2;原文=`.mq.md`;Markdown 不判语义 | PASS | `protocol/*`、`execution/controller.rs`、`reader/markdown.rs`;Trace 绑定/错误包络测试 |
|
||||||
|
| M3 | 打开/刷新/搜索/切换/导出/预览/目录/诊断绝不运行 | PASS(0001 证据,待 0002 复核) | `tests/integration/http_live.rs`、`tests/integration/export.rs`、浏览器证据 |
|
||||||
|
| M4 | 单一 Read Model / HTML 组件 / CSS / JS;Live=Export | PASS(0001 证据) | `src/render.rs`、`src/assets.rs`、`tests/contract/no_coupling.rs`、`tests/contract/asset_integrity.rs` |
|
||||||
|
| M5 | 原生执行只经 `MARQDO_BIN run/call` 子进程;无第二运行时 | PASS | `execution/process.rs` 唯一适配器;`no_coupling` 门禁;无第二解释器 |
|
||||||
|
| M6 | Tool 是普通进程;不得宣称 OS 沙箱 | PASS | README/COMPATIBILITY/UI project 警告明确;无“安全运行”措辞 |
|
||||||
|
| M7 | 不开发 lint/knowledge/prove;无硬依赖 | N/A(合规) | 无相关目录/依赖 |
|
||||||
|
| M8 | 可见按钮必须有效;无公开数据/执行能力的面板删除 | PASS | 每个 Dock/对话框动作有效;变量/内存仅一个 UNSUPPORTED 说明,无假按钮 |
|
||||||
|
|
||||||
|
## 2. §1.2 功能范围(MVP 强制项)
|
||||||
|
|
||||||
|
| 功能 | 状态 | 计划/证据 |
|
||||||
|
|---|---|---|
|
||||||
|
| Markdown/GFM 阅读 | PASS | `src/document.rs`、`src/render.rs`、浏览器证据 |
|
||||||
|
| `@exec`/`@knowledge` 轻量标识(依 Analysis) | PASS | `src/semantic.rs`、`tests/integration/rendering.rs` |
|
||||||
|
| 源码态 | PASS | `src/render.rs`、`tests/integration/unicode_spans.rs` |
|
||||||
|
| 函数清单/导航 | PASS | `src/presentation.rs`、`src/render.rs` |
|
||||||
|
| 单函数参数填写 + 调用 | PASS | `assets/reader.js` 动态表单 + `execution/request.rs` + HTTP/SSE 测试 |
|
||||||
|
| 文档入口 `main` 执行 | PASS | `POST /api/runs` → SSE;无 main 时引导函数列表 |
|
||||||
|
| 运行结果(返回/stdout/stderr/错误) | PASS | 安全文本/DOM 渲染、`value_text`、stderr/stdout、错误码;浏览器/HTTP 测试 |
|
||||||
|
| 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 架构与目录
|
||||||
|
|
||||||
|
| 条款 | 状态 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| 唯一 Reader+Controller+CLI;无 DocumentService→Execution 隐式调用 | PASS | 只有 `POST /api/runs` 处理函数持有 Controller;页面/导出/GET 无执行边 |
|
||||||
|
| 层间数据结构(SourceDocument/AnalysisArtifact/SemanticAnchor/ExecutionRecord/PresentationModel) | PASS | `reader::{source,model,assemble}`、`StaticDocument`、`ExecutionRecord`-equivalent job/event DTO;serde 显式 DTO |
|
||||||
|
| §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 |
|
||||||
|
| §5.4 单一渲染流水线;Export 类型边界不可执行 | PASS(0001) | `src/export.rs` 不依赖执行层;PR-06 复核 |
|
||||||
|
| 无第二 Markdown AST/解释器/主题/JS 入口 | PASS | `tests/contract/no_coupling.rs`、`tests/contract/asset_integrity.rs` |
|
||||||
|
|
||||||
|
## 4. §6 HTTP / SSE / 执行合同
|
||||||
|
|
||||||
|
| 条款 | 状态 | 计划 |
|
||||||
|
|---|---|---|
|
||||||
|
| 7 条最小路由 | PASS | `server/routes.rs`;旧路由 404 测试 |
|
||||||
|
| 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 测试 |
|
||||||
|
| 校验顺序(会话→CSRF/Origin/Host→大小/schema→containment→check→digest→函数/参数→模式/grants→并发→202) | PASS | `server/security.rs` + Controller;拒绝路径不启动进程测试 |
|
||||||
|
| 同 `client_request_id` 幂等/不同 payload 409 | PASS | Controller + HTTP 集成测试 |
|
||||||
|
| SSE 帧合同(事件类型/seq/id/schema/心跳) | PASS | `server/sse.rs`、`tests/integration/http_live.rs` |
|
||||||
|
| Last-Event-ID 重放、快照、128 缓冲、TTL、≤2 连接/任务 | PASS | 重放/伪造游标/2 连接/终态快照测试 |
|
||||||
|
| 单活动任务、409 run.busy、后台执行不阻塞 SSE | PASS | Controller + HTTP 409/并发测试 |
|
||||||
|
| 进程组取消(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 里程碑
|
||||||
|
|
||||||
|
| PR | 状态 | 提交 |
|
||||||
|
|---|---|---|
|
||||||
|
| PR-00 取证/基线 | **完成** | 待提交(本提交) |
|
||||||
|
| PR-01 Tool/打包/scripts/CI/0.2.0 | **完成** | `scripts/package.sh`、`scripts/install-smoke.sh`、`scripts/verify-frozen-cli.sh`、`.github/workflows/ci.yml` |
|
||||||
|
| PR-02 Reader/Analysis 结构与只读路由 | **完成** | `src/protocol/*`、`src/reader/*`、`src/config.rs`、`/api/documents`、`tests/{contract,integration}`;`docs/evidence/PR-02/` |
|
||||||
|
| PR-03 执行层/请求/进程/控制器 | **完成** | `src/execution/*`、ADR-0008、`docs/evidence/PR-03/` |
|
||||||
|
| PR-04 SSE/路由/会话/前端闭环 | **完成** | `docs/evidence/PR-04/`(含真实 Chromium + 真实冻结 CLI) |
|
||||||
|
| PR-05 Trace 绑定/标注/浏览器回归 | **完成** | ADR-0010、`docs/evidence/PR-05/` |
|
||||||
|
| PR-06 导出/发布/文档闭环 | **完成** | `examples/`、`scripts/{check-examples,test-no-exec}.sh`、`docs/ACCEPTANCE.md`、最终 evidence manifest |
|
||||||
|
|
||||||
|
## 6. §9 验收测试矩阵(E01–E16 / N01–N22)
|
||||||
|
|
||||||
|
| 组 | 状态 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| 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 |
|
||||||
|
| 2. Tool 独立安装;CLI 无 View 核心提交;SHA 不变 | PASS | acceptance `archive_install`/`core_sha`(0.2.0 重跑) |
|
||||||
|
| 3. 打开/刷新/导出零副作用;执行仅来自显式 POST;跨站/CSRF 全绿 | PASS | `no_exec_suite`、`security_suite`、`tests/security/` |
|
||||||
|
| 4. SSE 生命周期/心跳/序号/重连/有界重放;无轮询 | PASS | HTTP/SSE 集成 + 浏览器请求记录 |
|
||||||
|
| 5. 真值来自 CLI/Analysis/Trace;无假变量/内存/证明 | 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 |
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
architecture/RFC-VIEW-0002.md
|
||||||
@@ -1,81 +1,92 @@
|
|||||||
# marqdo-view 现状(STATUS)
|
# marqdo-view 现状(STATUS)
|
||||||
|
|
||||||
> 唯一现状来源。设计/规范见 RFC 与 ADR;本文只记录**实际完成、证据与限制**。
|
> 唯一现状来源。规范见 `docs/architecture/RFC-VIEW-0002.md`;本文只记录
|
||||||
> 最后更新:2026-11-22(PR-06 完成)
|
> **实际完成、证据与限制**。最后更新:2026-11-22(Issue #2 复验)
|
||||||
|
|
||||||
## 版本与基线
|
## 版本与基线
|
||||||
|
|
||||||
| 项 | 值 |
|
| 项 | 值 |
|
||||||
|---|---|
|
|---|---|
|
||||||
| View 版本 | `0.1.0` |
|
| View 产品版本 | `0.2.0` |
|
||||||
|
| 实施规范 | `docs/architecture/RFC-VIEW-0002.md`(2026-11-22) |
|
||||||
| 目标 CLI 产品范围 | `>=3.0.0-beta.1,<4.0.0` |
|
| 目标 CLI 产品范围 | `>=3.0.0-beta.1,<4.0.0` |
|
||||||
| 冻结 CLI 二进制 | 发布归档 `marqdo-3.0.0-beta.1-x86_64-unknown-linux-gnu.tar.gz` 中的 `marqdo` |
|
| 冻结 CLI 二进制 SHA-256 | `062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f` |
|
||||||
| 冻结 CLI SHA-256 | `062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f` |
|
|
||||||
| CLI 源码 SHA | `2c7c4f31e7a388d3fcfa717a77067e696ed13854`(tag `v3.0.0-beta.1`) |
|
| CLI 源码 SHA | `2c7c4f31e7a388d3fcfa717a77067e696ed13854`(tag `v3.0.0-beta.1`) |
|
||||||
| 协议 | Tool v1 / Analysis v2 / Trace v2 / markdown profile `marqdo.md.v1` |
|
| 协议 | Tool v1 / Analysis v2 / Trace v2 / `marqdo.md.v1` |
|
||||||
| 目标平台 | Linux x86_64 glibc(正式);其他平台未验证 |
|
| 目标平台 | Linux x86_64 glibc(正式);其他平台不支持/未验证 |
|
||||||
| 视觉基准 | `docs/design/reference-old-view-reader.png`(1664×920) |
|
| 视觉基准 | `docs/design/reference-old-view-reader.png`(**2048×1133**) |
|
||||||
| 验收证据 | `docs/evidence/<CLI-SHA>/manifest.json`(由 `tools/acceptance.sh` 真实命令生成) |
|
| 验收状态 | `docs/ACCEPTANCE.md`;最新本地复验证据见 `docs/evidence/issue-2/manifest.json` |
|
||||||
|
|
||||||
## 分阶段进度
|
## RFC-VIEW-0002 里程碑(全部完成)
|
||||||
|
|
||||||
| 阶段 | 状态 | 证据 |
|
| 阶段 | 状态 | 证据 |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| PR-00 基线与旧 View 静态取证 | **完成** | `docs/audits/legacy-render-paths.md`、`docs/design/*`、ADR-0001/0002 |
|
| PR-00 基线、旧 View 取证、冻结 CLI 合同 | **完成** | `docs/audits/legacy-view.md`、`docs/audits/protocol-contract-0002.md`、ADR-0007 |
|
||||||
| PR-01 Tool v1 安装闭环 | **完成** | `tool.json`、`tools/package.sh`、`tools/install-smoke.sh`、`tests/core_contract.rs`、`tests/no_coupling.rs` |
|
| 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/` |
|
||||||
| PR-02 DocumentModel + Analysis v2 浏览 | **完成** | `src/document.rs`、`src/semantic.rs`、`src/presentation.rs`、`src/render.rs`、`src/server.rs`、冻结 Analysis golden |
|
| PR-02 Reader/Analysis 目标目录与只读面 | **完成** | `src/protocol/*`、`src/reader/*`、`src/config.rs`、`/api/documents`、`tests/{contract,integration}`、`docs/evidence/PR-02/` |
|
||||||
| PR-03 Reader 视觉重建 | **完成(像素级人工比对未执行)** | 单一 `assets/reader.css`/`reader.js`;真实 Chromium 7 宽度/无 JS/打印/运行 PASS;`docs/evidence/PR-03/` |
|
| PR-03 执行层:request/process/controller、pure + project grants | **完成** | `src/execution/*`、`--run-timeout`、ADR-0008、`docs/evidence/PR-03/` |
|
||||||
| PR-04 Trace v2 运行可视化 | **完成** | `src/trace.rs`、CSRF/确认运行 API、真实 Trace golden、`tests/trace_contract.rs`、ADR-0004 |
|
| PR-04 SSE 任务生命周期、取消、7 路由、会话 Cookie/CSRF | **完成** | `src/server/{mod,routes,security,sse}.rs`、`assets/reader.js`、ADR-0009、`docs/evidence/PR-04/`(真实 CLI + Chromium) |
|
||||||
| PR-05 Live 安全 + 静态导出 | **完成** | `src/export.rs`、`tools/test-export.sh`、`tools/test-security.sh`、`tests/export.rs`、ADR-0005 |
|
| PR-05 Trace 绑定/原文标注/浏览器回归 | **完成** | Controller Trace 摘要/`source_id`/stale、ADR-0010、`docs/evidence/PR-05/` |
|
||||||
| PR-06 冻结 CLI 端到端验收 | **完成(CI 远端未运行)** | `tools/acceptance.sh` 全部 PASS;`docs/evidence/<CLI-SHA>/manifest.json`;`docs/ACCEPTANCE.md`;ADR-0006 |
|
| PR-06 静态导出/发布包/示例/文档闭环 | **完成** | `examples/*.mq.md`、`scripts/check-examples.sh`、`scripts/test-no-exec.sh`、`docs/ACCEPTANCE.md`、最终 evidence manifest |
|
||||||
|
|
||||||
## 能力现状
|
## 能力现状
|
||||||
|
|
||||||
| 能力 | 状态 |
|
| 能力 | 状态 |
|
||||||
|---|---|
|
|---|---|
|
||||||
| 原始 Markdown 阅读(GFM 表/任务列表/引用/围栏/数学原文) | 已实现 |
|
| 原始 Markdown/GFM 阅读、源码态、搜索/设置/打印/深色主题 | 已实现(单一 `assets/reader.css` + `assets/reader.js`) |
|
||||||
| 文档态 / 源码态(原文逐行,含标记) | 已实现 |
|
| Analysis v2 严格校验 + 函数/Unit/签名/诊断/导入/引用/资源投影 | 已实现(无效 span/摘要降级,未知 major 拒绝) |
|
||||||
| Analysis v2 静态语义(Unit/Function/Signature/诊断/导入/引用/资源) | 已实现,严格校验 + 无效 span 降级 |
|
| 单一 Read Model/HTML 组件/CSS/JS;Live=Export | 已实现(门禁测试) |
|
||||||
| 单一 `ReaderRenderer`,Live/Export 共用 | 已实现(门禁测试) |
|
| 固定 7 路由 Live 服务;打开/刷新/搜索/切换/导出零执行 | 已实现并测试 |
|
||||||
| Live 只读 API(`/`、`/file`、`/assets`、`/api/document`、`/api/health`) | 已实现 |
|
| 显式单任务执行(run main / call function),纯 + 受控 project fs grants | 已实现(两阶段确认、命令预览、二次确认) |
|
||||||
| 显式确认运行 + Trace v2 可视化(`pure` 模式) | 已实现(CSRF/Origin/单活动/超时) |
|
| SSE 状态/终态、取消、心跳、Last-Event-ID 重放、无轮询 | 已实现(单任务、128 环形缓冲、2 连接上限) |
|
||||||
| 静态离线导出(纯只读、manifest/哈希、原子发布) | 已实现 |
|
| 运行结果(Wire Value/stdout/stderr/错误/诊断)安全文本展示 | 已实现(无 innerHTML 服务端数据) |
|
||||||
| 搜索/导航/设置/打印/无 JS/响应式 | 已实现(真实浏览器验收) |
|
| Trace v2 调用/分支/循环/副作用 + 原文锚点 + stale 降级 | 已实现(分组 chip、来源标注、截断/无效显式) |
|
||||||
| `view verify`(CLI/Analysis/source 绑定,无执行) | 已实现 |
|
| Tool v1 独立安装/分发、冻结 CLI SHA 前后一致 | 已实现(0.2.0 包,篡改拒绝) |
|
||||||
|
| 静态离线导出(无执行、无联网、manifest/哈希、不可变发布) | 已实现并重新验收 |
|
||||||
|
| 固定 examples(welcome/branch-loop/function-params/knowledge-only/unsafe-side-effect) | 已实现,冻结 CLI check/call/run 实测 |
|
||||||
| 逐语句变量值 / 参数实际值 / 内存快照 | **UNSUPPORTED**(Trace v2 不提供,绝不伪造) |
|
| 逐语句变量值 / 参数实际值 / 内存快照 | **UNSUPPORTED**(Trace v2 不提供,绝不伪造) |
|
||||||
| 知识“已证明” / Prove / Knowledge / Lint | **UNSUPPORTED**(等待独立协议) |
|
| 知识“已证明” / Prove / Lint | **UNSUPPORTED**(等待独立版本化报告协议) |
|
||||||
| 调试器/断点/单步、Notebook、旧 2.x 语法 | **不实现**(非目标) |
|
| 调试器/断点/单步/调用栈、Notebook/持久内核、Session/journal | **不实现**(RFC 明确删除) |
|
||||||
| `project`/`strict` 运行与 grants 授权界面 | **未实现**(首版仅 `pure`,拒绝其他模式) |
|
| AI/Agent/Token 流、插件市场、DB/多租户 | **不实现**(非目标) |
|
||||||
| SSE 流式输出、多运行历史、取消运行 | **未实现**(运行完成后整页重载) |
|
| `strict`、net/process/env/plugin/provider/kernel 授权 UI | **不提供**(拒绝并引导终端 CLI) |
|
||||||
| SVG 曲线侧注 | **未实现**(使用内联 keyed chip,U-04 PARTIAL) |
|
| Windows/macOS 发行 | **不支持/未验证** |
|
||||||
| 像素级视觉比对 | **UNVERIFIED**(人工复核待办,U-01) |
|
|
||||||
| 远端 CI 实际运行 | **UNVERIFIED**(`.woodpecker.yml` 已提供;本地可复现证据已生成) |
|
|
||||||
|
|
||||||
## 验收证据
|
## 明确 UNSUPPORTED / 非目标(不得伪造)
|
||||||
|
|
||||||
- 一键:`MARQDO_BIN=/abs/path/marqdo tools/acceptance.sh`
|
- 变量/内存/逐语句值:Trace v2 不提供;UI 只有一个明确的“未提供的能力”说明。
|
||||||
- 全链路结果:`fmt/clippy/test/build/bundle/archive_install/view_help/verify/export/browse/real_run/export_suite/security_suite/browser/core_sha` 全部 PASS。
|
- 数学/领域正确性与“已证明”:Analysis 成功 ≠ 证明;未来 Prove 独立提供。
|
||||||
- 冻结核心 SHA-256 在验收前后完全相同(`062cb56e…`),View 从未重编译/链接 CLI。
|
- Notebook/Run All/内核重启、断点/单步/时间旅行、第二套 Markdown AST/解释器。
|
||||||
- 安装来自 `.tar.gz` 发布归档解包到临时目录;不读取 CLI 源码或旧仓库运行代码。
|
- 网络/进程/环境/插件/Provider/Foreign 授权 UI;高级执行由用户在终端运行 CLI。
|
||||||
- 浏览器:Chromium Headless Shell 131(Playwright 1.49),7 个宽度、无外部请求、无 console 错误、无 JS 可读、打印、恶意 fixture、显式运行。
|
|
||||||
- 详见 `docs/ACCEPTANCE.md` 与 `docs/evidence/`。
|
|
||||||
|
|
||||||
## 已知限制与偏差
|
## 证据入口
|
||||||
|
|
||||||
- 测试按 crate 根级集成测试文件组织,而非 RFC 建议的子目录树;职责与门禁不变(ADR-0006)。
|
| 内容 | 路径 |
|
||||||
- 运行完成后整页重载;不实现 SSE/取消/历史。
|
|---|---|
|
||||||
- 静态导出每个文档执行一次 `check`(非执行),无增量导出。
|
| 一键验收 + 最终 manifest | `scripts/acceptance.sh`;`docs/evidence/2c7c4f31…/manifest.json` |
|
||||||
- 首版运行仅 `pure`;`project`/`strict` grants 需要未来独立授权 UI。
|
| 验收门禁报告 | `docs/ACCEPTANCE.md` |
|
||||||
- 平台:仅 Linux x86_64 glibc 正式验证;macOS/Windows 未验证。
|
| 0002 合规矩阵 | `docs/CONFORMANCE.md` |
|
||||||
- 视觉:几何/颜色/响应式/无外部资源自动化 PASS,但像素级人工比对未执行。
|
| 冻结 CLI 合同 | `docs/audits/protocol-contract-0002.md` |
|
||||||
|
| 旧 View 取证 | `docs/audits/legacy-view.md`(静态;运行时 `LEGACY_RUNTIME_UNVERIFIED`) |
|
||||||
|
| 分 PR 证据 | `docs/evidence/PR-01..PR-06/` |
|
||||||
|
| 示例 fixture 实测 | `scripts/check-examples.sh`(输出见 `docs/evidence/PR-06/`) |
|
||||||
|
| 零执行哨兵 | `scripts/test-no-exec.sh` |
|
||||||
|
| 浏览器截图/日志 | `docs/evidence/PR-04/`、`docs/evidence/PR-05/` |
|
||||||
|
| 决策记录 | `docs/decisions/0001..0010` |
|
||||||
|
|
||||||
|
## 已知限制与偏差(诚实状态)
|
||||||
|
|
||||||
|
- 首版运行仅 `pure` 与受控 `project` fs read/write;`project` 不是 OS 沙箱,
|
||||||
|
不自动提升 `marqdo.yaml` capability 请求。
|
||||||
|
- SSE 只推送 View 生命周期与终态数据,不承诺逐字 stdout/Token 流(RFC §6.1)。
|
||||||
|
- 观测侧注采用内联分组 chip,而非 SVG 曲线;按 RFC §4.4 允许降级(ADR-0010)。
|
||||||
|
- 像素级人工视觉比对与完整 screen-reader 走查仍为 `UNVERIFIED`;自动化证据充分。
|
||||||
|
- 本地验收与远端 CI 使用同一入口 `scripts/acceptance.sh`;远端状态以 PR 检查为准。
|
||||||
|
- 平台:Linux x86_64 glibc 正式验证;其他平台不声明支持。
|
||||||
|
|
||||||
## 复现文档
|
## 复现文档
|
||||||
|
|
||||||
- 一分钟使用:`README.md`
|
- 使用/安装:`README.md`
|
||||||
- 规范:`docs/RFC-VIEW-0001.md`
|
- 规范:`docs/architecture/RFC-VIEW-0002.md`(当前)、`RFC-VIEW-0001.md`(历史)
|
||||||
- 兼容性:`COMPATIBILITY.md`
|
- 兼容性:`COMPATIBILITY.md`
|
||||||
- 变更:`CHANGELOG.md`
|
- 变更:`CHANGELOG.md`
|
||||||
- 旧 View 审计:`docs/audits/legacy-render-paths.md`
|
- 决策:`docs/decisions/`
|
||||||
- 协议一致性:`docs/audits/protocol-conformance.md`
|
|
||||||
- 验收:`docs/ACCEPTANCE.md`
|
|
||||||
- 决策:`docs/ADR/0001..0006`
|
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
# 旧 View 静态取证与迁移裁决(RFC-VIEW-0002 §3 / PR-00)
|
||||||
|
|
||||||
|
- 状态:静态源码审计完成,**旧运行时浏览器复验未执行**
|
||||||
|
(`LEGACY_RUNTIME_UNVERIFIED`)
|
||||||
|
- 日期:2026-11-22
|
||||||
|
- 旧产品来源:`cflmy/marqdo`,`main@1c55baabd570e18b9da8f9057cef2f848e176690`
|
||||||
|
(本机只读 checkout `/root/work/marqdo`;新仓库**没有**任何 Git/path/Cargo 依赖)
|
||||||
|
- 新仓库:`marqdo-view`(独立 crate,见 `Cargo.toml` / `tests/contract/no_coupling.rs`)
|
||||||
|
- 结论适用范围:只作为**视觉与历史取证**。旧 `view` 的运行结果、旧 AST、旧
|
||||||
|
`RunCapture` 都**不是** 3.0 语言语义真值;语言真值只来自冻结 CLI 的
|
||||||
|
Analysis v2 / Trace v2(见 `docs/audits/protocol-contract-0002.md`)。
|
||||||
|
|
||||||
|
## 0. 证据分级与审计限定
|
||||||
|
|
||||||
|
| 级别 | 含义 | 本文用法 |
|
||||||
|
|---|---|---|
|
||||||
|
| LEGACY-OBSERVED | 在旧源码中直接读到的入口、样式注入、事件监听、执行调用 | 均可给出 `file:line` |
|
||||||
|
| LEGACY_RUNTIME_UNVERIFIED | 只有源码证据,没有在浏览器逐像素/交互复现 | 所有旧运行时结论均加此标记 |
|
||||||
|
| KEEP_ASSET | 只把已核验图形的**字节**迁入新仓库,附来源与许可证 | 见 §5 |
|
||||||
|
| REIMPLEMENT | 保留设计特征,按新架构重写 | 视觉 token、Dock、侧注 |
|
||||||
|
| DROP | 明确不迁移 | Notebook/Debug/Memory/旧 CSS 栈等 |
|
||||||
|
| UNKNOWN | 证据不足,不据此实现 | 截图右侧黑线 artifact 等 |
|
||||||
|
|
||||||
|
**限定**:§3.1 的旧结构与样式覆盖事实来自源码阅读;旧项目是否仍能编译、旧
|
||||||
|
README 截图对应哪一版运行 DOM,都**未**在本工作周期复现,不得当作软件事实引用。
|
||||||
|
参考截图 `docs/design/reference-old-view-reader.png` 已核验为 **2048×1133**
|
||||||
|
PNG(`file` 输出:`PNG image data, 2048 x 1133, 8-bit/color RGBA`),是视觉验收
|
||||||
|
基准,不是源码实现证据。
|
||||||
|
|
||||||
|
## 1. 旧命令树与页面入口
|
||||||
|
|
||||||
|
命令定义在旧 `src/main.rs`(LEGACY-OBSERVED):
|
||||||
|
|
||||||
|
| 旧入口 | 位置 | 构建/执行路径 | 新 View 裁决 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `Commands::View { action: None }` → `serve(ViewOptions)` | `src/main.rs:1741-1750`、`src/view/mod.rs:74` | Live HTTP 页面,`/api/run`、Notebook/调试 API 同进程 | **REIMPLEMENT**:只保留阅读 + 显式单任务运行(RFC §5.2 路由表) |
|
||||||
|
| `ViewAction::Output` → `write_static(OutputOptions)` | `src/main.rs:1664-1678`、`src/view/output.rs:266` | 静态导出;`no_exec` 开关决定是否在导出时执行文档 | **REIMPLEMENT**:新导出从类型边界就不能执行(`src/export.rs`,RFC §5.4) |
|
||||||
|
| `ViewAction::Capture` → `write_capture` | `src/main.rs:1679-1687`、`src/view/output.rs:189` | 运行捕获快照(依赖旧 `RunCapture`/session 产物) | **DROP**:Trace v2 不提供逐句变量/参数快照 |
|
||||||
|
| `ViewAction::Document` → `workbench::build_document_view` | `src/main.rs:1688-1740` | Workbench HTML fragment 输出 | **DROP**:不是阅读器,不建第二套 DOM/工作台 |
|
||||||
|
| `Commands::Debug` → `serve_debug(DebugOptions)` | `src/main.rs:1751-1760`、`src/view/mod.rs:102` | 独立暗色调试服务器;断点、单步、`page_debug` | **DROP**:RFC §1.2/§3.3/§4.5 明令删除 |
|
||||||
|
| Live `serve` 内路径分派 | `src/view/mod.rs:74-101`、`240-390` | `page_file`、`page_debug`、`/api/run`、`/api/session/*`、`/api/debug/*` | **REIMPLEMENT**:新服务固定 7 条路由(RFC §6.2) |
|
||||||
|
|
||||||
|
**多页面生成路径事实**:Live 主路径 `page_file`(`src/view/html.rs:4111`)、调试
|
||||||
|
路径 `page_debug`(`src/view/debug_page.rs:50`)、Workbench fragment、静态导出
|
||||||
|
`write_static` 各自组装 HTML。这证明旧代码存在多条页面/模板路径;它**不**证明
|
||||||
|
浏览器里同时加载了两套 View(那需要运行时复验,`LEGACY_RUNTIME_UNVERIFIED`)。
|
||||||
|
|
||||||
|
## 2. CSS/JS 注入顺序与覆盖(必须整体废弃的叠层)
|
||||||
|
|
||||||
|
旧 `layout()`/`page_file` 在 `src/view/html.rs:1680` 起组装 `<body class="reader-page">`,
|
||||||
|
同文件 `2660-2700` 一处同时注入:
|
||||||
|
|
||||||
|
- `stylesheet()`(`src/view/html.rs:30`):包含 Notebook 工作台皮肤和
|
||||||
|
`body.notebook-page ...` 数百条规则(同文件 `699-704`、`2849` 之后的
|
||||||
|
`notebook_ui()` 大段 CSS);
|
||||||
|
- `notebook_ui()`(`src/view/html.rs:2849` 起):`body.notebook-page` 作用域样式;
|
||||||
|
- KaTeX CSS/JS 通过 `include_str!("assets/vendor/katex*.{css,js}")` 内联;
|
||||||
|
- 最后追加 `reader.css`(`include_str!("reader.css")`)与 `reader.js`
|
||||||
|
(`include_str!("reader.js")`,`src/view/html.rs:2689-2690`)。
|
||||||
|
|
||||||
|
`reader.css` 自身又以更高优先级反向覆盖 Notebook 皮肤,例如
|
||||||
|
`body.reader-page, body.reader-page.notebook-page, ...`(`src/view/reader.css:2`)、
|
||||||
|
`body.reader-page.notebook-page[data-theme="dark"]`(同文件 `18`)、
|
||||||
|
`body.reader-page #notebook-bar ...`(同文件 `102-105`)。也就是说旧页面的最终外观
|
||||||
|
依赖“两套皮肤 + 后置覆盖”的偶然顺序。
|
||||||
|
|
||||||
|
`reader.js` 在运行时再 `document.body.classList.add("notebook-page")`
|
||||||
|
(`src/view/reader.js:3561` 附近逻辑),把 Notebook 皮肤激活到阅读页上。
|
||||||
|
|
||||||
|
**裁决:DROP 整个旧 CSS/JS 叠层。** 新仓库只有 `assets/reader.css` 与
|
||||||
|
`assets/reader.js` 两个发布入口(见 `docs/decisions/0001`、`0002`),没有
|
||||||
|
`.notebook-page` 皮肤,不内联第三方 CSS/JS(KaTeX 不引入;公式按原文呈现)。
|
||||||
|
|
||||||
|
## 3. JS 初始化与执行调用连线
|
||||||
|
|
||||||
|
| 旧行为 | 证据 | 裁决 |
|
||||||
|
|---|---|---|
|
||||||
|
| Welcome Hero 由**文件名正则**注入:`/(^|\/)(00[-_])?(welcome|欢迎)/i.test(path)` 后 `hero.innerHTML = ...` 并 `prepend` | `src/view/reader.js:569-575` | **REIMPLEMENT**:只允许显式 `view.json` welcome 配置;禁止路径猜测 |
|
||||||
|
| 侧注曲线:创建 `svg.reader-connectors`、`g.reader-connector`,按 DOM 矩形计算路径 | `src/view/reader.js:221`、`341`、`366`、`555-559` | **REIMPLEMENT**(可降级):新 View 首版用内联 keyed chip,不画无来源线;曲线是增强而非布局条件 |
|
||||||
|
| 旧注解焦点/搜索/对话框键盘事件与 `MutationObserver` 重排 | `src/view/reader.js:555-600` | REIMPLEMENT(仅保留阅读所需搜索/设置/焦点) |
|
||||||
|
| 页面内执行:`POST /api/run`,服务端 `api_run` 调 `run_file_capture(abs, opts)`,再把 stdout/bindings 注入 HTML | `src/view/mod.rs:245-246`、`805`;`src/view/mod.rs:430-520`;`src/view/output.rs:189` | **DROP**:执行必须由用户显式提交、经 SSE 观察、结果只按文本/DOM 展示,不得由页面加载/导出触发 |
|
||||||
|
| 运行后重读源码、重算 annots 并原地替换 surface | `src/view/mod.rs:500-520` | REIMPLEMENT:新 View 以 Analysis/Trace span 绑定,源码变化即 stale |
|
||||||
|
| 会话/Notebook/调试 REST:`/api/session/*` 20+ 路由、`/api/debug/*`、`/api/events` | `src/view/mod.rs:197-246`、`300-338` | **DROP**:新服务不允许 shell 执行端点、Notebook REST 兼容层、EventBus |
|
||||||
|
|
||||||
|
## 4. 新仓库必须拒绝“复制再隐藏”
|
||||||
|
|
||||||
|
RFC §3.3 的禁建目录(新仓库确实都不存在):`src/notebook/`、`src/debug/`、
|
||||||
|
`src/memory_inspector/`、`src/session_kernel/`、`src/knowledge_compiler/`、
|
||||||
|
`src/proof_engine/`、`src/agent/`、`src/legacy_compat/`。
|
||||||
|
新仓库保留旧代码特征的地方只有**视觉 token 与三张已核验图片**;没有旧 AST、
|
||||||
|
没有旧 `RunCapture`、没有旧事件总线、没有旧页面模板。
|
||||||
|
|
||||||
|
## 5. 资产来源与许可证(已迁入 assets/)
|
||||||
|
|
||||||
|
| 文件 | 旧路径 | SHA-256(新仓库实测) | 许可证 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `assets/logo.svg` | `src/view/assets/logo.svg` | `52b2338468c62a7da86178ecec86cbb7ea44a996cd1bc4275ebb56f16f2244fe` | Apache-2.0(旧 marqdo) |
|
||||||
|
| `assets/blossom.webp` | `src/view/assets/blossom.webp` | `901fd6b37ebb20d1dfc3bf4d265a063308605350fd317e41914fa35b06f46e00` | Apache-2.0(旧 marqdo) |
|
||||||
|
| `assets/feather.webp` | `src/view/assets/feather.webp` | `fbd787174be1e8027ae4661b99f7f2cc01b824d8fc875a1d2d39cbd0c052e5de` | Apache-2.0(旧 marqdo) |
|
||||||
|
|
||||||
|
旧 `assets/README.md` 说明 blossom/feather 是为阅读器改版生成的原生透明素材,logo
|
||||||
|
为项目自绘几何 M/书签图形;旧仓库整体 Apache-2.0。详细许可说明见
|
||||||
|
`assets/licenses/ASSETS.md`;三个文件由 `src/assets.rs`(构建期嵌入)以 SHA-256
|
||||||
|
断言,Live 与 Export 提供完全相同的字节(ADR-0002)。
|
||||||
|
|
||||||
|
**UNKNOWN**:参考截图右侧的黑色短线/竖线不是品牌元素,不复刻;没有来源证据说明
|
||||||
|
它是 UI 组成。
|
||||||
|
|
||||||
|
## 6. 逐资源迁移裁决表
|
||||||
|
|
||||||
|
| 旧资源/行为 | 裁决 | 理由 |
|
||||||
|
|---|---|---|
|
||||||
|
| 暖纸色/金/橄榄/衬线正文视觉 token(旧 `reader.css` 色感) | REIMPLEMENT | 重新定义为 `assets/reader.css` 的唯一 token 集(RFC §4.3) |
|
||||||
|
| 左上樱花、品牌 logo、羽毛 | KEEP_ASSET | 已核验来源/许可/HASH;仅装饰 |
|
||||||
|
| 顶栏菜单 / 品牌 / 搜索、三项导航 `文档/函数/运行` | REIMPLEMENT | 新 IA,删除变量/内存 |
|
||||||
|
| 五按钮 Dock(刷新/设置/运行/清理/更多) | REIMPLEMENT | 每个按钮单一真实行为(RFC §4.2) |
|
||||||
|
| 金色函数竖标、连续阅读区、轻边框表格、底部浮动椭圆栏 | REIMPLEMENT | 设计特征,不复制 DOM/CSS |
|
||||||
|
| 侧注连接曲线 | REIMPLEMENT(首版降级为行内编号 chip) | 先准确关联,再追求曲线;失败可降级 |
|
||||||
|
| 旧 Welcome 文件名注入 | DROP / REIMPLEMENT 为显式配置 | RFC §9.3.3 禁止按名字前缀注入 |
|
||||||
|
| `stylesheet()` + `notebook_ui()` + `reader.css` 叠层 | DROP | 唯一主题入口;禁止旧 `.notebook-page` 覆盖 |
|
||||||
|
| 旧 `reader.js` Notebook/调试/连接线状态监听器 | DROP | 不复活 Notebook 状态机;新 JS 只做 DOM/SSE |
|
||||||
|
| KaTeX 内联渲染 | DROP(公式按原文显示) | 禁 CDN/第三方运行时;数学不属 View 语义 |
|
||||||
|
| `debug_page.rs`、`debug_api.rs`、断点/单步/调用栈 | DROP | RFC §1.2 REMOVED |
|
||||||
|
| `write_capture` / `RunCapture` / 变量面板 / 内存网格 | DROP | Trace v2 不提供逐句值;不得伪造 |
|
||||||
|
| `/api/session/*`、`/api/debug/*`、`/api/events`、Workbench fragment | DROP | 单一阅读 + 单任务执行;固定最小路由 |
|
||||||
|
| 旧 `serve` 的多页面入口与执行抓取交错 | DROP | 新架构 `Reader → assemble → Renderer` 单一流水线 |
|
||||||
|
|
||||||
|
## 7. 风险结论
|
||||||
|
|
||||||
|
1. 静态可证:旧 View 存在多页面生成路径、CSS/JS 叠层、页面加载/导出可触发执行的
|
||||||
|
代码路径、以及大量 Notebook/调试 REST 入口。
|
||||||
|
2. 未证:旧页面在浏览器中的实际最终 DOM、样式优先级与截图对应关系;
|
||||||
|
一律 `LEGACY_RUNTIME_UNVERIFIED`,不得引用为通过证据。
|
||||||
|
3. 新 View 的任何“视觉相似”都不构成语言/执行正确性证据;语言事实以冻结
|
||||||
|
CLI `check --emit` + `run/call --json` + Trace v2 的黑盒结果为准。
|
||||||
|
4. 旧的代码/资产只能按 §5 的字节级来源迁入;不得对旧仓库建立任何构建依赖。
|
||||||
@@ -17,12 +17,12 @@
|
|||||||
|
|
||||||
| 条款 | 实现 | 测试/证据 |
|
| 条款 | 实现 | 测试/证据 |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `tool.json` schema/字段/SemVer/command/entrypoint | `tool.json`、`tools/package.sh` | `tests/no_coupling.rs`;`tools/install-smoke.sh` |
|
| `tool.json` schema/字段/SemVer/command/entrypoint | `tool.json`、`scripts/package.sh` | `tests/contract/no_coupling.rs`;`scripts/install-smoke.sh` |
|
||||||
| 冻结核心安装、整包摘要、启动校验 | `tools/install-smoke.sh`、`tools/acceptance.sh` | acceptance `archive_install` PASS;手工篡改字节验证 README(PR-01 证据) |
|
| 冻结核心安装、整包摘要、启动校验 | `scripts/install-smoke.sh`、`scripts/acceptance.sh` | acceptance `archive_install` PASS;手工篡改字节验证 README(PR-01 证据) |
|
||||||
| 环境变量 `MARQDO_BIN`/协议协商 | `src/core_client.rs`、`src/version.rs` | `tests/core_contract.rs`、`tests/http_live.rs` |
|
| 环境变量 `MARQDO_BIN`/协议协商 | `src/core_client.rs`、`src/version.rs` | `tests/contract/core_contract.rs`、`tests/integration/http_live.rs` |
|
||||||
| argv 数组、无 shell、保留退出码/stdio | `src/core_client.rs` | `tests/core_contract.rs`(argv、timeout、fake core) |
|
| argv 数组、无 shell、保留退出码/stdio | `src/core_client.rs` | `tests/contract/core_contract.rs`(argv、timeout、fake core) |
|
||||||
| 不链接/不重编译/不读 CLI 源码 | 依赖图 | `tests/no_coupling.rs`、`docs/ADR/0001` |
|
| 不链接/不重编译/不读 CLI 源码 | 依赖图 | `tests/contract/no_coupling.rs`、`docs/ADR/0001` |
|
||||||
| 篡改/缺文件/协议不兼容拒绝 | CLI 自身 + View 侧协商 | `tests/core_contract.rs`、`tools/install-smoke.sh` |
|
| 篡改/缺文件/协议不兼容拒绝 | CLI 自身 + View 侧协商 | `tests/contract/core_contract.rs`、`scripts/install-smoke.sh` |
|
||||||
|
|
||||||
## 3. Analysis v2
|
## 3. Analysis v2
|
||||||
|
|
||||||
@@ -32,7 +32,7 @@
|
|||||||
| `schema/schema_version=2`、未知 major 拒绝 | `src/semantic.rs`、`src/app.rs`、`verify` |
|
| `schema/schema_version=2`、未知 major 拒绝 | `src/semantic.rs`、`src/app.rs`、`verify` |
|
||||||
| `producer.markdown_profile=marqdo.md.v1` | `src/semantic.rs` |
|
| `producer.markdown_profile=marqdo.md.v1` | `src/semantic.rs` |
|
||||||
| `project.root_id/identity_kind/lock_digest/stdlib` | `SemanticProjection` 字段 + `verify --json` |
|
| `project.root_id/identity_kind/lock_digest/stdlib` | `SemanticProjection` 字段 + `verify --json` |
|
||||||
| `source_digest` 精确字节校验 | `src/semantic.rs`、`tests/unicode_spans.rs`(CRLF) |
|
| `source_digest` 精确字节校验 | `src/semantic.rs`、`tests/integration/unicode_spans.rs`(CRLF) |
|
||||||
| modules/units/functions/signature/body kind/span | `src/semantic.rs`(typed projection) |
|
| modules/units/functions/signature/body kind/span | `src/semantic.rs`(typed projection) |
|
||||||
| `resources[]` formula/code + `display`/language | `StaticResource`,渲染为惰性资源 |
|
| `resources[]` formula/code + `display`/language | `StaticResource`,渲染为惰性资源 |
|
||||||
| `imports[]`/`references[]`/`calls[]` | 标签与引用状态;不重新解析优先级 |
|
| `imports[]`/`references[]`/`calls[]` | 标签与引用状态;不重新解析优先级 |
|
||||||
@@ -44,7 +44,7 @@
|
|||||||
| 条款 | 实现 |
|
| 条款 | 实现 |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `schema/schema_version=2` | `src/trace.rs` |
|
| `schema/schema_version=2` | `src/trace.rs` |
|
||||||
| `sha256(analysis bytes)==source.analysis_digest` | `verify_trace`;`tests/trace_contract.rs` |
|
| `sha256(analysis bytes)==source.analysis_digest` | `verify_trace`;`tests/contract/trace_contract.rs` |
|
||||||
| `source.root_id==project.root_id` | `verify_trace` |
|
| `source.root_id==project.root_id` | `verify_trace` |
|
||||||
| 事件 `module_id` ∈ Analysis modules | `verify_trace` |
|
| 事件 `module_id` ∈ Analysis modules | `verify_trace` |
|
||||||
| `seq` 严格递增 | `verify_trace` |
|
| `seq` 严格递增 | `verify_trace` |
|
||||||
@@ -62,37 +62,37 @@
|
|||||||
| 原始 Markdown 是阅读主体 | `DocumentModel` + `ReaderRenderer` |
|
| 原始 Markdown 是阅读主体 | `DocumentModel` + `ReaderRenderer` |
|
||||||
| 不重新决定可执行性 | 只有 `semantic.rs` 的 Analysis 事实创建锚点 |
|
| 不重新决定可执行性 | 只有 `semantic.rs` 的 Analysis 事实创建锚点 |
|
||||||
| `@exec/@knowledge` 显示前缀仅显示层剥离 | `docs/ADR/0003` |
|
| `@exec/@knowledge` 显示前缀仅显示层剥离 | `docs/ADR/0003` |
|
||||||
| 知识区强调/行内代码不执行 | `tests/unicode_spans.rs::knowledge_emphasis_never_becomes_an_execution_anchor` |
|
| 知识区强调/行内代码不执行 | `tests/integration/unicode_spans.rs::knowledge_emphasis_never_becomes_an_execution_anchor` |
|
||||||
| GFM 表/任务列表/围栏/数学可读且惰性 | `tests/rendering.rs`、`tests/export.rs` |
|
| GFM 表/任务列表/围栏/数学可读且惰性 | `tests/integration/rendering.rs`、`tests/integration/export.rs` |
|
||||||
| 原始 HTML 默认忽略、URL scheme 净化 | `src/render.rs`、浏览器安全 fixture |
|
| 原始 HTML 默认忽略、URL scheme 净化 | `src/render.rs`、浏览器安全 fixture |
|
||||||
|
|
||||||
## 6. Security 边界(View 自身)
|
## 6. Security 边界(View 自身)
|
||||||
|
|
||||||
| 条款 | 实现 | 测试 |
|
| 条款 | 实现 | 测试 |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| loopback-only + Host 校验 | `src/server.rs` | `tests/http_live.rs` |
|
| loopback-only + Host 校验 | `src/server.rs` | `tests/integration/http_live.rs` |
|
||||||
| CSRF/Origin/确认 | `POST /api/run` | `tests/http_live.rs` |
|
| CSRF/Origin/确认 | `POST /api/run` | `tests/integration/http_live.rs` |
|
||||||
| 路径边界/单次解码/无遍历 | `SafeRelativePath`、`percent_decode` | `tests/http_live.rs`、`tests/project` 单测 |
|
| 路径边界/单次解码/无遍历 | `SafeRelativePath`、`percent_decode` | `tests/integration/http_live.rs`、`tests/project` 单测 |
|
||||||
| 导出纯只读、无执行 | `src/export.rs` | `tests/export.rs`(marker 假核心) |
|
| 导出纯只读、无执行 | `src/export.rs` | `tests/integration/export.rs`(marker 假核心) |
|
||||||
| 离线文件:// | 内嵌资产 + 相对链接 | `tools/test-export.sh` Chromium file:// |
|
| 离线文件:// | 内嵌资产 + 相对链接 | `scripts/test-export.sh` Chromium file:// |
|
||||||
| 输出/错误不泄露绝对路径 | `ViewError::public_message`、manifest 相对路径 | `tests/http_live.rs`、`tests/export.rs` |
|
| 输出/错误不泄露绝对路径 | `ViewError::public_message`、manifest 相对路径 | `tests/integration/http_live.rs`、`tests/integration/export.rs` |
|
||||||
| 无第二渲染器/第二主题 | 代码门禁 | `tests/no_coupling.rs`、`tests/asset_integrity.rs` |
|
| 无第二渲染器/第二主题 | 代码门禁 | `tests/contract/no_coupling.rs`、`tests/contract/asset_integrity.rs` |
|
||||||
|
|
||||||
## 7. 明确 UNSUPPORTED / 非目标
|
## 7. 明确 UNSUPPORTED / 非目标
|
||||||
|
|
||||||
- 逐语句赋值实际值、参数实际值、变量历史、Memory 全状态:Trace v2 不提供,UI 只显示静态分析目标并明确说明。
|
- 逐语句赋值实际值、参数实际值、变量历史、Memory 全状态:Trace v2 不提供,UI 只显示静态分析目标并明确说明。
|
||||||
- 知识“已证明”/Prove/Lint/Knowledge 引擎:不实现,等独立版本化协议。
|
- 知识“已证明”/Prove/Lint/Knowledge 引擎:不实现,等独立版本化协议。
|
||||||
- 调试器/断点/单步、Notebook/旧 2.x 语法兼容、SSE 流式运行、多运行历史:非首版目标。
|
- 调试器/断点/单步、Notebook/旧 2.x 语法兼容、SSE 流式运行、多运行历史:非首版目标。
|
||||||
- `inspect --ir` / 私有 IR / 旧 `ViewExecutionReport`:没有作为依赖;`tests/no_coupling.rs` 门禁。
|
- `inspect --ir` / 私有 IR / 旧 `ViewExecutionReport`:没有作为依赖;`tests/contract/no_coupling.rs` 门禁。
|
||||||
- 严格模式/项目 grants:首版运行仅 `pure`;`project`/`strict` 需要未来独立授权界面。
|
- 严格模式/项目 grants:首版运行仅 `pure`;`project`/`strict` 需要未来独立授权界面。
|
||||||
|
|
||||||
## 8. 复核命令
|
## 8. 复核命令
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
export MARQDO_BIN=/abs/path/to/frozen/marqdo
|
export MARQDO_BIN=/abs/path/to/frozen/marqdo
|
||||||
tools/acceptance.sh # §18.1 全链路 + evidence manifest
|
scripts/acceptance.sh # §18.1 全链路 + evidence manifest
|
||||||
tools/test-contract.sh # code + Tool v1 + verify + export
|
scripts/test-contract.sh # code + Tool v1 + verify + export
|
||||||
tools/test-export.sh # 纯只读导出 + file:// Chromium
|
scripts/test-export.sh # 纯只读导出 + file:// Chromium
|
||||||
tools/test-security.sh # HTTP/路径/XSS/导出对抗
|
scripts/test-security.sh # HTTP/路径/XSS/导出对抗
|
||||||
tools/test-browser.sh # 真实 Chromium 视觉/交互/响应式/运行
|
scripts/test-browser.sh # 真实 Chromium 视觉/交互/响应式/运行
|
||||||
```
|
```
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
# 冻结 CLI 公共合同黑盒审计(RFC-VIEW-0002 §2 / PR-00)
|
||||||
|
|
||||||
|
- 状态:已用发行二进制黑盒复现;**CLI 源码只读,不修改、不重编译**
|
||||||
|
- 日期:2026-11-22
|
||||||
|
- 发行基线:`marqdo 3.0.0-beta.1`(tag `v3.0.0-beta.1`,
|
||||||
|
`2c7c4f31e7a388d3fcfa717a77067e696ed13854`)
|
||||||
|
- 二进制:`/root/work/marqdo-cli/dist/marqdo-3.0.0-beta.1-x86_64-unknown-linux-gnu/marqdo`
|
||||||
|
- SHA-256:`062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f`
|
||||||
|
- 平台:`x86_64-unknown-linux-gnu`;协议:Tool v1 / Analysis v2 / Trace v2 /
|
||||||
|
Markdown Profile `marqdo.md.v1`
|
||||||
|
- 规范来源:`/root/work/marqdo-cli/spec/{tool-v1,analysis-v2,trace-v2,callable-resolution,value-wire}.md`、
|
||||||
|
`spec/schemas/*.json`、`crates/cli/src/commands/run.rs`(只读参考)。
|
||||||
|
正式发布后若规范更新,以**确切发布版**为准,不以本文代替规范。
|
||||||
|
|
||||||
|
> 本文是 marqdo-view 实现与测试的合同摘要。任何字段都以“规范 + 黑盒复现二选一”
|
||||||
|
> 为依据;未复现项显式标 `UNVERIFIED`,绝不推断。
|
||||||
|
|
||||||
|
## 1. 命令面(`--help` 实测)
|
||||||
|
|
||||||
|
- `run [FILE]`:运行入口文件 `main`;`--mode` 默认 **`project`**(View 必须显式传
|
||||||
|
`--mode pure`)。
|
||||||
|
- `call <FILE> <FUNCTION>`:调用命名函数;`--arg <NAME=VALUE>` 常量表达式,可重复。
|
||||||
|
- `check [FILE] [--refs] [--emit PATH] [--json]`:纯静态,不执行。
|
||||||
|
- 预算/追踪参数(`run`/`call` 共有):`--fuel`、`--stack`、`--max-output`、
|
||||||
|
`--timeout`、`--trace-file`、`--trace-max-events`、`--trace-max-bytes`。
|
||||||
|
- 权限参数:`--allow-read/--allow-write/--allow-net/--allow-env/--allow-process/
|
||||||
|
--allow-random/--allow-foreign/--allow-plugin/--plugin/--provider/--allow-provider/
|
||||||
|
--kernel/--trust-native-plugin`。View 首版只使用 `--allow-read/--allow-write`
|
||||||
|
(且仅在显式 `project` 请求中),其余一律不暴露。
|
||||||
|
- 未知顶层命令通过 Tool v1 注册表分发到外部二进制(`spec/tool-v1.md`)。
|
||||||
|
|
||||||
|
## 2. `check --emit` 合同
|
||||||
|
|
||||||
|
规范:`spec/analysis-v2.md` §1;实测:
|
||||||
|
|
||||||
|
| 场景 | 结果 |
|
||||||
|
|---|---|
|
||||||
|
| 成功 | exit 0;`--json` stdout 为 `{"command":"check","diagnostics":[],"errors":0,"success":true}`;`--emit` 路径写出 Analysis v2 精确 UTF-8 字节(pretty JSON),原子写入 |
|
||||||
|
| 失败 | exit 1;stdout 为 `{"command":"check","diagnostics":[...],"errors":N,"success":false}`;**逐条诊断带 `code/severity/message/line/column/module/hints`**(`file` 可能出现绝对路径,View 必须不泄漏/只保留相对信息) |
|
||||||
|
| stale emit | 失败时 **删除目标路径的旧文件**(实测:先写 `stale.json` 再失败 check,文件不存在)。View 必须同样丢弃自己的旧 Analysis 缓存 |
|
||||||
|
| `--refs` | 额外链接检查,可能产生额外 `diagnostics`;不得当作语言执行/编译成功证明 |
|
||||||
|
|
||||||
|
`AnalysisDigest` = `sha256:` + 精确 emit 文件字节的小写 hex SHA-256;**不是**
|
||||||
|
反序列化再序列化的哈希。`Trace v2.source.analysis_digest` 必须与它一致。
|
||||||
|
|
||||||
|
## 3. Analysis v2 关键字段(View 消费面)
|
||||||
|
|
||||||
|
- 顶层:`schema="marqdo.analysis"`、`schema_version=2`、`producer{name,version,
|
||||||
|
markdown_profile}`、`project{root_id,identity_kind,lock_digest,stdlib}`、
|
||||||
|
`modules[]`、`diagnostics[]`。
|
||||||
|
- `project.root_id`:`root:<name>@<version>`(有 manifest)或
|
||||||
|
`sha256:<workspace snapshot>`;是 Trace `source.root_id` 的唯一比对值。
|
||||||
|
- `modules[].{id,package_instance_id,relative_path,source_digest,units,functions,
|
||||||
|
imports,references,calls,resources}`。`source_digest` = 精确源文件字节的 SHA-256
|
||||||
|
(不含 `sha256:` 前缀)。
|
||||||
|
- `functions[].{id,unit_id,local_name,namespace,span,heading_span,signature{kind,
|
||||||
|
params[]},body,effects}`;`params[].{name,required,type,default,span}`。
|
||||||
|
`signature.kind` 为 `explicit|inferred`;`required = default.is_none()`。
|
||||||
|
- `units[].kind`:`root|namespace|function|knowledge|section`,带 `level`、
|
||||||
|
`span`、`function`、`name`、`id`。**Analysis 不公开 H3+ 的最终 EffectiveMode**;
|
||||||
|
View 不得自行重建并宣称为编译器状态(RFC §2.7)。
|
||||||
|
- `diagnostics[]` 标记 UTF-8 字节 `span`(`start/end`)或行列;View 显示原文与
|
||||||
|
诊断即可,不从错误推断 IR。
|
||||||
|
- `effects` 是保守摘要(如 `["unknown"]`),不是纯度证明,不能作为“安全运行”依据。
|
||||||
|
|
||||||
|
黑盒样例(`target/probe/function-params.mq.md`,2 个 H1/H2 中文标题)证明:
|
||||||
|
中文 namespace/local_name、UTF-8 `span`、`heading_span`、`unit_id` 均按字节偏移
|
||||||
|
给出;`id` 形如
|
||||||
|
`root:<name>@<ver>::<relative path>::<namespace>.<local_name>`(无 namespace 时
|
||||||
|
`::<local_name>`)。
|
||||||
|
|
||||||
|
## 4. 函数定位与 `call` 的名称解析(关键)
|
||||||
|
|
||||||
|
CLI `call FILE FUNCTION` 的查找实现:`Module::function(name)`
|
||||||
|
(`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 见头部 |
|
||||||
|
| 2 | `check function-params.mq.md --emit a1.json --json` | exit 0,success:true,写出 Analysis v2 |
|
||||||
|
| 3 | `check broken.mq.md --emit stale.json --json` | exit 1,failure JSON,旧 `stale.json` 被删除 |
|
||||||
|
| 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 写入 |
|
||||||
|
| 5 | `call function-params.mq.md 计算示例.double --arg n=7 --mode pure` | exit 0,`decimal:14`(canonical 名称可用) |
|
||||||
|
| 6 | `call function-params.mq.md double --arg 'n="x"' --mode pure --json` | exit 1,`error.code=runtime.type`(对象包络) |
|
||||||
|
| 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)
|
||||||
|
|
||||||
|
- 插件/Provider/Foreign/Kernel 的完整运行时行为(View 首版不暴露;不属 MVP)。
|
||||||
|
- `--max-output`/`--fuel`/`--stack` 触顶时的精确错误码与包络(由 View 外部的
|
||||||
|
Core 负责;View 只显示真实错误)。
|
||||||
|
- 多模块/依赖包事件在入口正文的跨模块绘制(必须按 module_id 拒绝;无有效样本)。
|
||||||
|
- Windows/macOS 行为(发行范围仅 Linux x86_64)。
|
||||||
@@ -28,7 +28,7 @@ Tool Protocol v1 安装时复制整个 bundle,并对每个文件做 SHA-256、
|
|||||||
CSS/JS/图片不额外放在 bundle 根(已内嵌),避免“内嵌 + 外部”双来源。
|
CSS/JS/图片不额外放在 bundle 根(已内嵌),避免“内嵌 + 外部”双来源。
|
||||||
3. `tool.json` 由源码模板 `tool.json` 固定,`compatibility.marqdo = ">=3.0.0-beta.1,<4.0.0"`、`analysis: [2]`、`trace: [2]`;bundle 目录内 `bin/marqdo-view` 是 release 构建产物。
|
3. `tool.json` 由源码模板 `tool.json` 固定,`compatibility.marqdo = ">=3.0.0-beta.1,<4.0.0"`、`analysis: [2]`、`trace: [2]`;bundle 目录内 `bin/marqdo-view` 是 release 构建产物。
|
||||||
4. 开发时允许 `marqdo-view --marqdo-bin PATH` 直启;安装态必须以 `MARQDO_BIN` 为准,且不向核心传自定义参数格式。
|
4. 开发时允许 `marqdo-view --marqdo-bin PATH` 直启;安装态必须以 `MARQDO_BIN` 为准,且不向核心传自定义参数格式。
|
||||||
5. `tools/package.sh` 负责:`cargo build --release --locked` → 校验工具协议/SHA → 组装 dist → 写 `SHA256SUMS`/`SOURCE_SHA`/`RELEASE_INFO.json` → 用冻结 CLI 做一次 `tool install` + `view --help` 烟测。
|
5. `scripts/package.sh` 负责:`cargo build --release --locked` → 校验工具协议/SHA → 组装 dist → 写 `SHA256SUMS`/`SOURCE_SHA`/`RELEASE_INFO.json` → 用冻结 CLI 做一次 `tool install` + `view --help` 烟测。
|
||||||
|
|
||||||
## 后果
|
## 后果
|
||||||
|
|
||||||
@@ -22,6 +22,6 @@
|
|||||||
|
|
||||||
## 后果
|
## 后果
|
||||||
|
|
||||||
- 同页多个 H2/H3 永远得到不同 id;`tests/rendering.rs::semantic_annotations_come_from_analysis_and_are_unique` 断言唯一性。
|
- 同页多个 H2/H3 永远得到不同 id;`tests/integration/rendering.rs::semantic_annotations_come_from_analysis_and_are_unique` 断言唯一性。
|
||||||
- Setext 标题没有合法前缀声明,会被原样显示并沿用自身 span 锚点;如果未来需要更精确的继承模式标注,必须通过新的公开协议字段实现,不能在 JS/CSS 里猜。
|
- Setext 标题没有合法前缀声明,会被原样显示并沿用自身 span 锚点;如果未来需要更精确的继承模式标注,必须通过新的公开协议字段实现,不能在 JS/CSS 里猜。
|
||||||
- 标题显示与源码态自动保持一致;无需额外“复制原文”逻辑。
|
- 标题显示与源码态自动保持一致;无需额外“复制原文”逻辑。
|
||||||
@@ -22,4 +22,4 @@
|
|||||||
|
|
||||||
- 正面:运行路径可被 HTTP 层测试完整覆盖(拒绝路径不产生 `run` 进程;页面加载 10 次为 0 次运行);Live 与 Export 继续共用唯一的 Reader 渲染字节。
|
- 正面:运行路径可被 HTTP 层测试完整覆盖(拒绝路径不产生 `run` 进程;页面加载 10 次为 0 次运行);Live 与 Export 继续共用唯一的 Reader 渲染字节。
|
||||||
- 负面:运行完成后整页重载(保留阅读位置);首版无流式输出/取消/多运行历史;这些属于后续 PR,不得伪造。
|
- 负面:运行完成后整页重载(保留阅读位置);首版无流式输出/取消/多运行历史;这些属于后续 PR,不得伪造。
|
||||||
- 门禁:`tests/http_live.rs` 覆盖 token/Origin/confirm/mode/单活动/清缓存/源码变化 stale;`tests/trace_contract.rs` 覆盖 digest、module、seq、truncated、failed。
|
- 门禁:`tests/integration/http_live.rs` 覆盖 token/Origin/confirm/mode/单活动/清缓存/源码变化 stale;`tests/contract/trace_contract.rs` 覆盖 digest、module、seq、truncated、failed。
|
||||||
@@ -20,5 +20,5 @@
|
|||||||
## 后果
|
## 后果
|
||||||
|
|
||||||
- 对抗测试 `tests/export.rs` 使用会写 marker 的假核心:导出后 marker 不存在、假核心 argv 中没有 `run`。
|
- 对抗测试 `tests/export.rs` 使用会写 marker 的假核心:导出后 marker 不存在、假核心 argv 中没有 `run`。
|
||||||
- 真实冻结核心导出两个文档页面均为 `static-ok`;`tools/test-export.sh` 校验离线资源、manifest 哈希与核心 SHA 不变。
|
- 真实冻结核心导出两个文档页面均为 `static-ok`;`scripts/test-export.sh` 校验离线资源、manifest 哈希与核心 SHA 不变。
|
||||||
- 副作用:导出对每个文档执行一次 `check`(非执行),大项目导出耗时与文档数线性相关;首版不做增量导出,保持正确性优先。
|
- 副作用:导出对每个文档执行一次 `check`(非执行),大项目导出耗时与文档数线性相关;首版不做增量导出,保持正确性优先。
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
# ADR-0007:以 RFC-VIEW-0002 为唯一实施基线
|
||||||
|
|
||||||
|
- 状态:Accepted
|
||||||
|
- 日期:2026-11-22
|
||||||
|
- 关联:`docs/architecture/RFC-VIEW-0002.md`(本 ADR 的规范来源);
|
||||||
|
`docs/architecture/RFC-VIEW-0001.md`(历史基础设计);
|
||||||
|
既有 ADR-0001~0006(0001 时期决策,除与 0002 冲突的部分外仍有效)
|
||||||
|
|
||||||
|
## 背景
|
||||||
|
|
||||||
|
仓库此前按 `RFC-VIEW-0001` 完成了 PR-00~PR-06,具备只读 Reader、Analysis v2
|
||||||
|
校验、显式确认后同步执行 `pure`、Trace v2 绑定、静态导出和冻结 CLI 验收。
|
||||||
|
随后 `docs/RFC-VIEW-0002.md` 发布,明确:
|
||||||
|
|
||||||
|
1. 执行闭环必须使用 **SSE**(POST 建任务、GET SSE 观察、POST 取消),**禁止轮询**;
|
||||||
|
2. 路由收敛为 7 条固定最小 API,运行只能从 `POST /api/runs` 发起;
|
||||||
|
3. 首版必须提供单函数 `call` 表单与受控 `project` fs grants(MVP CONTROLLED);
|
||||||
|
4. 页面收敛为 `文档 / 函数 / 运行`,删除变量/内存等旧工作台概念;
|
||||||
|
5. 仓库结构、测试树、脚本、示例和发布门禁按 0002 §5.3/§8/§9 落地;
|
||||||
|
6. 0002 在执行控制、权限、默认只读、产品裁剪、UI 路由与交互流程上**优先于
|
||||||
|
0001**;不得单方面更改 Tool/Analysis/Trace 版本、默认不执行、显式授权、
|
||||||
|
单渲染链、SSE 无轮询和 CLI 冻结验收要求。
|
||||||
|
|
||||||
|
## 决策
|
||||||
|
|
||||||
|
1. **0002 是当前唯一实施基线**。0001 仅作历史视觉/阅读原则参考;凡冲突以 0002
|
||||||
|
为准。`docs/RFC-VIEW-0001.md` 移入 `docs/architecture/` 归档,不再作为验收
|
||||||
|
依据。
|
||||||
|
2. **目标结构**按 0002 §5.3 迁移:`src/{main,cli,config,core_client,export}.rs` +
|
||||||
|
`src/protocol/{analysis_v2,trace_v2,tool_v1}.rs` +
|
||||||
|
`src/reader/{source,markdown,model,assemble,render,assets}.rs` +
|
||||||
|
`src/execution/{request,controller,process,events}.rs` +
|
||||||
|
`src/server/{mod,routes,security,sse}.rs`。
|
||||||
|
- `lib.rs`、`error.rs`、各 `mod.rs` 是 Rust 单 crate 的必要支撑模块;
|
||||||
|
- `assets.rs` 归入 `reader/`(构建期资产嵌入,仍只有 `assets/reader.css` 与
|
||||||
|
`assets/reader.js` 两个发布入口);
|
||||||
|
- 不拆分多个 Rust crate;不引入第二个 Markdown/语义/执行管线。
|
||||||
|
3. **只重构 View**:冻结 CLI 不改、不重编译、不链接其私有 crate;黑盒证据以
|
||||||
|
`062cb56e…`(3.0.0-beta.1)为准,验收前后 SHA 必须相同。
|
||||||
|
4. **PR 顺序即提交顺序**:PR-00 取证/基线 → PR-01 Tool/打包 → PR-02 Reader +
|
||||||
|
Analysis 路由 → PR-03 执行层(request/process/controller)→ PR-04 SSE 服务与
|
||||||
|
前端闭环 → PR-05 Trace 绑定/标注与浏览器回归 → PR-06 导出/发布/文档闭环。
|
||||||
|
每个提交必须可构建、测试绿、无隐式执行;中间态功能不完整时在 STATUS 明示。
|
||||||
|
5. **版本**:View 产品版本从 `0.1.0` 升为 `0.2.0`(0002 §2.2 建议的独立 View
|
||||||
|
版本;不是 CLI 版本),同步 `Cargo.toml`、`tool.json`、文档与验收证据。
|
||||||
|
6. **测试组织**:按 0002 §5.3 建立 `tests/{contract,integration,security,browser,
|
||||||
|
fixtures,golden}`;通过 `[[test]]` 显式声明测试入口(Cargo 只自动发现
|
||||||
|
`tests/*.rs`,目录需显式声明),职责与门禁不变。
|
||||||
|
7. **文档一致性**:`docs/STATUS.md` 是唯一现状来源;`docs/CONFORMANCE.md` 维护
|
||||||
|
0002 条款 → 实现 → 测试/证据映射;任何未实现项必须标 `UNSUPPORTED/PENDING/
|
||||||
|
UNVERIFIED`,不得以视觉相似代替证据。
|
||||||
|
8. **允许的实现自由**:HTTP 细节、内部类型命名、并发原语、CSS 细节可按黑盒测试
|
||||||
|
调整;不得改变 0002 的公开协议、安全边界与验收门禁。
|
||||||
|
|
||||||
|
## 与 0001 时期偏差记录的关系
|
||||||
|
|
||||||
|
`docs/decisions/0006-rfc-deviations.md` 记录的是 0001 时期的目录/实现偏差,仍作为
|
||||||
|
历史有效。本 ADR 生效后:
|
||||||
|
|
||||||
|
- 0002 明确要求或重新定义的(SSE、路由、call 表单、project grants、页面三项、
|
||||||
|
tests 树、scripts/、examples/、0.2.0 版本)不再属于“可保留偏差”,必须实现;
|
||||||
|
- 0001 时期已实现且与 0002 不冲突的部分(精确 Analysis 校验、Trace 绑定、
|
||||||
|
单一渲染器、只读导出、安全头/路径 containment、冻结 CLI 验收)保留并迁移;
|
||||||
|
- 任何将来仍无法在首版完成的事项,必须新开 ADR 并在 STATUS/README 标
|
||||||
|
`UNSUPPORTED`,不得留下灰色按钮或占位路由。
|
||||||
|
|
||||||
|
## 后果
|
||||||
|
|
||||||
|
- 正面:执行闭环可观测、可取消、可重放;路由/权限面最小且可审计;结构符合
|
||||||
|
0002 审查口径;旧叠层与工作台概念彻底消失。
|
||||||
|
- 代价:需要重写 `server`/执行交互并迁移测试与文档;中间提交可能短暂出现
|
||||||
|
“旧同步运行 + 新执行层并存”,只能作为过渡并立即由 PR-04 替换,最终不允许
|
||||||
|
双运行框架或轮询 API。
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
# ADR-0008:单任务执行生命周期、取消竞态与 Trace 缺失语义
|
||||||
|
|
||||||
|
- 状态:Accepted
|
||||||
|
- 日期:2026-11-22
|
||||||
|
- 关联:`docs/architecture/RFC-VIEW-0002.md` §6.3–§6.7;PR-03/PR-04
|
||||||
|
|
||||||
|
本 ADR 固定 RFC 留给实现选择的几个边界,避免后续 UI/测试出现两套解释。
|
||||||
|
|
||||||
|
## 1. 单活动任务与接受顺序
|
||||||
|
|
||||||
|
- 每个 View 服务进程**最多 1 个活动 CLI 任务**;第二个请求返回 `409 run.busy`
|
||||||
|
(`view.run_busy`),不排队、不并发执行。
|
||||||
|
- `POST /api/runs` 的接受顺序:schema/大小/路径 → `client_request_id` 去重 →
|
||||||
|
单任务门禁 → **只读 `check --emit` + Analysis 字节摘要比对** → 目标/参数解析 →
|
||||||
|
创建 `accepted` 任务 → 后台线程 → `202`。
|
||||||
|
- 去重键是 `client_request_id` + **原始请求体字节的 SHA-256**:
|
||||||
|
- 相同 ID + 相同字节 → 返回同一 `run_id`(`reused=true`),**不启动第二次进程**;
|
||||||
|
- 相同 ID + 不同字节 → `409 Conflict`(`view.run_conflict`);
|
||||||
|
- ID 对应任务已过 TTL → 明确错误(`view.run_invalid`),不默认重跑。
|
||||||
|
- 去重/活动任务/任务表由同一个 Controller 锁保护;静态 `check` 在锁内完成,
|
||||||
|
保证两个并发请求不会同时越过单任务门禁。`check` 不执行目标程序。
|
||||||
|
|
||||||
|
## 2. 状态机与终态唯一性
|
||||||
|
|
||||||
|
- 状态:`accepted → running → {succeeded, failed, cancelled, timed_out}`,
|
||||||
|
`cancel_requested` 不是终态,`unavailable` 仅表示进程无法启动/环境不可用。
|
||||||
|
- `running` 只在内核进程**成功 spawn 之后**发布(进程适配器提供 spawn hook)。
|
||||||
|
- 终态由 Controller 在线程内、持有 job 锁时发布;发布前检查 `log.terminal()`,
|
||||||
|
所以任何任务最多一个终态事件。取消/超时/自然退出竞态都走同一路径。
|
||||||
|
|
||||||
|
## 3. 取消与退出竞态
|
||||||
|
|
||||||
|
- 取消 = 幂等 POST 设置取消标志并发布 `cancel_requested`;执行线程负责终止
|
||||||
|
进程组(先 SIGTERM,约 2s 后 SIGKILL)与唯一终态。
|
||||||
|
- 若进程在取消请求后自然退出:
|
||||||
|
- 退出码为 0 且 `--json.success=true` → 允许 `succeeded`(RFC §6.6 竞态条款);
|
||||||
|
- 其他情况(被信号终止、非零退出、JSON 缺失/失败)→ `cancelled`。
|
||||||
|
- 这一判断依赖“取消请求”标志而非仅依赖适配器是否发出了 SIGKILL,因为
|
||||||
|
SIGTERM 可能在 2s 宽限期内就让进程退出。
|
||||||
|
- 页面关闭/SSE 断开**不取消**任务;取消只能显式 POST。
|
||||||
|
|
||||||
|
## 4. Trace 缺失/无效与运行成功的关系
|
||||||
|
|
||||||
|
- 运行成功与否以 CLI `--json.success` + 进程退出状态为准;`trace_status` 独立:
|
||||||
|
- `verified`:Trace v2 通过 `analysis_digest`/`root_id`/`module_id`/span 校验;
|
||||||
|
- `unavailable`:CLI 未写 trace(例如失败路径或未请求);
|
||||||
|
- `invalid`:Trace 存在但 schema/摘要/事件绑定不合法。
|
||||||
|
- **Trace 缺失或 invalid 不把成功运行改判为失败**,但 UI 必须明确显示
|
||||||
|
“Trace 不可用/无效”,不得绘制执行侧注、不得伪造事件,也不得宣称完整观测。
|
||||||
|
- 运行后源码字节变化 → 结果 `stale=true`,Trace 即使曾校验通过也不得锚定当前
|
||||||
|
正文;前端仍可显示结果,但标注失效。
|
||||||
|
|
||||||
|
## 5. 预算与有界性
|
||||||
|
|
||||||
|
- 入口固定预算:`--timeout`=View 墙钟(默认 30s,最大 120s,`--run-timeout`
|
||||||
|
可配置且与 Core 参数一致)、`--fuel 1000000`、`--max-output 1048576`、
|
||||||
|
`--trace-max-events 10000`、`--trace-max-bytes 4194304`。
|
||||||
|
- View 侧再限制:stdout/JSON ≤4 MiB、stderr 保留 ≤64 KiB(继续排空管道避免
|
||||||
|
子进程阻塞)、Trace 文件 ≤4 MiB;超限以 `view.output_limit` 失败终态报告。
|
||||||
|
- 每次执行使用独立 0700 临时目录,Trace 读出后随临时目录删除;项目目录中不写
|
||||||
|
`.view-*` 运行产物。
|
||||||
|
|
||||||
|
## 6. 事件日志与 SSE
|
||||||
|
|
||||||
|
- 每任务事件日志保留最近 128 条 + 终态快照;序号严格递增,SSE `id` 与
|
||||||
|
`data.seq` 一致;心跳是注释不占序号。
|
||||||
|
- 快照使用**新的序号**(不重复旧 id),保证客户端去重逻辑不会误丢弃快照。
|
||||||
|
- 这些决定在 PR-04 的 HTTP/SSE 层消费;Controller 本身不实现 HTTP 轮询。
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
# ADR-0009:SSE 传输实现、会话模型与 7 路由收敛
|
||||||
|
|
||||||
|
- 状态:Accepted
|
||||||
|
- 日期:2026-11-22
|
||||||
|
- 关联:`docs/architecture/RFC-VIEW-0002.md` §6.2/§6.4/§6.5/§6.8;PR-04
|
||||||
|
|
||||||
|
## 1. SSE 传输:直接写 socket 并逐帧 flush
|
||||||
|
|
||||||
|
`tiny_http` 的流式 `Response` 使用 `chunked_transfer::Encoder::new`,只有缓冲区
|
||||||
|
填满或响应结束时才 flush。对 SSE 来说,这意味着已接受的 `accepted`/`running`/
|
||||||
|
心跳可能被扣留数秒,直到任务结束,**不满足“状态变化立即推送”**。
|
||||||
|
|
||||||
|
因此 `server/sse.rs` 在成功鉴权后使用 `Request::into_writer()` 取到底层 socket
|
||||||
|
writer,自行写入:
|
||||||
|
|
||||||
|
```
|
||||||
|
HTTP/1.1 200 OK
|
||||||
|
Content-Type: text/event-stream; charset=utf-8
|
||||||
|
Cache-Control: no-store
|
||||||
|
X-Accel-Buffering: no
|
||||||
|
Connection: close
|
||||||
|
|
||||||
|
event: ... / id: N / data: {...}
|
||||||
|
```
|
||||||
|
|
||||||
|
要点:
|
||||||
|
|
||||||
|
- **每帧/心跳后立即 `flush()`**,浏览器 EventSource 即时收到;
|
||||||
|
- 不设 `Content-Length` 且 `Connection: close`,body 以 EOF 结束(SSE 合法传输);
|
||||||
|
- 终态事件写出后主动关闭流;客户端 JS 在收到终态时关闭 EventSource,不会重连
|
||||||
|
重复执行;
|
||||||
|
- 客户端断开(broken pipe)只关闭观察连接,不取消任务、不产生执行终态;
|
||||||
|
- 只允许 4 种 `run.*` 事件 + `: heartbeat` 注释;心跳不使用序号;
|
||||||
|
- 每任务最多 2 个并发 SSE 观察连接(Controller 计数,超出 `429 view.sse_busy`);
|
||||||
|
128 条环形缓冲 + 终态快照 + `Last-Event-ID` 重放或权威 snapshot;
|
||||||
|
- 测试钩子 `MARQDO_VIEW_SSE_HEARTBEAT_SECS` 仅用于本地/CI 缩短心跳周期,默认
|
||||||
|
15 秒(不暴露为产品功能)。
|
||||||
|
|
||||||
|
## 2. 会话与鉴权
|
||||||
|
|
||||||
|
- 首次 `GET /` 或 `GET /file` 发放 `mq_view_session=<随机32字节hex>` Cookie:
|
||||||
|
`HttpOnly; SameSite=Strict; Path=/; Max-Age=43200`;loopback HTTP 不加 `Secure`
|
||||||
|
(不伪造 HTTPS)。
|
||||||
|
- 页面通过 `<meta name="mq-csrf-token" content="...">` 获得**该会话**的 CSRF;
|
||||||
|
POST 必须携带 `X-View-CSRF`,与 Cookie 会话匹配(常量时间比较)。
|
||||||
|
- POST 还要求:合法 `Host`(loopback+端口)、精确同源 `Origin`(缺失即拒绝)、
|
||||||
|
`Sec-Fetch-Site` 不得为 `cross-site`;`POST /api/runs` 要求
|
||||||
|
`Content-Type: application/json`,body ≤64 KiB。
|
||||||
|
- `POST /api/runs/{id}/cancel` 是无 body 的控制请求:允许无 JSON Content-Type,
|
||||||
|
但仍要求 Cookie + CSRF + Origin/Host。
|
||||||
|
- SSE GET 只允许**启动该 run 的会话**读取;事件/取消一律按 `session_id` 校验,
|
||||||
|
跨会话返回 404(不泄漏任务是否存在)。
|
||||||
|
- 会话表上限 64、空闲 TTL 12h;Cookie/CSRF 只存内存,不写磁盘、不进 URL。
|
||||||
|
|
||||||
|
## 3. 路由表(最终态)
|
||||||
|
|
||||||
|
只保留 7 条:`GET /`、`GET /file?path=`、`GET /assets/...`、
|
||||||
|
`GET /api/documents`、`POST /api/runs`、`GET /api/runs/{id}/events`、
|
||||||
|
`POST /api/runs/{id}/cancel`。
|
||||||
|
|
||||||
|
- 删除 `/api/health`、`/api/document`、`/api/run`、`/api/clear-run`;
|
||||||
|
- 不提供状态轮询路由、`/api/eval`、Notebook/session 兼容层或通用 shell 端点;
|
||||||
|
- `GET /api/documents` 是只读结构(文档列表 + 当前 outline/functions/analysis
|
||||||
|
摘要),无副作用;页面/刷新/搜索/切换/导出均不形成执行边。
|
||||||
|
|
||||||
|
## 4. 前端最小状态
|
||||||
|
|
||||||
|
`reader.js` 只做 DOM/表单/SSE:
|
||||||
|
|
||||||
|
- Dock 运行:有 main → 打开运行表单;无 main → 打开函数列表并解释,绝不替跑;
|
||||||
|
- 函数列表的“调用”按钮携带 Analysis 函数 id 与参数签名,动态生成表单;
|
||||||
|
- 表单有命令预览(文本节点)、pure/project 模式与 fs read/write glob;project
|
||||||
|
需要二次 `window.confirm`;无 net/process/env/plugin 等按钮;
|
||||||
|
- 提交一次 POST 后建立 `EventSource(..., {withCredentials:true})`,**没有
|
||||||
|
setInterval/轮询**;`seq` 去重、`run_id` 校验、终态关闭;
|
||||||
|
- 运行区/结果/stdout/stderr/Trace 全部用 `textContent`/DOM 文本构建,绝不
|
||||||
|
innerHTML 服务端数据;stale 结果不绘制原文锚点;
|
||||||
|
- 浏览器重载不会自动 POST;清理只隐藏本地展示,不删除项目文件/lock,也不取消
|
||||||
|
仍在服务端的任务。
|
||||||
|
|
||||||
|
## 5. 与 RFC 的关系
|
||||||
|
|
||||||
|
实现保留 RFC 的公开合同(事件类型、字段、状态机、`Last-Event-ID`、心跳语义),
|
||||||
|
仅选择“直接写 socket”作为传输细节——属于 RFC 允许的实现自由,不改变协议。
|
||||||
|
测试覆盖:HTTP/SSE 集成、真实 Chromium EventSource、跨会话/跨站拒绝、取消唯一
|
||||||
|
终态、心跳、2 连接上限与 Last-Event-ID 重放(见 `docs/evidence/PR-04/`)。
|
||||||
|
|
||||||
|
## Issue #2 验收补充
|
||||||
|
|
||||||
|
每个 SSE 事件和心跳各占一个 HTTP/1.1 chunk,写完立即 flush。
|
||||||
|
实时订阅和终态重放完成后都写入零长度 chunk,结束 HTTP 响应。
|
||||||
|
底层连接可以继续承载其他请求。事件 ID、重放和任务生命周期沿用
|
||||||
|
View Run Events v1。本地 HTTP 回归测试明确读取终态与结束标记。
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
# ADR-0010:静态/观测标注策略、分组与 stale 降级
|
||||||
|
|
||||||
|
- 状态:Accepted
|
||||||
|
- 日期:2026-11-22
|
||||||
|
- 关联:`docs/architecture/RFC-VIEW-0002.md` §4.4/§7.3/§7.4;PR-05
|
||||||
|
|
||||||
|
## 1. 两类标注,来源显式
|
||||||
|
|
||||||
|
- **Static(analysis)**:`render` 依据 Analysis v2 的 statement/function/unit
|
||||||
|
span 输出 `data-annotation-source="analysis"` 的锚点。未运行时只展示静态结构,
|
||||||
|
不出现“已发生”措辞。
|
||||||
|
- **Observed(trace)**:运行终态事件里每个带 `source_id` 的事件由前端以
|
||||||
|
`.mq-run-chip[data-annotation-source="trace"]` 就地附加,携带
|
||||||
|
`data-run-seq`/`data-run-kind`;只有经 `analysis_digest`/`root_id`/`module_id`/
|
||||||
|
span 校验后的 Trace v2 才会产生 `source_id`。
|
||||||
|
|
||||||
|
## 2. 曲线 vs 内联分组 chip
|
||||||
|
|
||||||
|
RFC §4.4 允许“先准确关联,再追求曲线审美”,并允许在空间不足/打印/禁 JS/来源
|
||||||
|
匹配失败时退化为正文内编号注释。首版选择**内联 keyed chip**作为唯一实现:
|
||||||
|
|
||||||
|
- 不绘制 SVG 曲线,也不把截图右侧未知黑线当品牌元素;
|
||||||
|
- 同一锚点的事件按 `source_id` 分组,最多显示 1 个 chip;>3 条时文本加 `×N`,
|
||||||
|
`title` 给出真实条数与事件种类——避免事件多时压过正文(近似 §4.4 的 ≤3 密度
|
||||||
|
建议);
|
||||||
|
- chip 只放在 `data-source-id` 精确匹配的语句锚点上;不做“找最近文本”的猜测;
|
||||||
|
- 无 JS/静态导出没有 Observed chip;静态信息仍完整可读;
|
||||||
|
- 打印模式隐藏交互控件但不丢正文/静态标注。
|
||||||
|
|
||||||
|
## 3. Stale 与降级(硬规则)
|
||||||
|
|
||||||
|
- Trace 的 `source.analysis_digest` 必须等于**运行前**由 `check --emit` 得到并进入
|
||||||
|
`POST /api/runs` 的 Analysis 原始字节 SHA-256;`root_id`/`module_id`/span 再逐项
|
||||||
|
校验;任何不符 → `trace_status=invalid`,**不产生 source_id**、不画 chip,但
|
||||||
|
运行 `result` 仍可见(不把 Trace 无效误判为程序失败,见 ADR-0008)。
|
||||||
|
- 运行结束后重新读取源文件:字节变化 → `stale=true`。服务端 Trace 摘要仍保留
|
||||||
|
`status=verified` 供参考,但所有 `anchor`/`source_id` 置空;前端显示“结果过期,
|
||||||
|
不锚定当前正文”,绝不把上一轮事件压到新源码上。
|
||||||
|
- `truncated`(`event_budget`/`byte_budget`)显式提示“Trace 被截断,不代表程序
|
||||||
|
终止”,不声称观察到全部路径。
|
||||||
|
- 无 Trace(`unavailable`)时只显示 CLI 返回/输出,不伪造空 Trace 或“完整执行”。
|
||||||
|
|
||||||
|
## 4. 测试与证据
|
||||||
|
|
||||||
|
- `tests/integration/execution.rs`:stale 源编辑 → `stale=true` 且所有 anchor/null;
|
||||||
|
Trace digest 不符 → `invalid` 且无事件;截断 Golden → `truncated` 保留;
|
||||||
|
- `tests/contract/trace_contract.rs`:Analysis 字节摘要、module/span/seq 校验;
|
||||||
|
- 浏览器套件:`observed chips carry trace provenance`、`static statement anchors
|
||||||
|
carry analysis provenance`、`at most one grouped chip per anchor`,并采集
|
||||||
|
`control-flow-run.png`、`control-flow-run-dark.png`、2048×1133/390×844 截图
|
||||||
|
(`docs/evidence/PR-05/`)。
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# PR-03 浏览器视觉验收证据
|
||||||
|
|
||||||
|
- 采集环境:Chromium Headless Shell 131(Playwright 1.49.0),Linux x86_64,
|
||||||
|
视口见文件名;真实冻结核心 `marqdo 3.0.0-beta.1`
|
||||||
|
(SHA-256 `062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f`)。
|
||||||
|
- 采集脚本:`tests/browser/reader.browser.cjs`,入口 `tools/test-browser.sh`。
|
||||||
|
- 断言范围(全部 PASS):单一 CSS/单一 script、无外部网络请求、无 console 错误、
|
||||||
|
文档/源码切换、搜索、设置字号与标注显隐、7 个宽度(390/600/900/1280/1664/
|
||||||
|
1920/2560)无横向溢出且 Dock 在视口内、无 JS 可读、打印隐藏交互栏、显式运行
|
||||||
|
确认后展示真实 Trace 与内联 chip、清理结果。
|
||||||
|
|
||||||
|
| 文件 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| `welcome-1664x920.png` | 显式 `view.json` Welcome 页,1664×920(与基准截图同尺寸),无运行 |
|
||||||
|
| `welcome-390x844.png` | 同一页面 390×844 单栏布局 |
|
||||||
|
| `control-flow-run-1664x920.png` | `examples/control-flow` 用户确认运行后的真实 Trace v2 运行面板与内联事件 chip |
|
||||||
|
|
||||||
|
## 诚实限制
|
||||||
|
|
||||||
|
- 未做与 `docs/design/reference-old-view-reader.png` 的像素差分:本环境无法进行
|
||||||
|
人工视觉判读,`U-01` 只声明“DOM/几何/字体栈/颜色令牌/无溢出/无外部资源”通过,
|
||||||
|
像素级视觉相似度标记为 **UNVERIFIED(人工复核待办)**,不以自动化 PASS 代替。
|
||||||
|
- 截图是证据,不是新的渲染路径:页面仍由唯一 `ReaderRenderer` 生成。
|
||||||
|
Before Width: | Height: | Size: 100 KiB After Width: | Height: | Size: 100 KiB |
|
Before Width: | Height: | Size: 174 KiB After Width: | Height: | Size: 174 KiB |
|
Before Width: | Height: | Size: 98 KiB After Width: | Height: | Size: 98 KiB |
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"analysis_protocol": 2,
|
"analysis_protocol": 2,
|
||||||
"archive_sha256": "b482d26c7098178de520aad14d5ac9b7160265eaf9c98666b3e9785a3ddbeafc",
|
"archive_sha256": "a3fb28c8d025f44dee6c06da80c13d3f65b9c62d1f657c04b02ef360ff24fcf5",
|
||||||
"cli_binary_sha256_after": "062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f",
|
"cli_binary_sha256_after": "062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f",
|
||||||
"cli_binary_sha256_before": "062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f",
|
"cli_binary_sha256_before": "062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f",
|
||||||
"cli_source_sha": "2c7c4f31e7a388d3fcfa717a77067e696ed13854",
|
"cli_source_sha": "2c7c4f31e7a388d3fcfa717a77067e696ed13854",
|
||||||
"commands": {
|
"commands": {
|
||||||
"notes": "Generated from real command exit statuses; install/verify/export/run use the frozen CLI archive copied to an isolated tool home.",
|
"notes": "Generated from real command exit statuses; install/verify/export/run use the frozen CLI archive copied to an isolated tool home.",
|
||||||
"script": "tools/acceptance.sh"
|
"script": "scripts/acceptance.sh"
|
||||||
},
|
},
|
||||||
"gates": {
|
"gates": {
|
||||||
"archive_install": "PASS",
|
"archive_install": "PASS",
|
||||||
@@ -16,9 +16,11 @@
|
|||||||
"bundle": "PASS",
|
"bundle": "PASS",
|
||||||
"clippy": "PASS",
|
"clippy": "PASS",
|
||||||
"core_sha": "PASS",
|
"core_sha": "PASS",
|
||||||
|
"examples_check": "PASS",
|
||||||
"export": "PASS",
|
"export": "PASS",
|
||||||
"export_suite": "PASS",
|
"export_suite": "PASS",
|
||||||
"fmt": "PASS",
|
"fmt": "PASS",
|
||||||
|
"no_exec_suite": "PASS",
|
||||||
"real_run": "PASS",
|
"real_run": "PASS",
|
||||||
"security_suite": "PASS",
|
"security_suite": "PASS",
|
||||||
"test": "PASS",
|
"test": "PASS",
|
||||||
@@ -26,18 +28,20 @@
|
|||||||
"verify": "PASS",
|
"verify": "PASS",
|
||||||
"view_help": "PASS"
|
"view_help": "PASS"
|
||||||
},
|
},
|
||||||
"generated_at_utc": "2026-11-22T04:07:21.776009+00:00",
|
"generated_at_utc": "2026-11-22T06:55:13.151362+00:00",
|
||||||
"schema": "marqdo.view-conformance",
|
"schema": "marqdo.view-conformance",
|
||||||
"schema_version": 1,
|
"schema_version": 1,
|
||||||
"target": "x86_64-unknown-linux-gnu",
|
"target": "x86_64-unknown-linux-gnu",
|
||||||
"tests": {
|
"tests": {
|
||||||
"browser": "PASS",
|
"browser": "PASS",
|
||||||
"contract": "PASS",
|
"contract": "PASS",
|
||||||
|
"examples": "PASS",
|
||||||
"export": "PASS",
|
"export": "PASS",
|
||||||
|
"no_exec": "PASS",
|
||||||
"security": "PASS"
|
"security": "PASS"
|
||||||
},
|
},
|
||||||
"tool_protocol": 1,
|
"tool_protocol": 1,
|
||||||
"trace_protocol": 2,
|
"trace_protocol": 2,
|
||||||
"view_binary_sha256": "97772ffefeb8df1f3dfbfe04c5112517ba3657497df4717ab85c6b026daf6bba",
|
"view_binary_sha256": "eb19f79632457f37ae3573696d7db84d57358627b65e618819ff80f132b0026a",
|
||||||
"view_source_sha": "d641ca58ac77c69a15a98c8a1233ae6dbd83017f"
|
"view_source_sha": "0fceb40088e728d481411c36a8d311aa3431b057"
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# PR-01 证据:Tool v1 独立打包、安装与分发(RFC-VIEW-0002)
|
||||||
|
|
||||||
|
- 日期:2026-11-22
|
||||||
|
- View 版本:`0.2.0`(`Cargo.toml`、`tool.json`、`marqdo-view --version` 一致)
|
||||||
|
- 冻结 CLI:`marqdo 3.0.0-beta.1`,SHA-256
|
||||||
|
`062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f`
|
||||||
|
- 平台:`x86_64-unknown-linux-gnu`
|
||||||
|
- 关键脚本:`scripts/package.sh`、`scripts/install-smoke.sh`、
|
||||||
|
`scripts/verify-frozen-cli.sh`
|
||||||
|
- 包:`dist/marqdo-view-0.2.0-x86_64-unknown-linux-gnu.tar.gz`
|
||||||
|
SHA-256 `c3504879c875bdf647f1d3269d5a3c422ca4de7f7c61982a383afadf33be0910`
|
||||||
|
(本次本地构建;该值随源码版本变化,最终发布由 PR-06 记录)
|
||||||
|
|
||||||
|
## 复现命令(均为实际执行)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export MARQDO_BIN=/abs/path/to/frozen/marqdo-3.0.0-beta.1
|
||||||
|
scripts/verify-frozen-cli.sh "$MARQDO_BIN" -- "$MARQDO_BIN" --version
|
||||||
|
|
||||||
|
cargo fmt --all -- --check
|
||||||
|
cargo clippy --all-targets --offline -- -D warnings
|
||||||
|
cargo test --locked --offline
|
||||||
|
MARQDO_BIN="$MARQDO_BIN" scripts/package.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
## 黑盒注册/分发结果
|
||||||
|
|
||||||
|
在隔离的 `MARQDO_TOOL_HOME` 中解包 `dist/marqdo-view-0.2.0-...tar.gz` 后:
|
||||||
|
|
||||||
|
| 步骤 | 命令 | 结果 |
|
||||||
|
|---|---|---|
|
||||||
|
| 安装 | `marqdo tool install .../tool.json` | `installed tool 'view' version 0.2.0 (marqdo-view)` |
|
||||||
|
| 列表 | `marqdo tool list` | `view 0.2.0 (marqdo-view)` |
|
||||||
|
| 分发帮助 | `marqdo view --help` | 输出由 View 提供(含 `export` / `verify`),CLI 未新增 `Command::View` |
|
||||||
|
| 分发版本 | `marqdo view --version` | `marqdo-view 0.2.0` |
|
||||||
|
| 整包篡改 | 向已安装 `view/bin/marqdo-view` 追加 1 字节后 `marqdo view --version` | exit 1,`error: tool 'view' bundle hash mismatch; reinstall it`(拒绝分发) |
|
||||||
|
| 卸载 | `marqdo tool remove view` | `removed tool 'view'`;`tool list` → `no tools installed` |
|
||||||
|
| 冻结 CLI SHA | 全流程前后 | 均为 `062cb56e…`,**未变化**;未构建/修改 CLI |
|
||||||
|
|
||||||
|
`cargo build --release --locked` 的依赖图不含 `marqdo-cli`/旧 `marqdo` 私有 crate
|
||||||
|
(`tests/contract/no_coupling.rs` 门禁)。
|
||||||
|
|
||||||
|
## 备注
|
||||||
|
|
||||||
|
- 包只含 `bin/marqdo-view`、`tool.json`、README/兼容性/许可证与
|
||||||
|
`RELEASE_INFO.json`/`SHA256SUMS`;CSS/JS/图片在构建期嵌入二进制(ADR-0002)。
|
||||||
|
- 安装后若发生篡改必须先 `tool remove view` 再重装(CLI 拒绝覆盖已安装命令),
|
||||||
|
这是 Core 的整包校验行为,View 不绕过。
|
||||||
|
- 远端 CI 配置为 `.github/workflows/ci.yml`;本次证据来自本地可复现命令,
|
||||||
|
未声称远端 CI 已运行。
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
# PR-02 证据:Reader/Analysis 结构与只读面(RFC-VIEW-0002)
|
||||||
|
|
||||||
|
- 日期:2026-11-22
|
||||||
|
- 范围:`src/protocol/*`、`src/reader/*`、`src/config.rs`、只读路由与阅读 UI 收敛
|
||||||
|
- 冻结 CLI:`marqdo 3.0.0-beta.1`(`062cb56e…`),本 PR 不改/不重编译
|
||||||
|
- 证据来源:本仓库 `cargo test`、`cargo clippy`、冻结 Analysis/Trace golden、
|
||||||
|
真实 Chromium 证据(0001 时期,PR-05 重新跑 0002 宽度矩阵)
|
||||||
|
|
||||||
|
## 1. 目标目录结构(§5.3 的 Reader 部分)
|
||||||
|
|
||||||
|
```
|
||||||
|
src/
|
||||||
|
main.rs # 唯一 composition root(解析参数后调用 lib::run)
|
||||||
|
lib.rs # 模块声明 + 用例分派(browse/verify/export),无第二管线
|
||||||
|
cli.rs # View 自有参数解析
|
||||||
|
config.rs # view.json 站点配置(不定义语言语义、不授权)
|
||||||
|
core_client.rs # 唯一 MARQDO_BIN 调用入口(check/negotiate/verify)
|
||||||
|
error.rs # 稳定错误码
|
||||||
|
export.rs # 静态导出(只依赖 Reader,不依赖执行)
|
||||||
|
protocol/
|
||||||
|
analysis_v2.rs # 公共 Analysis v2 解析/校验/投影
|
||||||
|
trace_v2.rs # 公共 Trace v2 解析/校验/绑定
|
||||||
|
tool_v1.rs # Tool v1 环境协商与版本轴
|
||||||
|
reader/
|
||||||
|
source.rs # 受控项目根、路径 containment、UTF-8 byte span、source digest
|
||||||
|
markdown.rs # 唯一 GFM 渲染器(无语义执行判断)
|
||||||
|
model.rs # PresentationModel / SourceStatus / Navigation / Outline
|
||||||
|
assemble.rs # 静态+运行产物合并、stale 判定、DocumentService
|
||||||
|
render.rs # 唯一 HTML 渲染入口(Live/Export 共用)
|
||||||
|
assets.rs # 构建期内嵌唯一 CSS/JS/图片
|
||||||
|
server.rs # 过渡文件:只读路由;PR-04 拆为 server/{mod,routes,security,sse}
|
||||||
|
```
|
||||||
|
|
||||||
|
`app.rs`/`project.rs`/`semantic.rs`/`trace.rs`/`document.rs`/`presentation.rs`/
|
||||||
|
`source_map.rs`/`render.rs`/`assets.rs` 旧路径已删除;`git mv` 保留历史。
|
||||||
|
没有对旧 `marqdo` 或 `marqdo-cli` 的 crate/Git/path 依赖(`tests/contract/no_coupling.rs`)。
|
||||||
|
|
||||||
|
## 2. 只读 API 收敛(本 PR 部分)
|
||||||
|
|
||||||
|
| 路由 | 状态 |
|
||||||
|
|---|---|
|
||||||
|
| `GET /` | 只读页面(不执行) |
|
||||||
|
| `GET /file?path=...` | 受控单文件页面(不执行) |
|
||||||
|
| `GET /assets/...` | 固定打包资产 |
|
||||||
|
| `GET /api/documents` | **新增**:文档列表 + 当前文档 outline/functions/analysis 摘要;只读 |
|
||||||
|
| `GET /api/document` | **删除**(旧单数路由,返回 404) |
|
||||||
|
| `GET /api/health`、`POST /api/run`、`/api/clear-run` | 过渡保留,PR-04 替换为 7 条合同路由(SSE) |
|
||||||
|
|
||||||
|
`GET /api/documents` 测试:`tests/integration/http_live.rs::documents_api_is_a_read_only_structure_and_old_route_is_gone`。
|
||||||
|
|
||||||
|
## 3. 阅读 UI 收敛(§4.2/§4.5)
|
||||||
|
|
||||||
|
- 页面只保留 `文档 / 函数 / 运行` 三项;`源码` 仍为“更多/局部切换”,无编辑器。
|
||||||
|
- “更多”菜单删除“变量信息/内存快照”占位项,改为一个“未提供的能力”说明项
|
||||||
|
(变量/内存/调试/证明均明确 UNSUPPORTED,不伪造)。
|
||||||
|
- 新增简单深色主题开关(`data-theme` + 单一 token 覆盖层 + localStorage 偏好),
|
||||||
|
无主题框架/远程皮肤;设置里可切字号/标注/主题/打印。
|
||||||
|
- `tests/integration/rendering.rs::reader_exposes_simple_theme_toggle_and_no_variable_or_memory_tabs`
|
||||||
|
断言页面不再出现 variables/memory 动作,且存在 theme/unsupported 动作。
|
||||||
|
|
||||||
|
## 4. 测试执行(实际)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cargo fmt --all -- --check
|
||||||
|
cargo clippy --all-targets --offline -- -D warnings
|
||||||
|
cargo test --locked --offline
|
||||||
|
```
|
||||||
|
|
||||||
|
结果:unit 41 + contract 41 + integration 33 = **115 passed / 0 failed**。
|
||||||
|
`cargo test` 的输出中每个 `[[test]]` 目标:
|
||||||
|
`contract`(CLI/Tool/Analysis/Trace/coupling/assets)、
|
||||||
|
`integration`(Live HTTP/renderer/unicode/export)。
|
||||||
|
|
||||||
|
## 5. 未完成/后续
|
||||||
|
|
||||||
|
- `server.rs` 仍是单文件过渡实现;PR-04 拆分为 `server/{mod,routes,security,sse}.rs`
|
||||||
|
并落实 7 路由、会话 Cookie、SSE、取消。
|
||||||
|
- `GET /api/health`/`/api/run`/`/api/clear-run` 是 PR-03/PR-04 前的过渡路由,
|
||||||
|
最终必须删除;当前不把“同步运行后整页重载”当作 0002 交付。
|
||||||
|
- `tests/security/` 套件与 `docs/design` 的 0002 宽度截图矩阵在 PR-04/PR-05 补齐。
|
||||||
@@ -1,23 +1,59 @@
|
|||||||
# PR-03 浏览器视觉验收证据
|
# PR-03 证据:执行层(request / process / controller / events)
|
||||||
|
|
||||||
- 采集环境:Chromium Headless Shell 131(Playwright 1.49.0),Linux x86_64,
|
- 日期:2026-11-22
|
||||||
视口见文件名;真实冻结核心 `marqdo 3.0.0-beta.1`
|
- 范围:`src/execution/{request,process,controller,events}.rs`、`core_client` 单一进程
|
||||||
(SHA-256 `062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f`)。
|
适配器、`--run-timeout`、`DocumentService::static_document`
|
||||||
- 采集脚本:`tests/browser/reader.browser.cjs`,入口 `tools/test-browser.sh`。
|
- 冻结 CLI:`marqdo 3.0.0-beta.1`(`062cb56e…`);本 PR 只用假核心做确定性进程级
|
||||||
- 断言范围(全部 PASS):单一 CSS/单一 script、无外部网络请求、无 console 错误、
|
测试,PR-04/06 再用真实冻结 CLI 做端到端验收
|
||||||
文档/源码切换、搜索、设置字号与标注显隐、7 个宽度(390/600/900/1280/1664/
|
- 说明:本 PR **不切换 HTTP 运行路由**;`POST /api/run`(同步旧路径)暂留到
|
||||||
1920/2560)无横向溢出且 Dock 在视口内、无 JS 可读、打印隐藏交互栏、显式运行
|
PR-04 被 7 路由 + SSE 替换。
|
||||||
确认后展示真实 Trace 与内联 chip、清理结果。
|
|
||||||
|
|
||||||
| 文件 | 说明 |
|
## 1. 实现结构
|
||||||
|
|
||||||
|
```
|
||||||
|
src/execution/
|
||||||
|
request.rs # §6.3 请求 schema/大小/路径/mode/grants/参数名校验;
|
||||||
|
# function_id -> CLI 名称(canonical 或唯一 local name)
|
||||||
|
process.rs # 唯一子进程适配器:argv 数组、独立进程组、SIGTERM→2s→SIGKILL、
|
||||||
|
# 有界 stdout/stderr(继续排空避免死锁)、spawn hook、墙钟
|
||||||
|
events.rs # RunState 状态机、run.* 事件、128 环形缓冲、Last-Event-ID 重放/
|
||||||
|
# 快照、SSE 帧、心跳常量
|
||||||
|
controller.rs # 单任务门禁、去重、静态 check+digest 比对、后台执行、
|
||||||
|
# Trace 校验投影、取消、终态唯一性、TTL 清理
|
||||||
|
```
|
||||||
|
|
||||||
|
`core_client` 的 `check`/`--version` 也改为走 `process::run_bounded`,因此
|
||||||
|
View 只有**一个**子进程实现;`build_run_args`/`build_call_args` 是唯一 argv 构造点。
|
||||||
|
|
||||||
|
## 2. 关键测试(`tests/integration/execution.rs`,假核心真实进程)
|
||||||
|
|
||||||
|
| 测试 | 断言 |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `welcome-1664x920.png` | 显式 `view.json` Welcome 页,1664×920(与基准截图同尺寸),无运行 |
|
| `explicit_entry_run_streams_accepted_running_and_succeeded_with_verified_trace` | 事件序号递增;accepted/running/succeeded;Trace `verified`、事件非空、`stale=false`、stdout 来自 CLI JSON |
|
||||||
| `welcome-390x844.png` | 同一页面 390×844 单栏布局 |
|
| `call_target_uses_the_call_subcommand_and_function_name` | argv 为 `call FILE <name>`;FUNCTION 名称由 function_id 精确解析 |
|
||||||
| `control-flow-run-1664x920.png` | `examples/control-flow` 用户确认运行后的真实 Trace v2 运行面板与内联事件 chip |
|
| `same_client_request_id_is_idempotent_and_different_payload_conflicts` | 同 ID 同 body → 同 `run_id`(reused);不同 body → `view.run_conflict` |
|
||||||
|
| `second_run_is_busy_while_one_is_active_and_cancel_is_idempotent` | 第二任务 `view.run_busy`;取消幂等;终态唯一 `cancelled`;<10s 结束 |
|
||||||
|
| `cross_session_observation_is_rejected` | 其他会话订阅/取消 → `view.run_not_found` |
|
||||||
|
| `stale_analysis_digest_is_rejected_before_any_process_starts` | digest 不符 → `view.run_invalid`,假核心无 run 调用 |
|
||||||
|
| `project_grants_are_mapped_to_explicit_cli_flags_and_pure_grants_are_rejected` | project 请求 argv 有 `--mode project`/`--allow-read`/`--allow-write`;pure+grants 被拒 |
|
||||||
|
| `run_without_a_trace_file_succeeds_but_reports_unavailable_trace` | 成功 + `trace=null` + `trace_status=unavailable`,不伪造 |
|
||||||
|
| `event_frames_use_the_view_run_events_schema_and_numeric_ids` | `marqdo.view-run-events` v1、run_id/seq 一致 |
|
||||||
|
| 单元测试(events/process/request) | 环形缓冲截断→快照、seq/id 一致、取消终止进程组、glob/参数/包络校验 |
|
||||||
|
|
||||||
## 诚实限制
|
## 3. 实测命令与结果
|
||||||
|
|
||||||
- 未做与 `docs/design/reference-old-view-reader.png` 的像素差分:本环境无法进行
|
```bash
|
||||||
人工视觉判读,`U-01` 只声明“DOM/几何/字体栈/颜色令牌/无溢出/无外部资源”通过,
|
cargo fmt --all -- --check
|
||||||
像素级视觉相似度标记为 **UNVERIFIED(人工复核待办)**,不以自动化 PASS 代替。
|
cargo clippy --all-targets --offline -- -D warnings
|
||||||
- 截图是证据,不是新的渲染路径:页面仍由唯一 `ReaderRenderer` 生成。
|
cargo test --locked --offline
|
||||||
|
```
|
||||||
|
|
||||||
|
结果:unit 58 + contract 41 + integration 42 = **141 passed / 0 failed**。
|
||||||
|
`--run-timeout` 限制在 1..=120 秒,默认 30 秒(`tests/contract/cli_surface.rs`)。
|
||||||
|
|
||||||
|
## 4. 明确未完成
|
||||||
|
|
||||||
|
- HTTP 路由/SSE 传输/session Cookie 属于 PR-04;当前 Controller 已提供
|
||||||
|
`submit/subscribe/cancel/job_state`,但未暴露公共状态轮询路由。
|
||||||
|
- 前端函数参数表单与运行区仍在 PR-04 切换;旧同步 `/api/run` 在此期间仍是过渡实现。
|
||||||
|
- 真实冻结 CLI 的 run/call/Trace 端到端证据在 PR-04/PR-06 记录(本 PR 不冒称)。
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
# PR-04 证据:SSE 执行闭环、7 路由与会话安全
|
||||||
|
|
||||||
|
- 日期:2026-11-22
|
||||||
|
- 范围:`src/server/{mod,routes,security,sse}.rs`、`src/reader/render.rs` 运行表单/
|
||||||
|
运行区、`assets/reader.js` SSE 前端、`tests/integration/http_live.rs`、
|
||||||
|
`tests/security/`、浏览器套件
|
||||||
|
- 冻结 CLI:`marqdo 3.0.0-beta.1`,SHA-256
|
||||||
|
`062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f`
|
||||||
|
(真实 run 证据 `real-run.log`,run 前后 SHA 不变)
|
||||||
|
- 产品规则:SSE 无轮询;运行唯一入口 `POST /api/runs`;单任务;取消唯一终态
|
||||||
|
|
||||||
|
## 1. 路由与安全
|
||||||
|
|
||||||
|
| 路由 | 验证 |
|
||||||
|
|---|---|
|
||||||
|
| `GET /` / `GET /file` | 发放 HttpOnly/SameSite=Strict Cookie + CSRF meta;重复打开 10 次无 `run` 调用(`pages_issue_a_session_cookie_and_never_execute_the_document`) |
|
||||||
|
| `GET /assets/...` | 唯一 CSS/JS、immutable、CSP/`nosniff`;未知资产 404 |
|
||||||
|
| `GET /api/documents` | `marqdo.view-documents` v1 只读结构;旧 `/api/document`、`/api/health`、`/api/run` 均 404 |
|
||||||
|
| `POST /api/runs` | 202 + run_id/events_url/cancel_url;无 Cookie/CSRF/Origin、错 Origin、非 JSON、超大 body 全部拒绝且不启动进程 |
|
||||||
|
| `GET /api/runs/{id}/events` | `text/event-stream`、逐帧 flush、心跳、Last-Event-ID 重放/伪造游标 snapshot、跨会话 404、无会话 401、>2 连接 429 |
|
||||||
|
| `POST /api/runs/{id}/cancel` | 幂等、唯一 `cancelled` 终态、跨会话 404、不新增进程 |
|
||||||
|
|
||||||
|
浏览器测试还断言:`Origin`/`Sec-Fetch-Site` 跨站拒绝、`HttpOnly`+`SameSite=Strict`、
|
||||||
|
CSP 无 `unsafe-inline`/`unsafe-eval`、symlink 出根被拒、Markdown 不能注入
|
||||||
|
`<script>`/事件处理器。
|
||||||
|
|
||||||
|
## 2. SSE 生命周期(真实事件序列)
|
||||||
|
|
||||||
|
`tests/integration/http_live.rs`:
|
||||||
|
|
||||||
|
- `explicit_run_streams_sse_accepted_running_and_terminal_with_verified_trace`:
|
||||||
|
accepted → running → succeeded;`id` 严格递增且与 `data.seq` 一致;终态含
|
||||||
|
CLI result 与 `trace.status=verified` 事件;
|
||||||
|
- `last_event_id_replays_only_newer_events_and_old_cursor_gets_snapshot`:重放
|
||||||
|
只发更新事件;伪造游标得权威 snapshot;
|
||||||
|
- `cancel_is_idempotent_and_yields_one_terminal_state`:两次 cancel 均 200,
|
||||||
|
SSE 只有一个 `cancelled` 终态且 <8s 结束;
|
||||||
|
- `sse_heartbeats_keep_a_slow_job_connected`:长任务期间收到 `: heartbeat`,
|
||||||
|
任务仍成功;
|
||||||
|
- `at_most_two_sse_observers_per_run`:第 3 个观察连接 429;
|
||||||
|
- `duplicate_request_id_is_idempotent_and_busy_or_conflict_never_starts_a_second_process`:
|
||||||
|
同 ID 同 body → 同 run_id;busy/conflict → 409,不启第二进程;
|
||||||
|
- `sse_and_cancel_are_scoped_to_the_owning_session`:跨会话读取/取消 404;
|
||||||
|
- `document_without_main_is_rejected_without_running_another_function`:400
|
||||||
|
`view.no_entry_function` 且无 run 调用。
|
||||||
|
|
||||||
|
## 3. 浏览器(真实 Chromium 131,七套视图宽度)
|
||||||
|
|
||||||
|
`browser.log` 为 `MARQDO_BIN=062cb56e… scripts/test-browser.sh` 的真实输出,
|
||||||
|
三个项目全部 PASS,包括:
|
||||||
|
|
||||||
|
- run 对话框 → 命令预览 → 确认 → **SSE 终态 succeeded**(无整页重载);
|
||||||
|
- 运行区、Trace 事件列表、stdout 文本、原文 `.mq-run-chip` 锚点;
|
||||||
|
- 请求记录中没有状态轮询 API;
|
||||||
|
- 清理隐藏运行区且不重载页面;
|
||||||
|
- 2048×1133 / 1664×920 / 1440×900 / 1024×768 / 768×1024 / 390×844 无横向溢出、
|
||||||
|
Dock 在视口内、无外部请求、无 console error、无 JS 可读、打印隐藏交互;
|
||||||
|
- 深色/暖纸主题切换并持久化,无 unsafe-inline/eval。
|
||||||
|
|
||||||
|
截图:`welcome-2048x1133.png`、`control-flow-2048x1133.png`、
|
||||||
|
`control-flow-390x844.png`、`control-flow-run.png`。
|
||||||
|
|
||||||
|
## 4. 真实冻结 CLI 端到端
|
||||||
|
|
||||||
|
`real-run.log`:启动 `target/release/marqdo-view examples/control-flow`(使用
|
||||||
|
冻结 CLI),脚本 `scripts/acceptance-run.py` 完成 GET 页面 → POST /api/runs →
|
||||||
|
读取 SSE 终态:`succeeded`、`trace.status=verified`、**285 条 Trace 事件**。
|
||||||
|
截图与日志均来自该实现;CLI SHA 在前后保持不变。
|
||||||
|
|
||||||
|
## 5. 测试计数(本 PR 合并时)
|
||||||
|
|
||||||
|
```
|
||||||
|
cargo test --locked --offline
|
||||||
|
unit 63 + contract 41 + integration 40 + security 11 = 155 passed / 0 failed
|
||||||
|
cargo clippy --all-targets --offline -- -D warnings # clean
|
||||||
|
```
|
||||||
|
|
||||||
|
## 6. 已知边界
|
||||||
|
|
||||||
|
- 首版不提供 net/process/env/plugin/provider/kernel 授权 UI;请求会被拒绝并提示
|
||||||
|
使用终端 CLI(`view.run_denied`/`view.run_invalid`)。
|
||||||
|
- `project` 模式需要显式 read/write glob 并二次确认;它不是 OS 沙箱。
|
||||||
|
- SSE 只推送 View 生命周期与终态数据,不推送逐字 stdout/Token 流(RFC §6.1)。
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
==> 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
|
||||||
|
|
||||||
|
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 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 trace event list rendered
|
||||||
|
ok stdout rendered escaped
|
||||||
|
ok no polling API was used
|
||||||
|
ok clear hides run panel
|
||||||
|
ok page was never reloaded by the run
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
browser: PASS
|
||||||
|
browser: PASS (core sha256 062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f unchanged; screenshots: /root/work/marqdo-view/tests/browser/artifacts)
|
||||||
|
After Width: | Height: | Size: 119 KiB |
|
After Width: | Height: | Size: 67 KiB |
|
After Width: | Height: | Size: 105 KiB |
@@ -0,0 +1 @@
|
|||||||
|
explicit real run: PASS (run_id=918359e1f4f5fd5155c86e6e55854b2c events=285)
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
marqdo view: http://127.0.0.1:40487/
|
||||||
|
root: /root/work/marqdo-view/examples/control-flow
|
||||||
|
1 .mq.md document(s). Ctrl+C to stop.
|
||||||
|
core: marqdo 3.0.0-beta.1 (Analysis v2, Trace v2)
|
||||||
|
run: explicit only (pure by default, one active job, 30s wall clock)
|
||||||
|
JOB_DEBUG id=918359e1f4f5fd5155c86e6e55854b2c run_core elapsed=61.583791ms cancel=false
|
||||||
|
JOB_DEBUG id=918359e1f4f5fd5155c86e6e55854b2c terminal state=Succeeded total=67.878533ms
|
||||||
|
After Width: | Height: | Size: 187 KiB |
@@ -0,0 +1,51 @@
|
|||||||
|
# PR-05 证据:Trace v2 绑定、原文标注与浏览器回归
|
||||||
|
|
||||||
|
- 日期:2026-11-22
|
||||||
|
- 范围:`src/execution/controller.rs`(Trace 摘要/`source_id`/stale)、
|
||||||
|
`assets/reader.js`(Observed chip 分组)、`src/reader/render.rs`
|
||||||
|
(`data-annotation-source`)、浏览器套件与视觉证据
|
||||||
|
- 冻结 CLI:`marqdo 3.0.0-beta.1`(`062cb56e…`),浏览器测试前后 SHA 不变
|
||||||
|
- 规范:RFC-VIEW-0002 §4.4、§7.3、§7.4;ADR-0010
|
||||||
|
|
||||||
|
## 1. 绑定与降级(测试)
|
||||||
|
|
||||||
|
| 场景 | 断言 | 测试 |
|
||||||
|
|---|---|---|
|
||||||
|
| 正常运行 | Trace `status=verified`、事件 `source_id` 可锚定、`stale=false` | `explicit_entry_run_streams_...` |
|
||||||
|
| 源在运行中被编辑 | `result.stale=true`、`trace.stale=true`、所有 `anchor/source_id=null` | `source_edit_during_a_run_marks_the_result_stale_and_drops_anchor_ids` |
|
||||||
|
| Trace digest 不符 | 运行仍 `succeeded`,`trace.status=invalid`,无事件/无锚点 | `trace_with_a_mismatched_digest_is_reported_invalid_but_the_run_still_succeeds` |
|
||||||
|
| Trace 截断 | `trace.truncated.reason=event_budget`,结果保留,不声称完整 | `truncated_trace_is_marked_without_claiming_complete_coverage` |
|
||||||
|
| Trace 缺失 | `trace=null`、`trace_status=unavailable`,不伪造 | `run_without_a_trace_file_succeeds_but_reports_unavailable_trace` |
|
||||||
|
| 非入口模块事件 | 不映射到入口正文(`source_id=null`),保留模块 id | Controller Trace 摘要/`trace_contract` 校验 |
|
||||||
|
| UTF-8/span/越界 | 既有 Analysis/Trace 校验测试保持通过 | `tests/contract/trace_contract.rs`、`integration/unicode_spans.rs` |
|
||||||
|
|
||||||
|
## 2. 浏览器回归(真实 Chromium 131)
|
||||||
|
|
||||||
|
`browser.log`:三个项目全部 PASS。关键断言:
|
||||||
|
|
||||||
|
- `observed chips carry trace provenance`:chip 带
|
||||||
|
`data-annotation-source="trace"`;
|
||||||
|
- `static statement anchors carry analysis provenance`:静态锚点带
|
||||||
|
`data-annotation-source="analysis"`;
|
||||||
|
- `at most one grouped chip per anchor`:同锚点多事件合并为单个 chip(>3 条显示
|
||||||
|
`×N` 与真实 `title`),不压过正文;
|
||||||
|
- run 终态/运行区/Trace 列表/stdout/清理与既有检查;
|
||||||
|
- 2048×1133、1664×920、1440×900、1024×768、768×1024、390×844:无横向溢出、
|
||||||
|
Dock 在视口、无外部请求、无 console error;
|
||||||
|
- 无 JS 可读、打印保持正文、深色/暖纸主题切换与持久化。
|
||||||
|
|
||||||
|
截图:`control-flow-run.png`、`control-flow-run-dark.png`、
|
||||||
|
`welcome-2048x1133.png`、`control-flow-390x844.png`。
|
||||||
|
|
||||||
|
## 3. 测试计数
|
||||||
|
|
||||||
|
```
|
||||||
|
unit 63 + contract 41 + integration 43 + security 11 = 158 passed / 0 failed
|
||||||
|
```
|
||||||
|
|
||||||
|
## 4. 未做/偏差
|
||||||
|
|
||||||
|
- 未实现 SVG 弯曲连接线;按 RFC §4.4 允许的降级采用内联分组 chip(ADR-0010),
|
||||||
|
不画无来源/错位曲线。
|
||||||
|
- 逐语句变量值/参数值/内存快照:Trace v2 不提供,保持 UNSUPPORTED。
|
||||||
|
- 人工像素级比对与完整 screen-reader 走查仍为 `UNVERIFIED`。
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
==> 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
|
||||||
|
|
||||||
|
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 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 trace provenance
|
||||||
|
ok static statement anchors carry analysis provenance
|
||||||
|
ok at most one grouped chip per anchor
|
||||||
|
ok trace event list rendered
|
||||||
|
ok stdout rendered escaped
|
||||||
|
ok no polling API was used
|
||||||
|
ok clear hides run panel
|
||||||
|
ok page was never reloaded by the run
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
browser: PASS
|
||||||
|
browser: PASS (core sha256 062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f unchanged; screenshots: /root/work/marqdo-view/tests/browser/artifacts)
|
||||||
|
After Width: | Height: | Size: 67 KiB |
|
After Width: | Height: | Size: 103 KiB |
|
After Width: | Height: | Size: 102 KiB |
|
After Width: | Height: | Size: 187 KiB |
@@ -0,0 +1,67 @@
|
|||||||
|
# PR-06 证据:示例、静态导出、发布门禁与文档闭环
|
||||||
|
|
||||||
|
- 日期:2026-11-22
|
||||||
|
- 范围:`examples/*.mq.md`、`scripts/{check-examples,test-no-exec}.sh`、
|
||||||
|
`scripts/acceptance.sh`、静态导出控件收敛、最终 ACCEPTANCE/STATUS/README
|
||||||
|
- 冻结 CLI:`marqdo 3.0.0-beta.1`,SHA-256
|
||||||
|
`062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f`
|
||||||
|
- 机器证据(最终):`docs/evidence/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json`
|
||||||
|
(在 PR-06 提交 `0fceb40` 上重跑 `scripts/acceptance.sh` 生成;
|
||||||
|
View binary `eb19f796…`、archive `a3fb28c8…`、CLI before/after
|
||||||
|
`062cb56e…`;`manifest.pre-commit.json` 为文档定稿前同一代码的预跑结果,
|
||||||
|
保留对照)
|
||||||
|
|
||||||
|
## 1. §13.3 示例(真实 CLI)
|
||||||
|
|
||||||
|
`check-examples.log`:
|
||||||
|
|
||||||
|
- 5 个示例全部 `check --emit` 成功;
|
||||||
|
- `call function-params.mq.md double --arg n=5` → `Int(10)`;
|
||||||
|
- `run branch-loop.mq.md` → `Int(0)`,Trace 含 `loop.iteration`/`return`;
|
||||||
|
- `run knowledge-only.mq.md` → exit 1 `sem.no_entry_function`(无隐式替代);
|
||||||
|
- `run unsafe-side-effect.mq.md --mode pure` → `permission.denied`,无文件;
|
||||||
|
- `--mode project --allow-write out --allow-write 'out/**'` → 仅此时写出
|
||||||
|
`out/view-sentinel.txt`(内容 `explicit run only\n`);
|
||||||
|
- 全程冻结 CLI SHA 不变。
|
||||||
|
|
||||||
|
## 2. §13.4 零执行哨兵(真实 HTTP + 导出)
|
||||||
|
|
||||||
|
`no-exec.log`:对 unsafe-side-effect 执行
|
||||||
|
`GET /`、`GET /file`、`GET /api/documents`、重复 reload、`view export` 后:
|
||||||
|
|
||||||
|
- `examples/**/*.mq.md`、`marqdo.yaml`、`view.json`、`marqdo.lock` 哈希不变;
|
||||||
|
- 无 `examples/out/view-sentinel.txt`;
|
||||||
|
- 导出的 HTML **不含** `data-action="run"`、`mq-csrf-token` 或外链;
|
||||||
|
- 冻结 CLI SHA 不变。
|
||||||
|
|
||||||
|
## 3. 一键验收(§9.4)
|
||||||
|
|
||||||
|
`acceptance.log`(真实命令输出)包含:
|
||||||
|
|
||||||
|
```
|
||||||
|
fmt / clippy / test / build / bundle / archive_install / tool_list / view_help /
|
||||||
|
verify / export / examples_check / browse / real_run / export_suite /
|
||||||
|
no_exec_suite / security_suite / browser / core_sha -> 全部 PASS
|
||||||
|
```
|
||||||
|
|
||||||
|
其中:
|
||||||
|
|
||||||
|
- `test`:unit 63 + contract 41 + integration 43 + security 11 = 158 PASS;
|
||||||
|
- `browser`:welcome/control-flow/security-project,真实 Chromium 131,
|
||||||
|
EventSource 终态、宽矩阵、主题、无外部请求、无 console error;
|
||||||
|
- `real_run`:真实冻结 CLI + SSE,`succeeded` + `trace.status=verified`;
|
||||||
|
- `core_sha`:CLI before == after == `062cb56e…`。
|
||||||
|
|
||||||
|
## 4. 发布包
|
||||||
|
|
||||||
|
- 版本:`marqdo-view 0.2.0`;
|
||||||
|
- 包:`dist/marqdo-view-0.2.0-x86_64-unknown-linux-gnu.tar.gz`
|
||||||
|
(SHA-256 记录在最终 manifest 的 `archive_sha256`);
|
||||||
|
- 从 `.tar.gz` 解包到独立临时目录后经冻结 CLI `tool install` 安装、`view --help`
|
||||||
|
分发与真实运行;安装态与本地源码目录解耦。
|
||||||
|
|
||||||
|
## 5. 仍未验证(诚实项)
|
||||||
|
|
||||||
|
- 人工像素级比对(相对 2048×1133 参考图)与完整 screen-reader 走查:`UNVERIFIED`;
|
||||||
|
- 远端 CI 未实际运行(配置已提供);
|
||||||
|
- Windows/macOS 未构建/未验证。
|
||||||
@@ -0,0 +1,538 @@
|
|||||||
|
==> fmt
|
||||||
|
[acceptance] fmt: PASS
|
||||||
|
==> clippy
|
||||||
|
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.03s
|
||||||
|
[acceptance] clippy: PASS
|
||||||
|
==> test
|
||||||
|
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.05s
|
||||||
|
Running unittests src/lib.rs (target/debug/build/marqdo-view/c349aa60d8df28c9/out/marqdo_view-c349aa60d8df28c9)
|
||||||
|
|
||||||
|
running 63 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::missing_bin_has_stable_code ... ok
|
||||||
|
test core_client::tests::scratch_dir_is_private_and_removed ... ok
|
||||||
|
test core_client::tests::run_args_are_explicit_argv_never_shell ... ok
|
||||||
|
test cli::tests::parses_browse_defaults ... ok
|
||||||
|
test core_client::tests::stderr_summary_is_bounded ... ok
|
||||||
|
test cli::tests::export_requires_out ... ok
|
||||||
|
test cli::tests::parses_verify_and_global_options_anywhere ... ok
|
||||||
|
test execution::controller::tests::cli_errors_support_both_envelope_shapes ... ok
|
||||||
|
test execution::controller::tests::run_ids_are_unguessable_and_unique ... 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::states_have_stable_wire_values_and_terminals ... ok
|
||||||
|
test cli::tests::parses_export_subcommand ... ok
|
||||||
|
test execution::events::tests::utc_formatting_is_stable ... ok
|
||||||
|
test execution::process::tests::bounded_capture_keeps_limit_and_drains ... ok
|
||||||
|
test cli::tests::run_timeout_is_bounded_to_rfc_range ... ok
|
||||||
|
test execution::process::tests::default_budget_matches_rfc ... ok
|
||||||
|
test execution::controller::tests::wire_value_summary_is_safe_and_never_html ... ok
|
||||||
|
test execution::events::tests::ring_is_bounded_and_old_cursor_gets_snapshot ... ok
|
||||||
|
test execution::events::tests::terminal_job_replays_snapshot_and_closes ... ok
|
||||||
|
test export::tests::export_target_outside_project_is_accepted ... ok
|
||||||
|
test execution::request::tests::rejects_absolute_and_parent_globs ... ok
|
||||||
|
test execution::request::tests::rejects_unknown_fields_and_bad_modes ... ok
|
||||||
|
test export::tests::manifest_relative_paths_are_validated ... ok
|
||||||
|
test protocol::analysis_v2::tests::rejects_digest_mismatch ... ok
|
||||||
|
test protocol::analysis_v2::tests::projects_valid_analysis ... ok
|
||||||
|
test execution::request::tests::canonical_names_and_targets_resolve ... ok
|
||||||
|
test protocol::analysis_v2::tests::rejects_unknown_schema_major_and_profile ... ok
|
||||||
|
test execution::request::tests::entry_without_main_is_explicitly_rejected ... ok
|
||||||
|
test protocol::analysis_v2::tests::source_id_is_deterministic_and_bounded ... ok
|
||||||
|
test protocol::tool_v1::tests::negotiates_known_protocols_only ... ok
|
||||||
|
test execution::request::tests::unknown_parameter_names_are_rejected_before_execution ... ok
|
||||||
|
test protocol::tool_v1::tests::parses_official_version_line ... ok
|
||||||
|
test protocol::tool_v1::tests::rejects_stable_only_reinterpretation ... ok
|
||||||
|
test protocol::trace_v2::tests::state_values_are_stable ... ok
|
||||||
|
test protocol::trace_v2::tests::trace_kinds_are_additive_safe ... 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::markdown::tests::parses_gfm_and_preserves_utf8_spans ... ok
|
||||||
|
test reader::markdown::tests::parses_math_and_code_as_inert_literals ... ok
|
||||||
|
test reader::markdown::tests::parses_lists_quotes_and_task_items ... ok
|
||||||
|
test reader::model::tests::heading_anchors_are_deterministic_and_collision_free ... ok
|
||||||
|
test reader::model::tests::status_values_are_stable ... 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::routes::tests::status_mapping_covers_execution_errors ... 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::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::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. 63 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.03s
|
||||||
|
|
||||||
|
Running unittests src/main.rs (target/debug/build/marqdo-view/35e1f759375c2551/out/marqdo_view-35e1f759375c2551)
|
||||||
|
|
||||||
|
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/8ae29fd710d6819e/out/contract-8ae29fd710d6819e)
|
||||||
|
|
||||||
|
running 41 tests
|
||||||
|
test asset_integrity::theme_has_one_token_layer_and_no_legacy_skin ... ok
|
||||||
|
test cli_surface::degradation_without_core_keeps_prose_readable ... 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::verify_without_core_is_an_argument_error ... ok
|
||||||
|
test cli_surface::export_requires_an_output_directory ... ok
|
||||||
|
test cli_surface::non_loopback_bind_is_refused_by_default ... ok
|
||||||
|
test cli_surface::version_is_the_tool_version ... ok
|
||||||
|
test cli_surface::help_comes_from_view_not_core ... 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::check_returns_exact_analysis_bytes_and_digest ... ok
|
||||||
|
test core_contract::check_refs_is_forwarded_as_a_stricter_flag ... ok
|
||||||
|
test core_contract::failed_check_normalizes_diagnostics_without_absolute_paths ... ok
|
||||||
|
test core_contract::incompatible_product_version_is_rejected_before_any_work ... ok
|
||||||
|
test asset_integrity::embedded_asset_bundle_matches_disk_and_has_one_theme ... ok
|
||||||
|
test core_contract::missing_emit_after_success_is_an_analysis_failure ... ok
|
||||||
|
test no_coupling::no_private_core_crate_dependencies ... ok
|
||||||
|
test no_coupling::release_lockfile_is_committed ... ok
|
||||||
|
test core_contract::run_invalid_json_is_a_protocol_io_error ... ok
|
||||||
|
test no_coupling::tool_manifest_matches_package_and_protocols ... ok
|
||||||
|
test core_contract::run_returns_json_and_raw_trace ... 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 core_contract::run_without_trace_file_reports_no_trace ... ok
|
||||||
|
test no_coupling::source_never_reads_or_links_the_legacy_repositories ... ok
|
||||||
|
test trace_contract::failed_run_keeps_the_core_error_code ... ok
|
||||||
|
test presentation_states::failed_check_keeps_prose_and_shows_core_diagnostics ... ok
|
||||||
|
test presentation_states::invalid_core_span_is_dropped_with_an_explicit_warning ... ok
|
||||||
|
test presentation_states::source_digest_mismatch_degrades_instead_of_misbinding ... ok
|
||||||
|
test presentation_states::unknown_analysis_schema_is_a_hard_protocol_error ... ok
|
||||||
|
test core_contract::cli_verify_rejects_schema_v3_and_digest_mismatch ... ok
|
||||||
|
test trace_contract::golden_digest_is_really_sha256_of_analysis_bytes ... ok
|
||||||
|
test trace_contract::truncated_trace_is_explicitly_marked ... ok
|
||||||
|
test trace_contract::non_monotonic_sequence_is_rejected ... ok
|
||||||
|
test core_contract::timeout_kills_the_process_group_and_reports_timeout ... ok
|
||||||
|
test trace_contract::stale_analysis_bytes_are_rejected ... ok
|
||||||
|
test trace_contract::unknown_schema_major_is_a_protocol_error_not_a_stale_trace ... ok
|
||||||
|
test trace_contract::real_control_flow_trace_binds_and_projects_events ... ok
|
||||||
|
test trace_contract::unknown_event_module_is_rejected ... ok
|
||||||
|
test presentation_states::run_attached_to_changed_source_becomes_stale ... ok
|
||||||
|
|
||||||
|
test result: ok. 41 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.67s
|
||||||
|
|
||||||
|
Running tests/integration/main.rs (target/debug/build/marqdo-view/09a14a21a5f580dd/out/integration-09a14a21a5f580dd)
|
||||||
|
|
||||||
|
running 43 tests
|
||||||
|
test execution::cross_session_observation_is_rejected ... ok
|
||||||
|
test execution::same_client_request_id_is_idempotent_and_different_payload_conflicts ... ok
|
||||||
|
test execution::run_without_a_trace_file_succeeds_but_reports_unavailable_trace ... ok
|
||||||
|
test execution::explicit_entry_run_streams_accepted_running_and_succeeded_with_verified_trace ... ok
|
||||||
|
test execution::second_run_is_busy_while_one_is_active_and_cancel_is_idempotent ... 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::project_grants_are_mapped_to_explicit_cli_flags_and_pure_grants_are_rejected ... ok
|
||||||
|
test export::exported_html_has_no_remote_subresources ... 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::refuses_to_export_inside_the_project_root ... ok
|
||||||
|
test export::exports_offline_site_with_shared_renderer_and_relative_links ... ok
|
||||||
|
test export::refuses_to_overwrite_unrelated_non_empty_directory ... ok
|
||||||
|
test execution::stale_analysis_digest_is_rejected_before_any_process_starts ... ok
|
||||||
|
test http_live::assets_are_immutable_and_carry_strict_headers ... ok
|
||||||
|
test execution::trace_with_a_mismatched_digest_is_reported_invalid_but_the_run_still_succeeds ... ok
|
||||||
|
test http_live::document_without_main_is_rejected_without_running_another_function ... ok
|
||||||
|
test execution::truncated_trace_is_marked_without_claiming_complete_coverage ... ok
|
||||||
|
test export::replaces_a_previous_export_atomically ... 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 export::export_never_executes_side_effects ... 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 http_live::at_most_two_sse_observers_per_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::knowledge_emphasis_never_becomes_an_execution_anchor ... ok
|
||||||
|
test unicode_spans::unicode_spans_are_exact_and_duplicate_returns_get_distinct_anchors ... ok
|
||||||
|
test rendering::run_controls_are_explicitly_unavailable_before_pr04 ... ok
|
||||||
|
test http_live::duplicate_request_id_is_idempotent_and_busy_or_conflict_never_starts_a_second_process ... ok
|
||||||
|
test http_live::cancel_is_idempotent_and_yields_one_terminal_state ... ok
|
||||||
|
test http_live::explicit_run_streams_sse_accepted_running_and_terminal_with_verified_trace ... ok
|
||||||
|
test execution::source_edit_during_a_run_marks_the_result_stale_and_drops_anchor_ids ... ok
|
||||||
|
test http_live::last_event_id_replays_only_newer_events_and_old_cursor_gets_snapshot ... ok
|
||||||
|
test http_live::sse_heartbeats_keep_a_slow_job_connected ... ok
|
||||||
|
|
||||||
|
test result: ok. 43 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 5.38s
|
||||||
|
|
||||||
|
Running tests/security/main.rs (target/debug/build/marqdo-view/a005d0c01f80685f/out/security-a005d0c01f80685f)
|
||||||
|
|
||||||
|
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 symlink_escape_outside_the_project_root_is_rejected ... ok
|
||||||
|
test sec_fetch_site_cross_site_is_rejected_even_with_a_valid_token ... ok
|
||||||
|
test oversized_and_unknown_fields_are_rejected_before_execution ... 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 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.71s
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
[acceptance] test: PASS
|
||||||
|
==> build
|
||||||
|
Finished `release` profile [optimized] target(s) in 0.03s
|
||||||
|
[acceptance] build: PASS
|
||||||
|
==> bundle
|
||||||
|
==> cargo build --release --locked
|
||||||
|
Finished `release` profile [optimized] target(s) in 0.03s
|
||||||
|
==> smoke install against frozen core
|
||||||
|
install-smoke: PASS (core sha256 062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f unchanged, tool home /root/work/marqdo-view/dist/smoke-tool-home.R8mnIg)
|
||||||
|
bundle: /root/work/marqdo-view/dist/marqdo-view
|
||||||
|
archive: /root/work/marqdo-view/dist/marqdo-view-0.2.0-x86_64-unknown-linux-gnu.tar.gz
|
||||||
|
sha256: a3fb28c8d025f44dee6c06da80c13d3f65b9c62d1f657c04b02ef360ff24fcf5
|
||||||
|
[acceptance] bundle: PASS
|
||||||
|
==> archive_install
|
||||||
|
installed tool `view` version 0.2.0 (marqdo-view)
|
||||||
|
[acceptance] archive_install: PASS
|
||||||
|
==> tool_list
|
||||||
|
[acceptance] tool_list: PASS
|
||||||
|
==> view_help
|
||||||
|
[acceptance] view_help: PASS
|
||||||
|
==> verify
|
||||||
|
core: marqdo 3.0.0-beta.1 (supported >=3.0.0-beta.1,<4.0.0)
|
||||||
|
project: root:mixed-modes@0.1.0 (manifest)
|
||||||
|
document: index.mq.md
|
||||||
|
analysis: schema=marqdo.analysis v2 modules=1 functions=1 digest=sha256:5b13d0cd2044cbe3d5d5f51145a9dd0015e2992400f803dad5f0e42214ce4959
|
||||||
|
source digest: match
|
||||||
|
result: PASS (static only; document not executed)
|
||||||
|
[acceptance] verify: PASS
|
||||||
|
==> export
|
||||||
|
marqdo view export: 1 page(s), 8 file(s) → /root/work/marqdo-view/dist/acceptance/site
|
||||||
|
manifest: sha256:74059e7274165cf341e576aac6f6a7fef0d8210261186b234fa85a2a2308bdb7
|
||||||
|
executed: false (纯静态导出,未运行任何文档)
|
||||||
|
[acceptance] export: PASS
|
||||||
|
==> examples_check
|
||||||
|
==> check all five example documents (no execution)
|
||||||
|
==> call function-params.double(n=5) -> 10
|
||||||
|
call double(5): PASS (Int 10)
|
||||||
|
==> run branch-loop main -> Int 0 with loop/return trace
|
||||||
|
run branch-loop: PASS (value 0, events: call.enter,call.exit,loop.iteration,return)
|
||||||
|
==> knowledge-only has no main (truthful failure, 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 062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f unchanged)
|
||||||
|
[acceptance] examples_check: PASS
|
||||||
|
[acceptance] browse: PASS
|
||||||
|
explicit real run: PASS (run_id=7b8adab46d3d5ba5d14affb44284ca82 events=285)
|
||||||
|
[acceptance] real_run: PASS
|
||||||
|
==> export_suite
|
||||||
|
marqdo view export: 2 page(s), 9 file(s) → /root/work/marqdo-view/dist/test-export-site
|
||||||
|
manifest: sha256:47c8931c864c86d7d5a4f7ec11a68fba56961f5f03d29d19eac447f9db7645a3
|
||||||
|
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 062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f unchanged)
|
||||||
|
[acceptance] export_suite: PASS
|
||||||
|
==> no_exec_suite
|
||||||
|
==> Live read-only requests
|
||||||
|
==> Static export
|
||||||
|
no-exec: PASS (sources/lock unchanged, no sentinel, no run control in export; core sha unchanged)
|
||||||
|
[acceptance] no_exec_suite: PASS
|
||||||
|
==> security_suite
|
||||||
|
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.03s
|
||||||
|
Running tests/security/main.rs (target/debug/build/marqdo-view/a005d0c01f80685f/out/security-a005d0c01f80685f)
|
||||||
|
|
||||||
|
running 11 tests
|
||||||
|
test path_traversal_is_rejected_and_the_old_document_route_is_gone ... ok
|
||||||
|
test aggressive_markdown_links_cannot_become_a_file_read_api ... ok
|
||||||
|
test adversarial_markdown_never_injects_markup_or_handlers ... ok
|
||||||
|
test session_cookie_and_headers_are_hardened ... ok
|
||||||
|
test symlink_escape_outside_the_project_root_is_rejected ... 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 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.73s
|
||||||
|
|
||||||
|
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.03s
|
||||||
|
Running tests/integration/main.rs (target/debug/build/marqdo-view/09a14a21a5f580dd/out/integration-09a14a21a5f580dd)
|
||||||
|
|
||||||
|
running 43 tests
|
||||||
|
test execution::cross_session_observation_is_rejected ... ok
|
||||||
|
test execution::run_without_a_trace_file_succeeds_but_reports_unavailable_trace ... ok
|
||||||
|
test execution::same_client_request_id_is_idempotent_and_different_payload_conflicts ... ok
|
||||||
|
test execution::second_run_is_busy_while_one_is_active_and_cancel_is_idempotent ... 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::explicit_entry_run_streams_accepted_running_and_succeeded_with_verified_trace ... ok
|
||||||
|
test execution::project_grants_are_mapped_to_explicit_cli_flags_and_pure_grants_are_rejected ... ok
|
||||||
|
test export::exported_html_has_no_remote_subresources ... ok
|
||||||
|
test export::real_frozen_core_export_marks_both_pages_static_ok ... ok
|
||||||
|
test export::refuses_to_export_inside_the_project_root ... ok
|
||||||
|
test export::no_annotations_keeps_prose_but_removes_anchors ... ok
|
||||||
|
test export::exports_offline_site_with_shared_renderer_and_relative_links ... ok
|
||||||
|
test export::refuses_to_overwrite_unrelated_non_empty_directory ... ok
|
||||||
|
test http_live::assets_are_immutable_and_carry_strict_headers ... ok
|
||||||
|
test execution::stale_analysis_digest_is_rejected_before_any_process_starts ... ok
|
||||||
|
test execution::trace_with_a_mismatched_digest_is_reported_invalid_but_the_run_still_succeeds ... ok
|
||||||
|
test http_live::document_without_main_is_rejected_without_running_another_function ... ok
|
||||||
|
test execution::truncated_trace_is_marked_without_claiming_complete_coverage ... ok
|
||||||
|
test export::replaces_a_previous_export_atomically ... 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 export::export_never_executes_side_effects ... 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 http_live::at_most_two_sse_observers_per_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::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::cancel_is_idempotent_and_yields_one_terminal_state ... ok
|
||||||
|
test rendering::run_controls_are_explicitly_unavailable_before_pr04 ... 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 execution::source_edit_during_a_run_marks_the_result_stale_and_drops_anchor_ids ... ok
|
||||||
|
test http_live::sse_heartbeats_keep_a_slow_job_connected ... ok
|
||||||
|
|
||||||
|
test result: ok. 43 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 5.34s
|
||||||
|
|
||||||
|
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.03s
|
||||||
|
Running tests/contract/main.rs (target/debug/build/marqdo-view/8ae29fd710d6819e/out/contract-8ae29fd710d6819e)
|
||||||
|
|
||||||
|
running 41 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::help_comes_from_view_not_core ... 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::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::check_refs_is_forwarded_as_a_stricter_flag ... ok
|
||||||
|
test core_contract::check_returns_exact_analysis_bytes_and_digest ... ok
|
||||||
|
test core_contract::failed_check_normalizes_diagnostics_without_absolute_paths ... ok
|
||||||
|
test core_contract::incompatible_product_version_is_rejected_before_any_work ... ok
|
||||||
|
test asset_integrity::embedded_asset_bundle_matches_disk_and_has_one_theme ... ok
|
||||||
|
test no_coupling::exactly_one_reader_theme_and_script_entry ... ok
|
||||||
|
test core_contract::missing_emit_after_success_is_an_analysis_failure ... ok
|
||||||
|
test no_coupling::no_private_core_crate_dependencies ... ok
|
||||||
|
test no_coupling::release_lockfile_is_committed ... ok
|
||||||
|
test no_coupling::tool_manifest_matches_package_and_protocols ... ok
|
||||||
|
test core_contract::run_invalid_json_is_a_protocol_io_error ... ok
|
||||||
|
test core_contract::run_returns_json_and_raw_trace ... ok
|
||||||
|
test core_contract::cli_verify_end_to_end_against_fake_core ... ok
|
||||||
|
test core_contract::run_without_trace_file_reports_no_trace ... ok
|
||||||
|
test no_coupling::source_never_reads_or_links_the_legacy_repositories ... ok
|
||||||
|
test trace_contract::failed_run_keeps_the_core_error_code ... ok
|
||||||
|
test presentation_states::failed_check_keeps_prose_and_shows_core_diagnostics ... ok
|
||||||
|
test presentation_states::invalid_core_span_is_dropped_with_an_explicit_warning ... ok
|
||||||
|
test presentation_states::source_digest_mismatch_degrades_instead_of_misbinding ... ok
|
||||||
|
test core_contract::cli_verify_rejects_schema_v3_and_digest_mismatch ... ok
|
||||||
|
test presentation_states::unknown_analysis_schema_is_a_hard_protocol_error ... ok
|
||||||
|
test trace_contract::golden_digest_is_really_sha256_of_analysis_bytes ... ok
|
||||||
|
test trace_contract::real_control_flow_trace_binds_and_projects_events ... ok
|
||||||
|
test core_contract::timeout_kills_the_process_group_and_reports_timeout ... ok
|
||||||
|
test trace_contract::unknown_schema_major_is_a_protocol_error_not_a_stale_trace ... ok
|
||||||
|
test trace_contract::stale_analysis_bytes_are_rejected ... ok
|
||||||
|
test trace_contract::truncated_trace_is_explicitly_marked ... ok
|
||||||
|
test trace_contract::non_monotonic_sequence_is_rejected ... ok
|
||||||
|
test trace_contract::unknown_event_module_is_rejected ... ok
|
||||||
|
test presentation_states::run_attached_to_changed_source_becomes_stale ... ok
|
||||||
|
|
||||||
|
test result: ok. 41 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.68s
|
||||||
|
|
||||||
|
note: MARQDO_FROZEN_BIN not set; skipped real-core export script
|
||||||
|
security: PASS
|
||||||
|
[acceptance] security_suite: PASS
|
||||||
|
==> browser
|
||||||
|
==> 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
|
||||||
|
|
||||||
|
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 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 trace provenance
|
||||||
|
ok static statement anchors carry analysis provenance
|
||||||
|
ok at most one grouped chip per anchor
|
||||||
|
ok trace event list rendered
|
||||||
|
ok stdout rendered escaped
|
||||||
|
ok no polling API was used
|
||||||
|
ok clear hides run panel
|
||||||
|
ok page was never reloaded by the run
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
browser: PASS
|
||||||
|
browser: PASS (core sha256 062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f unchanged; screenshots: /root/work/marqdo-view/tests/browser/artifacts)
|
||||||
|
[acceptance] browser: PASS
|
||||||
|
[acceptance] core_sha: PASS
|
||||||
|
evidence manifest: /root/work/marqdo-view/docs/evidence/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json
|
||||||
|
|
||||||
|
acceptance: PASS
|
||||||
|
evidence: /root/work/marqdo-view/docs/evidence/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json
|
||||||
|
archive sha256: a3fb28c8d025f44dee6c06da80c13d3f65b9c62d1f657c04b02ef360ff24fcf5
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
==> check all five example documents (no execution)
|
||||||
|
==> call function-params.double(n=5) -> 10
|
||||||
|
call double(5): PASS (Int 10)
|
||||||
|
==> run branch-loop main -> Int 0 with loop/return trace
|
||||||
|
run branch-loop: PASS (value 0, events: call.enter,call.exit,loop.iteration,return)
|
||||||
|
==> knowledge-only has no main (truthful failure, 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 062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f unchanged)
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
{
|
||||||
|
"analysis_protocol": 2,
|
||||||
|
"archive_sha256": "9abd996e1c54b24ef0ec2c7e80c93ca93993ca73cce573f07b922df73a1863f6",
|
||||||
|
"cli_binary_sha256_after": "062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f",
|
||||||
|
"cli_binary_sha256_before": "062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f",
|
||||||
|
"cli_source_sha": "2c7c4f31e7a388d3fcfa717a77067e696ed13854",
|
||||||
|
"commands": {
|
||||||
|
"notes": "Generated from real command exit statuses; install/verify/export/run use the frozen CLI archive copied to an isolated tool home.",
|
||||||
|
"script": "scripts/acceptance.sh"
|
||||||
|
},
|
||||||
|
"gates": {
|
||||||
|
"archive_install": "PASS",
|
||||||
|
"browse": "PASS",
|
||||||
|
"browser": "PASS",
|
||||||
|
"build": "PASS",
|
||||||
|
"bundle": "PASS",
|
||||||
|
"clippy": "PASS",
|
||||||
|
"core_sha": "PASS",
|
||||||
|
"examples_check": "PASS",
|
||||||
|
"export": "PASS",
|
||||||
|
"export_suite": "PASS",
|
||||||
|
"fmt": "PASS",
|
||||||
|
"no_exec_suite": "PASS",
|
||||||
|
"real_run": "PASS",
|
||||||
|
"security_suite": "PASS",
|
||||||
|
"test": "PASS",
|
||||||
|
"tool_list": "PASS",
|
||||||
|
"verify": "PASS",
|
||||||
|
"view_help": "PASS"
|
||||||
|
},
|
||||||
|
"generated_at_utc": "2026-11-22T06:48:46.803005+00:00",
|
||||||
|
"schema": "marqdo.view-conformance",
|
||||||
|
"schema_version": 1,
|
||||||
|
"target": "x86_64-unknown-linux-gnu",
|
||||||
|
"tests": {
|
||||||
|
"browser": "PASS",
|
||||||
|
"contract": "PASS",
|
||||||
|
"examples": "PASS",
|
||||||
|
"export": "PASS",
|
||||||
|
"no_exec": "PASS",
|
||||||
|
"security": "PASS"
|
||||||
|
},
|
||||||
|
"tool_protocol": 1,
|
||||||
|
"trace_protocol": 2,
|
||||||
|
"view_binary_sha256": "eb19f79632457f37ae3573696d7db84d57358627b65e618819ff80f132b0026a",
|
||||||
|
"view_source_sha": "807c24b9523bd3f8ace5b36582b5de905327eecb"
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
==> Live read-only requests
|
||||||
|
==> Static export
|
||||||
|
no-exec: PASS (sources/lock unchanged, no sentinel, no run control in export; core sha unchanged)
|
||||||
@@ -1,22 +1,34 @@
|
|||||||
# 验收证据
|
# 验收证据
|
||||||
|
|
||||||
本目录保存**由真实命令生成**的验收证据,命名 `<CLI-SOURCE-SHA>/manifest.json`:
|
本目录保存**由真实命令生成**的验收证据。历史证据使用 `<CLI-SOURCE-SHA>/manifest.json`,工单复验另存于 `issue-2/manifest.json`:
|
||||||
|
|
||||||
- `view_source_sha`:生成证据时的 View Git SHA。
|
- `schema`/`schema_version`:`marqdo.view-conformance` v1(View 自有,非 CLI 协议);
|
||||||
- `view_binary_sha256`:发布 bundle 内 `bin/marqdo-view` 摘要。
|
- `view_source_sha`:生成证据时的 View Git SHA;
|
||||||
- `cli_binary_sha256_before/after`:冻结 CLI 在验收前后的 SHA-256,必须相同。
|
- `view_binary_sha256`:发布 bundle 内 `bin/marqdo-view` 摘要;
|
||||||
- `cli_source_sha`:CLI 发布归档 `SOURCE_SHA`。
|
- `cli_source_sha`:CLI 发布归档记录的源码 SHA;
|
||||||
- `tool/analysis/trace_protocol`、`target`、`archive_sha256`。
|
- `cli_binary_sha256_before/after`:冻结 CLI 在验收前后的 SHA-256,必须相同;
|
||||||
- `gates`:`tools/acceptance.sh` 每一步的真实退出状态。
|
- `tool_protocol`/`analysis_protocol`/`trace_protocol`、`target`、`archive_sha256`;
|
||||||
- `tests`:contract/browser/export/security 的 PASS/FAIL/SKIP。
|
- `gates`:`scripts/acceptance.sh` 每一步的真实退出状态,包括冻结身份、代码、浏览器、Tool 完整性和卸载;
|
||||||
|
- `tests`:contract/examples/export/no_exec/security/browser 的 PASS/FAIL/SKIP。
|
||||||
|
|
||||||
生成方式(不要手写/篡改):
|
生成方式(不要手写/篡改):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
MARQDO_BIN=/abs/path/to/frozen/marqdo tools/acceptance.sh
|
# 输出到 dist/acceptance/manifest.json
|
||||||
|
MARQDO_BIN=/abs/path/to/frozen/marqdo scripts/acceptance.sh
|
||||||
```
|
```
|
||||||
|
|
||||||
`manifest.json` 在验收的最后一步写入;若某一步失败,脚本以非零退出且不会声称 PASS。
|
`manifest.json` 在验收最后一步写入;任一步失败时脚本非零退出且不会声称 PASS。
|
||||||
CI URL 只有在 `.woodpecker.yml` 真正运行后才可补入;本仓库当前未声称远端 CI 通过。
|
冻结 CLI 的 `--version`/SHA 与发布归档必须一致(`scripts/verify-frozen-cli.sh`),
|
||||||
|
CI 证据只在 `.github/workflows/ci.yml` 真正运行后才可补入;本仓库当前**未声称**
|
||||||
|
远端 CI 通过。
|
||||||
|
|
||||||
`PR-03/` 子目录保存浏览器截图证据(非协议证据),说明见其 `README.md`。
|
分 PR 证据目录(人工/截图/日志,非协议证据):
|
||||||
|
|
||||||
|
- `PR-01/`:Tool v1 安装/分发/篡改拒绝实测;
|
||||||
|
- `PR-02/`:Reader 结构与 `/api/documents` 只读面;
|
||||||
|
- `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 时期的浏览器截图(历史归档)。
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
{
|
||||||
|
"analysis_protocol": 2,
|
||||||
|
"archive_sha256": "a821de86eb7590de91bd96ca24cd1f13b8c9f28d2799ea0316512ee7655d6df4",
|
||||||
|
"cli_binary_sha256_after": "062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f",
|
||||||
|
"cli_binary_sha256_before": "062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f",
|
||||||
|
"cli_source_sha": "2c7c4f31e7a388d3fcfa717a77067e696ed13854",
|
||||||
|
"commands": {
|
||||||
|
"notes": "Generated from real command exit statuses; install/verify/export/run use the frozen CLI archive copied to an isolated tool home.",
|
||||||
|
"script": "scripts/acceptance.sh"
|
||||||
|
},
|
||||||
|
"gates": {
|
||||||
|
"archive_install": "PASS",
|
||||||
|
"browse": "PASS",
|
||||||
|
"browser": "PASS",
|
||||||
|
"build": "PASS",
|
||||||
|
"bundle": "PASS",
|
||||||
|
"clippy": "PASS",
|
||||||
|
"core_sha": "PASS",
|
||||||
|
"examples_check": "PASS",
|
||||||
|
"export": "PASS",
|
||||||
|
"export_suite": "PASS",
|
||||||
|
"fmt": "PASS",
|
||||||
|
"no_exec_suite": "PASS",
|
||||||
|
"real_run": "PASS",
|
||||||
|
"security_suite": "PASS",
|
||||||
|
"test": "PASS",
|
||||||
|
"tool_list": "PASS",
|
||||||
|
"tool_remove": "PASS",
|
||||||
|
"tool_tamper_refused": "PASS",
|
||||||
|
"verify": "PASS",
|
||||||
|
"view_help": "PASS",
|
||||||
|
"wrong_cli_refused": "PASS"
|
||||||
|
},
|
||||||
|
"generated_at_utc": "2026-11-22T13:29:37.931389+00:00",
|
||||||
|
"schema": "marqdo.view-conformance",
|
||||||
|
"schema_version": 1,
|
||||||
|
"target": "x86_64-unknown-linux-gnu",
|
||||||
|
"tests": {
|
||||||
|
"browser": "PASS",
|
||||||
|
"contract": "PASS",
|
||||||
|
"examples": "PASS",
|
||||||
|
"export": "PASS",
|
||||||
|
"no_exec": "PASS",
|
||||||
|
"security": "PASS"
|
||||||
|
},
|
||||||
|
"tool_protocol": 1,
|
||||||
|
"trace_protocol": 2,
|
||||||
|
"view_binary_sha256": "a7921f5e659d3baed714699038eaef9b34bd5537ffc8796636db82e42066180f",
|
||||||
|
"view_source_sha": "34de5a34d9cd8488ae4d753aff7d27b9c95379f3"
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# @knowledge 分支与循环
|
||||||
|
|
||||||
|
## @exec main
|
||||||
|
|
||||||
|
`n = 3`
|
||||||
|
|
||||||
|
**while n > 0**
|
||||||
|
|
||||||
|
`n = n - 1`
|
||||||
|
|
||||||
|
**end**
|
||||||
|
|
||||||
|
*return n*
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
# @knowledge 控制流演示
|
# @knowledge 控制流演示
|
||||||
|
|
||||||
下面的函数没有任何必需参数,因此可以在 `pure` 模式下显式运行并产生真实 Trace。
|
下面的函数可以在 `pure` 模式显式运行并产生真实 Trace。示例把 ASCII 数字和换行写入标准输出资源。
|
||||||
|
|
||||||
# @exec 演示
|
# @exec 演示
|
||||||
|
|
||||||
@@ -8,20 +8,30 @@
|
|||||||
|
|
||||||
`x = 0`
|
`x = 0`
|
||||||
|
|
||||||
|
`buffer = memory.new(1, 1)`
|
||||||
|
|
||||||
|
`buffer[1] = 10`
|
||||||
|
|
||||||
|
`stdout = resource.open("stdio", "stdout", ["write"])`
|
||||||
|
|
||||||
**while x < 3**
|
**while x < 3**
|
||||||
|
|
||||||
**if x > 1**
|
**if x > 1**
|
||||||
|
|
||||||
**print(x)**
|
`buffer[0] = 48 + x`
|
||||||
|
|
||||||
**else**
|
**else**
|
||||||
|
|
||||||
**print(0)**
|
`buffer[0] = 48`
|
||||||
|
|
||||||
**end**
|
**end**
|
||||||
|
|
||||||
|
`resource.write(stdout, buffer, 0, 2)`
|
||||||
|
|
||||||
**x = x + 1**
|
**x = x + 1**
|
||||||
|
|
||||||
**end**
|
**end**
|
||||||
|
|
||||||
|
`resource.close(stdout)`
|
||||||
|
|
||||||
`return 3`
|
`return 3`
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
# @knowledge 计算示例
|
||||||
|
|
||||||
|
这是一个可读取、可独立调用的函数。未点击运行时不能发生计算副作用。
|
||||||
|
|
||||||
|
## @exec double
|
||||||
|
|
||||||
|
`params(n: Int)`
|
||||||
|
|
||||||
|
`return n * 2`
|
||||||
|
|
||||||
|
## @exec format_arguments
|
||||||
|
|
||||||
|
组合表单提交的文本和列表,用于展示常量参数经过 CLI 后返回的结果。
|
||||||
|
|
||||||
|
`params(label: Text, items: List)`
|
||||||
|
|
||||||
|
`return label + items[0] + " · " + 文本(items[1])`
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# @knowledge 只读知识文档
|
||||||
|
|
||||||
|
本文件只有知识单元与说明文字,没有 `@exec` 函数,因此不能运行 `main`,
|
||||||
|
也不能被替换成“随便挑一个函数”执行。View 会解释原因并建议改选函数。
|
||||||
|
|
||||||
|
## @knowledge 为什么没有 main
|
||||||
|
|
||||||
|
知识不等于可执行程序入口;`@knowledge` 也不等于“已经数学证明”。
|
||||||
|
这里的内容只用于阅读与静态语义展示。
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
# @knowledge 受控写入示例
|
||||||
|
|
||||||
|
本文件只有在显式提交 `project` 运行并授予项目内 `out/**` 写入权限时才会写文件。
|
||||||
|
打开、刷新、搜索、切换和静态导出都不会运行它。
|
||||||
|
|
||||||
|
## @exec main
|
||||||
|
|
||||||
|
**创建 = resource.request("fs.mkdir", ["out"])**
|
||||||
|
|
||||||
|
**写入 = fs.write("out/view-sentinel.txt", "explicit run only\n")**
|
||||||
|
|
||||||
|
*return 写入*
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"schema": "marqdo.view-config",
|
||||||
|
"schema_version": 1,
|
||||||
|
"welcome": "welcome.mq.md",
|
||||||
|
"site_title": "Marqdo View 示例"
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
# @knowledge 欢迎来到 Marqdo View
|
||||||
|
|
||||||
|
这是一份普通的可执行 Markdown 文档:你可以像读任何文档一样从头读到尾,
|
||||||
|
也可以在明确选择后调用其中的函数。阅读、搜索、刷新与导出都不会执行任何代码。
|
||||||
|
|
||||||
|
## @knowledge 阅读约定
|
||||||
|
|
||||||
|
- 正文顺序就是原始 Markdown 顺序;
|
||||||
|
- 函数与知识标识来自冻结 CLI 的 Analysis v2,而不是路径名或标题猜测;
|
||||||
|
- 运行必须由你显式确认,结果来自官方 `run/call --json` 与 Trace v2。
|
||||||
|
|
||||||
|
> 深色主题、字号与标注显隐可以在“设置”中调整。
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Explicit real-run acceptance over the frozen CLI + Live SSE server.
|
||||||
|
|
||||||
|
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
|
||||||
|
one run, observes one SSE stream until the single terminal event, and asserts
|
||||||
|
the verified Trace binding.
|
||||||
|
"""
|
||||||
|
import http.cookiejar
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
url = sys.argv[1]
|
||||||
|
origin = url.rstrip("/")
|
||||||
|
jar = http.cookiejar.CookieJar()
|
||||||
|
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
|
||||||
|
|
||||||
|
|
||||||
|
def get(path):
|
||||||
|
with opener.open(origin + path, timeout=30) as response:
|
||||||
|
return response.read().decode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
page = get("/")
|
||||||
|
csrf = re.search(r'name="mq-csrf-token" content="([0-9a-f]+)"', page)
|
||||||
|
assert csrf, "csrf token missing"
|
||||||
|
digest = re.search(r'data-analysis-digest="(sha256:[0-9a-f]{64})"', page)
|
||||||
|
assert digest, "analysis digest missing"
|
||||||
|
body = json.dumps({
|
||||||
|
"document": "index.mq.md",
|
||||||
|
"target": {"kind": "entry"},
|
||||||
|
"parameters": [],
|
||||||
|
"analysis_digest": digest.group(1),
|
||||||
|
"mode": "pure",
|
||||||
|
"grants": {"read": [], "write": []},
|
||||||
|
"client_request_id": "acceptance-real-run-1",
|
||||||
|
}).encode()
|
||||||
|
request = urllib.request.Request(
|
||||||
|
origin + "/api/runs",
|
||||||
|
data=body,
|
||||||
|
headers={
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Origin": origin,
|
||||||
|
"X-View-CSRF": csrf.group(1),
|
||||||
|
},
|
||||||
|
method="POST",
|
||||||
|
)
|
||||||
|
with opener.open(request, timeout=60) as response:
|
||||||
|
assert response.status == 202, response.status
|
||||||
|
accepted = json.loads(response.read().decode("utf-8"))
|
||||||
|
assert accepted["state"] == "accepted", accepted
|
||||||
|
events_url = origin + accepted["events_url"]
|
||||||
|
terminal = None
|
||||||
|
with opener.open(events_url, timeout=120) as stream:
|
||||||
|
data_lines = []
|
||||||
|
for raw in stream:
|
||||||
|
line = raw.decode("utf-8").rstrip("\n")
|
||||||
|
if line.startswith("data: "):
|
||||||
|
data_lines.append(line[6:])
|
||||||
|
elif line == "" and data_lines:
|
||||||
|
event = json.loads("\n".join(data_lines))
|
||||||
|
data_lines = []
|
||||||
|
if event.get("state") in (
|
||||||
|
"succeeded",
|
||||||
|
"failed",
|
||||||
|
"cancelled",
|
||||||
|
"timed_out",
|
||||||
|
"unavailable",
|
||||||
|
):
|
||||||
|
terminal = event
|
||||||
|
break
|
||||||
|
assert terminal is not None, "no terminal SSE event"
|
||||||
|
assert terminal["state"] == "succeeded", terminal
|
||||||
|
assert terminal["result"]["success"] is True, terminal["result"]
|
||||||
|
assert terminal["trace"]["status"] == "verified", terminal.get("trace")
|
||||||
|
print(
|
||||||
|
"explicit real run: PASS (run_id=%s events=%d)"
|
||||||
|
% (accepted["run_id"], len(terminal["trace"]["events"]))
|
||||||
|
)
|
||||||
@@ -0,0 +1,241 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# RFC-VIEW-0002 §9.4 one-command acceptance.
|
||||||
|
#
|
||||||
|
# Usage:
|
||||||
|
# MARQDO_BIN=/abs/path/to/frozen/marqdo scripts/acceptance.sh
|
||||||
|
#
|
||||||
|
# Optional:
|
||||||
|
# VIEW_EVIDENCE_OUT=path override dist/acceptance/manifest.json
|
||||||
|
# SKIP_BROWSER=1 skip Chromium suite (recorded as SKIP, not PASS)
|
||||||
|
#
|
||||||
|
# The script never modifies or recompiles the frozen CLI; it records its
|
||||||
|
# SHA-256 before and after and fails if it changes.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
|
cd "$repo_root"
|
||||||
|
|
||||||
|
: "${MARQDO_BIN:?set MARQDO_BIN to the frozen marqdo release binary}"
|
||||||
|
[[ -x "$MARQDO_BIN" ]] || { echo "error: MARQDO_BIN not executable" >&2; exit 1; }
|
||||||
|
MARQDO_BIN="$(realpath "$MARQDO_BIN")"
|
||||||
|
export MARQDO_BIN
|
||||||
|
"$repo_root/scripts/frozen-beta.sh" verify "$MARQDO_BIN"
|
||||||
|
export MARQDO_FROZEN_BIN="$MARQDO_BIN"
|
||||||
|
|
||||||
|
work="$repo_root/dist/acceptance"
|
||||||
|
rm -rf "$work"
|
||||||
|
mkdir -p "$work"
|
||||||
|
|
||||||
|
statuses=""
|
||||||
|
record() { statuses+="$1=$2"$'\n'; echo "[acceptance] $1: $2"; }
|
||||||
|
|
||||||
|
run_step() {
|
||||||
|
local name="$1"
|
||||||
|
shift
|
||||||
|
echo "==> $name"
|
||||||
|
if "$@"; then
|
||||||
|
record "$name" PASS
|
||||||
|
else
|
||||||
|
record "$name" FAIL
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
core_before="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)"
|
||||||
|
cli_source_sha="$(cat "$(dirname "$MARQDO_BIN")/SOURCE_SHA")"
|
||||||
|
view_source_sha="$(git rev-parse HEAD 2>/dev/null || echo unknown)"
|
||||||
|
|
||||||
|
export PATH="${HOME}/.cargo/bin:${PATH}"
|
||||||
|
export CARGO_HOME="${CARGO_HOME:-$repo_root/.cargo-home}"
|
||||||
|
|
||||||
|
# 0. code quality / unit / contract tests
|
||||||
|
check_wrong_cli() {
|
||||||
|
mkdir -p "$work/wrong-cli"
|
||||||
|
cp "$(dirname "$MARQDO_BIN")/SOURCE_SHA" "$work/wrong-cli/SOURCE_SHA"
|
||||||
|
cat >"$work/wrong-cli/marqdo" <<'FAKE'
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
touch "$(dirname "$0")/executed"
|
||||||
|
FAKE
|
||||||
|
chmod +x "$work/wrong-cli/marqdo"
|
||||||
|
if scripts/frozen-beta.sh verify "$work/wrong-cli/marqdo"; then
|
||||||
|
echo "error: mismatched CLI passed the baseline check" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
test ! -e "$work/wrong-cli/executed"
|
||||||
|
}
|
||||||
|
run_step wrong_cli_refused check_wrong_cli
|
||||||
|
run_step fmt cargo fmt --all -- --check
|
||||||
|
run_step clippy cargo clippy --locked --all-targets -- -D warnings
|
||||||
|
run_step test cargo test --locked
|
||||||
|
run_step build cargo build --release --locked
|
||||||
|
|
||||||
|
# 1. controlled Tool bundle + frozen-CLI install smoke
|
||||||
|
run_step bundle env MARQDO_BIN="$MARQDO_BIN" ./scripts/package.sh
|
||||||
|
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"])')
|
||||||
|
archive="$repo_root/dist/marqdo-view-$version-$target.tar.gz"
|
||||||
|
archive_sha="$(sha256sum "$archive" | cut -d' ' -f1)"
|
||||||
|
|
||||||
|
# 2. clean install from the *archive*, in a moved temporary directory
|
||||||
|
mkdir -p "$work/extracted"
|
||||||
|
tar -xzf "$archive" -C "$work/extracted"
|
||||||
|
extracted_bundle="$work/extracted/marqdo-view"
|
||||||
|
(cd "$extracted_bundle" && sha256sum -c SHA256SUMS)
|
||||||
|
tool_home="$work/tool-home"
|
||||||
|
mkdir -p "$tool_home"
|
||||||
|
export MARQDO_TOOL_HOME="$tool_home"
|
||||||
|
export VIEW_USE_INSTALLED_TOOL=1
|
||||||
|
run_step archive_install "$MARQDO_BIN" tool install "$extracted_bundle/tool.json"
|
||||||
|
check_tool_list() {
|
||||||
|
grep -q '^view ' <<<"$("$MARQDO_BIN" tool list)"
|
||||||
|
}
|
||||||
|
check_view_help() {
|
||||||
|
grep -q 'marqdo-view' <<<"$("$MARQDO_BIN" view --help)"
|
||||||
|
}
|
||||||
|
run_step tool_list check_tool_list
|
||||||
|
run_step view_help check_view_help
|
||||||
|
run_step verify "$MARQDO_BIN" view verify examples/mixed-modes/index.mq.md
|
||||||
|
run_step export "$MARQDO_BIN" view export examples/control-flow --out "$work/site"
|
||||||
|
run_step examples_check env MARQDO_BIN="$MARQDO_BIN" ./scripts/check-examples.sh
|
||||||
|
test -f "$work/site/manifest.json"
|
||||||
|
|
||||||
|
# Tool dispatch starts View as a child. Keep both in one disposable group.
|
||||||
|
server_pid=""
|
||||||
|
stop_server() {
|
||||||
|
if [[ -n "$server_pid" ]]; then
|
||||||
|
kill -- "-$server_pid" 2>/dev/null || true
|
||||||
|
wait "$server_pid" 2>/dev/null || true
|
||||||
|
server_pid=""
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
trap stop_server EXIT
|
||||||
|
|
||||||
|
# 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
|
||||||
|
record browse PASS
|
||||||
|
else
|
||||||
|
record browse FAIL
|
||||||
|
cat "$browse_log" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
stop_server
|
||||||
|
|
||||||
|
# 4. Explicit real run through the installed tool + CSRF flow
|
||||||
|
run_log="$work/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
|
||||||
|
record real_run FAIL
|
||||||
|
cat "$run_log" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
stop_server
|
||||||
|
|
||||||
|
# 5. project-local verification suites
|
||||||
|
run_step export_suite env MARQDO_BIN="$MARQDO_BIN" ./scripts/test-export.sh
|
||||||
|
run_step no_exec_suite env MARQDO_BIN="$MARQDO_BIN" ./scripts/test-no-exec.sh
|
||||||
|
run_step security_suite ./scripts/test-security.sh
|
||||||
|
if [[ "${SKIP_BROWSER:-0}" == "1" ]]; then
|
||||||
|
record browser SKIP
|
||||||
|
else
|
||||||
|
run_step browser env MARQDO_BIN="$MARQDO_BIN" ./scripts/test-browser.sh
|
||||||
|
fi
|
||||||
|
|
||||||
|
check_tampered_install() {
|
||||||
|
local output
|
||||||
|
printf 'x' >> "$tool_home/view/README.md" || return 1
|
||||||
|
if output="$("$MARQDO_BIN" view --version 2>&1)"; then
|
||||||
|
echo "error: tampered Tool installation was dispatched" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
grep -q 'bundle hash mismatch' <<<"$output"
|
||||||
|
}
|
||||||
|
run_step tool_tamper_refused check_tampered_install
|
||||||
|
run_step tool_remove "$MARQDO_BIN" tool remove view
|
||||||
|
|
||||||
|
# 6. frozen core must be byte-identical
|
||||||
|
core_after="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)"
|
||||||
|
if [[ "$core_before" != "$core_after" ]]; then
|
||||||
|
record core_sha FAIL
|
||||||
|
echo "error: frozen core binary changed during acceptance" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
record core_sha PASS
|
||||||
|
|
||||||
|
view_binary_sha="$(sha256sum "$bundle/bin/marqdo-view" | cut -d' ' -f1)"
|
||||||
|
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"
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# RFC-VIEW-0002 §13.3/§13.4: prove the five 3.0 example documents against the
|
||||||
|
# frozen released CLI. 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
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
|
cd "$repo_root"
|
||||||
|
|
||||||
|
: "${MARQDO_BIN:?set MARQDO_BIN to the frozen marqdo binary}"
|
||||||
|
core_sha_before="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)"
|
||||||
|
|
||||||
|
work="$repo_root/dist/examples-check"
|
||||||
|
rm -rf "$work"
|
||||||
|
mkdir -p "$work"
|
||||||
|
cp examples/welcome.mq.md examples/branch-loop.mq.md examples/function-params.mq.md \
|
||||||
|
examples/knowledge-only.mq.md examples/unsafe-side-effect.mq.md "$work/"
|
||||||
|
cp examples/view.json "$work/"
|
||||||
|
|
||||||
|
cd "$work"
|
||||||
|
|
||||||
|
echo "==> check all five example documents (no execution)"
|
||||||
|
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
|
||||||
|
echo "error: frozen CLI refused $file" >&2
|
||||||
|
cat "check-$file.json" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
test -s "analysis-$file.json"
|
||||||
|
done
|
||||||
|
|
||||||
|
echo "==> call function-params.double(n=5) -> 10"
|
||||||
|
call_json="$("$MARQDO_BIN" call function-params.mq.md double --arg n=5 --mode pure --json --trace-file call.trace.json)"
|
||||||
|
python3 - "$call_json" <<'PY'
|
||||||
|
import json, sys
|
||||||
|
data = json.loads(sys.argv[1])
|
||||||
|
assert data["success"] is True, data
|
||||||
|
assert data["value"] == {"type": "int", "decimal": "10"}, data["value"]
|
||||||
|
print("call double(5): PASS (Int 10)")
|
||||||
|
PY
|
||||||
|
|
||||||
|
echo "==> run branch-loop main -> Int 0 with loop/return trace"
|
||||||
|
run_json="$("$MARQDO_BIN" run branch-loop.mq.md --mode pure --json --trace-file run.trace.json)"
|
||||||
|
python3 - "$run_json" "run.trace.json" <<'PY'
|
||||||
|
import json, sys
|
||||||
|
data = json.loads(sys.argv[1])
|
||||||
|
assert data["success"] is True, data
|
||||||
|
assert data["value"] == {"type": "int", "decimal": "0"}, data["value"]
|
||||||
|
trace = json.load(open(sys.argv[2]))
|
||||||
|
kinds = {event["kind"] for event in trace["events"]}
|
||||||
|
assert "loop.iteration" in kinds and "return" in kinds, kinds
|
||||||
|
print("run branch-loop: PASS (value 0, events: %s)" % ",".join(sorted(kinds)))
|
||||||
|
PY
|
||||||
|
|
||||||
|
echo "==> knowledge-only has no main (truthful failure, no fallback)"
|
||||||
|
set +e
|
||||||
|
"$MARQDO_BIN" run knowledge-only.mq.md --mode pure --json > knowledge.json 2>&1
|
||||||
|
status=$?
|
||||||
|
set -e
|
||||||
|
test "$status" -ne 0
|
||||||
|
python3 - knowledge.json <<'PY'
|
||||||
|
import json, sys
|
||||||
|
data = json.load(open(sys.argv[1]))
|
||||||
|
assert data["success"] is False, data
|
||||||
|
assert data["code"] == "sem.no_entry_function", data
|
||||||
|
print("knowledge-only: PASS (explicit sem.no_entry_function)")
|
||||||
|
PY
|
||||||
|
|
||||||
|
echo "==> unsafe-side-effect writes nothing in pure mode"
|
||||||
|
set +e
|
||||||
|
"$MARQDO_BIN" run unsafe-side-effect.mq.md --mode pure --json > unsafe-pure.json 2>&1
|
||||||
|
status=$?
|
||||||
|
set -e
|
||||||
|
test "$status" -ne 0
|
||||||
|
test ! -e out/view-sentinel.txt
|
||||||
|
python3 - unsafe-pure.json <<'PY'
|
||||||
|
import json, sys
|
||||||
|
data = json.load(open(sys.argv[1]))
|
||||||
|
assert data["success"] is False, data
|
||||||
|
assert data["error"]["code"] == "permission.denied", data["error"]
|
||||||
|
print("unsafe-side-effect pure: PASS (permission.denied, no file)")
|
||||||
|
PY
|
||||||
|
|
||||||
|
echo "==> unsafe-side-effect writes only with explicit project grants"
|
||||||
|
"$MARQDO_BIN" run unsafe-side-effect.mq.md --mode project \
|
||||||
|
--allow-write out --allow-write 'out/**' --json --trace-file unsafe.trace.json >/dev/null
|
||||||
|
test -f out/view-sentinel.txt
|
||||||
|
python3 - <<'PY'
|
||||||
|
content = open("out/view-sentinel.txt", "rb").read()
|
||||||
|
assert content == b"explicit run only\n", content
|
||||||
|
print("unsafe-side-effect project+grants: PASS (sentinel written explicitly)")
|
||||||
|
PY
|
||||||
|
rm -rf out
|
||||||
|
|
||||||
|
core_sha_after="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)"
|
||||||
|
test "$core_sha_before" = "$core_sha_after"
|
||||||
|
echo "examples: PASS (frozen CLI sha256 $core_sha_before unchanged)"
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Identity of the released CLI used by the RFC-VIEW-0002 acceptance gate.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
version=3.0.0-beta.1
|
||||||
|
source_sha=2c7c4f31e7a388d3fcfa717a77067e696ed13854
|
||||||
|
binary_sha=062cb56e226bee55c21d238e195920caa985e62bb3877ba7b07abcc04dc0fe3f
|
||||||
|
archive_sha=507e4cd358f75f517433935ce90d5fc2eb5cecda4f19121a68b136c83b15f317
|
||||||
|
artifact="marqdo-$version-x86_64-unknown-linux-gnu"
|
||||||
|
root="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
|
||||||
|
verify() {
|
||||||
|
local binary="$1"
|
||||||
|
local install
|
||||||
|
install="$(dirname "$binary")"
|
||||||
|
if [[ ! -f "$install/SOURCE_SHA" || "$(cat "$install/SOURCE_SHA")" != "$source_sha" ]]; then
|
||||||
|
echo "error: expected the official marqdo $version installation ($source_sha)" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
"$root/verify-frozen-cli.sh" "$binary" -- "$binary_sha" >&2
|
||||||
|
if [[ "$("$binary" --version)" != "marqdo $version" ]]; then
|
||||||
|
echo "error: frozen marqdo version does not match $version" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
if [[ $# != 2 ]]; then
|
||||||
|
echo "usage: $0 fetch EMPTY_DIRECTORY | $0 verify /absolute/path/to/marqdo" >&2
|
||||||
|
exit 2
|
||||||
|
fi
|
||||||
|
case "$1" in
|
||||||
|
fetch)
|
||||||
|
mkdir -p "$2"
|
||||||
|
destination="$(cd "$2" && pwd)"
|
||||||
|
if [[ -n "$(ls -A "$destination")" ]]; then
|
||||||
|
echo "error: frozen CLI destination must be empty: $destination" >&2
|
||||||
|
exit 2
|
||||||
|
fi
|
||||||
|
archive="$destination/$artifact.tar.gz"
|
||||||
|
curl -fsSL --retry 3 --connect-timeout 15 --max-time 90 \
|
||||||
|
"https://git.cflmy.cn/cflmy/marqdo-cli/releases/download/v$version/$artifact.tar.gz" -o "$archive"
|
||||||
|
printf '%s %s\n' "$archive_sha" "$archive" | sha256sum -c - >&2
|
||||||
|
tar -xzf "$archive" -C "$destination"
|
||||||
|
verify "$destination/$artifact/marqdo"
|
||||||
|
printf '%s\n' "$destination/$artifact/marqdo"
|
||||||
|
;;
|
||||||
|
verify)
|
||||||
|
verify "$2"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "unknown frozen CLI operation: $1" >&2
|
||||||
|
exit 2
|
||||||
|
;;
|
||||||
|
esac
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
# Regenerate committed Analysis v2 goldens from the frozen CLI release binary.
|
# Regenerate committed Analysis v2 goldens from the frozen CLI release binary.
|
||||||
#
|
#
|
||||||
# Usage: MARQDO_BIN=/abs/path/marqdo tools/gen-golden.sh
|
# Usage: MARQDO_BIN=/abs/path/marqdo scripts/gen-golden.sh
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
# 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).
|
||||||
#
|
#
|
||||||
# Usage: MARQDO_BIN=/abs/path/marqdo tools/install-smoke.sh [tool.json]
|
# Usage: MARQDO_BIN=/abs/path/marqdo scripts/install-smoke.sh [tool.json]
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
@@ -110,7 +110,7 @@ tar --sort=name --owner=0 --group=0 --numeric-owner --mtime='UTC 2026-01-01' \
|
|||||||
|
|
||||||
if [[ -n "$MARQDO_BIN" ]]; then
|
if [[ -n "$MARQDO_BIN" ]]; then
|
||||||
echo "==> smoke install against frozen core"
|
echo "==> smoke install against frozen core"
|
||||||
MARQDO_BIN="$MARQDO_BIN" "$repo_root/tools/install-smoke.sh" "$bundle/tool.json"
|
MARQDO_BIN="$MARQDO_BIN" "$repo_root/scripts/install-smoke.sh" "$bundle/tool.json"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo "bundle: $bundle"
|
echo "bundle: $bundle"
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
# Browser acceptance for the Live reader: real Chromium, real frozen core.
|
# Browser acceptance for the Live reader: real Chromium, real frozen core.
|
||||||
#
|
#
|
||||||
# Usage:
|
# Usage:
|
||||||
# MARQDO_BIN=/abs/path/marqdo tools/test-browser.sh
|
# MARQDO_BIN=/abs/path/marqdo scripts/test-browser.sh
|
||||||
#
|
#
|
||||||
# Requires `cd tests/browser && npm install` once (Playwright + Chromium).
|
# Requires `cd tests/browser && npm install` once (Playwright + Chromium).
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
@@ -29,17 +29,20 @@ if [[ ! -d "$PLAYWRIGHT_BROWSERS_PATH" ]]; then
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
binary="$repo_root/target/release/marqdo-view"
|
if [[ "${VIEW_USE_INSTALLED_TOOL:-0}" == 1 ]]; then
|
||||||
if [[ ! -x "$binary" ]]; then
|
view=("$MARQDO_BIN" view)
|
||||||
echo "==> cargo build --release --locked"
|
else
|
||||||
cargo build --release --locked
|
binary="$repo_root/target/release/marqdo-view"
|
||||||
|
[[ -x "$binary" ]] || cargo build --release --locked
|
||||||
|
view=("$binary")
|
||||||
fi
|
fi
|
||||||
|
|
||||||
server_pid=""
|
server_pid=""
|
||||||
cleanup() {
|
cleanup() {
|
||||||
if [[ -n "$server_pid" ]] && kill -0 "$server_pid" 2>/dev/null; then
|
if [[ -n "$server_pid" ]]; then
|
||||||
kill "$server_pid" 2>/dev/null || true
|
kill -- "-$server_pid" 2>/dev/null || true
|
||||||
wait "$server_pid" 2>/dev/null || true
|
wait "$server_pid" 2>/dev/null || true
|
||||||
|
server_pid=""
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
trap cleanup EXIT
|
trap cleanup EXIT
|
||||||
@@ -49,7 +52,7 @@ run_suite() {
|
|||||||
local log
|
local log
|
||||||
log="$(mktemp "$repo_root/tests/.cache/browser-server.XXXXXX.log")"
|
log="$(mktemp "$repo_root/tests/.cache/browser-server.XXXXXX.log")"
|
||||||
echo "==> browser suite: $project"
|
echo "==> browser suite: $project"
|
||||||
"$binary" "$project" --port 0 --no-open >"$log" 2>&1 &
|
setsid "${view[@]}" "$project" --port 0 --no-open >"$log" 2>&1 &
|
||||||
server_pid=$!
|
server_pid=$!
|
||||||
local url=""
|
local url=""
|
||||||
for _ in $(seq 1 100); do
|
for _ in $(seq 1 100); do
|
||||||
@@ -68,15 +71,18 @@ run_suite() {
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
MQ_URL="$url" MQ_PROJECT="$project" node tests/browser/reader.browser.cjs
|
MQ_URL="$url" MQ_PROJECT="$project" node tests/browser/reader.browser.cjs
|
||||||
kill "$server_pid" 2>/dev/null || true
|
cleanup
|
||||||
wait "$server_pid" 2>/dev/null || true
|
if curl -fsS --max-time 2 "$url" >/dev/null 2>&1; then
|
||||||
server_pid=""
|
echo "error: test server remained active after cleanup" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
rm -f "$log"
|
rm -f "$log"
|
||||||
}
|
}
|
||||||
|
|
||||||
mkdir -p "$repo_root/tests/.cache" "$MQ_SCREENSHOT_DIR"
|
mkdir -p "$repo_root/tests/.cache" "$MQ_SCREENSHOT_DIR"
|
||||||
run_suite examples/welcome
|
run_suite examples/welcome
|
||||||
run_suite examples/control-flow
|
run_suite examples/control-flow
|
||||||
|
run_suite examples/function-params.mq.md
|
||||||
run_suite tests/fixtures/security-project
|
run_suite tests/fixtures/security-project
|
||||||
|
|
||||||
core_after="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)"
|
core_after="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)"
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
# Contract-focused gate: formatting, lints, all tests, Tool v1 install smoke,
|
# Contract-focused gate: formatting, lints, all tests, Tool v1 install smoke,
|
||||||
# static verify and static export against the frozen core. No browser.
|
# static verify and static export against the frozen core. No browser.
|
||||||
#
|
#
|
||||||
# Usage: MARQDO_BIN=/abs/path/marqdo tools/test-contract.sh
|
# Usage: MARQDO_BIN=/abs/path/marqdo scripts/test-contract.sh
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
@@ -17,7 +17,7 @@ cargo clippy --all-targets -- -D warnings
|
|||||||
cargo test --locked
|
cargo test --locked
|
||||||
cargo build --release --locked
|
cargo build --release --locked
|
||||||
|
|
||||||
MARQDO_BIN="$MARQDO_BIN" ./tools/package.sh
|
MARQDO_BIN="$MARQDO_BIN" ./scripts/package.sh
|
||||||
|
|
||||||
export MARQDO_TOOL_HOME="$repo_root/dist/contract-tool-home"
|
export MARQDO_TOOL_HOME="$repo_root/dist/contract-tool-home"
|
||||||
rm -rf "$MARQDO_TOOL_HOME"
|
rm -rf "$MARQDO_TOOL_HOME"
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
#!/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.
|
||||||
#
|
#
|
||||||
# Usage: MARQDO_BIN=/abs/path/marqdo tools/test-export.sh
|
# Usage: MARQDO_BIN=/abs/path/marqdo scripts/test-export.sh
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
@@ -11,12 +11,17 @@ cd "$repo_root"
|
|||||||
[[ -x "$MARQDO_BIN" ]] || { echo "error: MARQDO_BIN not executable" >&2; exit 1; }
|
[[ -x "$MARQDO_BIN" ]] || { echo "error: MARQDO_BIN not executable" >&2; exit 1; }
|
||||||
core_before="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)"
|
core_before="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)"
|
||||||
|
|
||||||
binary="$repo_root/target/release/marqdo-view"
|
if [[ "${VIEW_USE_INSTALLED_TOOL:-0}" == 1 ]]; then
|
||||||
[[ -x "$binary" ]] || cargo build --release --locked
|
view=("$MARQDO_BIN" view)
|
||||||
|
else
|
||||||
|
binary="$repo_root/target/release/marqdo-view"
|
||||||
|
[[ -x "$binary" ]] || cargo build --release --locked
|
||||||
|
view=("$binary")
|
||||||
|
fi
|
||||||
|
|
||||||
site="$repo_root/dist/test-export-site"
|
site="$repo_root/dist/test-export-site"
|
||||||
rm -rf "$site"
|
rm -rf "$site"
|
||||||
MARQDO_BIN="$MARQDO_BIN" "$binary" export examples/welcome --out "$site"
|
MARQDO_BIN="$MARQDO_BIN" "${view[@]}" export examples/welcome --out "$site"
|
||||||
|
|
||||||
python3 - "$site" <<'PY'
|
python3 - "$site" <<'PY'
|
||||||
import hashlib
|
import hashlib
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# RFC-VIEW-0002 §13.4 / §6 / §10.3: opening, searching, switching and exporting
|
||||||
|
# must never execute a document. Uses the unsafe-side-effect fixture and checks
|
||||||
|
# source/lock hashes plus the absence of any write sentinel around the whole
|
||||||
|
# read-only operation set.
|
||||||
|
#
|
||||||
|
# Usage: MARQDO_BIN=/abs/path/marqdo scripts/test-no-exec.sh
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
|
cd "$repo_root"
|
||||||
|
|
||||||
|
: "${MARQDO_BIN:?set MARQDO_BIN to the frozen marqdo binary}"
|
||||||
|
core_sha_before="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)"
|
||||||
|
if [[ "${VIEW_USE_INSTALLED_TOOL:-0}" == 1 ]]; then
|
||||||
|
view=("$MARQDO_BIN" view)
|
||||||
|
else
|
||||||
|
binary="$repo_root/target/release/marqdo-view"
|
||||||
|
[[ -x "$binary" ]] || cargo build --release --locked
|
||||||
|
view=("$binary")
|
||||||
|
fi
|
||||||
|
|
||||||
|
mkdir -p "$repo_root/dist"
|
||||||
|
work="$(mktemp -d "$repo_root/dist/no-exec.XXXXXX")"
|
||||||
|
pid=""
|
||||||
|
cleanup() {
|
||||||
|
if [[ -n "$pid" ]]; then
|
||||||
|
kill -- "-$pid" 2>/dev/null || true
|
||||||
|
wait "$pid" 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
rm -rf "$work"
|
||||||
|
}
|
||||||
|
trap cleanup EXIT
|
||||||
|
|
||||||
|
project="$work/project"
|
||||||
|
mkdir "$project"
|
||||||
|
cp examples/unsafe-side-effect.mq.md "$project/"
|
||||||
|
cat > "$project/marqdo.yaml" <<'YAML'
|
||||||
|
project:
|
||||||
|
name: view-no-exec
|
||||||
|
version: 0.1.0
|
||||||
|
dependencies: {}
|
||||||
|
YAML
|
||||||
|
(cd "$project" && "$MARQDO_BIN" lock >/dev/null)
|
||||||
|
doc="$project/unsafe-side-effect.mq.md"
|
||||||
|
sentinel="$project/out/view-sentinel.txt"
|
||||||
|
|
||||||
|
hash_tree() {
|
||||||
|
sha256sum "$doc" "$project/marqdo.yaml" "$project/marqdo.lock"
|
||||||
|
}
|
||||||
|
|
||||||
|
before="$(hash_tree)"
|
||||||
|
test ! -e "$sentinel"
|
||||||
|
|
||||||
|
echo "==> Live read-only requests"
|
||||||
|
setsid "${view[@]}" "$doc" --port 0 --no-open >"$work/server.log" 2>&1 &
|
||||||
|
pid=$!
|
||||||
|
url=""
|
||||||
|
for _ in $(seq 1 100); do
|
||||||
|
url="$(grep -o 'http://127.0.0.1:[0-9]*/' "$work/server.log" | head -1 || true)"
|
||||||
|
[[ -n "$url" ]] && break
|
||||||
|
sleep 0.1
|
||||||
|
done
|
||||||
|
test -n "$url"
|
||||||
|
cookie_jar="$work/cookies.txt"
|
||||||
|
curl -fsS -c "$cookie_jar" "${url}" > "$work/page.html"
|
||||||
|
curl -fsS -c "$cookie_jar" -b "$cookie_jar" "${url}file?path=unsafe-side-effect.mq.md" >/dev/null
|
||||||
|
curl -fsS -b "$cookie_jar" "${url}api/documents" >/dev/null
|
||||||
|
curl -fsS -b "$cookie_jar" "${url}api/documents?path=unsafe-side-effect.mq.md" >/dev/null
|
||||||
|
# Reloading the page multiple times must remain side-effect free.
|
||||||
|
for _ in $(seq 1 5); do curl -fsS -b "$cookie_jar" "${url}" >/dev/null; done
|
||||||
|
kill -- "-$pid" 2>/dev/null || true
|
||||||
|
wait "$pid" 2>/dev/null || true
|
||||||
|
pid=""
|
||||||
|
|
||||||
|
echo "==> Static export"
|
||||||
|
"${view[@]}" export "$doc" --out "$work/site" >/dev/null
|
||||||
|
test -f "$work/site/manifest.json"
|
||||||
|
# Export has no execution controls and no CSRF/session material.
|
||||||
|
if grep -q 'data-action="run"' "$work/site/pages/unsafe-side-effect.mq.md.html"; then
|
||||||
|
echo "error: exported page contains a run control" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if grep -q 'mq-csrf-token' "$work/site/pages/unsafe-side-effect.mq.md.html"; then
|
||||||
|
echo "error: exported page contains a CSRF token" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
after="$(hash_tree)"
|
||||||
|
if [[ "$before" != "$after" ]]; then
|
||||||
|
echo "error: read-only/export operations modified project sources" >&2
|
||||||
|
diff <(printf '%s\n' "$before") <(printf '%s\n' "$after") >&2 || true
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
test ! -e "$sentinel"
|
||||||
|
test ! -e "$project/out"
|
||||||
|
|
||||||
|
# Prove the fixture is capable of writing when an operator grants it.
|
||||||
|
"$MARQDO_BIN" run "$doc" --mode project --allow-write out --allow-write 'out/**' >/dev/null
|
||||||
|
grep -qx 'explicit run only' "$sentinel"
|
||||||
|
|
||||||
|
core_sha_after="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)"
|
||||||
|
test "$core_sha_before" = "$core_sha_after"
|
||||||
|
echo "no-exec: PASS (sources/lock unchanged, no sentinel from read-only operations, explicit write control passed, no run control in export; core sha unchanged)"
|
||||||
@@ -2,20 +2,18 @@
|
|||||||
# Security/contract suite: HTTP boundary, CSRF/Origin, path escapes, XSS
|
# Security/contract suite: HTTP boundary, CSRF/Origin, path escapes, XSS
|
||||||
# sanitization, export-no-exec, architectural coupling gates.
|
# sanitization, export-no-exec, architectural coupling gates.
|
||||||
#
|
#
|
||||||
# Usage: tools/test-security.sh
|
# Usage: scripts/test-security.sh
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
cd "$repo_root"
|
cd "$repo_root"
|
||||||
|
|
||||||
cargo test --locked --test http_live
|
cargo test --locked --test security
|
||||||
cargo test --locked --test rendering
|
cargo test --locked --test integration
|
||||||
cargo test --locked --test export
|
cargo test --locked --test contract
|
||||||
cargo test --locked --test no_coupling
|
|
||||||
cargo test --locked --test asset_integrity
|
|
||||||
|
|
||||||
if [[ -n "${MARQDO_FROZEN_BIN:-}" ]]; then
|
if [[ -n "${MARQDO_FROZEN_BIN:-}" ]]; then
|
||||||
MARQDO_BIN="$MARQDO_FROZEN_BIN" ./tools/test-export.sh
|
MARQDO_BIN="$MARQDO_FROZEN_BIN" ./scripts/test-export.sh
|
||||||
else
|
else
|
||||||
echo "note: MARQDO_FROZEN_BIN not set; skipped real-core export script"
|
echo "note: MARQDO_FROZEN_BIN not set; skipped real-core export script"
|
||||||
fi
|
fi
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Prove a frozen marqdo release binary is byte-identical before and after a
|
||||||
|
# command sequence (RFC-VIEW-0002 §2 / §9.4 / §10.2).
|
||||||
|
#
|
||||||
|
# Usage:
|
||||||
|
# scripts/verify-frozen-cli.sh /abs/path/marqdo [-- EXPECTED_SHA256] -- CMD [ARGS...]
|
||||||
|
# EXPECTED_SHA256=<hex> scripts/verify-frozen-cli.sh /abs/path/marqdo -- CMD [ARGS...]
|
||||||
|
# scripts/verify-frozen-cli.sh /abs/path/marqdo # version/SHA report only
|
||||||
|
#
|
||||||
|
# The script never rebuilds or modifies the CLI. It records the version, the
|
||||||
|
# SHA-256 before/after, and exits non-zero if the SHA changes or if an expected
|
||||||
|
# SHA (argument or EXPECTED_SHA256 env) does not match.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
core="${1:-}"
|
||||||
|
if [[ -z "$core" ]]; then
|
||||||
|
echo "usage: $0 /abs/path/marqdo [-- EXPECTED_SHA256] -- CMD [ARGS...]" >&2
|
||||||
|
exit 2
|
||||||
|
fi
|
||||||
|
shift
|
||||||
|
|
||||||
|
expected="${EXPECTED_SHA256:-}"
|
||||||
|
if [[ "${1:-}" == "--" && ( "${2:-}" =~ ^[0-9a-f]{64}$ ) ]]; then
|
||||||
|
expected="$2"
|
||||||
|
shift 2
|
||||||
|
fi
|
||||||
|
if [[ "${1:-}" == "--" ]]; then
|
||||||
|
shift
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ ! -x "$core" ]]; then
|
||||||
|
echo "error: frozen CLI is not executable: $core" >&2
|
||||||
|
exit 2
|
||||||
|
fi
|
||||||
|
|
||||||
|
sha_before="$(sha256sum "$core" | cut -d' ' -f1)"
|
||||||
|
|
||||||
|
if [[ -n "$expected" && "$expected" != "$sha_before" ]]; then
|
||||||
|
echo "error: frozen CLI SHA-256 mismatch" >&2
|
||||||
|
echo " expected: $expected" >&2
|
||||||
|
echo " actual: $sha_before" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
version_line="$("$core" --version)"
|
||||||
|
command_status=0
|
||||||
|
if [[ $# -gt 0 ]]; then
|
||||||
|
"$@" || command_status=$?
|
||||||
|
fi
|
||||||
|
|
||||||
|
sha_after="$(sha256sum "$core" | cut -d' ' -f1)"
|
||||||
|
if [[ "$sha_before" != "$sha_after" ]]; then
|
||||||
|
echo "error: frozen CLI binary changed during the command" >&2
|
||||||
|
echo " before: $sha_before" >&2
|
||||||
|
echo " after: $sha_after" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
printf 'verify-frozen-cli: PASS\n'
|
||||||
|
printf ' path: %s\n' "$core"
|
||||||
|
printf ' version: %s\n' "$version_line"
|
||||||
|
printf ' sha256: %s (unchanged)\n' "$sha_before"
|
||||||
|
|
||||||
|
exit "$command_status"
|
||||||
@@ -1,475 +0,0 @@
|
|||||||
//! Application layer: turns parsed commands into use cases.
|
|
||||||
//!
|
|
||||||
//! No HTML is built here and no Markdown semantics are decided here. Browse and
|
|
||||||
//! (later) Export call the same `load` + one `ReaderRenderer`.
|
|
||||||
|
|
||||||
use crate::cli::{ExportArgs, RuntimeOpts, VerifyArgs};
|
|
||||||
use crate::core_client::{
|
|
||||||
CheckOptions, CheckResponse, CoreClient, RawCheckDiagnostic, RunOptions, SandboxMode,
|
|
||||||
};
|
|
||||||
use crate::document::{DocumentIdentity, DocumentModel};
|
|
||||||
use crate::error::{ViewError, ViewResult};
|
|
||||||
use crate::export::{export as run_export, ExportOptions};
|
|
||||||
use crate::presentation::{self, BuildInput, Navigation, PresentationModel, SourceStatus};
|
|
||||||
use crate::project::{Project, SafeRelativePath, ViewConfig};
|
|
||||||
use crate::semantic::{self, CoreDiagnostic};
|
|
||||||
use crate::trace::{self, TraceVerificationInput, VerifiedRun};
|
|
||||||
use crate::version;
|
|
||||||
|
|
||||||
/// Process-wide context for one browsed project: root, optional site config and
|
|
||||||
/// an optional negotiated frozen core. A missing core degrades to prose only;
|
|
||||||
/// an incompatible protocol is a hard error (RFC §4).
|
|
||||||
pub struct AppContext {
|
|
||||||
project: Project,
|
|
||||||
config: ViewConfig,
|
|
||||||
core: Option<CoreClient>,
|
|
||||||
core_version: Option<String>,
|
|
||||||
core_note: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AppContext {
|
|
||||||
pub fn open(path: &std::path::Path, marqdo_bin: Option<&std::path::Path>) -> ViewResult<Self> {
|
|
||||||
let project = Project::open(path)?;
|
|
||||||
let config = ViewConfig::load(project.root())?;
|
|
||||||
let (core, core_version, core_note) = match CoreClient::from_env(marqdo_bin) {
|
|
||||||
Ok(client) => match client.negotiate() {
|
|
||||||
Ok(version) => (Some(client), Some(version.version.to_string()), None),
|
|
||||||
Err(err) if err.code() == "view.protocol_incompatible" => return Err(err),
|
|
||||||
Err(err) => (None, None, Some(generic_core_note(&err))),
|
|
||||||
},
|
|
||||||
Err(err) if err.code() == "view.core_missing" => {
|
|
||||||
(None, None, Some(generic_core_note(&err)))
|
|
||||||
}
|
|
||||||
Err(err) => return Err(err),
|
|
||||||
};
|
|
||||||
Ok(Self {
|
|
||||||
project,
|
|
||||||
config,
|
|
||||||
core,
|
|
||||||
core_version,
|
|
||||||
core_note,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn project(&self) -> &Project {
|
|
||||||
&self.project
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn config(&self) -> &ViewConfig {
|
|
||||||
&self.config
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn core(&self) -> Option<&CoreClient> {
|
|
||||||
self.core.as_ref()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn core_version(&self) -> Option<&str> {
|
|
||||||
self.core_version.as_deref()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn core_note(&self) -> Option<&str> {
|
|
||||||
self.core_note.as_deref()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Read + parse + (optionally) check one document into the one presentation
|
|
||||||
/// model. Never executes the document.
|
|
||||||
pub fn load(&self, relative: &SafeRelativePath) -> ViewResult<PresentationModel> {
|
|
||||||
self.load_with_run(relative, None)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Same pipeline, optionally attaching an already-verified run projection.
|
|
||||||
/// The run is re-bound to freshly checked Analysis bytes; if the source or
|
|
||||||
/// analysis changed meanwhile the result becomes `STALE` instead of being
|
|
||||||
/// attached to the wrong text.
|
|
||||||
pub fn load_with_run(
|
|
||||||
&self,
|
|
||||||
relative: &SafeRelativePath,
|
|
||||||
run: Option<&VerifiedRun>,
|
|
||||||
) -> ViewResult<PresentationModel> {
|
|
||||||
let source_bytes = self.project.read_source(relative)?;
|
|
||||||
let source = String::from_utf8(source_bytes).map_err(|err| ViewError::Io {
|
|
||||||
detail: format!("{relative} is not valid UTF-8: {err}"),
|
|
||||||
})?;
|
|
||||||
let document = DocumentModel::parse(source, DocumentIdentity::placeholder(relative));
|
|
||||||
let navigation = Navigation::from_project(&self.project, &self.config, relative);
|
|
||||||
|
|
||||||
let mut status = SourceStatus::CoreUnavailable;
|
|
||||||
let mut status_note = self.core_note.clone();
|
|
||||||
let mut diagnostics = Vec::new();
|
|
||||||
let mut verified = None;
|
|
||||||
|
|
||||||
if let Some(client) = &self.core {
|
|
||||||
match client.check(
|
|
||||||
&self.project,
|
|
||||||
relative,
|
|
||||||
&CheckOptions {
|
|
||||||
refs: false,
|
|
||||||
timeout: Some(std::time::Duration::from_secs(30)),
|
|
||||||
},
|
|
||||||
)? {
|
|
||||||
CheckResponse {
|
|
||||||
success: false,
|
|
||||||
diagnostics: raw_diagnostics,
|
|
||||||
exit_code,
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
status = SourceStatus::CoreError;
|
|
||||||
status_note = Some(format!(
|
|
||||||
"Core 检查失败(exit {exit_code}):语义标注已撤销,正文仍可阅读。"
|
|
||||||
));
|
|
||||||
diagnostics = raw_diagnostics
|
|
||||||
.iter()
|
|
||||||
.map(|diagnostic| diagnostic_to_view(diagnostic, relative))
|
|
||||||
.collect();
|
|
||||||
}
|
|
||||||
CheckResponse {
|
|
||||||
success: true,
|
|
||||||
analysis: Some(check),
|
|
||||||
..
|
|
||||||
} => match semantic::verify_analysis(
|
|
||||||
&check.analysis_bytes,
|
|
||||||
&document.source,
|
|
||||||
&document.source_index,
|
|
||||||
relative.as_str(),
|
|
||||||
) {
|
|
||||||
Ok(verified_analysis) => {
|
|
||||||
status = SourceStatus::StaticOk;
|
|
||||||
status_note = None;
|
|
||||||
verified = Some(verified_analysis);
|
|
||||||
}
|
|
||||||
Err(err) if err.code() == "view.source_mismatch" => {
|
|
||||||
status = SourceStatus::SourceMismatch;
|
|
||||||
status_note = Some(
|
|
||||||
"当前源码字节与 Analysis 的 source_digest 不一致,语义标注已禁用。"
|
|
||||||
.to_string(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Err(err) if err.code() == "view.protocol_incompatible" => {
|
|
||||||
return Err(err);
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
status = SourceStatus::CoreError;
|
|
||||||
status_note = Some(generic_core_note(&err));
|
|
||||||
}
|
|
||||||
},
|
|
||||||
CheckResponse {
|
|
||||||
success: true,
|
|
||||||
analysis: None,
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
status = SourceStatus::CoreError;
|
|
||||||
status_note = Some("Core 声称检查成功但没有产出 Analysis。".to_string());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let attached_run: Option<VerifiedRun> = match (run, verified.as_ref()) {
|
|
||||||
(Some(run), Some(analysis)) => {
|
|
||||||
let expected = format!("sha256:{}", analysis.projection.analysis_sha256);
|
|
||||||
if expected == run.projection.analysis_digest {
|
|
||||||
Some(VerifiedRun {
|
|
||||||
projection: run.projection.clone(),
|
|
||||||
})
|
|
||||||
} else {
|
|
||||||
Some(VerifiedRun {
|
|
||||||
projection: trace::stale_projection(
|
|
||||||
&run.projection.analysis_digest,
|
|
||||||
&document.source_index,
|
|
||||||
),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
(Some(run), None) => Some(VerifiedRun {
|
|
||||||
projection: trace::stale_projection(
|
|
||||||
&run.projection.analysis_digest,
|
|
||||||
&document.source_index,
|
|
||||||
),
|
|
||||||
}),
|
|
||||||
(None, _) => None,
|
|
||||||
};
|
|
||||||
|
|
||||||
Ok(presentation::build(BuildInput {
|
|
||||||
document,
|
|
||||||
analysis: verified.as_ref(),
|
|
||||||
status,
|
|
||||||
status_note,
|
|
||||||
diagnostics,
|
|
||||||
navigation,
|
|
||||||
core_version: self.core_version.clone(),
|
|
||||||
run: attached_run.as_ref(),
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Execute one document through the public Core `run` channel after the
|
|
||||||
/// caller has obtained explicit user confirmation and a CSRF token. Never
|
|
||||||
/// called from page loads or exports.
|
|
||||||
pub fn run_document(&self, relative: &SafeRelativePath) -> ViewResult<ExecutedRun> {
|
|
||||||
let client = self.core.as_ref().ok_or_else(|| ViewError::RunDenied {
|
|
||||||
detail: "没有可用的冻结核心(MARQDO_BIN),运行被拒绝".to_string(),
|
|
||||||
})?;
|
|
||||||
let source_bytes = self.project.read_source(relative)?;
|
|
||||||
let source_digest = crate::source_map::sha256_hex(&source_bytes);
|
|
||||||
let source = String::from_utf8(source_bytes).map_err(|err| ViewError::Io {
|
|
||||||
detail: format!("{relative} is not valid UTF-8: {err}"),
|
|
||||||
})?;
|
|
||||||
let source_index = crate::source_map::SourceIndex::new(&source);
|
|
||||||
|
|
||||||
let run = client.run(
|
|
||||||
&self.project,
|
|
||||||
relative,
|
|
||||||
&RunOptions {
|
|
||||||
mode: SandboxMode::Pure,
|
|
||||||
view_timeout: Some(std::time::Duration::from_secs(120)),
|
|
||||||
timeout_seconds: Some(90),
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
)?;
|
|
||||||
let trace_bytes = run
|
|
||||||
.trace_bytes
|
|
||||||
.clone()
|
|
||||||
.ok_or_else(|| ViewError::RunDenied {
|
|
||||||
detail: "Core 未写出 Trace v2 文件,运行结果不可绑定".to_string(),
|
|
||||||
})?;
|
|
||||||
|
|
||||||
// Re-check after the run so the digest binds to the exact Analysis of
|
|
||||||
// the source that was executed and is still current.
|
|
||||||
let response = client.check(&self.project, relative, &CheckOptions::default())?;
|
|
||||||
let check = response.analysis.ok_or_else(|| ViewError::AnalysisFailed {
|
|
||||||
detail: "运行后的静态检查失败,无法绑定 Trace".to_string(),
|
|
||||||
})?;
|
|
||||||
let verified = semantic::verify_analysis(
|
|
||||||
&check.analysis_bytes,
|
|
||||||
&source,
|
|
||||||
&source_index,
|
|
||||||
relative.as_str(),
|
|
||||||
)?;
|
|
||||||
let verified_run = trace::verify_trace(TraceVerificationInput {
|
|
||||||
trace_bytes: &trace_bytes,
|
|
||||||
analysis_bytes: &check.analysis_bytes,
|
|
||||||
semantic: &verified.projection,
|
|
||||||
modules: &verified.projection.modules,
|
|
||||||
source: &source,
|
|
||||||
source_index: &source_index,
|
|
||||||
run_json: &run.json,
|
|
||||||
exit_code: run.exit_code,
|
|
||||||
})?;
|
|
||||||
Ok(ExecutedRun {
|
|
||||||
verified: verified_run,
|
|
||||||
source_digest,
|
|
||||||
analysis_digest: check.analysis_digest,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct ExecutedRun {
|
|
||||||
pub verified: VerifiedRun,
|
|
||||||
pub source_digest: String,
|
|
||||||
pub analysis_digest: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn verify(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32> {
|
|
||||||
let path = args
|
|
||||||
.path
|
|
||||||
.clone()
|
|
||||||
.or_else(|| opts.path.clone())
|
|
||||||
.unwrap_or_else(|| std::path::PathBuf::from("."));
|
|
||||||
let project = Project::open(&path)?;
|
|
||||||
let entry = project.entry().relative.clone();
|
|
||||||
let source_bytes = project.read_source(&entry)?;
|
|
||||||
let source = String::from_utf8(source_bytes).map_err(|err| ViewError::Io {
|
|
||||||
detail: format!("{entry} is not valid UTF-8: {err}"),
|
|
||||||
})?;
|
|
||||||
let source_index = crate::source_map::SourceIndex::new(&source);
|
|
||||||
|
|
||||||
let client = CoreClient::from_env(opts.marqdo_bin.as_deref())?;
|
|
||||||
let core_version = client.negotiate()?;
|
|
||||||
let response = client.check(
|
|
||||||
&project,
|
|
||||||
&entry,
|
|
||||||
&CheckOptions {
|
|
||||||
refs: args.refs,
|
|
||||||
timeout: None,
|
|
||||||
},
|
|
||||||
)?;
|
|
||||||
let check = match response {
|
|
||||||
CheckResponse {
|
|
||||||
success: false,
|
|
||||||
diagnostics,
|
|
||||||
exit_code,
|
|
||||||
..
|
|
||||||
} => {
|
|
||||||
let first = diagnostics
|
|
||||||
.first()
|
|
||||||
.map(|diagnostic| {
|
|
||||||
format!(
|
|
||||||
"{}: {}",
|
|
||||||
if diagnostic.code.is_empty() {
|
|
||||||
"diagnostic"
|
|
||||||
} else {
|
|
||||||
&diagnostic.code
|
|
||||||
},
|
|
||||||
diagnostic.message
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.unwrap_or_else(|| "no diagnostic detail".to_string());
|
|
||||||
return Err(ViewError::AnalysisFailed {
|
|
||||||
detail: format!(
|
|
||||||
"`marqdo check` failed with exit code {exit_code} ({} diagnostic(s)); first: {first}",
|
|
||||||
diagnostics.len()
|
|
||||||
),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
CheckResponse {
|
|
||||||
analysis: Some(check),
|
|
||||||
..
|
|
||||||
} => check,
|
|
||||||
CheckResponse { analysis: None, .. } => {
|
|
||||||
return Err(ViewError::AnalysisFailed {
|
|
||||||
detail: "`marqdo check` succeeded but emitted no Analysis".to_string(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let verified = semantic::verify_analysis(
|
|
||||||
&check.analysis_bytes,
|
|
||||||
&source,
|
|
||||||
&source_index,
|
|
||||||
entry.as_str(),
|
|
||||||
)?;
|
|
||||||
let projection = &verified.projection;
|
|
||||||
|
|
||||||
if args.json {
|
|
||||||
let doc = serde_json::json!({
|
|
||||||
"schema": "marqdo.view-verify",
|
|
||||||
"schema_version": 1,
|
|
||||||
"ok": true,
|
|
||||||
"core": {
|
|
||||||
"version": core_version.version.to_string(),
|
|
||||||
"supported_range": version::PRODUCT_RANGE,
|
|
||||||
},
|
|
||||||
"analysis": {
|
|
||||||
"schema": "marqdo.analysis",
|
|
||||||
"schema_version": version::ANALYSIS_PROTOCOL,
|
|
||||||
"digest": projection.analysis_digest,
|
|
||||||
"producer_version": projection.producer_version,
|
|
||||||
"markdown_profile": projection.markdown_profile,
|
|
||||||
"functions": projection.functions.len(),
|
|
||||||
"units": projection.units.len(),
|
|
||||||
"diagnostics": projection.diagnostics.len(),
|
|
||||||
},
|
|
||||||
"project": {
|
|
||||||
"root_id": projection.project_root_id,
|
|
||||||
"identity_kind": projection.identity_kind,
|
|
||||||
"lock_digest": projection.lock_digest,
|
|
||||||
"stdlib_version": projection.stdlib_version,
|
|
||||||
},
|
|
||||||
"document": {
|
|
||||||
"relative_path": entry.as_str(),
|
|
||||||
"module_id": projection.module_id,
|
|
||||||
"source_digest": projection.source_digest,
|
|
||||||
"source_digest_matches": true,
|
|
||||||
},
|
|
||||||
"result": "PASS",
|
|
||||||
"executed": false,
|
|
||||||
"note": "Static verification only; the document was not executed.",
|
|
||||||
});
|
|
||||||
println!(
|
|
||||||
"{}",
|
|
||||||
serde_json::to_string_pretty(&doc).unwrap_or_else(|_| "{}".to_string())
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
println!(
|
|
||||||
"core: marqdo {} (supported {})",
|
|
||||||
core_version.version,
|
|
||||||
version::PRODUCT_RANGE
|
|
||||||
);
|
|
||||||
println!(
|
|
||||||
"project: {} ({})",
|
|
||||||
projection.project_root_id, projection.identity_kind
|
|
||||||
);
|
|
||||||
println!("document: {entry}");
|
|
||||||
println!(
|
|
||||||
"analysis: schema=marqdo.analysis v2 modules={} functions={} digest={}",
|
|
||||||
projection.modules.len(),
|
|
||||||
projection.functions.len(),
|
|
||||||
projection.analysis_digest
|
|
||||||
);
|
|
||||||
println!("source digest: match");
|
|
||||||
println!("result: PASS (static only; document not executed)");
|
|
||||||
}
|
|
||||||
Ok(0)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn browse(opts: &RuntimeOpts) -> ViewResult<i32> {
|
|
||||||
let path = opts
|
|
||||||
.path
|
|
||||||
.clone()
|
|
||||||
.unwrap_or_else(|| std::path::PathBuf::from("."));
|
|
||||||
let context = AppContext::open(&path, opts.marqdo_bin.as_deref())?;
|
|
||||||
crate::server::serve(context, opts)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn export(opts: &RuntimeOpts, args: &ExportArgs) -> ViewResult<i32> {
|
|
||||||
let path = args
|
|
||||||
.path
|
|
||||||
.clone()
|
|
||||||
.or_else(|| opts.path.clone())
|
|
||||||
.unwrap_or_else(|| std::path::PathBuf::from("."));
|
|
||||||
let context = AppContext::open(&path, opts.marqdo_bin.as_deref())?;
|
|
||||||
let summary = run_export(
|
|
||||||
&context,
|
|
||||||
&ExportOptions {
|
|
||||||
out: args.out.clone(),
|
|
||||||
no_annotations: args.no_annotations,
|
|
||||||
},
|
|
||||||
)?;
|
|
||||||
println!(
|
|
||||||
"marqdo view export: {} page(s), {} file(s) → {}",
|
|
||||||
summary.pages,
|
|
||||||
summary.files,
|
|
||||||
summary.out.display()
|
|
||||||
);
|
|
||||||
println!("manifest: sha256:{}", summary.manifest_sha256);
|
|
||||||
println!("executed: false (纯静态导出,未运行任何文档)");
|
|
||||||
Ok(0)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn generic_core_note(err: &ViewError) -> String {
|
|
||||||
match err.code() {
|
|
||||||
"view.core_missing" => {
|
|
||||||
"未找到可用的冻结核心(MARQDO_BIN);当前为无语义标注的纯 Markdown 阅读模式。"
|
|
||||||
.to_string()
|
|
||||||
}
|
|
||||||
"view.analysis_failed" => "Core 检查失败;语义标注已撤销,正文仍可阅读。".to_string(),
|
|
||||||
other => format!("{other}:语义标注不可用,正文仍可阅读。"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn diagnostic_to_view(
|
|
||||||
diagnostic: &RawCheckDiagnostic,
|
|
||||||
relative: &SafeRelativePath,
|
|
||||||
) -> CoreDiagnostic {
|
|
||||||
let belongs_to_entry = diagnostic
|
|
||||||
.module
|
|
||||||
.as_deref()
|
|
||||||
.map(|module| module.ends_with(relative.as_str()))
|
|
||||||
.unwrap_or(true);
|
|
||||||
CoreDiagnostic {
|
|
||||||
module: diagnostic.module.clone(),
|
|
||||||
relative_path: if belongs_to_entry {
|
|
||||||
Some(relative.as_str().to_string())
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
},
|
|
||||||
span: None,
|
|
||||||
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(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -41,6 +41,16 @@ pub struct Cli {
|
|||||||
#[arg(long, global = true)]
|
#[arg(long, global = true)]
|
||||||
pub no_open: bool,
|
pub no_open: bool,
|
||||||
|
|
||||||
|
/// Wall-clock limit for one explicit run, in seconds (RFC-VIEW-0002 §6.7).
|
||||||
|
/// The frozen Core receives the same value via `--timeout`.
|
||||||
|
#[arg(
|
||||||
|
long,
|
||||||
|
default_value_t = 30,
|
||||||
|
global = true,
|
||||||
|
value_parser = clap::value_parser!(u64).range(1..=120)
|
||||||
|
)]
|
||||||
|
pub run_timeout: u64,
|
||||||
|
|
||||||
/// Advanced: allow a non-loopback bind. No execution API is opened by it.
|
/// Advanced: allow a non-loopback bind. No execution API is opened by it.
|
||||||
#[arg(long, global = true, hide = true)]
|
#[arg(long, global = true, hide = true)]
|
||||||
pub unsafe_expose: bool,
|
pub unsafe_expose: bool,
|
||||||
@@ -97,6 +107,7 @@ pub struct RuntimeOpts {
|
|||||||
pub port: u16,
|
pub port: u16,
|
||||||
pub no_open: bool,
|
pub no_open: bool,
|
||||||
pub unsafe_expose: bool,
|
pub unsafe_expose: bool,
|
||||||
|
pub run_timeout_secs: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Cli {
|
impl Cli {
|
||||||
@@ -108,6 +119,7 @@ impl Cli {
|
|||||||
port: self.port,
|
port: self.port,
|
||||||
no_open: self.no_open,
|
no_open: self.no_open,
|
||||||
unsafe_expose: self.unsafe_expose,
|
unsafe_expose: self.unsafe_expose,
|
||||||
|
run_timeout_secs: self.run_timeout,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -141,6 +153,7 @@ mod tests {
|
|||||||
assert!(cli.command.is_none());
|
assert!(cli.command.is_none());
|
||||||
assert_eq!(cli.host, "127.0.0.1");
|
assert_eq!(cli.host, "127.0.0.1");
|
||||||
assert_eq!(cli.port, 7429);
|
assert_eq!(cli.port, 7429);
|
||||||
|
assert_eq!(cli.run_timeout, 30);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -187,6 +200,14 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn run_timeout_is_bounded_to_rfc_range() {
|
||||||
|
assert!(Cli::try_parse_from(["marqdo-view", "--run-timeout", "0"]).is_err());
|
||||||
|
assert!(Cli::try_parse_from(["marqdo-view", "--run-timeout", "121"]).is_err());
|
||||||
|
let cli = Cli::parse_from(["marqdo-view", "--run-timeout", "45"]);
|
||||||
|
assert_eq!(cli.runtime().run_timeout_secs, 45);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn bind_policy_is_loopback_by_default() {
|
fn bind_policy_is_loopback_by_default() {
|
||||||
assert!(validate_bind("127.0.0.1", false).is_ok());
|
assert!(validate_bind("127.0.0.1", false).is_ok());
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
//! View-only site configuration (`view.json`).
|
||||||
|
//!
|
||||||
|
//! This is **not** a Marqdo language protocol and cannot grant execution. Only
|
||||||
|
//! welcome/site_title/theme are read, and the welcome path is subject to the
|
||||||
|
//! same project-root boundary (RFC-VIEW-0002 §4.2/§5.3).
|
||||||
|
|
||||||
|
use crate::error::{ViewError, ViewResult};
|
||||||
|
use crate::reader::source::SafeRelativePath;
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
/// Optional View-only site configuration (`view.json`).
|
||||||
|
///
|
||||||
|
/// This is **not** a Marqdo language protocol and cannot grant execution: only
|
||||||
|
/// the fields below are read, and the welcome path is still subject to the same
|
||||||
|
/// project-root boundary (RFC-VIEW-0001 §9.4).
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct ViewConfig {
|
||||||
|
pub welcome: Option<SafeRelativePath>,
|
||||||
|
pub site_title: Option<String>,
|
||||||
|
pub theme: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ViewConfig {
|
||||||
|
pub fn load(root: &Path) -> ViewResult<Self> {
|
||||||
|
let path = root.join("view.json");
|
||||||
|
let metadata = match std::fs::metadata(&path) {
|
||||||
|
Ok(metadata) => metadata,
|
||||||
|
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Self::default()),
|
||||||
|
Err(err) => return Err(ViewError::io(&format!("stat {}", path.display()), err)),
|
||||||
|
};
|
||||||
|
if !metadata.is_file() || metadata.len() > 64 * 1024 {
|
||||||
|
return Err(ViewError::PathForbidden {
|
||||||
|
detail: "view.json must be a regular file under 64 KiB".to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let bytes = std::fs::read(&path)
|
||||||
|
.map_err(|err| ViewError::io(&format!("read {}", path.display()), err))?;
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
struct RawConfig {
|
||||||
|
#[serde(default)]
|
||||||
|
schema: String,
|
||||||
|
#[serde(default)]
|
||||||
|
schema_version: u32,
|
||||||
|
#[serde(default)]
|
||||||
|
welcome: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
site_title: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
theme: Option<String>,
|
||||||
|
}
|
||||||
|
let raw: RawConfig = serde_json::from_slice(&bytes).map_err(|err| ViewError::Io {
|
||||||
|
detail: format!("view.json is not valid JSON: {err}"),
|
||||||
|
})?;
|
||||||
|
if raw.schema != "marqdo.view-config" || raw.schema_version != 1 {
|
||||||
|
return Err(ViewError::ProtocolIncompatible {
|
||||||
|
detail: format!(
|
||||||
|
"unsupported view.json schema {:?} version {}; expected marqdo.view-config v1",
|
||||||
|
raw.schema, raw.schema_version
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let welcome = match raw.welcome {
|
||||||
|
Some(path) => Some(SafeRelativePath::parse(&path)?),
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
if let Some(welcome) = &welcome {
|
||||||
|
if !root.join(welcome.to_path()).is_file() {
|
||||||
|
return Err(ViewError::PathForbidden {
|
||||||
|
detail: format!(
|
||||||
|
"view.json welcome file {welcome} does not exist under the project root"
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let site_title = raw
|
||||||
|
.site_title
|
||||||
|
.map(|title| title.trim().to_string())
|
||||||
|
.filter(|title| !title.is_empty() && title.chars().count() <= 80);
|
||||||
|
let theme = raw
|
||||||
|
.theme
|
||||||
|
.map(|theme| theme.trim().to_string())
|
||||||
|
.filter(|theme| theme == "botanical" || theme == "paper");
|
||||||
|
Ok(Self {
|
||||||
|
welcome,
|
||||||
|
site_title,
|
||||||
|
theme,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,15 +10,14 @@
|
|||||||
//! drop.
|
//! drop.
|
||||||
|
|
||||||
use crate::error::{ViewError, ViewResult};
|
use crate::error::{ViewError, ViewResult};
|
||||||
use crate::project::{Project, SafeRelativePath};
|
use crate::execution::process::{run_bounded, ProcessBudget};
|
||||||
use crate::source_map::{sha256_hex, sha256_prefixed};
|
use crate::protocol::tool_v1::{self, CoreVersion};
|
||||||
use crate::version::{self, CoreVersion};
|
use crate::reader::source::{sha256_hex, sha256_prefixed};
|
||||||
|
use crate::reader::source::{Project, SafeRelativePath};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::ffi::OsString;
|
use std::ffi::OsString;
|
||||||
use std::io::Read;
|
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::process::{Command, Stdio};
|
use std::time::Duration;
|
||||||
use std::time::{Duration, Instant};
|
|
||||||
|
|
||||||
/// Default View-level wall clock cap for one Core `run`.
|
/// Default View-level wall clock cap for one Core `run`.
|
||||||
pub const DEFAULT_RUN_TIMEOUT: Duration = Duration::from_secs(120);
|
pub const DEFAULT_RUN_TIMEOUT: Duration = Duration::from_secs(120);
|
||||||
@@ -240,9 +239,9 @@ impl CoreClient {
|
|||||||
Ok(Self {
|
Ok(Self {
|
||||||
bin,
|
bin,
|
||||||
protocol_env: ProtocolEnv {
|
protocol_env: ProtocolEnv {
|
||||||
tool: std::env::var(version::ENV_TOOL_PROTOCOL).ok(),
|
tool: std::env::var(tool_v1::ENV_TOOL_PROTOCOL).ok(),
|
||||||
analysis: std::env::var(version::ENV_PROTOCOL_ANALYSIS).ok(),
|
analysis: std::env::var(tool_v1::ENV_PROTOCOL_ANALYSIS).ok(),
|
||||||
trace: std::env::var(version::ENV_PROTOCOL_TRACE).ok(),
|
trace: std::env::var(tool_v1::ENV_PROTOCOL_TRACE).ok(),
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -265,7 +264,7 @@ impl CoreClient {
|
|||||||
/// environment variables. A missing Development-mode env is allowed; an
|
/// environment variables. A missing Development-mode env is allowed; an
|
||||||
/// unknown major is a hard error.
|
/// unknown major is a hard error.
|
||||||
pub fn negotiate(&self) -> ViewResult<CoreVersion> {
|
pub fn negotiate(&self) -> ViewResult<CoreVersion> {
|
||||||
version::negotiate_protocol_env(
|
tool_v1::negotiate_protocol_env(
|
||||||
self.protocol_env.tool.as_deref(),
|
self.protocol_env.tool.as_deref(),
|
||||||
self.protocol_env.analysis.as_deref(),
|
self.protocol_env.analysis.as_deref(),
|
||||||
self.protocol_env.trace.as_deref(),
|
self.protocol_env.trace.as_deref(),
|
||||||
@@ -285,13 +284,13 @@ impl CoreClient {
|
|||||||
),
|
),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
let version = version::parse_version_output(&output.stdout)?;
|
let version = tool_v1::parse_version_output(&output.stdout)?;
|
||||||
if !version::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 {}",
|
||||||
version.version,
|
version.version,
|
||||||
version::PRODUCT_RANGE
|
tool_v1::PRODUCT_RANGE
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -433,75 +432,27 @@ impl CoreClient {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Spawn the core with an explicit argv, private cwd and a wall-clock cap.
|
/// Spawn the core through the single process adapter with an explicit
|
||||||
|
/// 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> {
|
||||||
let mut command = Command::new(&self.bin);
|
let budget = ProcessBudget {
|
||||||
command
|
wall_clock: timeout,
|
||||||
.args(args)
|
..Default::default()
|
||||||
.current_dir(cwd)
|
|
||||||
.stdin(Stdio::null())
|
|
||||||
.stdout(Stdio::piped())
|
|
||||||
.stderr(Stdio::piped());
|
|
||||||
// Put the core in its own process group so a View-level timeout kills
|
|
||||||
// the whole subtree, not just the immediate shell-less child.
|
|
||||||
#[cfg(unix)]
|
|
||||||
{
|
|
||||||
use std::os::unix::process::CommandExt;
|
|
||||||
// SAFETY: `setpgid` is async-signal-safe and only touches the child
|
|
||||||
// before exec.
|
|
||||||
unsafe {
|
|
||||||
command.pre_exec(|| {
|
|
||||||
if libc::setpgid(0, 0) != 0 {
|
|
||||||
return Err(std::io::Error::last_os_error());
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut child = command.spawn().map_err(|err| ViewError::CoreSpawn {
|
|
||||||
detail: format!("spawn {}: {err}", self.bin.display()),
|
|
||||||
})?;
|
|
||||||
let stdout = child.stdout.take().expect("piped stdout");
|
|
||||||
let stderr = child.stderr.take().expect("piped stderr");
|
|
||||||
let stdout_thread = std::thread::spawn(move || read_all(stdout));
|
|
||||||
let stderr_thread = std::thread::spawn(move || read_all(stderr));
|
|
||||||
|
|
||||||
let deadline = Instant::now() + timeout;
|
|
||||||
let status = loop {
|
|
||||||
match child.try_wait() {
|
|
||||||
Ok(Some(status)) => break status,
|
|
||||||
Ok(None) => {
|
|
||||||
if Instant::now() >= deadline {
|
|
||||||
kill_process_tree(&mut child);
|
|
||||||
let _ = child.wait();
|
|
||||||
let _ = stdout_thread.join();
|
|
||||||
let _ = stderr_thread.join();
|
|
||||||
return Err(ViewError::CoreTimeout {
|
|
||||||
detail: format!(
|
|
||||||
"core did not finish within {}s and was killed",
|
|
||||||
timeout.as_secs()
|
|
||||||
),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
std::thread::sleep(Duration::from_millis(10));
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
let _ = child.kill();
|
|
||||||
return Err(ViewError::CoreSpawn {
|
|
||||||
detail: format!("wait for {}: {err}", self.bin.display()),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
let outcome = run_bounded(&self.bin, args, cwd, &budget, None)?;
|
||||||
let stdout_bytes = stdout_thread.join().unwrap_or_default();
|
if outcome.timed_out {
|
||||||
let stderr_bytes = stderr_thread.join().unwrap_or_default();
|
return Err(ViewError::CoreTimeout {
|
||||||
let stdout = String::from_utf8_lossy(&stdout_bytes).to_string();
|
detail: format!(
|
||||||
let stderr = String::from_utf8_lossy(&stderr_bytes).to_string();
|
"core did not finish within {}s and was killed",
|
||||||
|
timeout.as_secs()
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let stdout = outcome.stdout.text_lossy();
|
||||||
|
let stderr = outcome.stderr.text_lossy();
|
||||||
Ok(ExecOutput {
|
Ok(ExecOutput {
|
||||||
exit_code: status.code().unwrap_or(-1),
|
exit_code: outcome.exit_code.unwrap_or(-1),
|
||||||
stdout_bytes,
|
stdout_bytes: outcome.stdout.bytes,
|
||||||
stdout,
|
stdout,
|
||||||
stderr,
|
stderr,
|
||||||
})
|
})
|
||||||
@@ -515,86 +466,88 @@ struct ExecOutput {
|
|||||||
stderr: String,
|
stderr: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Kill the core and every descendant in its process group (Unix), or just the
|
|
||||||
/// direct child elsewhere. Never leaves a runaway subprocess behind.
|
|
||||||
fn kill_process_tree(child: &mut std::process::Child) {
|
|
||||||
#[cfg(unix)]
|
|
||||||
{
|
|
||||||
let pid = child.id() as i32;
|
|
||||||
if pid > 0 {
|
|
||||||
// SAFETY: negative pid targets the process group created by
|
|
||||||
// pre_exec(setpgid); ESRCH is harmless when it already exited.
|
|
||||||
unsafe {
|
|
||||||
libc::kill(-pid, libc::SIGKILL);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let _ = child.kill();
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_all(mut reader: impl Read) -> Vec<u8> {
|
|
||||||
let mut bytes = Vec::new();
|
|
||||||
let _ = reader.read_to_end(&mut bytes);
|
|
||||||
bytes
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Build the base `check` arguments. The caller appends `--emit <path>` and
|
/// Build the base `check` arguments. The caller appends `--emit <path>` and
|
||||||
/// optionally `--refs`; this function exists so the argv shape is unit-testable.
|
/// optionally `--refs`; this function exists so the argv shape is unit-testable.
|
||||||
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()]
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Build `run` arguments from an already user-approved request.
|
/// Common explicit flags shared by `run` and `call`. Budgets are always sent
|
||||||
pub fn build_run_args(entry: &Path, trace_path: &Path, options: &RunOptions) -> Vec<OsString> {
|
/// explicitly by the execution controller (RFC-VIEW-0002 §6.7).
|
||||||
let mut args = vec![
|
fn append_common_args(args: &mut Vec<OsString>, trace_path: &Path, options: &RunOptions) {
|
||||||
OsString::from("run"),
|
|
||||||
entry.as_os_str().to_os_string(),
|
|
||||||
OsString::from("--mode"),
|
|
||||||
OsString::from(options.mode.as_str()),
|
|
||||||
OsString::from("--json"),
|
|
||||||
OsString::from("--trace-file"),
|
|
||||||
trace_path.as_os_str().to_os_string(),
|
|
||||||
];
|
|
||||||
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(options.mode.as_str()));
|
||||||
|
args.push(OsString::from("--json"));
|
||||||
|
args.push(OsString::from("--trace-file"));
|
||||||
|
args.push(trace_path.as_os_str().to_os_string());
|
||||||
for glob in &options.grants.allow_read {
|
for glob in &options.grants.allow_read {
|
||||||
push_pair(&mut args, "--allow-read", glob);
|
push_pair(args, "--allow-read", glob);
|
||||||
}
|
}
|
||||||
for glob in &options.grants.allow_write {
|
for glob in &options.grants.allow_write {
|
||||||
push_pair(&mut args, "--allow-write", glob);
|
push_pair(args, "--allow-write", glob);
|
||||||
}
|
}
|
||||||
for host in &options.grants.allow_net {
|
for host in &options.grants.allow_net {
|
||||||
push_pair(&mut args, "--allow-net", host);
|
push_pair(args, "--allow-net", host);
|
||||||
}
|
}
|
||||||
for name in &options.grants.allow_env {
|
for name in &options.grants.allow_env {
|
||||||
push_pair(&mut args, "--allow-env", name);
|
push_pair(args, "--allow-env", name);
|
||||||
}
|
}
|
||||||
for program in &options.grants.allow_process {
|
for program in &options.grants.allow_process {
|
||||||
push_pair(&mut args, "--allow-process", program);
|
push_pair(args, "--allow-process", program);
|
||||||
}
|
}
|
||||||
if options.grants.allow_random {
|
if options.grants.allow_random {
|
||||||
args.push(OsString::from("--allow-random"));
|
args.push(OsString::from("--allow-random"));
|
||||||
}
|
}
|
||||||
if let Some(fuel) = options.fuel {
|
if let Some(fuel) = options.fuel {
|
||||||
push_pair(&mut args, "--fuel", &fuel.to_string());
|
push_pair(args, "--fuel", &fuel.to_string());
|
||||||
}
|
}
|
||||||
if let Some(stack) = options.stack {
|
if let Some(stack) = options.stack {
|
||||||
push_pair(&mut args, "--stack", &stack.to_string());
|
push_pair(args, "--stack", &stack.to_string());
|
||||||
}
|
}
|
||||||
if let Some(max_output) = options.max_output {
|
if let Some(max_output) = options.max_output {
|
||||||
push_pair(&mut args, "--max-output", &max_output.to_string());
|
push_pair(args, "--max-output", &max_output.to_string());
|
||||||
}
|
}
|
||||||
if let Some(timeout) = options.timeout_seconds {
|
if let Some(timeout) = options.timeout_seconds {
|
||||||
push_pair(&mut args, "--timeout", &timeout.to_string());
|
push_pair(args, "--timeout", &timeout.to_string());
|
||||||
}
|
}
|
||||||
if let Some(max_events) = options.trace_max_events {
|
if let Some(max_events) = options.trace_max_events {
|
||||||
push_pair(&mut args, "--trace-max-events", &max_events.to_string());
|
push_pair(args, "--trace-max-events", &max_events.to_string());
|
||||||
}
|
}
|
||||||
if let Some(max_bytes) = options.trace_max_bytes {
|
if let Some(max_bytes) = options.trace_max_bytes {
|
||||||
push_pair(&mut args, "--trace-max-bytes", &max_bytes.to_string());
|
push_pair(args, "--trace-max-bytes", &max_bytes.to_string());
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build `run` arguments from an already user-approved request.
|
||||||
|
pub fn build_run_args(entry: &Path, trace_path: &Path, options: &RunOptions) -> Vec<OsString> {
|
||||||
|
let mut args = vec![OsString::from("run"), entry.as_os_str().to_os_string()];
|
||||||
|
append_common_args(&mut args, trace_path, options);
|
||||||
|
args
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build `call` arguments: explicit argv, one `--arg name=expression` per
|
||||||
|
/// parameter, never a shell string and never client-supplied flags.
|
||||||
|
pub fn build_call_args(
|
||||||
|
entry: &Path,
|
||||||
|
function: &str,
|
||||||
|
arguments: &[(String, String)],
|
||||||
|
trace_path: &Path,
|
||||||
|
options: &RunOptions,
|
||||||
|
) -> Vec<OsString> {
|
||||||
|
let mut args = vec![
|
||||||
|
OsString::from("call"),
|
||||||
|
entry.as_os_str().to_os_string(),
|
||||||
|
OsString::from(function),
|
||||||
|
];
|
||||||
|
for (name, expression) in arguments {
|
||||||
|
args.push(OsString::from("--arg"));
|
||||||
|
args.push(OsString::from(format!("{name}={expression}")));
|
||||||
|
}
|
||||||
|
append_common_args(&mut args, trace_path, options);
|
||||||
args
|
args
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -655,6 +608,145 @@ fn summarize_stderr(stderr: &str) -> String {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// `marqdo view verify`: static Analysis/source binding check. Never executes.
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
use crate::cli::{RuntimeOpts, VerifyArgs};
|
||||||
|
use crate::protocol::analysis_v2;
|
||||||
|
|
||||||
|
pub fn verify_command(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32> {
|
||||||
|
let path = args
|
||||||
|
.path
|
||||||
|
.clone()
|
||||||
|
.or_else(|| opts.path.clone())
|
||||||
|
.unwrap_or_else(|| std::path::PathBuf::from("."));
|
||||||
|
let project = Project::open(&path)?;
|
||||||
|
let entry = project.entry().relative.clone();
|
||||||
|
let source_bytes = project.read_source(&entry)?;
|
||||||
|
let source = String::from_utf8(source_bytes).map_err(|err| ViewError::Io {
|
||||||
|
detail: format!("{entry} is not valid UTF-8: {err}"),
|
||||||
|
})?;
|
||||||
|
let source_index = crate::reader::source::SourceIndex::new(&source);
|
||||||
|
|
||||||
|
let client = CoreClient::from_env(opts.marqdo_bin.as_deref())?;
|
||||||
|
let core_version = client.negotiate()?;
|
||||||
|
let response = client.check(
|
||||||
|
&project,
|
||||||
|
&entry,
|
||||||
|
&CheckOptions {
|
||||||
|
refs: args.refs,
|
||||||
|
timeout: None,
|
||||||
|
},
|
||||||
|
)?;
|
||||||
|
let check = match response {
|
||||||
|
CheckResponse {
|
||||||
|
success: false,
|
||||||
|
diagnostics,
|
||||||
|
exit_code,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
let first = diagnostics
|
||||||
|
.first()
|
||||||
|
.map(|diagnostic| {
|
||||||
|
format!(
|
||||||
|
"{}: {}",
|
||||||
|
if diagnostic.code.is_empty() {
|
||||||
|
"diagnostic"
|
||||||
|
} else {
|
||||||
|
&diagnostic.code
|
||||||
|
},
|
||||||
|
diagnostic.message
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.unwrap_or_else(|| "no diagnostic detail".to_string());
|
||||||
|
return Err(ViewError::AnalysisFailed {
|
||||||
|
detail: format!(
|
||||||
|
"`marqdo check` failed with exit code {exit_code} ({} diagnostic(s)); first: {first}",
|
||||||
|
diagnostics.len()
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
CheckResponse {
|
||||||
|
analysis: Some(check),
|
||||||
|
..
|
||||||
|
} => check,
|
||||||
|
CheckResponse { analysis: None, .. } => {
|
||||||
|
return Err(ViewError::AnalysisFailed {
|
||||||
|
detail: "`marqdo check` succeeded but emitted no Analysis".to_string(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let verified = analysis_v2::verify_analysis(
|
||||||
|
&check.analysis_bytes,
|
||||||
|
&source,
|
||||||
|
&source_index,
|
||||||
|
entry.as_str(),
|
||||||
|
)?;
|
||||||
|
let projection = &verified.projection;
|
||||||
|
|
||||||
|
if args.json {
|
||||||
|
let doc = serde_json::json!({
|
||||||
|
"schema": "marqdo.view-verify",
|
||||||
|
"schema_version": 1,
|
||||||
|
"ok": true,
|
||||||
|
"core": {
|
||||||
|
"version": core_version.version.to_string(),
|
||||||
|
"supported_range": tool_v1::PRODUCT_RANGE,
|
||||||
|
},
|
||||||
|
"analysis": {
|
||||||
|
"schema": "marqdo.analysis",
|
||||||
|
"schema_version": tool_v1::ANALYSIS_PROTOCOL,
|
||||||
|
"digest": projection.analysis_digest,
|
||||||
|
"producer_version": projection.producer_version,
|
||||||
|
"markdown_profile": projection.markdown_profile,
|
||||||
|
"functions": projection.functions.len(),
|
||||||
|
"units": projection.units.len(),
|
||||||
|
"diagnostics": projection.diagnostics.len(),
|
||||||
|
},
|
||||||
|
"project": {
|
||||||
|
"root_id": projection.project_root_id,
|
||||||
|
"identity_kind": projection.identity_kind,
|
||||||
|
"lock_digest": projection.lock_digest,
|
||||||
|
"stdlib_version": projection.stdlib_version,
|
||||||
|
},
|
||||||
|
"document": {
|
||||||
|
"relative_path": entry.as_str(),
|
||||||
|
"module_id": projection.module_id,
|
||||||
|
"source_digest": projection.source_digest,
|
||||||
|
"source_digest_matches": true,
|
||||||
|
},
|
||||||
|
"result": "PASS",
|
||||||
|
"executed": false,
|
||||||
|
"note": "Static verification only; the document was not executed.",
|
||||||
|
});
|
||||||
|
println!(
|
||||||
|
"{}",
|
||||||
|
serde_json::to_string_pretty(&doc).unwrap_or_else(|_| "{}".to_string())
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
println!(
|
||||||
|
"core: marqdo {} (supported {})",
|
||||||
|
core_version.version,
|
||||||
|
tool_v1::PRODUCT_RANGE
|
||||||
|
);
|
||||||
|
println!(
|
||||||
|
"project: {} ({})",
|
||||||
|
projection.project_root_id, projection.identity_kind
|
||||||
|
);
|
||||||
|
println!("document: {entry}");
|
||||||
|
println!(
|
||||||
|
"analysis: schema=marqdo.analysis v2 modules={} functions={} digest={}",
|
||||||
|
projection.modules.len(),
|
||||||
|
projection.functions.len(),
|
||||||
|
projection.analysis_digest
|
||||||
|
);
|
||||||
|
println!("source digest: match");
|
||||||
|
println!("result: PASS (static only; document not executed)");
|
||||||
|
}
|
||||||
|
Ok(0)
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|||||||
@@ -42,6 +42,24 @@ pub enum ViewError {
|
|||||||
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.
|
||||||
|
RunInvalid { detail: String },
|
||||||
|
/// The entry document has no resolvable `main`; View never substitutes one.
|
||||||
|
NoEntryFunction { detail: String },
|
||||||
|
/// A page/SSE/POST requires a valid local session cookie.
|
||||||
|
SessionRequired { detail: String },
|
||||||
|
/// Another explicit run is already active; View allows one at a time.
|
||||||
|
RunBusy { detail: String },
|
||||||
|
/// The same client request id was reused with a different payload.
|
||||||
|
RunConflict { detail: String },
|
||||||
|
/// The requested run id is unknown, expired or belongs to another session.
|
||||||
|
RunNotFound { detail: String },
|
||||||
|
/// Bounded capture of CLI stdout/stderr/JSON/trace exceeded the budget.
|
||||||
|
OutputLimit { detail: String },
|
||||||
|
/// The CLI exited but its `--json` document was missing or invalid.
|
||||||
|
CoreProtocol { detail: String },
|
||||||
|
/// More than two concurrent SSE observers for one job.
|
||||||
|
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.
|
||||||
@@ -67,6 +85,15 @@ impl ViewError {
|
|||||||
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",
|
||||||
|
ViewError::RunInvalid { .. } => "view.run_invalid",
|
||||||
|
ViewError::NoEntryFunction { .. } => "view.no_entry_function",
|
||||||
|
ViewError::SessionRequired { .. } => "view.session_required",
|
||||||
|
ViewError::RunBusy { .. } => "view.run_busy",
|
||||||
|
ViewError::RunConflict { .. } => "view.run_conflict",
|
||||||
|
ViewError::RunNotFound { .. } => "view.run_not_found",
|
||||||
|
ViewError::OutputLimit { .. } => "view.output_limit",
|
||||||
|
ViewError::CoreProtocol { .. } => "view.core_protocol",
|
||||||
|
ViewError::SseBusy { .. } => "view.sse_busy",
|
||||||
ViewError::Io { .. } => "view.io",
|
ViewError::Io { .. } => "view.io",
|
||||||
ViewError::Unsupported { .. } => "view.unsupported",
|
ViewError::Unsupported { .. } => "view.unsupported",
|
||||||
}
|
}
|
||||||
@@ -80,7 +107,16 @@ impl ViewError {
|
|||||||
| ViewError::PathForbidden { .. }
|
| ViewError::PathForbidden { .. }
|
||||||
| ViewError::BindDenied { .. }
|
| ViewError::BindDenied { .. }
|
||||||
| ViewError::SourceSpanInvalid { .. }
|
| ViewError::SourceSpanInvalid { .. }
|
||||||
| ViewError::Unsupported { .. } => ExitClass::Argument,
|
| ViewError::Unsupported { .. }
|
||||||
|
| ViewError::RunInvalid { .. }
|
||||||
|
| ViewError::NoEntryFunction { .. }
|
||||||
|
| ViewError::SessionRequired { .. }
|
||||||
|
| ViewError::RunBusy { .. }
|
||||||
|
| ViewError::RunConflict { .. }
|
||||||
|
| ViewError::RunNotFound { .. }
|
||||||
|
| ViewError::OutputLimit { .. }
|
||||||
|
| ViewError::CoreProtocol { .. }
|
||||||
|
| ViewError::SseBusy { .. } => ExitClass::Argument,
|
||||||
_ => ExitClass::Runtime,
|
_ => ExitClass::Runtime,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -118,6 +154,15 @@ impl ViewError {
|
|||||||
"view.resource_limit" => "超过配置的资源上限。",
|
"view.resource_limit" => "超过配置的资源上限。",
|
||||||
"view.core_spawn" => "无法启动冻结核心。",
|
"view.core_spawn" => "无法启动冻结核心。",
|
||||||
"view.core_timeout" => "冻结核心执行超时,已终止。",
|
"view.core_timeout" => "冻结核心执行超时,已终止。",
|
||||||
|
"view.run_invalid" => "运行请求未通过校验(目标、参数、模式或授权不合法)。",
|
||||||
|
"view.no_entry_function" => "文档没有可调用的 main;请改选一个 H2 Exec 函数。",
|
||||||
|
"view.session_required" => "缺少或过期的本地会话;请先打开阅读页面。",
|
||||||
|
"view.run_busy" => "已有一次运行正在进行;本版本每个 View 服务只允许一个任务。",
|
||||||
|
"view.run_conflict" => "同一客户端请求 ID 携带了不同内容,拒绝执行。",
|
||||||
|
"view.run_not_found" => "运行任务不存在、已过期或不属于当前会话。",
|
||||||
|
"view.core_protocol" => "冻结核心退出但未给出合法的 --json 结果。",
|
||||||
|
"view.sse_busy" => "该运行任务的 SSE 观察连接超过上限,请稍后重试。",
|
||||||
|
"view.output_limit" => "执行输出超过 View 的接收上限,已停止接收。",
|
||||||
"view.io" => "本地 I/O 失败。",
|
"view.io" => "本地 I/O 失败。",
|
||||||
"view.unsupported" => "当前版本不支持该功能。",
|
"view.unsupported" => "当前版本不支持该功能。",
|
||||||
_ => "View 内部错误。",
|
_ => "View 内部错误。",
|
||||||
@@ -162,6 +207,15 @@ impl ViewError {
|
|||||||
| ViewError::ResourceLimit { detail }
|
| ViewError::ResourceLimit { detail }
|
||||||
| ViewError::CoreSpawn { detail }
|
| ViewError::CoreSpawn { detail }
|
||||||
| ViewError::CoreTimeout { detail }
|
| ViewError::CoreTimeout { detail }
|
||||||
|
| ViewError::RunInvalid { detail }
|
||||||
|
| ViewError::NoEntryFunction { detail }
|
||||||
|
| ViewError::SessionRequired { detail }
|
||||||
|
| ViewError::RunBusy { detail }
|
||||||
|
| ViewError::RunConflict { detail }
|
||||||
|
| ViewError::RunNotFound { detail }
|
||||||
|
| ViewError::OutputLimit { detail }
|
||||||
|
| ViewError::CoreProtocol { detail }
|
||||||
|
| ViewError::SseBusy { detail }
|
||||||
| ViewError::Io { detail }
|
| ViewError::Io { detail }
|
||||||
| ViewError::Unsupported { detail } => detail,
|
| ViewError::Unsupported { detail } => detail,
|
||||||
ViewError::SourceMismatch { expected, actual } => {
|
ViewError::SourceMismatch { expected, actual } => {
|
||||||
|
|||||||
@@ -0,0 +1,430 @@
|
|||||||
|
//! 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
|
||||||
|
//! only carries four event types 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::sync::mpsc::{self, Receiver, SyncSender, TrySendError};
|
||||||
|
|
||||||
|
/// In-memory replay buffer per job (RFC-VIEW-0002 §6.5).
|
||||||
|
pub const EVENT_RING_CAPACITY: usize = 128;
|
||||||
|
/// Heartbeat comment cadence; not an event and does not use a sequence number.
|
||||||
|
pub const HEARTBEAT_INTERVAL_SECS: u64 = 15;
|
||||||
|
pub const HEARTBEAT_FRAME: &str = ": heartbeat\n\n";
|
||||||
|
|
||||||
|
pub const EVENTS_SCHEMA: &str = "marqdo.view-run-events";
|
||||||
|
pub const EVENTS_SCHEMA_VERSION: u32 = 1;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum RunState {
|
||||||
|
Accepted,
|
||||||
|
Running,
|
||||||
|
CancelRequested,
|
||||||
|
Succeeded,
|
||||||
|
Failed,
|
||||||
|
Cancelled,
|
||||||
|
TimedOut,
|
||||||
|
Unavailable,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RunState {
|
||||||
|
pub fn data_value(&self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
RunState::Accepted => "accepted",
|
||||||
|
RunState::Running => "running",
|
||||||
|
RunState::CancelRequested => "cancel_requested",
|
||||||
|
RunState::Succeeded => "succeeded",
|
||||||
|
RunState::Failed => "failed",
|
||||||
|
RunState::Cancelled => "cancelled",
|
||||||
|
RunState::TimedOut => "timed_out",
|
||||||
|
RunState::Unavailable => "unavailable",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn label(&self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
RunState::Accepted => "已接受",
|
||||||
|
RunState::Running => "运行中",
|
||||||
|
RunState::CancelRequested => "正在取消",
|
||||||
|
RunState::Succeeded => "成功",
|
||||||
|
RunState::Failed => "失败",
|
||||||
|
RunState::Cancelled => "已取消",
|
||||||
|
RunState::TimedOut => "超时",
|
||||||
|
RunState::Unavailable => "不可用",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_terminal(&self) -> bool {
|
||||||
|
matches!(
|
||||||
|
self,
|
||||||
|
RunState::Succeeded
|
||||||
|
| RunState::Failed
|
||||||
|
| RunState::Cancelled
|
||||||
|
| RunState::TimedOut
|
||||||
|
| RunState::Unavailable
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum EventKind {
|
||||||
|
State,
|
||||||
|
Complete,
|
||||||
|
Error,
|
||||||
|
Snapshot,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventKind {
|
||||||
|
pub fn sse_name(&self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
EventKind::State => "run.state",
|
||||||
|
EventKind::Complete => "run.complete",
|
||||||
|
EventKind::Error => "run.error",
|
||||||
|
EventKind::Snapshot => "run.snapshot",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct RunEvent {
|
||||||
|
pub seq: u64,
|
||||||
|
pub kind: EventKind,
|
||||||
|
pub state: RunState,
|
||||||
|
pub at: String,
|
||||||
|
/// Safe parsed CLI result summary (never raw HTML/innerHTML material).
|
||||||
|
pub result: Option<serde_json::Value>,
|
||||||
|
/// Verified Trace v2 summary, only after digest/binding checks.
|
||||||
|
pub trace: Option<serde_json::Value>,
|
||||||
|
/// `{code, message}` for terminal failures.
|
||||||
|
pub error: Option<serde_json::Value>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RunEvent {
|
||||||
|
pub fn data(&self, run_id: &str) -> serde_json::Value {
|
||||||
|
let mut data = serde_json::json!({
|
||||||
|
"schema": EVENTS_SCHEMA,
|
||||||
|
"schema_version": EVENTS_SCHEMA_VERSION,
|
||||||
|
"run_id": run_id,
|
||||||
|
"seq": self.seq,
|
||||||
|
"state": self.state.data_value(),
|
||||||
|
"at": self.at,
|
||||||
|
});
|
||||||
|
if let Some(result) = &self.result {
|
||||||
|
data["result"] = result.clone();
|
||||||
|
}
|
||||||
|
if let Some(trace) = &self.trace {
|
||||||
|
data["trace"] = trace.clone();
|
||||||
|
}
|
||||||
|
if let Some(error) = &self.error {
|
||||||
|
data["error"] = error.clone();
|
||||||
|
}
|
||||||
|
data
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One SSE frame with `event:`, numeric `id` equal to `data.seq`, and JSON
|
||||||
|
/// data on a single line.
|
||||||
|
pub fn to_sse(&self, run_id: &str) -> String {
|
||||||
|
let data = serde_json::to_string(&self.data(run_id))
|
||||||
|
.unwrap_or_else(|_| "{\"schema\":\"marqdo.view-run-events\"}".to_string());
|
||||||
|
format!(
|
||||||
|
"event: {}\nid: {}\ndata: {}\n\n",
|
||||||
|
self.kind.sse_name(),
|
||||||
|
self.seq,
|
||||||
|
data
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Result of subscribing: the frames to write first, then a bounded receiver.
|
||||||
|
pub struct Subscription {
|
||||||
|
pub replay: Vec<RunEvent>,
|
||||||
|
pub receiver: Receiver<RunEvent>,
|
||||||
|
/// True when the stream must be closed after writing replay (terminal job).
|
||||||
|
pub terminal: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Per-job event log. Callers provide the locking (the controller holds the job
|
||||||
|
/// lock while publishing and while snapshot+subscribe to avoid races).
|
||||||
|
pub struct EventLog {
|
||||||
|
next_seq: u64,
|
||||||
|
ring: VecDeque<RunEvent>,
|
||||||
|
subscribers: Vec<SyncSender<RunEvent>>,
|
||||||
|
last_state: RunState,
|
||||||
|
terminal_snapshot: Option<RunEvent>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for EventLog {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventLog {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
next_seq: 1,
|
||||||
|
ring: VecDeque::with_capacity(EVENT_RING_CAPACITY),
|
||||||
|
subscribers: Vec::new(),
|
||||||
|
last_state: RunState::Accepted,
|
||||||
|
terminal_snapshot: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn next_event(&mut self, kind: EventKind, state: RunState) -> RunEvent {
|
||||||
|
let event = RunEvent {
|
||||||
|
seq: self.next_seq,
|
||||||
|
kind,
|
||||||
|
state,
|
||||||
|
at: utc_now(),
|
||||||
|
result: None,
|
||||||
|
trace: None,
|
||||||
|
error: None,
|
||||||
|
};
|
||||||
|
self.next_seq += 1;
|
||||||
|
self.last_state = state;
|
||||||
|
event
|
||||||
|
}
|
||||||
|
|
||||||
|
fn record(&mut self, mut event: RunEvent) -> RunEvent {
|
||||||
|
if self.ring.len() == EVENT_RING_CAPACITY {
|
||||||
|
self.ring.pop_front();
|
||||||
|
}
|
||||||
|
// A single terminal event is the only one ever stored as the final
|
||||||
|
// snapshot; once terminal, later publishes are ignored by the caller.
|
||||||
|
if event.state.is_terminal() {
|
||||||
|
event.kind = match event.kind {
|
||||||
|
EventKind::State => EventKind::State,
|
||||||
|
other => other,
|
||||||
|
};
|
||||||
|
self.terminal_snapshot = Some(event.clone());
|
||||||
|
}
|
||||||
|
self.ring.push_back(event.clone());
|
||||||
|
self.subscribers
|
||||||
|
.retain(|sender| match sender.try_send(event.clone()) {
|
||||||
|
Ok(()) => true,
|
||||||
|
Err(TrySendError::Full(_)) | Err(TrySendError::Disconnected(_)) => false,
|
||||||
|
});
|
||||||
|
event
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn publish_state(&mut self, state: RunState) -> RunEvent {
|
||||||
|
let event = self.next_event(EventKind::State, state);
|
||||||
|
self.record(event)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn publish_complete(
|
||||||
|
&mut self,
|
||||||
|
result: serde_json::Value,
|
||||||
|
trace: Option<serde_json::Value>,
|
||||||
|
) -> RunEvent {
|
||||||
|
let mut event = self.next_event(EventKind::Complete, RunState::Succeeded);
|
||||||
|
event.result = Some(result);
|
||||||
|
event.trace = trace;
|
||||||
|
self.record(event)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn publish_error(
|
||||||
|
&mut self,
|
||||||
|
state: RunState,
|
||||||
|
code: &str,
|
||||||
|
message: &str,
|
||||||
|
result: Option<serde_json::Value>,
|
||||||
|
trace: Option<serde_json::Value>,
|
||||||
|
) -> RunEvent {
|
||||||
|
let mut event = self.next_event(EventKind::Error, state);
|
||||||
|
event.error = Some(serde_json::json!({
|
||||||
|
"code": code,
|
||||||
|
"message": message,
|
||||||
|
}));
|
||||||
|
event.result = result;
|
||||||
|
event.trace = trace;
|
||||||
|
self.record(event)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn last_state(&self) -> RunState {
|
||||||
|
self.last_state
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn terminal(&self) -> bool {
|
||||||
|
self.terminal_snapshot.is_some() || self.last_state.is_terminal()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn oldest_seq(&self) -> Option<u64> {
|
||||||
|
self.ring.front().map(|event| event.seq)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build the current snapshot frame from the latest known state (and the
|
||||||
|
/// terminal result when present). A snapshot always carries the newest
|
||||||
|
/// sequence number, never a fake historical one.
|
||||||
|
pub fn snapshot_event(&mut self) -> RunEvent {
|
||||||
|
// A snapshot always takes a fresh sequence so a client that already saw
|
||||||
|
// earlier frames never mistakes it for a duplicate and skips it.
|
||||||
|
let seq = self.next_seq;
|
||||||
|
self.next_seq += 1;
|
||||||
|
if let Some(terminal) = &self.terminal_snapshot {
|
||||||
|
let mut snapshot = terminal.clone();
|
||||||
|
snapshot.seq = seq;
|
||||||
|
snapshot.kind = EventKind::Snapshot;
|
||||||
|
return snapshot;
|
||||||
|
}
|
||||||
|
RunEvent {
|
||||||
|
seq,
|
||||||
|
kind: EventKind::Snapshot,
|
||||||
|
state: self.last_state,
|
||||||
|
at: utc_now(),
|
||||||
|
result: None,
|
||||||
|
trace: None,
|
||||||
|
error: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Atomically build replay and register the subscriber. The caller must
|
||||||
|
/// hold the job lock (controller's Mutex) across this call.
|
||||||
|
pub fn subscribe(&mut self, last_event_id: Option<u64>) -> Subscription {
|
||||||
|
let (sender, receiver) = mpsc::sync_channel(EVENT_RING_CAPACITY);
|
||||||
|
let terminal = self.terminal();
|
||||||
|
let mut replay: Vec<RunEvent> = Vec::new();
|
||||||
|
|
||||||
|
match last_event_id {
|
||||||
|
Some(cursor) => {
|
||||||
|
let oldest = self.oldest_seq().unwrap_or(self.next_seq);
|
||||||
|
let last = self.next_seq.saturating_sub(1);
|
||||||
|
if cursor > last || cursor + 1 < oldest {
|
||||||
|
// Too old (already evicted) or forged: synchronise with one
|
||||||
|
// authoritative snapshot instead of a discontinuous history.
|
||||||
|
replay.push(self.snapshot_event());
|
||||||
|
} else {
|
||||||
|
replay.extend(self.ring.iter().filter(|event| event.seq > cursor).cloned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
replay.push(self.snapshot_event());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !terminal {
|
||||||
|
self.subscribers.push(sender);
|
||||||
|
}
|
||||||
|
Subscription {
|
||||||
|
replay,
|
||||||
|
receiver,
|
||||||
|
terminal,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Minimal RFC3339 UTC timestamp without a date/time dependency.
|
||||||
|
pub fn utc_now() -> String {
|
||||||
|
let now = std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.unwrap_or_default();
|
||||||
|
format_utc(now.as_secs())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn format_utc(epoch_secs: u64) -> String {
|
||||||
|
let days = (epoch_secs / 86_400) as i64;
|
||||||
|
let seconds = epoch_secs % 86_400;
|
||||||
|
let (year, month, day) = civil_from_days(days);
|
||||||
|
format!(
|
||||||
|
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
|
||||||
|
seconds / 3600,
|
||||||
|
(seconds % 3600) / 60,
|
||||||
|
seconds % 60
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Howard Hinnant's `civil_from_days`, valid for the Unix epoch range.
|
||||||
|
fn civil_from_days(days: i64) -> (i64, u32, u32) {
|
||||||
|
let z = days + 719_468;
|
||||||
|
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
|
||||||
|
let doe = z - era * 146_097;
|
||||||
|
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
|
||||||
|
let y = yoe + era * 400;
|
||||||
|
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||||
|
let mp = (5 * doy + 2) / 153;
|
||||||
|
let d = doy - (153 * mp + 2) / 5 + 1;
|
||||||
|
let m = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||||
|
(if m <= 2 { y + 1 } else { y }, m as u32, d as u32)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn states_have_stable_wire_values_and_terminals() {
|
||||||
|
assert_eq!(RunState::CancelRequested.data_value(), "cancel_requested");
|
||||||
|
assert!(!RunState::CancelRequested.is_terminal());
|
||||||
|
for state in [
|
||||||
|
RunState::Succeeded,
|
||||||
|
RunState::Failed,
|
||||||
|
RunState::Cancelled,
|
||||||
|
RunState::TimedOut,
|
||||||
|
RunState::Unavailable,
|
||||||
|
] {
|
||||||
|
assert!(state.is_terminal());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn frames_have_event_id_and_matching_data_seq() {
|
||||||
|
let mut log = EventLog::new();
|
||||||
|
let event = log.publish_state(RunState::Running);
|
||||||
|
let frame = event.to_sse("run-1");
|
||||||
|
assert!(frame.starts_with("event: run.state\n"));
|
||||||
|
assert!(frame.contains(&format!("id: {}", event.seq)));
|
||||||
|
let data_line = frame
|
||||||
|
.lines()
|
||||||
|
.find(|line| line.starts_with("data: "))
|
||||||
|
.expect("data line");
|
||||||
|
let data: serde_json::Value =
|
||||||
|
serde_json::from_str(data_line.trim_start_matches("data: ")).expect("json");
|
||||||
|
assert_eq!(data["seq"], event.seq);
|
||||||
|
assert_eq!(data["run_id"], "run-1");
|
||||||
|
assert_eq!(data["state"], "running");
|
||||||
|
assert_eq!(data["schema"], EVENTS_SCHEMA);
|
||||||
|
assert_eq!(data["schema_version"], 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ring_is_bounded_and_old_cursor_gets_snapshot() {
|
||||||
|
let mut log = EventLog::new();
|
||||||
|
for _ in 0..(EVENT_RING_CAPACITY + 40) {
|
||||||
|
log.publish_state(RunState::Running);
|
||||||
|
}
|
||||||
|
assert_eq!(log.ring.len(), EVENT_RING_CAPACITY);
|
||||||
|
let subscription = log.subscribe(Some(1));
|
||||||
|
assert_eq!(subscription.replay.len(), 1);
|
||||||
|
assert_eq!(subscription.replay[0].kind, EventKind::Snapshot);
|
||||||
|
assert!(!subscription.terminal);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn terminal_job_replays_snapshot_and_closes() {
|
||||||
|
let mut log = EventLog::new();
|
||||||
|
log.publish_state(RunState::Running);
|
||||||
|
log.publish_complete(serde_json::json!({"success": true}), None);
|
||||||
|
let subscription = log.subscribe(None);
|
||||||
|
assert!(subscription.terminal);
|
||||||
|
assert_eq!(subscription.replay[0].kind, EventKind::Snapshot);
|
||||||
|
assert_eq!(subscription.replay[0].state, RunState::Succeeded);
|
||||||
|
assert!(subscription.replay[0].result.is_some());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn utc_formatting_is_stable() {
|
||||||
|
assert_eq!(format_utc(0), "1970-01-01T00:00:00Z");
|
||||||
|
assert_eq!(format_utc(1_700_000_000), "2023-11-14T22:13:20Z");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn newest_cursor_replays_only_new_events() {
|
||||||
|
let mut log = EventLog::new();
|
||||||
|
let first = log.publish_state(RunState::Accepted);
|
||||||
|
let second = log.publish_state(RunState::Running);
|
||||||
|
let subscription = log.subscribe(Some(first.seq));
|
||||||
|
assert_eq!(subscription.replay.len(), 1);
|
||||||
|
assert_eq!(subscription.replay[0].seq, second.seq);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
//! Execution layer: the only path from an explicit user request to a Core
|
||||||
|
//! subprocess.
|
||||||
|
//!
|
||||||
|
//! `DocumentService` and the renderer never depend on this module; only the
|
||||||
|
//! `POST /api/runs` server handler can reach it (RFC-VIEW-0002 §5.1).
|
||||||
|
//!
|
||||||
|
//! - `request`: schema/target/parameter/mode/grant validation
|
||||||
|
//! - `process`: the one cancellable Core process adapter with bounded capture
|
||||||
|
//! - `events`: bounded, sequenced View-owned run events and SSE frames
|
||||||
|
//! - `controller`: single-job lifecycle, dedupe, cancel, Trace binding
|
||||||
|
|
||||||
|
pub mod controller;
|
||||||
|
pub mod events;
|
||||||
|
pub mod process;
|
||||||
|
pub mod request;
|
||||||
@@ -0,0 +1,293 @@
|
|||||||
|
//! The one cancellable CLI process adapter.
|
||||||
|
//!
|
||||||
|
//! Every explicit run/call is spawned here as an explicit argv array (never a
|
||||||
|
//! shell), in its own process group, with bounded stdout/stderr capture and a
|
||||||
|
//! View-owned wall-clock cap that does not rely on the Core terminating itself
|
||||||
|
//! (RFC-VIEW-0002 §6.7).
|
||||||
|
//!
|
||||||
|
//! The adapter is also used by `core_client` for read-only `check`/`--version`
|
||||||
|
//! calls so there is exactly one process-spawning implementation in View.
|
||||||
|
|
||||||
|
use crate::error::{ViewError, ViewResult};
|
||||||
|
use std::ffi::OsString;
|
||||||
|
use std::io::Read;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::process::{Child, Command, Stdio};
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
/// Default stdout/JSON budget (4 MiB, RFC-VIEW-0002 §6.7).
|
||||||
|
pub const MAX_STDOUT_BYTES: usize = 4 * 1024 * 1024;
|
||||||
|
/// Default stderr budget retained for display.
|
||||||
|
pub const MAX_STDERR_BYTES: usize = 64 * 1024;
|
||||||
|
/// Grace period between SIGTERM and SIGKILL when cancelling.
|
||||||
|
pub const CANCEL_GRACE: Duration = Duration::from_secs(2);
|
||||||
|
/// Poll interval for child state/cancel/wall-clock checks.
|
||||||
|
const POLL: Duration = Duration::from_millis(20);
|
||||||
|
|
||||||
|
/// Execution budgets sent to the Core and enforced again by View.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ProcessBudget {
|
||||||
|
/// View-owned wall clock. Always <= the Core `--timeout` value.
|
||||||
|
pub wall_clock: Duration,
|
||||||
|
pub max_stdout: usize,
|
||||||
|
pub max_stderr: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for ProcessBudget {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
wall_clock: Duration::from_secs(30),
|
||||||
|
max_stdout: MAX_STDOUT_BYTES,
|
||||||
|
max_stderr: MAX_STDERR_BYTES,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One bounded stream capture. Reading continues past the cap (so the child
|
||||||
|
/// never blocks on a full pipe) but retained bytes stay bounded.
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct Captured {
|
||||||
|
pub bytes: Vec<u8>,
|
||||||
|
pub total: usize,
|
||||||
|
pub truncated: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Captured {
|
||||||
|
pub fn text_lossy(&self) -> String {
|
||||||
|
String::from_utf8_lossy(&self.bytes).to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ProcessOutcome {
|
||||||
|
pub exit_code: Option<i32>,
|
||||||
|
pub stdout: Captured,
|
||||||
|
pub stderr: Captured,
|
||||||
|
pub cancelled: bool,
|
||||||
|
pub timed_out: bool,
|
||||||
|
pub duration: Duration,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProcessOutcome {
|
||||||
|
pub fn status_ok(&self) -> bool {
|
||||||
|
self.exit_code == Some(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Spawn one Core process and wait for it with bounded capture, optional
|
||||||
|
/// cancellation and a hard wall-clock cap. Never uses a shell.
|
||||||
|
pub fn run_bounded(
|
||||||
|
bin: &Path,
|
||||||
|
args: &[OsString],
|
||||||
|
cwd: &Path,
|
||||||
|
budget: &ProcessBudget,
|
||||||
|
cancel: Option<Arc<AtomicBool>>,
|
||||||
|
) -> ViewResult<ProcessOutcome> {
|
||||||
|
run_bounded_with_hook(bin, args, cwd, budget, cancel, Box::new(|| {}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Same as [`run_bounded`], with a hook invoked exactly once **after** the
|
||||||
|
/// child process was successfully spawned (used to publish `running`).
|
||||||
|
pub fn run_bounded_with_hook(
|
||||||
|
bin: &Path,
|
||||||
|
args: &[OsString],
|
||||||
|
cwd: &Path,
|
||||||
|
budget: &ProcessBudget,
|
||||||
|
cancel: Option<Arc<AtomicBool>>,
|
||||||
|
on_spawn: Box<dyn FnOnce() + Send>,
|
||||||
|
) -> ViewResult<ProcessOutcome> {
|
||||||
|
let started = Instant::now();
|
||||||
|
let mut command = Command::new(bin);
|
||||||
|
command
|
||||||
|
.args(args)
|
||||||
|
.current_dir(cwd)
|
||||||
|
.stdin(Stdio::null())
|
||||||
|
.stdout(Stdio::piped())
|
||||||
|
.stderr(Stdio::piped());
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::process::CommandExt;
|
||||||
|
// SAFETY: async-signal-safe child-only setup before exec.
|
||||||
|
unsafe {
|
||||||
|
command.pre_exec(|| {
|
||||||
|
if libc::setpgid(0, 0) != 0 {
|
||||||
|
return Err(std::io::Error::last_os_error());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut child = command.spawn().map_err(|err| ViewError::CoreSpawn {
|
||||||
|
detail: format!("spawn {}: {err}", bin.display()),
|
||||||
|
})?;
|
||||||
|
on_spawn();
|
||||||
|
let stdout = child.stdout.take().expect("piped stdout");
|
||||||
|
let stderr = child.stderr.take().expect("piped stderr");
|
||||||
|
let stdout_cap = budget.max_stdout;
|
||||||
|
let stderr_cap = budget.max_stderr;
|
||||||
|
let stdout_thread = std::thread::spawn(move || read_bounded(stdout, stdout_cap));
|
||||||
|
let stderr_thread = std::thread::spawn(move || read_bounded(stderr, stderr_cap));
|
||||||
|
|
||||||
|
let deadline = started + budget.wall_clock;
|
||||||
|
let mut cancelled = false;
|
||||||
|
let mut timed_out = false;
|
||||||
|
let mut cancel_sent: Option<Instant> = None;
|
||||||
|
let status = loop {
|
||||||
|
match child.try_wait() {
|
||||||
|
Ok(Some(status)) => break status,
|
||||||
|
Ok(None) => {}
|
||||||
|
Err(err) => {
|
||||||
|
terminate_group(&mut child);
|
||||||
|
return Err(ViewError::CoreSpawn {
|
||||||
|
detail: format!("wait for {}: {err}", bin.display()),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(flag) = cancel.as_deref() {
|
||||||
|
if flag.load(Ordering::SeqCst) && cancel_sent.is_none() {
|
||||||
|
cancel_sent = Some(Instant::now());
|
||||||
|
signal_group(child.id(), libc::SIGTERM);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(since) = cancel_sent {
|
||||||
|
if since.elapsed() >= CANCEL_GRACE {
|
||||||
|
signal_group(child.id(), libc::SIGKILL);
|
||||||
|
cancelled = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if Instant::now() >= deadline {
|
||||||
|
signal_group(child.id(), libc::SIGKILL);
|
||||||
|
timed_out = true;
|
||||||
|
}
|
||||||
|
if cancelled || timed_out {
|
||||||
|
// Keep polling until the child is reaped; the group may take a
|
||||||
|
// moment to die after SIGKILL.
|
||||||
|
std::thread::sleep(POLL);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
std::thread::sleep(POLL);
|
||||||
|
};
|
||||||
|
|
||||||
|
// A cancel request that raced with a natural exit must not fabricate a
|
||||||
|
// cancellation: only a kill initiated by this adapter marks it cancelled.
|
||||||
|
if cancel_sent.is_some() && !cancelled && !timed_out {
|
||||||
|
cancelled = false;
|
||||||
|
}
|
||||||
|
let stdout = stdout_thread.join().unwrap_or_default();
|
||||||
|
let stderr = stderr_thread.join().unwrap_or_default();
|
||||||
|
Ok(ProcessOutcome {
|
||||||
|
exit_code: status.code(),
|
||||||
|
stdout,
|
||||||
|
stderr,
|
||||||
|
cancelled,
|
||||||
|
timed_out,
|
||||||
|
duration: started.elapsed(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Signal a whole process group (Unix) or only the child elsewhere.
|
||||||
|
pub fn signal_group(pid: u32, signal: i32) {
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
let pgid = pid as i32;
|
||||||
|
if pgid > 0 {
|
||||||
|
// SAFETY: negative pid targets the group created by setpgid; ESRCH
|
||||||
|
// is harmless when the process already exited.
|
||||||
|
unsafe {
|
||||||
|
libc::kill(-pgid, signal);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
{
|
||||||
|
let _ = (pid, signal);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn terminate_group(child: &mut Child) {
|
||||||
|
signal_group(child.id(), kill_signal());
|
||||||
|
let _ = child.kill();
|
||||||
|
let _ = child.wait();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn kill_signal() -> i32 {
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
libc::SIGKILL
|
||||||
|
}
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
{
|
||||||
|
9
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_bounded(mut reader: impl Read, cap: usize) -> Captured {
|
||||||
|
let mut captured = Captured::default();
|
||||||
|
let mut buffer = [0u8; 16 * 1024];
|
||||||
|
loop {
|
||||||
|
match reader.read(&mut buffer) {
|
||||||
|
Ok(0) => break,
|
||||||
|
Ok(read) => {
|
||||||
|
captured.total += read;
|
||||||
|
let remaining = cap.saturating_sub(captured.bytes.len());
|
||||||
|
if remaining > 0 {
|
||||||
|
let take = remaining.min(read);
|
||||||
|
captured.bytes.extend_from_slice(&buffer[..take]);
|
||||||
|
}
|
||||||
|
if captured.total > cap {
|
||||||
|
captured.truncated = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(err) if err.kind() == std::io::ErrorKind::Interrupted => continue,
|
||||||
|
Err(_) => break,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
captured
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bounded_capture_keeps_limit_and_drains() {
|
||||||
|
let captured = read_bounded(std::io::Cursor::new(vec![b'x'; 100]), 10);
|
||||||
|
assert_eq!(captured.bytes.len(), 10);
|
||||||
|
assert_eq!(captured.total, 100);
|
||||||
|
assert!(captured.truncated);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn default_budget_matches_rfc() {
|
||||||
|
let budget = ProcessBudget::default();
|
||||||
|
assert_eq!(budget.wall_clock, Duration::from_secs(30));
|
||||||
|
assert_eq!(budget.max_stdout, 4 * 1024 * 1024);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn cancellation_terminates_the_process_group() {
|
||||||
|
let flag = Arc::new(AtomicBool::new(true));
|
||||||
|
let start = Instant::now();
|
||||||
|
let outcome = run_bounded(
|
||||||
|
Path::new("/bin/sleep"),
|
||||||
|
&[OsString::from("30")],
|
||||||
|
Path::new("/"),
|
||||||
|
&ProcessBudget {
|
||||||
|
wall_clock: Duration::from_secs(20),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
Some(flag),
|
||||||
|
)
|
||||||
|
.expect("spawn sleep");
|
||||||
|
assert_ne!(
|
||||||
|
outcome.exit_code,
|
||||||
|
Some(0),
|
||||||
|
"cancel must not look successful"
|
||||||
|
);
|
||||||
|
assert!(start.elapsed() < Duration::from_secs(10));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,594 @@
|
|||||||
|
//! 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
|
||||||
|
//! from Analysis v2, constant parameter expressions, the exact Analysis digest
|
||||||
|
//! 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
|
||||||
|
//! cwd, flags, a binary path or shell text.
|
||||||
|
|
||||||
|
use crate::core_client::Grants;
|
||||||
|
use crate::error::{ViewError, ViewResult};
|
||||||
|
use crate::protocol::analysis_v2::SemanticProjection;
|
||||||
|
use crate::reader::source::SafeRelativePath;
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
/// Bounded request body size accepted before JSON parsing (RFC §6.8).
|
||||||
|
pub const MAX_RUN_BODY_BYTES: usize = 64 * 1024;
|
||||||
|
pub const MAX_PARAMETERS: usize = 32;
|
||||||
|
pub const MAX_EXPRESSION_CHARS: usize = 4096;
|
||||||
|
pub const MAX_GRANT_GLOBS: usize = 16;
|
||||||
|
pub const MAX_GRANT_CHARS: usize = 256;
|
||||||
|
pub const MAX_CLIENT_REQUEST_ID_CHARS: usize = 128;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct RunRequest {
|
||||||
|
pub document: String,
|
||||||
|
pub target: RunTarget,
|
||||||
|
#[serde(default)]
|
||||||
|
pub parameters: Vec<ParameterInput>,
|
||||||
|
pub analysis_digest: String,
|
||||||
|
#[serde(default = "default_mode")]
|
||||||
|
pub mode: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub grants: GrantRequest,
|
||||||
|
pub client_request_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_mode() -> String {
|
||||||
|
"pure".to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
#[serde(tag = "kind", deny_unknown_fields)]
|
||||||
|
pub enum RunTarget {
|
||||||
|
#[serde(rename = "entry")]
|
||||||
|
Entry,
|
||||||
|
#[serde(rename = "function")]
|
||||||
|
Function { function_id: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct ParameterInput {
|
||||||
|
pub name: String,
|
||||||
|
pub expression: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct GrantRequest {
|
||||||
|
#[serde(default)]
|
||||||
|
pub read: Vec<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub write: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum RunMode {
|
||||||
|
Pure,
|
||||||
|
Project,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RunMode {
|
||||||
|
pub fn as_str(&self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
RunMode::Pure => "pure",
|
||||||
|
RunMode::Project => "project",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A request that passed schema/size/path/mode/grant validation, before the
|
||||||
|
/// read-only `check` and Analysis-digest step performed by the controller.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ValidatedRequest {
|
||||||
|
pub document: SafeRelativePath,
|
||||||
|
pub target: RunTarget,
|
||||||
|
pub parameters: Vec<ParameterInput>,
|
||||||
|
pub analysis_digest: String,
|
||||||
|
pub mode: RunMode,
|
||||||
|
pub grants: Grants,
|
||||||
|
pub client_request_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The target resolved against the entry module's verified Analysis.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum ExecutionTarget {
|
||||||
|
/// `marqdo run FILE` (entry `main`).
|
||||||
|
Entry,
|
||||||
|
/// `marqdo call FILE NAME --arg ...`.
|
||||||
|
Function {
|
||||||
|
/// Canonical or unique local name accepted by the frozen CLI.
|
||||||
|
cli_name: String,
|
||||||
|
/// Display label from Analysis (`namespace.local_name` when present).
|
||||||
|
label: String,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One target/parameter plan for the Core argv builder.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ExecutionPlan {
|
||||||
|
pub document: SafeRelativePath,
|
||||||
|
pub target: ExecutionTarget,
|
||||||
|
pub arguments: Vec<(String, String)>,
|
||||||
|
pub mode: RunMode,
|
||||||
|
pub grants: Grants,
|
||||||
|
pub analysis_digest: String,
|
||||||
|
pub client_request_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ValidatedRequest {
|
||||||
|
/// Resolve the target and parameter names against the verified entry-module
|
||||||
|
/// Analysis. Never accepts a dependency-module function id (RFC §6.3).
|
||||||
|
pub fn plan_against(self, projection: &SemanticProjection) -> ViewResult<ExecutionPlan> {
|
||||||
|
let target = match &self.target {
|
||||||
|
RunTarget::Entry => {
|
||||||
|
if resolve_main(projection).is_none() {
|
||||||
|
return Err(ViewError::NoEntryFunction {
|
||||||
|
detail: format!(
|
||||||
|
"{} 没有可调用的 main;请从函数面板选择一个 H2 Exec 函数",
|
||||||
|
self.document
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
ExecutionTarget::Entry
|
||||||
|
}
|
||||||
|
RunTarget::Function { function_id } => {
|
||||||
|
let function = projection
|
||||||
|
.functions
|
||||||
|
.iter()
|
||||||
|
.find(|function| &function.id == function_id)
|
||||||
|
.ok_or_else(|| ViewError::RunInvalid {
|
||||||
|
detail: format!(
|
||||||
|
"function_id {function_id:?} 不在当前入口模块可调用函数中;依赖模块函数不能作为 call 目标"
|
||||||
|
),
|
||||||
|
})?;
|
||||||
|
let canonical = canonical_name(&function.id, &projection.module_id);
|
||||||
|
let cli_name = if unique_local_name(projection, &function.local_name, &function.id)
|
||||||
|
{
|
||||||
|
function.local_name.clone()
|
||||||
|
} else {
|
||||||
|
canonical.clone()
|
||||||
|
};
|
||||||
|
let label = canonical;
|
||||||
|
validate_parameters(&self.parameters, projection, &function.id)?;
|
||||||
|
ExecutionTarget::Function { cli_name, label }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Ok(ExecutionPlan {
|
||||||
|
document: self.document,
|
||||||
|
target,
|
||||||
|
arguments: self
|
||||||
|
.parameters
|
||||||
|
.into_iter()
|
||||||
|
.map(|parameter| (parameter.name, parameter.expression))
|
||||||
|
.collect(),
|
||||||
|
mode: self.mode,
|
||||||
|
grants: self.grants,
|
||||||
|
analysis_digest: self.analysis_digest,
|
||||||
|
client_request_id: self.client_request_id,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse and validate the raw request against fixed limits. Does not touch the
|
||||||
|
/// file system or the Core; the controller performs the read-only check next.
|
||||||
|
pub fn validate_request(body: &[u8]) -> ViewResult<ValidatedRequest> {
|
||||||
|
if body.len() > MAX_RUN_BODY_BYTES {
|
||||||
|
return Err(ViewError::RunInvalid {
|
||||||
|
detail: format!("运行请求体超过 {MAX_RUN_BODY_BYTES} 字节上限"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let request: RunRequest =
|
||||||
|
serde_json::from_slice(body).map_err(|err| ViewError::RunInvalid {
|
||||||
|
detail: format!("运行请求不是合法的 marqdo.view-run-request v1 JSON: {err}"),
|
||||||
|
})?;
|
||||||
|
|
||||||
|
validate_client_request_id(&request.client_request_id)?;
|
||||||
|
validate_digest(&request.analysis_digest)?;
|
||||||
|
let document = SafeRelativePath::parse(&request.document)?;
|
||||||
|
if !document.as_str().ends_with(".mq.md") {
|
||||||
|
return Err(ViewError::RunInvalid {
|
||||||
|
detail: "运行目标必须是受控项目根内的 .mq.md 文档".to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
match &request.target {
|
||||||
|
RunTarget::Entry => {}
|
||||||
|
RunTarget::Function { function_id } => {
|
||||||
|
if function_id.is_empty()
|
||||||
|
|| function_id.len() > 512
|
||||||
|
|| function_id.chars().any(|ch| ch.is_control() || ch == '\0')
|
||||||
|
{
|
||||||
|
return Err(ViewError::RunInvalid {
|
||||||
|
detail: "function_id 必须来自 Analysis v2 且长度为 1..=512".to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if request.parameters.len() > MAX_PARAMETERS {
|
||||||
|
return Err(ViewError::RunInvalid {
|
||||||
|
detail: format!("参数数量超过 {MAX_PARAMETERS} 个上限"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
for parameter in &request.parameters {
|
||||||
|
validate_parameter_name(¶meter.name)?;
|
||||||
|
validate_expression(¶meter.expression)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let (mode, grants) = validate_mode_and_grants(&request.mode, &request.grants)?;
|
||||||
|
|
||||||
|
Ok(ValidatedRequest {
|
||||||
|
document,
|
||||||
|
target: request.target,
|
||||||
|
parameters: request.parameters,
|
||||||
|
analysis_digest: request.analysis_digest,
|
||||||
|
mode,
|
||||||
|
grants,
|
||||||
|
client_request_id: request.client_request_id,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_client_request_id(value: &str) -> ViewResult<()> {
|
||||||
|
if value.is_empty()
|
||||||
|
|| value.chars().count() > MAX_CLIENT_REQUEST_ID_CHARS
|
||||||
|
|| !value
|
||||||
|
.chars()
|
||||||
|
.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.' | ':'))
|
||||||
|
{
|
||||||
|
return Err(ViewError::RunInvalid {
|
||||||
|
detail: format!(
|
||||||
|
"client_request_id 必须是不透明的 ASCII 标识(1..={MAX_CLIENT_REQUEST_ID_CHARS},字母/数字/-_ .:)"
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_digest(value: &str) -> ViewResult<()> {
|
||||||
|
let Some(hex) = value.strip_prefix("sha256:") else {
|
||||||
|
return Err(ViewError::RunInvalid {
|
||||||
|
detail: "analysis_digest 必须以 sha256: 开头".to_string(),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
if hex.len() != 64 || !hex.chars().all(|ch| ch.is_ascii_hexdigit()) {
|
||||||
|
return Err(ViewError::RunInvalid {
|
||||||
|
detail: "analysis_digest 必须是 sha256:<64 hex>".to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_parameter_name(name: &str) -> ViewResult<()> {
|
||||||
|
if name.is_empty()
|
||||||
|
|| name.chars().count() > 128
|
||||||
|
|| name
|
||||||
|
.chars()
|
||||||
|
.any(|ch| ch.is_control() || ch.is_whitespace() || ch == '=')
|
||||||
|
{
|
||||||
|
return Err(ViewError::RunInvalid {
|
||||||
|
detail: "参数名必须非空且不包含控制字符、空白或 '='".to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_expression(expression: &str) -> ViewResult<()> {
|
||||||
|
if expression.trim().is_empty() {
|
||||||
|
return Err(ViewError::RunInvalid {
|
||||||
|
detail: "参数 expression 不能为空;View 不做隐式裸文本转字符串".to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if expression.chars().count() > MAX_EXPRESSION_CHARS {
|
||||||
|
return Err(ViewError::RunInvalid {
|
||||||
|
detail: format!("参数 expression 超过 {MAX_EXPRESSION_CHARS} 字符上限"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if expression.chars().any(|ch| ch == '\0' || ch.is_control()) {
|
||||||
|
return Err(ViewError::RunInvalid {
|
||||||
|
detail: "参数 expression 不能包含 NUL/控制字符".to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_mode_and_grants(mode: &str, grants: &GrantRequest) -> ViewResult<(RunMode, Grants)> {
|
||||||
|
match mode {
|
||||||
|
"pure" => {
|
||||||
|
if !grants.read.is_empty() || !grants.write.is_empty() {
|
||||||
|
return Err(ViewError::RunInvalid {
|
||||||
|
detail: "pure 模式不能携带 fs grants;需要文件访问时请显式选择 project 模式"
|
||||||
|
.to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok((RunMode::Pure, Grants::default()))
|
||||||
|
}
|
||||||
|
"project" => {
|
||||||
|
if grants.read.len() > MAX_GRANT_GLOBS || grants.write.len() > MAX_GRANT_GLOBS {
|
||||||
|
return Err(ViewError::RunInvalid {
|
||||||
|
detail: format!("每个 fs grant 列表最多 {MAX_GRANT_GLOBS} 项"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let mut seen = std::collections::BTreeSet::new();
|
||||||
|
let mut validated = Grants::default();
|
||||||
|
for glob in &grants.read {
|
||||||
|
validate_glob(glob)?;
|
||||||
|
if seen.insert(glob.clone()) {
|
||||||
|
validated.allow_read.push(glob.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut seen_write = std::collections::BTreeSet::new();
|
||||||
|
for glob in &grants.write {
|
||||||
|
validate_glob(glob)?;
|
||||||
|
if seen_write.insert(glob.clone()) {
|
||||||
|
validated.allow_write.push(glob.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok((RunMode::Project, validated))
|
||||||
|
}
|
||||||
|
"strict" => Err(ViewError::RunDenied {
|
||||||
|
detail: "strict 模式不在 View 首版提供;请改用 pure/project 或直接在终端运行 CLI"
|
||||||
|
.to_string(),
|
||||||
|
}),
|
||||||
|
other => Err(ViewError::RunDenied {
|
||||||
|
detail: format!(
|
||||||
|
"模式 {other:?} 不在首版支持范围;仅允许 pure 或受控 project(fs read/write)"
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_glob(glob: &str) -> ViewResult<()> {
|
||||||
|
if glob.is_empty() || glob.chars().count() > MAX_GRANT_CHARS {
|
||||||
|
return Err(ViewError::RunInvalid {
|
||||||
|
detail: format!("fs grant glob 必须为 1..={MAX_GRANT_CHARS} 字符"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if glob.starts_with('/')
|
||||||
|
|| glob.starts_with('\\')
|
||||||
|
|| glob.starts_with('~')
|
||||||
|
|| glob.contains('\\')
|
||||||
|
|| glob.contains('\0')
|
||||||
|
|| glob.chars().any(|ch| ch.is_control())
|
||||||
|
|| glob.split('/').any(|segment| segment == "..")
|
||||||
|
|| glob.contains(':')
|
||||||
|
{
|
||||||
|
return Err(ViewError::RunInvalid {
|
||||||
|
detail: format!(
|
||||||
|
"fs grant {glob:?} 必须是项目根相对 glob(禁止绝对路径、..、反斜杠、盘符/控制字符)"
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolve `main` exactly like the frozen CLI does for `run`: canonical name
|
||||||
|
/// first, then a unique local name. No fallback to any other function.
|
||||||
|
fn resolve_main(projection: &SemanticProjection) -> Option<(String, String)> {
|
||||||
|
if let Some(function) = projection.functions.iter().find(|function| {
|
||||||
|
canonical_name(&function.id, &projection.module_id) == "main"
|
||||||
|
|| function.local_name == "main"
|
||||||
|
}) {
|
||||||
|
return Some((
|
||||||
|
canonical_name(&function.id, &projection.module_id),
|
||||||
|
function.local_name.clone(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unique_local_name(projection: &SemanticProjection, local_name: &str, id: &str) -> bool {
|
||||||
|
let matches = projection
|
||||||
|
.functions
|
||||||
|
.iter()
|
||||||
|
.filter(|function| function.local_name == local_name)
|
||||||
|
.count();
|
||||||
|
if matches == 1 {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
// If several namespaces define the same local name, only the canonical
|
||||||
|
// qualified name is unambiguous; the CLI resolver has the same rule.
|
||||||
|
let canonical = canonical_name(id, &projection.module_id);
|
||||||
|
canonical == local_name
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Analysis v2 function ids are `<module id>::<canonical name>`.
|
||||||
|
pub fn canonical_name(function_id: &str, module_id: &str) -> String {
|
||||||
|
function_id
|
||||||
|
.strip_prefix(&format!("{module_id}::"))
|
||||||
|
.unwrap_or(function_id)
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_parameters(
|
||||||
|
parameters: &[ParameterInput],
|
||||||
|
projection: &SemanticProjection,
|
||||||
|
function_id: &str,
|
||||||
|
) -> ViewResult<()> {
|
||||||
|
let function = projection
|
||||||
|
.functions
|
||||||
|
.iter()
|
||||||
|
.find(|function| function.id == function_id)
|
||||||
|
.ok_or_else(|| ViewError::RunInvalid {
|
||||||
|
detail: "函数在选择后消失,请刷新页面重新选择".to_string(),
|
||||||
|
})?;
|
||||||
|
let mut seen = std::collections::BTreeSet::new();
|
||||||
|
for parameter in parameters {
|
||||||
|
if !function
|
||||||
|
.signature
|
||||||
|
.params
|
||||||
|
.iter()
|
||||||
|
.any(|param| param.name == parameter.name)
|
||||||
|
{
|
||||||
|
return Err(ViewError::RunInvalid {
|
||||||
|
detail: format!(
|
||||||
|
"参数 {:?} 不在函数 {} 的签名中",
|
||||||
|
parameter.name, function.local_name
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if !seen.insert(parameter.name.clone()) {
|
||||||
|
return Err(ViewError::RunInvalid {
|
||||||
|
detail: format!("参数 {:?} 重复提交", parameter.name),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stable digest of the exact request bytes, used for `client_request_id`
|
||||||
|
/// idempotency (same id + same bytes => same run; different bytes => 409).
|
||||||
|
pub fn payload_digest(bytes: &[u8]) -> String {
|
||||||
|
crate::reader::source::sha256_hex(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn projection() -> SemanticProjection {
|
||||||
|
let source = "x".repeat(200);
|
||||||
|
let digest = crate::reader::source::sha256_hex(source.as_bytes());
|
||||||
|
let analysis = serde_json::json!({
|
||||||
|
"schema": "marqdo.analysis",
|
||||||
|
"schema_version": 2,
|
||||||
|
"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": [
|
||||||
|
{"id": "root:t@0.1.0::index.mq.md::main", "unit_id": "u1", "local_name": "main",
|
||||||
|
"namespace": null, "span": {"start": 0, "end": 10}, "heading_span": {"start": 0, "end": 10},
|
||||||
|
"signature": {"kind": "inferred", "params": []}, "body": [], "effects": ["unknown"]},
|
||||||
|
{"id": "root:t@0.1.0::index.mq.md::N.f", "unit_id": "u2", "local_name": "f",
|
||||||
|
"namespace": "N", "span": {"start": 20, "end": 30}, "heading_span": {"start": 20, "end": 30},
|
||||||
|
"signature": {"kind": "explicit", "params": [
|
||||||
|
{"name": "n", "required": true, "type": "Int", "default": null, "span": null}
|
||||||
|
]}, "body": [], "effects": ["unknown"]}
|
||||||
|
],
|
||||||
|
"imports": [], "references": [], "calls": [], "resources": []
|
||||||
|
}],
|
||||||
|
"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]
|
||||||
|
fn rejects_unknown_fields_and_bad_modes() {
|
||||||
|
let base = serde_json::json!({
|
||||||
|
"document": "index.mq.md",
|
||||||
|
"target": {"kind": "entry"},
|
||||||
|
"analysis_digest": format!("sha256:{}", "a".repeat(64)),
|
||||||
|
"mode": "pure",
|
||||||
|
"client_request_id": "req-1"
|
||||||
|
});
|
||||||
|
let mut with_unknown = base.clone();
|
||||||
|
with_unknown["cwd"] = serde_json::json!("/tmp");
|
||||||
|
assert!(validate_request(with_unknown.to_string().as_bytes()).is_err());
|
||||||
|
let mut strict = base.clone();
|
||||||
|
strict["mode"] = serde_json::json!("strict");
|
||||||
|
assert_eq!(
|
||||||
|
validate_request(strict.to_string().as_bytes())
|
||||||
|
.unwrap_err()
|
||||||
|
.code(),
|
||||||
|
"view.run_denied"
|
||||||
|
);
|
||||||
|
let mut project_without_globs = base;
|
||||||
|
project_without_globs["mode"] = serde_json::json!("project");
|
||||||
|
assert!(validate_request(project_without_globs.to_string().as_bytes()).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_absolute_and_parent_globs() {
|
||||||
|
let request = serde_json::json!({
|
||||||
|
"document": "index.mq.md",
|
||||||
|
"target": {"kind": "entry"},
|
||||||
|
"analysis_digest": format!("sha256:{}", "a".repeat(64)),
|
||||||
|
"mode": "project",
|
||||||
|
"grants": {"read": ["../secret"], "write": []},
|
||||||
|
"client_request_id": "req-1"
|
||||||
|
});
|
||||||
|
assert!(validate_request(request.to_string().as_bytes()).is_err());
|
||||||
|
let request = serde_json::json!({
|
||||||
|
"document": "index.mq.md",
|
||||||
|
"target": {"kind": "entry"},
|
||||||
|
"analysis_digest": format!("sha256:{}", "a".repeat(64)),
|
||||||
|
"mode": "project",
|
||||||
|
"grants": {"read": ["/etc/passwd"], "write": []},
|
||||||
|
"client_request_id": "req-1"
|
||||||
|
});
|
||||||
|
assert!(validate_request(request.to_string().as_bytes()).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn canonical_names_and_targets_resolve() {
|
||||||
|
let projection = projection();
|
||||||
|
let request = serde_json::json!({
|
||||||
|
"document": "index.mq.md",
|
||||||
|
"target": {"kind": "function", "function_id": "root:t@0.1.0::index.mq.md::N.f"},
|
||||||
|
"parameters": [{"name": "n", "expression": "5"}],
|
||||||
|
"analysis_digest": format!("sha256:{}", projection.analysis_sha256),
|
||||||
|
"mode": "pure",
|
||||||
|
"client_request_id": "req-2"
|
||||||
|
});
|
||||||
|
let validated = validate_request(request.to_string().as_bytes()).expect("valid");
|
||||||
|
let plan = validated.plan_against(&projection).expect("plan");
|
||||||
|
match plan.target {
|
||||||
|
ExecutionTarget::Function { cli_name, .. } => assert_eq!(cli_name, "f"),
|
||||||
|
ExecutionTarget::Entry => panic!("expected function"),
|
||||||
|
}
|
||||||
|
assert_eq!(plan.arguments, vec![("n".to_string(), "5".to_string())]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn entry_without_main_is_explicitly_rejected() {
|
||||||
|
let mut projection = projection();
|
||||||
|
projection
|
||||||
|
.functions
|
||||||
|
.retain(|function| function.local_name != "main");
|
||||||
|
let request = serde_json::json!({
|
||||||
|
"document": "index.mq.md",
|
||||||
|
"target": {"kind": "entry"},
|
||||||
|
"analysis_digest": format!("sha256:{}", projection.analysis_sha256),
|
||||||
|
"mode": "pure",
|
||||||
|
"client_request_id": "req-3"
|
||||||
|
});
|
||||||
|
let validated = validate_request(request.to_string().as_bytes()).expect("valid");
|
||||||
|
assert_eq!(
|
||||||
|
validated.plan_against(&projection).unwrap_err().code(),
|
||||||
|
"view.no_entry_function"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unknown_parameter_names_are_rejected_before_execution() {
|
||||||
|
let projection = projection();
|
||||||
|
let request = serde_json::json!({
|
||||||
|
"document": "index.mq.md",
|
||||||
|
"target": {"kind": "function", "function_id": "root:t@0.1.0::index.mq.md::N.f"},
|
||||||
|
"parameters": [{"name": "bogus", "expression": "5"}],
|
||||||
|
"analysis_digest": format!("sha256:{}", projection.analysis_sha256),
|
||||||
|
"mode": "pure",
|
||||||
|
"client_request_id": "req-4"
|
||||||
|
});
|
||||||
|
let validated = validate_request(request.to_string().as_bytes()).expect("valid");
|
||||||
|
assert_eq!(
|
||||||
|
validated.plan_against(&projection).unwrap_err().code(),
|
||||||
|
"view.run_invalid"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,15 +1,15 @@
|
|||||||
//! Pure static site export.
|
//! Pure static site export.
|
||||||
//!
|
//!
|
||||||
//! Export uses the same `AppContext::load` (static `check` only) and the same
|
//! Export uses the same `DocumentService::load` (static `check` only) and the same
|
||||||
//! `ReaderRenderer` as Live; it never calls `run`, never starts a provider and
|
//! `ReaderRenderer` as Live; it never calls `run`, never starts a provider and
|
||||||
//! never writes into the source project (RFC-VIEW-0001 §11.3).
|
//! never writes into the source project (RFC-VIEW-0001 §11.3).
|
||||||
|
|
||||||
use crate::app::AppContext;
|
|
||||||
use crate::assets::AssetBundle;
|
|
||||||
use crate::error::{ViewError, ViewResult};
|
use crate::error::{ViewError, ViewResult};
|
||||||
use crate::project::SafeRelativePath;
|
use crate::reader::assemble::DocumentService;
|
||||||
use crate::render::ReaderRenderer;
|
use crate::reader::assets::AssetBundle;
|
||||||
use crate::source_map::sha256_hex;
|
use crate::reader::render::ReaderRenderer;
|
||||||
|
use crate::reader::source::sha256_hex;
|
||||||
|
use crate::reader::source::SafeRelativePath;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
const MANIFEST_SCHEMA: &str = "marqdo.view-export";
|
const MANIFEST_SCHEMA: &str = "marqdo.view-export";
|
||||||
@@ -28,7 +28,7 @@ pub struct ExportSummary {
|
|||||||
pub manifest_sha256: String,
|
pub manifest_sha256: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn export(context: &AppContext, options: &ExportOptions) -> ViewResult<ExportSummary> {
|
pub fn export(context: &DocumentService, options: &ExportOptions) -> ViewResult<ExportSummary> {
|
||||||
let bundle = AssetBundle::get();
|
let bundle = AssetBundle::get();
|
||||||
let renderer = ReaderRenderer::new();
|
let renderer = ReaderRenderer::new();
|
||||||
let root = context.project().root().to_path_buf();
|
let root = context.project().root().to_path_buf();
|
||||||
@@ -89,7 +89,7 @@ pub fn export(context: &AppContext, options: &ExportOptions) -> ViewResult<Expor
|
|||||||
let model = context.load(relative)?;
|
let model = context.load(relative)?;
|
||||||
let depth = relative.as_str().split('/').count();
|
let depth = relative.as_str().split('/').count();
|
||||||
let context =
|
let context =
|
||||||
crate::render::RenderContext::static_export(depth, !options.no_annotations);
|
crate::reader::render::RenderContext::static_export(depth, !options.no_annotations);
|
||||||
let page = renderer.render(&model, &context);
|
let page = renderer.render(&model, &context);
|
||||||
let page_path = pages_dir.join(format!("{}.html", relative.as_str()));
|
let page_path = pages_dir.join(format!("{}.html", relative.as_str()));
|
||||||
if let Some(parent) = page_path.parent() {
|
if let Some(parent) = page_path.parent() {
|
||||||
@@ -119,7 +119,8 @@ pub fn export(context: &AppContext, options: &ExportOptions) -> ViewResult<Expor
|
|||||||
|
|
||||||
// index.html is the same renderer output with site-root depth.
|
// index.html is the same renderer output with site-root depth.
|
||||||
let entry_model = context.load(&entry)?;
|
let entry_model = context.load(&entry)?;
|
||||||
let entry_context = crate::render::RenderContext::static_export(0, !options.no_annotations);
|
let entry_context =
|
||||||
|
crate::reader::render::RenderContext::static_export(0, !options.no_annotations);
|
||||||
let index_page = renderer.render(&entry_model, &entry_context);
|
let index_page = renderer.render(&entry_model, &entry_context);
|
||||||
let index_path = staging.join("index.html");
|
let index_path = staging.join("index.html");
|
||||||
std::fs::write(&index_path, index_page.html.as_bytes())
|
std::fs::write(&index_path, index_page.html.as_bytes())
|
||||||
@@ -145,10 +146,10 @@ pub fn export(context: &AppContext, options: &ExportOptions) -> ViewResult<Expor
|
|||||||
"version": env!("CARGO_PKG_VERSION"),
|
"version": env!("CARGO_PKG_VERSION"),
|
||||||
},
|
},
|
||||||
"compatibility": {
|
"compatibility": {
|
||||||
"marqdo": crate::version::PRODUCT_RANGE,
|
"marqdo": crate::protocol::tool_v1::PRODUCT_RANGE,
|
||||||
"tool_protocol": crate::version::TOOL_PROTOCOL,
|
"tool_protocol": crate::protocol::tool_v1::TOOL_PROTOCOL,
|
||||||
"analysis": crate::version::ANALYSIS_PROTOCOL,
|
"analysis": crate::protocol::tool_v1::ANALYSIS_PROTOCOL,
|
||||||
"trace": crate::version::TRACE_PROTOCOL,
|
"trace": crate::protocol::tool_v1::TRACE_PROTOCOL,
|
||||||
"markdown_profile": "marqdo.md.v1",
|
"markdown_profile": "marqdo.md.v1",
|
||||||
},
|
},
|
||||||
"core_version": entry_model.core_version,
|
"core_version": entry_model.core_version,
|
||||||
|
|||||||
@@ -1,38 +1,73 @@
|
|||||||
//! marqdo-view library: a single package with one presentation pipeline.
|
//! marqdo-view library: one package, one presentation pipeline, one renderer.
|
||||||
//!
|
//!
|
||||||
//! Layer direction (RFC-VIEW-0001 §6.1):
|
//! Dependency direction (RFC-VIEW-0002 §5.1/§5.4):
|
||||||
//! `CLI/Server → Application → Domain → ProtocolAdapter`, and
|
//! `CLI/Server → Reader(assemble) → Protocol(Analysis/Trace) + CoreClient`,
|
||||||
//! `Application → Presentation → Renderer → Assets`.
|
//! and `Reader(model) → Renderer → Assets`. `Execution` may only be reached
|
||||||
//! `main.rs` is only a dispatcher; integration tests and future server code use
|
//! from an explicit `POST /api/runs` handler; page loads and export never form
|
||||||
//! this library so there is never a second renderer or a second parser.
|
//! an execution edge.
|
||||||
|
|
||||||
pub mod app;
|
|
||||||
pub mod assets;
|
|
||||||
pub mod cli;
|
pub mod cli;
|
||||||
|
pub mod config;
|
||||||
pub mod core_client;
|
pub mod core_client;
|
||||||
pub mod document;
|
|
||||||
pub mod error;
|
pub mod error;
|
||||||
|
pub mod execution;
|
||||||
pub mod export;
|
pub mod export;
|
||||||
pub mod presentation;
|
pub mod protocol;
|
||||||
pub mod project;
|
pub mod reader;
|
||||||
pub mod render;
|
|
||||||
pub mod semantic;
|
|
||||||
pub mod server;
|
pub mod server;
|
||||||
pub mod source_map;
|
|
||||||
pub mod trace;
|
|
||||||
pub mod version;
|
|
||||||
|
|
||||||
pub use cli::Cli;
|
pub use cli::Cli;
|
||||||
pub use error::{ViewError, ViewResult};
|
pub use error::{ViewError, ViewResult};
|
||||||
|
|
||||||
|
use cli::{ExportArgs, RuntimeOpts};
|
||||||
|
use export::ExportOptions;
|
||||||
|
use reader::assemble::DocumentService;
|
||||||
|
|
||||||
/// Dispatch a parsed CLI invocation. Returns the process exit code.
|
/// Dispatch a parsed CLI invocation. Returns the process exit code.
|
||||||
pub fn run(cli: Cli) -> ViewResult<i32> {
|
pub fn run(cli: Cli) -> ViewResult<i32> {
|
||||||
let opts = cli.runtime();
|
let opts = cli.runtime();
|
||||||
cli::validate_bind(&opts.host, opts.unsafe_expose)
|
cli::validate_bind(&opts.host, opts.unsafe_expose)
|
||||||
.map_err(|detail| ViewError::BindDenied { detail })?;
|
.map_err(|detail| ViewError::BindDenied { detail })?;
|
||||||
match cli.command {
|
match cli.command {
|
||||||
Some(cli::Command::Verify(args)) => app::verify(&opts, &args),
|
Some(cli::Command::Verify(args)) => core_client::verify_command(&opts, &args),
|
||||||
Some(cli::Command::Export(args)) => app::export(&opts, &args),
|
Some(cli::Command::Export(args)) => export_command(&opts, &args),
|
||||||
None => app::browse(&opts),
|
None => browse_command(&opts),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `marqdo view [PATH]`: open the read-only Live reader. Never executes.
|
||||||
|
fn browse_command(opts: &RuntimeOpts) -> ViewResult<i32> {
|
||||||
|
let path = opts
|
||||||
|
.path
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_else(|| std::path::PathBuf::from("."));
|
||||||
|
let service = DocumentService::open(&path, opts.marqdo_bin.as_deref())?;
|
||||||
|
crate::server::serve(service, opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `marqdo view export PATH --out DIR`: static export through the same Reader
|
||||||
|
/// model. The export path has no execution capability by type (RFC §5.4).
|
||||||
|
fn export_command(opts: &RuntimeOpts, args: &ExportArgs) -> ViewResult<i32> {
|
||||||
|
let path = args
|
||||||
|
.path
|
||||||
|
.clone()
|
||||||
|
.or_else(|| opts.path.clone())
|
||||||
|
.unwrap_or_else(|| std::path::PathBuf::from("."));
|
||||||
|
let service = DocumentService::open(&path, opts.marqdo_bin.as_deref())?;
|
||||||
|
let summary = export::export(
|
||||||
|
&service,
|
||||||
|
&ExportOptions {
|
||||||
|
out: args.out.clone(),
|
||||||
|
no_annotations: args.no_annotations,
|
||||||
|
},
|
||||||
|
)?;
|
||||||
|
println!(
|
||||||
|
"marqdo view export: {} page(s), {} file(s) → {}",
|
||||||
|
summary.pages,
|
||||||
|
summary.files,
|
||||||
|
summary.out.display()
|
||||||
|
);
|
||||||
|
println!("manifest: sha256:{}", summary.manifest_sha256);
|
||||||
|
println!("executed: false (纯静态导出,未运行任何文档)");
|
||||||
|
Ok(0)
|
||||||
|
}
|
||||||
@@ -7,8 +7,7 @@
|
|||||||
//! instead of being pointed at nearby text (RFC-VIEW-0001 §4.3, §8.2).
|
//! instead of being pointed at nearby text (RFC-VIEW-0001 §4.3, §8.2).
|
||||||
|
|
||||||
use crate::error::{ViewError, ViewResult};
|
use crate::error::{ViewError, ViewResult};
|
||||||
use crate::source_map::{sha256_hex, sha256_prefixed, SourceIndex, SourceSpan};
|
use crate::reader::source::{sha256_hex, sha256_prefixed, SourceIndex, SourceSpan};
|
||||||
use crate::version;
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
||||||
@@ -549,12 +548,12 @@ pub fn verify_analysis(
|
|||||||
detail: format!("unexpected Analysis schema {:?}", raw.schema),
|
detail: format!("unexpected Analysis schema {:?}", raw.schema),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if raw.schema_version != version::ANALYSIS_PROTOCOL {
|
if raw.schema_version != crate::protocol::tool_v1::ANALYSIS_PROTOCOL {
|
||||||
return Err(ViewError::ProtocolIncompatible {
|
return Err(ViewError::ProtocolIncompatible {
|
||||||
detail: format!(
|
detail: format!(
|
||||||
"Analysis schema_version {} is not supported (View implements v{})",
|
"Analysis schema_version {} is not supported (View implements v{})",
|
||||||
raw.schema_version,
|
raw.schema_version,
|
||||||
version::ANALYSIS_PROTOCOL
|
crate::protocol::tool_v1::ANALYSIS_PROTOCOL
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
//! Public protocol adapters consumed by View.
|
||||||
|
//!
|
||||||
|
//! These modules are a **consumer** of the published CLI formats, never a
|
||||||
|
//! second publisher or implementation of them (RFC-VIEW-0002 §5.3).
|
||||||
|
|
||||||
|
pub mod analysis_v2;
|
||||||
|
pub mod tool_v1;
|
||||||
|
pub mod trace_v2;
|
||||||
@@ -7,8 +7,8 @@
|
|||||||
//! states, never invented (RFC-VIEW-0001 §4.4, §12).
|
//! states, never invented (RFC-VIEW-0001 §4.4, §12).
|
||||||
|
|
||||||
use crate::error::{ViewError, ViewResult};
|
use crate::error::{ViewError, ViewResult};
|
||||||
use crate::semantic::{ModuleSummary, SemanticProjection};
|
use crate::protocol::analysis_v2::{ModuleSummary, SemanticProjection};
|
||||||
use crate::source_map::{sha256_hex, sha256_prefixed, SourceIndex, SourceSpan};
|
use crate::reader::source::{sha256_hex, sha256_prefixed, SourceIndex, SourceSpan};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
||||||
@@ -343,12 +343,12 @@ pub fn verify_trace(input: TraceVerificationInput<'_>) -> ViewResult<VerifiedRun
|
|||||||
detail: format!("unexpected Trace schema {:?}", raw.schema),
|
detail: format!("unexpected Trace schema {:?}", raw.schema),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if raw.schema_version != crate::version::TRACE_PROTOCOL {
|
if raw.schema_version != crate::protocol::tool_v1::TRACE_PROTOCOL {
|
||||||
return Err(ViewError::ProtocolIncompatible {
|
return Err(ViewError::ProtocolIncompatible {
|
||||||
detail: format!(
|
detail: format!(
|
||||||
"Trace schema_version {} is not supported (View implements v{})",
|
"Trace schema_version {} is not supported (View implements v{})",
|
||||||
raw.schema_version,
|
raw.schema_version,
|
||||||
crate::version::TRACE_PROTOCOL
|
crate::protocol::tool_v1::TRACE_PROTOCOL
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,451 @@
|
|||||||
|
//! Assembly of the one `PresentationModel`.
|
||||||
|
//!
|
||||||
|
//! Merges the raw document, verified Analysis v2, diagnostics and an optional
|
||||||
|
//! verified Trace v2 run into the model; decides stale/revoked semantics here
|
||||||
|
//! and nowhere else (RFC-VIEW-0002 §5.2/§5.4).
|
||||||
|
|
||||||
|
use crate::config::ViewConfig;
|
||||||
|
use crate::protocol::analysis_v2::{CoreDiagnostic, SemanticProjection};
|
||||||
|
use crate::protocol::trace_v2::VerifiedRun;
|
||||||
|
use crate::reader::markdown::{DocumentIdentity, DocumentModel};
|
||||||
|
use crate::reader::model::{
|
||||||
|
Navigation, OutlineEntry, OutlineKind, PresentationModel, SourceStatus,
|
||||||
|
};
|
||||||
|
use crate::reader::source::{sha256_hex, Project, SafeRelativePath};
|
||||||
|
|
||||||
|
use crate::core_client::{CheckOptions, CheckResponse, CoreClient, RawCheckDiagnostic};
|
||||||
|
use crate::error::{ViewError, ViewResult};
|
||||||
|
use crate::protocol::analysis_v2;
|
||||||
|
use crate::protocol::trace_v2;
|
||||||
|
use crate::reader::model::{anchor_for_span, PRESENTATION_VERSION};
|
||||||
|
|
||||||
|
/// Input to the one builder. `analysis` is already protocol/byte verified.
|
||||||
|
pub struct BuildInput<'a> {
|
||||||
|
pub document: DocumentModel,
|
||||||
|
pub analysis: Option<&'a crate::protocol::analysis_v2::VerifiedAnalysis>,
|
||||||
|
pub status: SourceStatus,
|
||||||
|
pub status_note: Option<String>,
|
||||||
|
pub diagnostics: Vec<CoreDiagnostic>,
|
||||||
|
pub navigation: Navigation,
|
||||||
|
pub core_version: Option<String>,
|
||||||
|
pub run: Option<&'a crate::protocol::trace_v2::VerifiedRun>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn build(input: BuildInput<'_>) -> PresentationModel {
|
||||||
|
let BuildInput {
|
||||||
|
mut document,
|
||||||
|
analysis,
|
||||||
|
status,
|
||||||
|
status_note,
|
||||||
|
mut diagnostics,
|
||||||
|
navigation,
|
||||||
|
core_version,
|
||||||
|
run,
|
||||||
|
} = input;
|
||||||
|
|
||||||
|
let semantic = analysis.map(|verified| verified.projection.clone());
|
||||||
|
if let Some(projection) = &semantic {
|
||||||
|
document.identity = DocumentIdentity {
|
||||||
|
project_root_id: projection.project_root_id.clone(),
|
||||||
|
module_id: projection.module_id.clone(),
|
||||||
|
relative_path: projection.relative_path.clone(),
|
||||||
|
source_sha256: projection.source_digest.clone(),
|
||||||
|
};
|
||||||
|
for diagnostic in &projection.diagnostics {
|
||||||
|
if !diagnostics.iter().any(|existing| {
|
||||||
|
existing.code == diagnostic.code
|
||||||
|
&& existing.message == diagnostic.message
|
||||||
|
&& existing.span == diagnostic.span
|
||||||
|
}) {
|
||||||
|
diagnostics.push(diagnostic.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let warnings = semantic
|
||||||
|
.as_ref()
|
||||||
|
.map(|projection| projection.warnings.clone())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let outline = semantic.as_ref().map(build_outline).unwrap_or_default();
|
||||||
|
|
||||||
|
PresentationModel {
|
||||||
|
version: PRESENTATION_VERSION,
|
||||||
|
title: document.title(),
|
||||||
|
document,
|
||||||
|
semantic,
|
||||||
|
source_status: status,
|
||||||
|
status_note,
|
||||||
|
diagnostics,
|
||||||
|
warnings,
|
||||||
|
navigation,
|
||||||
|
outline,
|
||||||
|
core_version,
|
||||||
|
run: run.map(|verified| verified.projection.clone()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build_outline(projection: &SemanticProjection) -> Vec<OutlineEntry> {
|
||||||
|
let mut entries = Vec::new();
|
||||||
|
for function in &projection.functions {
|
||||||
|
let params = if function.signature.params.is_empty() {
|
||||||
|
String::new()
|
||||||
|
} else {
|
||||||
|
function
|
||||||
|
.signature
|
||||||
|
.params
|
||||||
|
.iter()
|
||||||
|
.map(|param| {
|
||||||
|
if param.ty.is_empty() {
|
||||||
|
param.name.clone()
|
||||||
|
} else {
|
||||||
|
format!("{}: {}", param.name, param.ty)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", ")
|
||||||
|
};
|
||||||
|
let detail = if params.is_empty() {
|
||||||
|
"无参数".to_string()
|
||||||
|
} else {
|
||||||
|
format!("params({params})")
|
||||||
|
};
|
||||||
|
entries.push(OutlineEntry {
|
||||||
|
label: function.local_name.clone(),
|
||||||
|
anchor: anchor_for_span(function.heading_span.start, function.heading_span.end),
|
||||||
|
detail,
|
||||||
|
kind: OutlineKind::Function,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
for unit in &projection.units {
|
||||||
|
let kind = match unit.kind {
|
||||||
|
crate::protocol::analysis_v2::UnitKind::Knowledge if unit.level >= 2 => {
|
||||||
|
OutlineKind::Knowledge
|
||||||
|
}
|
||||||
|
crate::protocol::analysis_v2::UnitKind::Section => OutlineKind::Section,
|
||||||
|
_ => continue,
|
||||||
|
};
|
||||||
|
if unit.name.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
entries.push(OutlineEntry {
|
||||||
|
label: unit.name.clone(),
|
||||||
|
anchor: anchor_for_span(unit.span.start, unit.span.end),
|
||||||
|
detail: if unit.level == 2 {
|
||||||
|
"知识单元".to_string()
|
||||||
|
} else {
|
||||||
|
"章节".to_string()
|
||||||
|
},
|
||||||
|
kind,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
entries
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct DocumentService {
|
||||||
|
project: Project,
|
||||||
|
config: ViewConfig,
|
||||||
|
core: Option<CoreClient>,
|
||||||
|
core_version: Option<String>,
|
||||||
|
core_note: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DocumentService {
|
||||||
|
pub fn open(path: &std::path::Path, marqdo_bin: Option<&std::path::Path>) -> ViewResult<Self> {
|
||||||
|
let project = Project::open(path)?;
|
||||||
|
let config = ViewConfig::load(project.root())?;
|
||||||
|
let (core, core_version, core_note) = match CoreClient::from_env(marqdo_bin) {
|
||||||
|
Ok(client) => match client.negotiate() {
|
||||||
|
Ok(version) => (Some(client), Some(version.version.to_string()), None),
|
||||||
|
Err(err) if err.code() == "view.protocol_incompatible" => return Err(err),
|
||||||
|
Err(err) => (None, None, Some(generic_core_note(&err))),
|
||||||
|
},
|
||||||
|
Err(err) if err.code() == "view.core_missing" => {
|
||||||
|
(None, None, Some(generic_core_note(&err)))
|
||||||
|
}
|
||||||
|
Err(err) => return Err(err),
|
||||||
|
};
|
||||||
|
Ok(Self {
|
||||||
|
project,
|
||||||
|
config,
|
||||||
|
core,
|
||||||
|
core_version,
|
||||||
|
core_note,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn project(&self) -> &Project {
|
||||||
|
&self.project
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn config(&self) -> &ViewConfig {
|
||||||
|
&self.config
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn core(&self) -> Option<&CoreClient> {
|
||||||
|
self.core.as_ref()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn core_client(&self) -> Option<&CoreClient> {
|
||||||
|
self.core.as_ref()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn core_version(&self) -> Option<&str> {
|
||||||
|
self.core_version.as_deref()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn core_note(&self) -> Option<&str> {
|
||||||
|
self.core_note.as_deref()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read + parse + (optionally) check one document into the one presentation
|
||||||
|
/// model. Never executes the document.
|
||||||
|
pub fn load(&self, relative: &SafeRelativePath) -> ViewResult<PresentationModel> {
|
||||||
|
self.load_with_run(relative, None)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Same pipeline, optionally attaching an already-verified run projection.
|
||||||
|
/// The run is re-bound to freshly checked Analysis bytes; if the source or
|
||||||
|
/// analysis changed meanwhile the result becomes `STALE` instead of being
|
||||||
|
/// attached to the wrong text.
|
||||||
|
pub fn load_with_run(
|
||||||
|
&self,
|
||||||
|
relative: &SafeRelativePath,
|
||||||
|
run: Option<&VerifiedRun>,
|
||||||
|
) -> ViewResult<PresentationModel> {
|
||||||
|
let source_bytes = self.project.read_source(relative)?;
|
||||||
|
let source = String::from_utf8(source_bytes).map_err(|err| ViewError::Io {
|
||||||
|
detail: format!("{relative} is not valid UTF-8: {err}"),
|
||||||
|
})?;
|
||||||
|
let document = DocumentModel::parse(source, DocumentIdentity::placeholder(relative));
|
||||||
|
let navigation = Navigation::from_project(&self.project, &self.config, relative);
|
||||||
|
|
||||||
|
let mut status = SourceStatus::CoreUnavailable;
|
||||||
|
let mut status_note = self.core_note.clone();
|
||||||
|
let mut diagnostics = Vec::new();
|
||||||
|
let mut verified = None;
|
||||||
|
|
||||||
|
if let Some(client) = &self.core {
|
||||||
|
match client.check(
|
||||||
|
&self.project,
|
||||||
|
relative,
|
||||||
|
&CheckOptions {
|
||||||
|
refs: false,
|
||||||
|
timeout: Some(std::time::Duration::from_secs(30)),
|
||||||
|
},
|
||||||
|
)? {
|
||||||
|
CheckResponse {
|
||||||
|
success: false,
|
||||||
|
diagnostics: raw_diagnostics,
|
||||||
|
exit_code,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
status = SourceStatus::CoreError;
|
||||||
|
status_note = Some(format!(
|
||||||
|
"Core 检查失败(exit {exit_code}):语义标注已撤销,正文仍可阅读。"
|
||||||
|
));
|
||||||
|
diagnostics = raw_diagnostics
|
||||||
|
.iter()
|
||||||
|
.map(|diagnostic| diagnostic_to_view(diagnostic, relative))
|
||||||
|
.collect();
|
||||||
|
}
|
||||||
|
CheckResponse {
|
||||||
|
success: true,
|
||||||
|
analysis: Some(check),
|
||||||
|
..
|
||||||
|
} => match analysis_v2::verify_analysis(
|
||||||
|
&check.analysis_bytes,
|
||||||
|
&document.source,
|
||||||
|
&document.source_index,
|
||||||
|
relative.as_str(),
|
||||||
|
) {
|
||||||
|
Ok(verified_analysis) => {
|
||||||
|
status = SourceStatus::StaticOk;
|
||||||
|
status_note = None;
|
||||||
|
verified = Some(verified_analysis);
|
||||||
|
}
|
||||||
|
Err(err) if err.code() == "view.source_mismatch" => {
|
||||||
|
status = SourceStatus::SourceMismatch;
|
||||||
|
status_note = Some(
|
||||||
|
"当前源码字节与 Analysis 的 source_digest 不一致,语义标注已禁用。"
|
||||||
|
.to_string(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Err(err) if err.code() == "view.protocol_incompatible" => {
|
||||||
|
return Err(err);
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
status = SourceStatus::CoreError;
|
||||||
|
status_note = Some(generic_core_note(&err));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
CheckResponse {
|
||||||
|
success: true,
|
||||||
|
analysis: None,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
status = SourceStatus::CoreError;
|
||||||
|
status_note = Some("Core 声称检查成功但没有产出 Analysis。".to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let attached_run: Option<VerifiedRun> = match (run, verified.as_ref()) {
|
||||||
|
(Some(run), Some(analysis)) => {
|
||||||
|
let expected = format!("sha256:{}", analysis.projection.analysis_sha256);
|
||||||
|
if expected == run.projection.analysis_digest {
|
||||||
|
Some(VerifiedRun {
|
||||||
|
projection: run.projection.clone(),
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
Some(VerifiedRun {
|
||||||
|
projection: trace_v2::stale_projection(
|
||||||
|
&run.projection.analysis_digest,
|
||||||
|
&document.source_index,
|
||||||
|
),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(Some(run), None) => Some(VerifiedRun {
|
||||||
|
projection: trace_v2::stale_projection(
|
||||||
|
&run.projection.analysis_digest,
|
||||||
|
&document.source_index,
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
(None, _) => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(build(BuildInput {
|
||||||
|
document,
|
||||||
|
analysis: verified.as_ref(),
|
||||||
|
status,
|
||||||
|
status_note,
|
||||||
|
diagnostics,
|
||||||
|
navigation,
|
||||||
|
core_version: self.core_version.clone(),
|
||||||
|
run: attached_run.as_ref(),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn generic_core_note(err: &ViewError) -> String {
|
||||||
|
match err.code() {
|
||||||
|
"view.core_missing" => {
|
||||||
|
"未找到可用的冻结核心(MARQDO_BIN);当前为无语义标注的纯 Markdown 阅读模式。"
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
|
"view.analysis_failed" => "Core 检查失败;语义标注已撤销,正文仍可阅读。".to_string(),
|
||||||
|
other => format!("{other}:语义标注不可用,正文仍可阅读。"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn diagnostic_to_view(
|
||||||
|
diagnostic: &RawCheckDiagnostic,
|
||||||
|
relative: &SafeRelativePath,
|
||||||
|
) -> CoreDiagnostic {
|
||||||
|
let belongs_to_entry = diagnostic
|
||||||
|
.module
|
||||||
|
.as_deref()
|
||||||
|
.map(|module| module.ends_with(relative.as_str()))
|
||||||
|
.unwrap_or(true);
|
||||||
|
CoreDiagnostic {
|
||||||
|
module: diagnostic.module.clone(),
|
||||||
|
relative_path: if belongs_to_entry {
|
||||||
|
Some(relative.as_str().to_string())
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
},
|
||||||
|
span: None,
|
||||||
|
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(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One read-only, byte-verified static view of a document, used by explicit
|
||||||
|
/// run validation and Trace binding. Nothing here executes the document.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct StaticDocument {
|
||||||
|
pub relative: SafeRelativePath,
|
||||||
|
pub source: String,
|
||||||
|
pub source_index: crate::reader::source::SourceIndex,
|
||||||
|
pub source_sha256: String,
|
||||||
|
/// Exact bytes written by `marqdo check --emit`.
|
||||||
|
pub analysis_bytes: Vec<u8>,
|
||||||
|
pub analysis_digest: String,
|
||||||
|
pub verified: crate::protocol::analysis_v2::VerifiedAnalysis,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DocumentService {
|
||||||
|
/// Re-run the read-only `check --emit` and verify Analysis v2 against the
|
||||||
|
/// current exact source bytes. This is the only static truth used before an
|
||||||
|
/// explicit run is accepted.
|
||||||
|
pub fn static_document(&self, relative: &SafeRelativePath) -> ViewResult<StaticDocument> {
|
||||||
|
let client = self.core.as_ref().ok_or_else(|| ViewError::RunDenied {
|
||||||
|
detail: "没有可用的冻结核心(MARQDO_BIN);无法验证运行请求".to_string(),
|
||||||
|
})?;
|
||||||
|
let source_bytes = self.project.read_source(relative)?;
|
||||||
|
let source_sha256 = sha256_hex(&source_bytes);
|
||||||
|
let source = String::from_utf8(source_bytes).map_err(|err| ViewError::Io {
|
||||||
|
detail: format!("{relative} is not valid UTF-8: {err}"),
|
||||||
|
})?;
|
||||||
|
let source_index = crate::reader::source::SourceIndex::new(&source);
|
||||||
|
let response = client.check(
|
||||||
|
&self.project,
|
||||||
|
relative,
|
||||||
|
&CheckOptions {
|
||||||
|
refs: false,
|
||||||
|
timeout: Some(std::time::Duration::from_secs(30)),
|
||||||
|
},
|
||||||
|
)?;
|
||||||
|
let check = match response {
|
||||||
|
CheckResponse {
|
||||||
|
success: true,
|
||||||
|
analysis: Some(check),
|
||||||
|
..
|
||||||
|
} => check,
|
||||||
|
CheckResponse {
|
||||||
|
success: false,
|
||||||
|
diagnostics,
|
||||||
|
exit_code,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
let first = diagnostics
|
||||||
|
.first()
|
||||||
|
.map(|diagnostic| format!("{}: {}", diagnostic.code, diagnostic.message))
|
||||||
|
.unwrap_or_else(|| "no diagnostic detail".to_string());
|
||||||
|
return Err(ViewError::AnalysisFailed {
|
||||||
|
detail: format!(
|
||||||
|
"Core 检查失败(exit {exit_code}, {} diagnostic(s));拒绝执行。first: {first}",
|
||||||
|
diagnostics.len()
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
CheckResponse { analysis: None, .. } => {
|
||||||
|
return Err(ViewError::AnalysisFailed {
|
||||||
|
detail: "Core 声称检查成功但没有产出 Analysis".to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let verified = crate::protocol::analysis_v2::verify_analysis(
|
||||||
|
&check.analysis_bytes,
|
||||||
|
&source,
|
||||||
|
&source_index,
|
||||||
|
relative.as_str(),
|
||||||
|
)?;
|
||||||
|
Ok(StaticDocument {
|
||||||
|
relative: relative.clone(),
|
||||||
|
source,
|
||||||
|
source_index,
|
||||||
|
source_sha256,
|
||||||
|
analysis_digest: check.analysis_digest,
|
||||||
|
analysis_bytes: check.analysis_bytes,
|
||||||
|
verified,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
//! asset carries its SHA-256; browser URLs use a hash prefix so a changed asset
|
//! asset carries its SHA-256; browser URLs use a hash prefix so a changed asset
|
||||||
//! can never be confused with a cached older one.
|
//! can never be confused with a cached older one.
|
||||||
|
|
||||||
use crate::source_map::sha256_hex;
|
use crate::reader::source::sha256_hex;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::sync::OnceLock;
|
use std::sync::OnceLock;
|
||||||
|
|
||||||
@@ -45,31 +45,31 @@ impl AssetBundle {
|
|||||||
"reader",
|
"reader",
|
||||||
"css",
|
"css",
|
||||||
"text/css; charset=utf-8",
|
"text/css; charset=utf-8",
|
||||||
include_bytes!("../assets/reader.css"),
|
include_bytes!("../../assets/reader.css"),
|
||||||
),
|
),
|
||||||
asset(
|
asset(
|
||||||
"reader",
|
"reader",
|
||||||
"js",
|
"js",
|
||||||
"text/javascript; charset=utf-8",
|
"text/javascript; charset=utf-8",
|
||||||
include_bytes!("../assets/reader.js"),
|
include_bytes!("../../assets/reader.js"),
|
||||||
),
|
),
|
||||||
asset(
|
asset(
|
||||||
"logo",
|
"logo",
|
||||||
"svg",
|
"svg",
|
||||||
"image/svg+xml",
|
"image/svg+xml",
|
||||||
include_bytes!("../assets/logo.svg"),
|
include_bytes!("../../assets/logo.svg"),
|
||||||
),
|
),
|
||||||
asset(
|
asset(
|
||||||
"blossom",
|
"blossom",
|
||||||
"webp",
|
"webp",
|
||||||
"image/webp",
|
"image/webp",
|
||||||
include_bytes!("../assets/blossom.webp"),
|
include_bytes!("../../assets/blossom.webp"),
|
||||||
),
|
),
|
||||||
asset(
|
asset(
|
||||||
"feather",
|
"feather",
|
||||||
"webp",
|
"webp",
|
||||||
"image/webp",
|
"image/webp",
|
||||||
include_bytes!("../assets/feather.webp"),
|
include_bytes!("../../assets/feather.webp"),
|
||||||
),
|
),
|
||||||
];
|
];
|
||||||
let mut by_hashed_name = HashMap::new();
|
let mut by_hashed_name = HashMap::new();
|
||||||
@@ -183,15 +183,15 @@ mod tests {
|
|||||||
let bundle = AssetBundle::get();
|
let bundle = AssetBundle::get();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
bundle.css().sha256,
|
bundle.css().sha256,
|
||||||
sha256_hex(include_bytes!("../assets/reader.css"))
|
sha256_hex(include_bytes!("../../assets/reader.css"))
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
bundle.js().sha256,
|
bundle.js().sha256,
|
||||||
sha256_hex(include_bytes!("../assets/reader.js"))
|
sha256_hex(include_bytes!("../../assets/reader.js"))
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
bundle.logo().sha256,
|
bundle.logo().sha256,
|
||||||
sha256_hex(include_bytes!("../assets/logo.svg"))
|
sha256_hex(include_bytes!("../../assets/logo.svg"))
|
||||||
);
|
);
|
||||||
assert_eq!(bundle.assets[3].sha256.len(), 64);
|
assert_eq!(bundle.assets[3].sha256.len(), 64);
|
||||||
assert!(bundle.by_path(&bundle.logo().hashed_name()).is_some());
|
assert!(bundle.by_path(&bundle.logo().hashed_name()).is_some());
|
||||||
@@ -6,8 +6,8 @@
|
|||||||
//! No semantic decision (which node is executable) is taken here — that comes
|
//! No semantic decision (which node is executable) is taken here — that comes
|
||||||
//! exclusively from validated Analysis v2 (`semantic.rs`).
|
//! exclusively from validated Analysis v2 (`semantic.rs`).
|
||||||
|
|
||||||
use crate::project::SafeRelativePath;
|
use crate::reader::source::SafeRelativePath;
|
||||||
use crate::source_map::{sha256_hex, SourceIndex, SourceSpan};
|
use crate::reader::source::{sha256_hex, SourceIndex, SourceSpan};
|
||||||
use comrak::nodes::{ListType, NodeValue, Sourcepos, TableAlignment};
|
use comrak::nodes::{ListType, NodeValue, Sourcepos, TableAlignment};
|
||||||
use comrak::{parse_document, Arena, Options};
|
use comrak::{parse_document, Arena, Options};
|
||||||
|
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
//! Reader layer: controlled source access, Markdown rendering, the one
|
||||||
|
//! presentation model, assembly from public protocols, and the one renderer.
|
||||||
|
//!
|
||||||
|
//! Live and Export share every type here; only link policy and interaction
|
||||||
|
//! availability differ (RFC-VIEW-0002 §4.3/§5.4).
|
||||||
|
|
||||||
|
pub mod assemble;
|
||||||
|
pub mod assets;
|
||||||
|
pub mod markdown;
|
||||||
|
pub mod model;
|
||||||
|
pub mod render;
|
||||||
|
pub mod source;
|
||||||
@@ -1,13 +1,14 @@
|
|||||||
//! Presentation model: the one intermediate form between verified domain data
|
//! Presentation model: the one intermediate form between verified domain data
|
||||||
//! and the one `ReaderRenderer`.
|
//! and the one `ReaderRenderer` (RFC-VIEW-0002 §5.2).
|
||||||
//!
|
//!
|
||||||
//! Nothing here spawns processes, builds HTML or parses Markdown semantics. It
|
//! Nothing here spawns processes, builds HTML or parses Markdown semantics.
|
||||||
//! only composes already-verified pieces (RFC-VIEW-0001 §6.3, §14.2).
|
//! Assembly from Analysis/Trace happens in `reader::assemble`.
|
||||||
|
|
||||||
use crate::document::{DocumentIdentity, DocumentModel};
|
use crate::config::ViewConfig;
|
||||||
use crate::project::{Project, SafeRelativePath, ViewConfig};
|
use crate::protocol::analysis_v2::{CoreDiagnostic, SemanticProjection, ViewWarning};
|
||||||
use crate::semantic::{CoreDiagnostic, SemanticProjection, ViewWarning};
|
use crate::protocol::trace_v2::{RunDisplayState, RunProjection};
|
||||||
use crate::trace::{RunDisplayState, RunProjection};
|
use crate::reader::markdown::DocumentModel;
|
||||||
|
use crate::reader::source::{Project, SafeRelativePath};
|
||||||
|
|
||||||
/// Private View presentation-model version. Not a public protocol.
|
/// Private View presentation-model version. Not a public protocol.
|
||||||
pub const PRESENTATION_VERSION: u32 = 1;
|
pub const PRESENTATION_VERSION: u32 = 1;
|
||||||
@@ -122,6 +123,19 @@ pub enum OutlineKind {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl PresentationModel {
|
impl PresentationModel {
|
||||||
|
/// True when the entry module exposes a resolvable `main` (canonical or
|
||||||
|
/// unique local name). The dock Run button never substitutes another
|
||||||
|
/// function for a missing entry function (RFC-VIEW-0002 §2.4).
|
||||||
|
pub fn has_entry_main(&self) -> bool {
|
||||||
|
let Some(semantic) = self.semantic.as_ref() else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
semantic.functions.iter().any(|function| {
|
||||||
|
let canonical = canonical_function_name(&function.id, &semantic.module_id);
|
||||||
|
canonical == "main" || function.local_name == "main"
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
pub fn run_state(&self) -> RunDisplayState {
|
pub fn run_state(&self) -> RunDisplayState {
|
||||||
match &self.run {
|
match &self.run {
|
||||||
Some(run) => run.state,
|
Some(run) => run.state,
|
||||||
@@ -158,131 +172,20 @@ impl PresentationModel {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Input to the one builder. `analysis` is already protocol/byte verified.
|
|
||||||
pub struct BuildInput<'a> {
|
|
||||||
pub document: DocumentModel,
|
|
||||||
pub analysis: Option<&'a crate::semantic::VerifiedAnalysis>,
|
|
||||||
pub status: SourceStatus,
|
|
||||||
pub status_note: Option<String>,
|
|
||||||
pub diagnostics: Vec<CoreDiagnostic>,
|
|
||||||
pub navigation: Navigation,
|
|
||||||
pub core_version: Option<String>,
|
|
||||||
pub run: Option<&'a crate::trace::VerifiedRun>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn build(input: BuildInput<'_>) -> PresentationModel {
|
|
||||||
let BuildInput {
|
|
||||||
mut document,
|
|
||||||
analysis,
|
|
||||||
status,
|
|
||||||
status_note,
|
|
||||||
mut diagnostics,
|
|
||||||
navigation,
|
|
||||||
core_version,
|
|
||||||
run,
|
|
||||||
} = input;
|
|
||||||
|
|
||||||
let semantic = analysis.map(|verified| verified.projection.clone());
|
|
||||||
if let Some(projection) = &semantic {
|
|
||||||
document.identity = DocumentIdentity {
|
|
||||||
project_root_id: projection.project_root_id.clone(),
|
|
||||||
module_id: projection.module_id.clone(),
|
|
||||||
relative_path: projection.relative_path.clone(),
|
|
||||||
source_sha256: projection.source_digest.clone(),
|
|
||||||
};
|
|
||||||
for diagnostic in &projection.diagnostics {
|
|
||||||
if !diagnostics.iter().any(|existing| {
|
|
||||||
existing.code == diagnostic.code
|
|
||||||
&& existing.message == diagnostic.message
|
|
||||||
&& existing.span == diagnostic.span
|
|
||||||
}) {
|
|
||||||
diagnostics.push(diagnostic.clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let warnings = semantic
|
|
||||||
.as_ref()
|
|
||||||
.map(|projection| projection.warnings.clone())
|
|
||||||
.unwrap_or_default();
|
|
||||||
let outline = semantic.as_ref().map(build_outline).unwrap_or_default();
|
|
||||||
|
|
||||||
PresentationModel {
|
|
||||||
version: PRESENTATION_VERSION,
|
|
||||||
title: document.title(),
|
|
||||||
document,
|
|
||||||
semantic,
|
|
||||||
source_status: status,
|
|
||||||
status_note,
|
|
||||||
diagnostics,
|
|
||||||
warnings,
|
|
||||||
navigation,
|
|
||||||
outline,
|
|
||||||
core_version,
|
|
||||||
run: run.map(|verified| verified.projection.clone()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn build_outline(projection: &SemanticProjection) -> Vec<OutlineEntry> {
|
|
||||||
let mut entries = Vec::new();
|
|
||||||
for function in &projection.functions {
|
|
||||||
let params = if function.signature.params.is_empty() {
|
|
||||||
String::new()
|
|
||||||
} else {
|
|
||||||
function
|
|
||||||
.signature
|
|
||||||
.params
|
|
||||||
.iter()
|
|
||||||
.map(|param| {
|
|
||||||
if param.ty.is_empty() {
|
|
||||||
param.name.clone()
|
|
||||||
} else {
|
|
||||||
format!("{}: {}", param.name, param.ty)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join(", ")
|
|
||||||
};
|
|
||||||
let detail = if params.is_empty() {
|
|
||||||
"无参数".to_string()
|
|
||||||
} else {
|
|
||||||
format!("params({params})")
|
|
||||||
};
|
|
||||||
entries.push(OutlineEntry {
|
|
||||||
label: function.local_name.clone(),
|
|
||||||
anchor: anchor_for_span(function.heading_span.start, function.heading_span.end),
|
|
||||||
detail,
|
|
||||||
kind: OutlineKind::Function,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
for unit in &projection.units {
|
|
||||||
let kind = match unit.kind {
|
|
||||||
crate::semantic::UnitKind::Knowledge if unit.level >= 2 => OutlineKind::Knowledge,
|
|
||||||
crate::semantic::UnitKind::Section => OutlineKind::Section,
|
|
||||||
_ => continue,
|
|
||||||
};
|
|
||||||
if unit.name.is_empty() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
entries.push(OutlineEntry {
|
|
||||||
label: unit.name.clone(),
|
|
||||||
anchor: anchor_for_span(unit.span.start, unit.span.end),
|
|
||||||
detail: if unit.level == 2 {
|
|
||||||
"知识单元".to_string()
|
|
||||||
} else {
|
|
||||||
"章节".to_string()
|
|
||||||
},
|
|
||||||
kind,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
entries
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Deterministic heading anchor derived from the heading byte span. It never
|
/// Deterministic heading anchor derived from the heading byte span. It never
|
||||||
/// depends on rendered text, so duplicate headings cannot collide.
|
/// depends on rendered text, so duplicate headings cannot collide.
|
||||||
pub fn anchor_for_span(start: u64, end: u64) -> String {
|
pub fn anchor_for_span(start: u64, end: u64) -> String {
|
||||||
format!("mq-h-{start:x}-{end:x}")
|
format!("mq-h-{start:x}-{end:x}")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Analysis v2 function ids are `<module id>::<canonical name>`.
|
||||||
|
fn canonical_function_name(function_id: &str, module_id: &str) -> String {
|
||||||
|
function_id
|
||||||
|
.strip_prefix(&format!("{module_id}::"))
|
||||||
|
.unwrap_or(function_id)
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -10,12 +10,12 @@
|
|||||||
//! Markdown is serialized here from the View-owned `DocBlock` tree, with raw
|
//! Markdown is serialized here from the View-owned `DocBlock` tree, with raw
|
||||||
//! HTML omitted by default and every URL scheme sanitized.
|
//! HTML omitted by default and every URL scheme sanitized.
|
||||||
|
|
||||||
use crate::assets::AssetBundle;
|
use crate::protocol::analysis_v2::{source_id, UnitKind};
|
||||||
use crate::document::{DocBlock, Inline, TableAlign};
|
use crate::reader::assets::AssetBundle;
|
||||||
use crate::presentation::{anchor_for_span, PresentationModel};
|
use crate::reader::markdown::{DocBlock, Inline, TableAlign};
|
||||||
use crate::project::SafeRelativePath;
|
use crate::reader::model::{anchor_for_span, PresentationModel};
|
||||||
use crate::semantic::{source_id, UnitKind};
|
use crate::reader::source::SafeRelativePath;
|
||||||
use crate::source_map::SourceSpan;
|
use crate::reader::source::SourceSpan;
|
||||||
use std::fmt::Write as _;
|
use std::fmt::Write as _;
|
||||||
|
|
||||||
/// How links to other documents are resolved. This is the only Live/Export
|
/// How links to other documents are resolved. This is the only Live/Export
|
||||||
@@ -71,6 +71,10 @@ pub struct RenderContext {
|
|||||||
pub run_available: bool,
|
pub run_available: bool,
|
||||||
/// Static exports may hide semantic/run annotations without changing prose.
|
/// Static exports may hide semantic/run annotations without changing prose.
|
||||||
pub annotations: bool,
|
pub annotations: bool,
|
||||||
|
/// View wall-clock limit shown in the explicit run form (seconds).
|
||||||
|
pub run_timeout_secs: u64,
|
||||||
|
/// Whether a frozen Core was negotiated (an explicit run form can exist).
|
||||||
|
pub core_available: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RenderContext {
|
impl RenderContext {
|
||||||
@@ -81,6 +85,8 @@ impl RenderContext {
|
|||||||
csrf_token: None,
|
csrf_token: None,
|
||||||
run_available: false,
|
run_available: false,
|
||||||
annotations: true,
|
annotations: true,
|
||||||
|
run_timeout_secs: 30,
|
||||||
|
core_available: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -91,6 +97,8 @@ impl RenderContext {
|
|||||||
csrf_token: None,
|
csrf_token: None,
|
||||||
run_available: false,
|
run_available: false,
|
||||||
annotations: true,
|
annotations: true,
|
||||||
|
run_timeout_secs: 0,
|
||||||
|
core_available: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -136,6 +144,13 @@ impl ReaderRenderer {
|
|||||||
);
|
);
|
||||||
let _ = document_href;
|
let _ = document_href;
|
||||||
let mut html = String::with_capacity(16 * 1024 + model.document.source.len());
|
let mut html = String::with_capacity(16 * 1024 + model.document.source.len());
|
||||||
|
let relative_path = model.document.identity.relative_path.clone();
|
||||||
|
let analysis_digest = model
|
||||||
|
.semantic
|
||||||
|
.as_ref()
|
||||||
|
.map(|semantic| semantic.analysis_digest.clone())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let has_main = model.has_entry_main();
|
||||||
let page_title = if navigation.site_title.is_empty() {
|
let page_title = if navigation.site_title.is_empty() {
|
||||||
model.title.clone()
|
model.title.clone()
|
||||||
} else {
|
} else {
|
||||||
@@ -156,7 +171,7 @@ impl ReaderRenderer {
|
|||||||
<link rel="stylesheet" href="{css}"/>
|
<link rel="stylesheet" href="{css}"/>
|
||||||
<script defer src="{js}"></script>
|
<script defer src="{js}"></script>
|
||||||
</head>
|
</head>
|
||||||
<body class="mq-reader" data-mode="document" data-annotations="{annotations}" data-size="normal" data-source-status="{status}" data-run-state="{run_state}" data-run-available="{run_available}" data-live="{live}">
|
<body class="mq-reader" data-mode="document" data-theme="light" data-annotations="{annotations}" data-size="normal" data-source-status="{status}" data-run-state="{run_state}" data-run-available="{run_available}" data-has-main="{has_main}" data-core-available="{core_available}" data-document="{document}" data-analysis-digest="{analysis_digest}" data-run-timeout="{run_timeout}" data-live="{live}">
|
||||||
<a class="mq-skip" href="#mq-main">跳到正文</a>
|
<a class="mq-skip" href="#mq-main">跳到正文</a>
|
||||||
"##,
|
"##,
|
||||||
presentation_version = model.version,
|
presentation_version = model.version,
|
||||||
@@ -170,6 +185,11 @@ impl ReaderRenderer {
|
|||||||
annotations = if ctx.annotations { "on" } else { "off" },
|
annotations = if ctx.annotations { "on" } else { "off" },
|
||||||
run_state = model.run_state().data_value(),
|
run_state = model.run_state().data_value(),
|
||||||
run_available = if ctx.run_available { "true" } else { "false" },
|
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" },
|
live = if ctx.live { "true" } else { "false" },
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -182,9 +202,13 @@ impl ReaderRenderer {
|
|||||||
}
|
}
|
||||||
self.render_document_meta(&mut html, model);
|
self.render_document_meta(&mut html, model);
|
||||||
self.render_diagnostics(&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_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_source_pane(&mut html, model, ctx);
|
||||||
self.render_footer(&mut html, model);
|
self.render_footer(&mut html, model);
|
||||||
let _ = write!(html, "</main>\n");
|
let _ = write!(html, "</main>\n");
|
||||||
@@ -204,8 +228,8 @@ impl ReaderRenderer {
|
|||||||
&self,
|
&self,
|
||||||
html: &mut String,
|
html: &mut String,
|
||||||
model: &PresentationModel,
|
model: &PresentationModel,
|
||||||
_ctx: &RenderContext,
|
ctx: &RenderContext,
|
||||||
navigation: &crate::presentation::Navigation,
|
navigation: &crate::reader::model::Navigation,
|
||||||
) {
|
) {
|
||||||
let active = model
|
let active = model
|
||||||
.navigation
|
.navigation
|
||||||
@@ -214,6 +238,11 @@ impl ReaderRenderer {
|
|||||||
.map(|path| path.as_str())
|
.map(|path| path.as_str())
|
||||||
.unwrap_or("");
|
.unwrap_or("");
|
||||||
let files_count = navigation.documents.len();
|
let files_count = navigation.documents.len();
|
||||||
|
let run_tab = if ctx.live {
|
||||||
|
"<button type=\"button\" class=\"mq-tab\" data-action=\"run\" title=\"显式运行\">运行</button>".to_string()
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
};
|
||||||
let _ = write!(
|
let _ = write!(
|
||||||
html,
|
html,
|
||||||
r##"<header class="mq-topbar">
|
r##"<header class="mq-topbar">
|
||||||
@@ -231,19 +260,13 @@ impl ReaderRenderer {
|
|||||||
<nav class="mq-tabs" aria-label="阅读导航">
|
<nav class="mq-tabs" aria-label="阅读导航">
|
||||||
<button type="button" class="mq-tab" data-action="mode-document" aria-current="page">文档</button>
|
<button type="button" class="mq-tab" data-action="mode-document" aria-current="page">文档</button>
|
||||||
<button type="button" class="mq-tab" data-action="functions">函数</button>
|
<button type="button" class="mq-tab" data-action="functions">函数</button>
|
||||||
<button type="button" class="mq-tab" data-action="run" data-disabled="{run_disabled}" title="{run_title}">运行</button>
|
{run_tab}
|
||||||
</nav>
|
</nav>
|
||||||
"##,
|
"##,
|
||||||
menu_icon = icon("M4 6h16M4 12h16M4 18h16"),
|
menu_icon = icon("M4 6h16M4 12h16M4 18h16"),
|
||||||
site_title = escape_text(&navigation.site_title),
|
site_title = escape_text(&navigation.site_title),
|
||||||
logo = escape_attr(&self.assets.logo().data_uri()),
|
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"),
|
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);
|
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!(
|
let _ = write!(
|
||||||
html,
|
html,
|
||||||
r##"<section class="mq-welcome" aria-label="欢迎页">
|
r##"<section class="mq-welcome" aria-label="欢迎页">
|
||||||
@@ -361,7 +384,7 @@ impl ReaderRenderer {
|
|||||||
html.push_str("</ol>\n</details>\n");
|
html.push_str("</ol>\n</details>\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() {
|
if model.outline.is_empty() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -375,12 +398,33 @@ impl ReaderRenderer {
|
|||||||
count = functions.len()
|
count = functions.len()
|
||||||
);
|
);
|
||||||
for entry in functions {
|
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!(
|
||||||
|
"<button type=\"button\" class=\"mq-fn-call\" data-action=\"call-function\" data-function-id=\"{id}\" data-function-label=\"{label}\" data-params=\"{params}\">调用</button>",
|
||||||
|
id = escape_attr(&function_id),
|
||||||
|
label = escape_attr(&entry.label),
|
||||||
|
params = escape_attr(¶ms)
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
};
|
||||||
let _ = write!(
|
let _ = write!(
|
||||||
html,
|
html,
|
||||||
"<li><a href=\"#{anchor}\" data-goto-anchor=\"{anchor}\">{label}</a><span class=\"mq-fn-sig\">{detail}</span></li>\n",
|
"<li><a href=\"#{anchor}\" data-goto-anchor=\"{anchor}\">{label}</a><span class=\"mq-fn-sig\">{detail}</span>{call_button}</li>\n",
|
||||||
anchor = escape_attr(&entry.anchor),
|
anchor = escape_attr(&entry.anchor),
|
||||||
label = escape_text(&entry.label),
|
label = escape_text(&entry.label),
|
||||||
detail = escape_text(&entry.detail)
|
detail = escape_text(&entry.detail),
|
||||||
|
call_button = call_button
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
html.push_str("</ul>\n</details>\n");
|
html.push_str("</ul>\n</details>\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##"<section class="mq-run-panel" id="mq-run-panel" data-run-state="idle" aria-labelledby="mq-run-title" hidden>
|
||||||
|
<h2 id="mq-run-title">本次运行</h2>
|
||||||
|
<p id="mq-run-status" class="mq-run-status" role="status" aria-live="polite">尚未运行。点击 Dock 的“运行”执行 main,或在函数面板选择函数。</p>
|
||||||
|
<div id="mq-run-actions" class="mq-run-actions" hidden>
|
||||||
|
<button type="button" class="mq-secondary" data-action="cancel-run">取消运行</button>
|
||||||
|
</div>
|
||||||
|
<div id="mq-run-summary"></div>
|
||||||
|
<pre id="mq-run-stdout" class="mq-stdout" aria-label="程序标准输出" hidden></pre>
|
||||||
|
<pre id="mq-run-stderr" class="mq-stdout mq-stderr" aria-label="程序标准错误" hidden></pre>
|
||||||
|
<details id="mq-run-trace-wrap" class="mq-run-events-wrap" hidden>
|
||||||
|
<summary>真实 Trace v2 事件</summary>
|
||||||
|
<ol id="mq-run-events" class="mq-run-events"></ol>
|
||||||
|
</details>
|
||||||
|
<p id="mq-run-note" class="mq-colophon">结果只来自本次显式运行的 CLI --json 与经摘要校验的 Trace v2;不提供参数实际值、逐语句变量或内存快照。</p>
|
||||||
|
</section>
|
||||||
|
"##,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
fn render_dock(&self, html: &mut String, ctx: &RenderContext) {
|
fn render_dock(&self, html: &mut String, ctx: &RenderContext) {
|
||||||
let run_disabled = if ctx.run_available {
|
let settings = icon("M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8M12 2v3M12 19v3M2 12h3M19 12h3M5 5l2 2M17 17l2 2M5 19l2-2M17 7l2-2");
|
||||||
""
|
let more = icon("M5 12h.01M12 12h.01M19 12h.01");
|
||||||
} else {
|
if ctx.live {
|
||||||
" data-disabled=\"true\""
|
let run_disabled = if ctx.core_available {
|
||||||
};
|
""
|
||||||
let _ = write!(
|
} else {
|
||||||
html,
|
" data-disabled=\"true\""
|
||||||
r##"<div class="mq-dock" role="toolbar" aria-label="文档操作">
|
};
|
||||||
|
let _ = write!(
|
||||||
|
html,
|
||||||
|
r##"<div class="mq-dock" role="toolbar" aria-label="文档操作">
|
||||||
<button type="button" class="mq-dock-btn" data-action="reload" aria-label="刷新页面">{reload}<span>刷新</span></button>
|
<button type="button" class="mq-dock-btn" data-action="reload" aria-label="刷新页面">{reload}<span>刷新</span></button>
|
||||||
<button type="button" class="mq-dock-btn" data-action="settings" aria-label="阅读设置">{settings}<span>设置</span></button>
|
<button type="button" class="mq-dock-btn" data-action="settings" aria-label="阅读设置">{settings}<span>设置</span></button>
|
||||||
<button type="button" class="mq-dock-btn" data-action="run" aria-label="运行文档"{run_disabled}>{play}<span>运行</span></button>
|
<button type="button" class="mq-dock-btn" data-action="run" aria-label="运行文档"{run_disabled}>{play}<span>运行</span></button>
|
||||||
@@ -473,13 +544,26 @@ impl ReaderRenderer {
|
|||||||
<button type="button" class="mq-dock-btn" data-action="more" aria-label="更多操作">{more}<span>更多</span></button>
|
<button type="button" class="mq-dock-btn" data-action="more" aria-label="更多操作">{more}<span>更多</span></button>
|
||||||
</div>
|
</div>
|
||||||
"##,
|
"##,
|
||||||
reload = icon("M20 7V3l-3 3a8 8 0 1 0 2 11M20 3h-5"),
|
reload = icon("M20 7V3l-3 3a8 8 0 1 0 2 11M20 3h-5"),
|
||||||
settings = icon("M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8M12 2v3M12 19v3M2 12h3M19 12h3M5 5l2 2M17 17l2 2M5 19l2-2M17 7l2-2"),
|
settings = settings,
|
||||||
play = icon("m9 5 11 7-11 7z"),
|
play = icon("m9 5 11 7-11 7z"),
|
||||||
clear = icon("m14 3 4 2-4 8M5 12l8 2 2 6H3zM7 15l-1 4M10 16l-1 4"),
|
clear = icon("m14 3 4 2-4 8M5 12l8 2 2 6H3zM7 15l-1 4M10 16l-1 4"),
|
||||||
more = icon("M5 12h.01M12 12h.01M19 12h.01"),
|
more = more,
|
||||||
run_disabled = run_disabled
|
run_disabled = run_disabled
|
||||||
);
|
);
|
||||||
|
} else {
|
||||||
|
// Static export has no execution controls (RFC-VIEW-0002 §7.2).
|
||||||
|
let _ = write!(
|
||||||
|
html,
|
||||||
|
r##"<div class="mq-dock" role="toolbar" aria-label="文档操作">
|
||||||
|
<button type="button" class="mq-dock-btn" data-action="settings" aria-label="阅读设置">{settings}<span>设置</span></button>
|
||||||
|
<button type="button" class="mq-dock-btn" data-action="more" aria-label="更多操作">{more}<span>更多</span></button>
|
||||||
|
</div>
|
||||||
|
"##,
|
||||||
|
settings = settings,
|
||||||
|
more = more
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn render_toast(&self, html: &mut String) {
|
fn render_toast(&self, html: &mut String) {
|
||||||
@@ -509,6 +593,7 @@ impl ReaderRenderer {
|
|||||||
<div class="mq-dialog-head"><h2 id="mq-settings-title">阅读设置</h2><button type="button" class="mq-icon-btn mq-close" data-action="close-dialog" aria-label="关闭设置">×</button></div>
|
<div class="mq-dialog-head"><h2 id="mq-settings-title">阅读设置</h2><button type="button" class="mq-icon-btn mq-close" data-action="close-dialog" aria-label="关闭设置">×</button></div>
|
||||||
<ul class="mq-menu-list">
|
<ul class="mq-menu-list">
|
||||||
<li><button type="button" data-action="size">正文字号 <span class="mq-menu-hint">标准 / 大 / 小</span></button></li>
|
<li><button type="button" data-action="size">正文字号 <span class="mq-menu-hint">标准 / 大 / 小</span></button></li>
|
||||||
|
<li><button type="button" data-action="theme">主题 <span class="mq-menu-hint">暖纸 / 深色</span></button></li>
|
||||||
<li><button type="button" data-action="annotations">语义标注显隐 <span class="mq-menu-hint">锚点与侧注</span></button></li>
|
<li><button type="button" data-action="annotations">语义标注显隐 <span class="mq-menu-hint">锚点与侧注</span></button></li>
|
||||||
<li><button type="button" data-action="print">打印 / 保存为 PDF <span class="mq-menu-hint">保留正文与注释</span></button></li>
|
<li><button type="button" data-action="print">打印 / 保存为 PDF <span class="mq-menu-hint">保留正文与注释</span></button></li>
|
||||||
</ul>
|
</ul>
|
||||||
@@ -519,8 +604,7 @@ impl ReaderRenderer {
|
|||||||
<li><button type="button" data-action="mode-document">文档态 <span class="mq-menu-hint">原始 Markdown 阅读</span></button></li>
|
<li><button type="button" data-action="mode-document">文档态 <span class="mq-menu-hint">原始 Markdown 阅读</span></button></li>
|
||||||
<li><button type="button" data-action="mode-source">源码态 <span class="mq-menu-hint">逐行原文,含标记</span></button></li>
|
<li><button type="button" data-action="mode-source">源码态 <span class="mq-menu-hint">逐行原文,含标记</span></button></li>
|
||||||
<li><button type="button" data-action="functions">函数大纲 <span class="mq-menu-hint">来自 Analysis v2</span></button></li>
|
<li><button type="button" data-action="functions">函数大纲 <span class="mq-menu-hint">来自 Analysis v2</span></button></li>
|
||||||
<li><button type="button" data-action="variables">变量信息 <span class="mq-menu-hint">静态目标 · 运行值不支持</span></button></li>
|
<li><button type="button" data-action="unsupported">未提供的能力 <span class="mq-menu-hint">变量 / 内存 / 调试 / 证明</span></button></li>
|
||||||
<li><button type="button" data-action="memory">内存快照 <span class="mq-menu-hint">当前协议不支持</span></button></li>
|
|
||||||
<li><button type="button" data-action="print">打印 <span class="mq-menu-hint">隐藏交互与装饰</span></button></li>
|
<li><button type="button" data-action="print">打印 <span class="mq-menu-hint">隐藏交互与装饰</span></button></li>
|
||||||
<li><button type="button" data-action="about">关于 Marqdo View <span class="mq-menu-hint">版本与协议</span></button></li>
|
<li><button type="button" data-action="about">关于 Marqdo View <span class="mq-menu-hint">版本与协议</span></button></li>
|
||||||
</ul>
|
</ul>
|
||||||
@@ -544,8 +628,8 @@ impl ReaderRenderer {
|
|||||||
"##,
|
"##,
|
||||||
csrf = csrf,
|
csrf = csrf,
|
||||||
files = self.render_file_list(model, ctx),
|
files = self.render_file_list(model, ctx),
|
||||||
run_dialog = if ctx.run_available {
|
run_dialog = if ctx.core_available {
|
||||||
render_run_confirm_dialog(model)
|
render_run_form_dialog(model, ctx)
|
||||||
} else {
|
} else {
|
||||||
String::new()
|
String::new()
|
||||||
},
|
},
|
||||||
@@ -918,7 +1002,7 @@ fn resolve_heading_unit(
|
|||||||
model: &PresentationModel,
|
model: &PresentationModel,
|
||||||
heading_span: SourceSpan,
|
heading_span: SourceSpan,
|
||||||
level: u8,
|
level: u8,
|
||||||
) -> Option<&crate::semantic::SemanticUnit> {
|
) -> Option<&crate::protocol::analysis_v2::SemanticUnit> {
|
||||||
let projection = model.semantic.as_ref()?;
|
let projection = model.semantic.as_ref()?;
|
||||||
// A function heading maps to its function unit exactly; never borrow the
|
// A function heading maps to its function unit exactly; never borrow the
|
||||||
// ancestor function for H3/H4 sections (that would duplicate DOM ids).
|
// ancestor function for H3/H4 sections (that would duplicate DOM ids).
|
||||||
@@ -945,7 +1029,7 @@ fn resolve_heading_unit(
|
|||||||
|
|
||||||
fn display_heading_content(
|
fn display_heading_content(
|
||||||
content: &[Inline],
|
content: &[Inline],
|
||||||
unit: Option<&crate::semantic::SemanticUnit>,
|
unit: Option<&crate::protocol::analysis_v2::SemanticUnit>,
|
||||||
) -> (Option<(&'static str, &'static str)>, Vec<Inline>) {
|
) -> (Option<(&'static str, &'static str)>, Vec<Inline>) {
|
||||||
let Some(unit) = unit else {
|
let Some(unit) = unit else {
|
||||||
return (None, content.to_vec());
|
return (None, content.to_vec());
|
||||||
@@ -1054,7 +1138,7 @@ fn render_inline(
|
|||||||
);
|
);
|
||||||
let _ = write!(
|
let _ = write!(
|
||||||
html,
|
html,
|
||||||
" class=\"mq-anchor\" data-source-id=\"{id}\" data-statement-kind=\"{kind}\" title=\"静态语句:{label}\"",
|
" class=\"mq-anchor\" data-annotation-source=\"analysis\" data-source-id=\"{id}\" data-statement-kind=\"{kind}\" title=\"静态语句:{label}\"",
|
||||||
id = escape_attr(&id),
|
id = escape_attr(&id),
|
||||||
kind = statement.kind.data_value(),
|
kind = statement.kind.data_value(),
|
||||||
label = statement.kind.label()
|
label = statement.kind.label()
|
||||||
@@ -1082,7 +1166,7 @@ fn render_inline(
|
|||||||
);
|
);
|
||||||
let _ = write!(
|
let _ = write!(
|
||||||
html,
|
html,
|
||||||
" class=\"mq-anchor\" data-source-id=\"{id}\" data-statement-kind=\"{kind}\" title=\"静态语句:{label}\"",
|
" class=\"mq-anchor\" data-annotation-source=\"analysis\" data-source-id=\"{id}\" data-statement-kind=\"{kind}\" title=\"静态语句:{label}\"",
|
||||||
id = escape_attr(&id),
|
id = escape_attr(&id),
|
||||||
kind = statement.kind.data_value(),
|
kind = statement.kind.data_value(),
|
||||||
label = statement.kind.label()
|
label = statement.kind.label()
|
||||||
@@ -1110,7 +1194,7 @@ fn render_inline(
|
|||||||
);
|
);
|
||||||
let _ = write!(
|
let _ = write!(
|
||||||
html,
|
html,
|
||||||
" class=\"mq-anchor\" data-source-id=\"{id}\" data-statement-kind=\"{kind}\" title=\"静态语句:{label}\"",
|
" class=\"mq-anchor\" data-annotation-source=\"analysis\" data-source-id=\"{id}\" data-statement-kind=\"{kind}\" title=\"静态语句:{label}\"",
|
||||||
id = escape_attr(&id),
|
id = escape_attr(&id),
|
||||||
kind = statement.kind.data_value(),
|
kind = statement.kind.data_value(),
|
||||||
label = statement.kind.label()
|
label = statement.kind.label()
|
||||||
@@ -1346,32 +1430,48 @@ fn render_run_chips(html: &mut String, model: &PresentationModel, statement_span
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn render_run_confirm_dialog(model: &PresentationModel) -> String {
|
fn function_params_json(function: &crate::protocol::analysis_v2::SemanticFunction) -> String {
|
||||||
let function = model
|
serde_json::json!(function
|
||||||
.semantic
|
.signature
|
||||||
.as_ref()
|
.params
|
||||||
.and_then(|semantic| {
|
.iter()
|
||||||
semantic
|
.map(|param| serde_json::json!({
|
||||||
.functions
|
"name": param.name,
|
||||||
.iter()
|
"type": param.ty,
|
||||||
.find(|function| function.local_name == "main")
|
"required": param.required,
|
||||||
})
|
"default": param.default,
|
||||||
.map(|function| function.local_name.clone())
|
}))
|
||||||
.unwrap_or_else(|| "main".to_string());
|
.collect::<Vec<_>>())
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_run_form_dialog(model: &PresentationModel, ctx: &RenderContext) -> String {
|
||||||
|
let path = &model.document.identity.relative_path;
|
||||||
format!(
|
format!(
|
||||||
r##"<dialog class="mq-dialog" id="mq-dialog-run-confirm" aria-labelledby="mq-run-confirm-title" data-path="{path}">
|
r##"<dialog class="mq-dialog mq-run-dialog" id="mq-dialog-run" aria-labelledby="mq-run-dialog-title" data-path="{path}" data-timeout="{timeout}">
|
||||||
<div class="mq-dialog-head"><h2 id="mq-run-confirm-title">确认运行本文档</h2><button type="button" class="mq-icon-btn mq-close" data-action="close-dialog" aria-label="取消运行">×</button></div>
|
<div class="mq-dialog-head"><h2 id="mq-run-dialog-title">显式运行</h2><button type="button" class="mq-icon-btn mq-close" data-action="close-dialog" aria-label="取消运行">×</button></div>
|
||||||
<p>即将通过冻结核心执行入口函数 <code>{function}</code>,沙箱模式 <code>pure</code>(无文件、网络、环境变量、进程权限)。</p>
|
<p class="mq-run-target"><span id="mq-run-target-label">入口 main</span> · <span id="mq-run-target-mode">pure</span></p>
|
||||||
<p>等价命令:<code>marqdo run {path} --mode pure --json --trace-file <临时文件></code></p>
|
<div id="mq-run-params" class="mq-run-params"></div>
|
||||||
<p>运行会在你的机器上真实执行文档中的 <code>@exec</code> 代码。Trace v2 不记录参数实际值、文件内容或敏感数据;View 不继承项目声明的 capabilities。</p>
|
<fieldset class="mq-run-mode">
|
||||||
<p class="mq-colophon">打开、刷新、搜索、导出都不会触发运行;只有本确认按钮会。</p>
|
<legend>执行模式</legend>
|
||||||
|
<label><input type="radio" name="mq-mode" value="pure" checked/> pure(默认:无文件/网络/环境/进程权限)</label>
|
||||||
|
<label><input type="radio" name="mq-mode" value="project"/> project(受控项目权限,需逐项确认)</label>
|
||||||
|
</fieldset>
|
||||||
|
<div id="mq-run-grants" class="mq-run-grants" hidden>
|
||||||
|
<p class="mq-run-warning" role="note">project 模式不是 OS 沙箱。只允许相对项目根的 fs read/write glob;网络、进程、环境、插件等权限不在首版 UI 中,必须改用终端 CLI。</p>
|
||||||
|
<label>允许读取(read glob,每行一个)<textarea id="mq-grant-read" rows="2" spellcheck="false" placeholder="data/**"></textarea></label>
|
||||||
|
<label>允许写入(write glob,每行一个)<textarea id="mq-grant-write" rows="2" spellcheck="false" placeholder="out/*.txt"></textarea></label>
|
||||||
|
</div>
|
||||||
|
<p class="mq-colophon">等价命令(点击“确认执行”后才会运行;<code><参数值></code> 由下方输入原样作为常量表达式提交):</p>
|
||||||
|
<pre class="mq-run-command" id="mq-run-command" aria-label="命令预览"></pre>
|
||||||
|
<p class="mq-colophon">墙钟上限 {timeout} 秒;结果通过 SSE 推送,不轮询。打开/刷新/导出不会执行。</p>
|
||||||
<div class="mq-dialog-actions">
|
<div class="mq-dialog-actions">
|
||||||
<button type="button" class="mq-secondary" data-action="close-dialog">取消</button>
|
<button type="button" class="mq-secondary" data-action="close-dialog">取消</button>
|
||||||
<button type="button" class="mq-primary" data-action="run-confirm">确认运行(pure)</button>
|
<button type="button" class="mq-primary" data-action="run-confirm">确认执行</button>
|
||||||
</div>
|
</div>
|
||||||
</dialog>
|
</dialog>
|
||||||
"##,
|
"##,
|
||||||
function = escape_text(&function),
|
path = escape_attr(path),
|
||||||
path = escape_text(&model.document.identity.relative_path)
|
timeout = ctx.run_timeout_secs
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,293 @@
|
|||||||
//! Project-root and path boundary enforcement.
|
//! Exact UTF-8 byte ↔ line/column ↔ JavaScript UTF-16 offset mapping.
|
||||||
//!
|
//!
|
||||||
//! Production, HTTP, Export and tests all use these functions; there is no
|
//! Core Analysis/Trace spans are half-open UTF-8 **byte** offsets into the
|
||||||
//! second path validator (RFC-VIEW-0001 §14.4).
|
//! original file bytes. Browsers count UTF-16 code units. This module is the
|
||||||
|
//! only place that converts between them (RFC-VIEW-0001 §8.2).
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
/// Half-open byte span `[start, end)` into one module's exact source bytes.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||||
|
pub struct SourceSpan {
|
||||||
|
pub start: u64,
|
||||||
|
pub end: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SourceSpan {
|
||||||
|
pub fn new(start: u64, end: u64) -> Self {
|
||||||
|
Self { start, end }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.start == self.end
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len(&self) -> u64 {
|
||||||
|
self.end.saturating_sub(self.start)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn contains(&self, other: SourceSpan) -> bool {
|
||||||
|
self.start <= other.start && other.end <= self.end
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn intersects(&self, other: SourceSpan) -> bool {
|
||||||
|
self.start < other.end && other.start < self.end
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_usize_range(&self) -> Option<std::ops::Range<usize>> {
|
||||||
|
let start = usize::try_from(self.start).ok()?;
|
||||||
|
let end = usize::try_from(self.end).ok()?;
|
||||||
|
if start > end {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(start..end)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compute lowercase hex SHA-256 of exact bytes (no normalization).
|
||||||
|
pub fn sha256_hex(bytes: &[u8]) -> String {
|
||||||
|
let mut hasher = Sha256::new();
|
||||||
|
hasher.update(bytes);
|
||||||
|
let digest = hasher.finalize();
|
||||||
|
let mut out = String::with_capacity(64);
|
||||||
|
for byte in digest {
|
||||||
|
use std::fmt::Write as _;
|
||||||
|
let _ = write!(out, "{byte:02x}");
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// SHA-256 with the `sha256:` prefix used by Analysis/Trace identity fields.
|
||||||
|
pub fn sha256_prefixed(bytes: &[u8]) -> String {
|
||||||
|
format!("sha256:{}", sha256_hex(bytes))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Immutable source index built from the exact original bytes.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct SourceIndex {
|
||||||
|
/// Byte length of the source.
|
||||||
|
len: usize,
|
||||||
|
/// Byte offset of the start of every line (0-based line number).
|
||||||
|
line_starts: Vec<usize>,
|
||||||
|
/// Number of leading UTF-8 BOM bytes tolerated before the first content
|
||||||
|
/// byte. Spans in Analysis are relative to the file bytes, so the BOM
|
||||||
|
/// stays part of the index.
|
||||||
|
bom_len: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SourceIndex {
|
||||||
|
pub fn new(source: &str) -> Self {
|
||||||
|
let bytes = source.as_bytes();
|
||||||
|
let bom_len = if source.starts_with('\u{feff}') { 3 } else { 0 };
|
||||||
|
let mut line_starts = vec![0usize];
|
||||||
|
let mut index = bom_len;
|
||||||
|
while index < bytes.len() {
|
||||||
|
if bytes[index] == b'\n' {
|
||||||
|
line_starts.push(index + 1);
|
||||||
|
}
|
||||||
|
index += 1;
|
||||||
|
}
|
||||||
|
Self {
|
||||||
|
len: bytes.len(),
|
||||||
|
line_starts,
|
||||||
|
bom_len,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len(&self) -> usize {
|
||||||
|
self.len
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.len == 0
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn bom_len(&self) -> usize {
|
||||||
|
self.bom_len
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn source_text<'a>(&self, source: &'a str, span: SourceSpan) -> Option<&'a str> {
|
||||||
|
if !self.validate_span_bytes(source.as_bytes(), span) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let range = span.as_usize_range()?;
|
||||||
|
source.get(range)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True when the span is in range and both ends are UTF-8 code-point
|
||||||
|
/// boundaries of the supplied original bytes.
|
||||||
|
pub fn validate_span_bytes(&self, bytes: &[u8], span: SourceSpan) -> bool {
|
||||||
|
let (Ok(start), Ok(end)) = (usize::try_from(span.start), usize::try_from(span.end)) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
if start > end || end > bytes.len() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
is_char_boundary(bytes, start) && is_char_boundary(bytes, end)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Byte offset of the start of a 1-based line.
|
||||||
|
pub fn line_start(&self, line: usize) -> Option<usize> {
|
||||||
|
if line == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
self.line_starts.get(line - 1).copied()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Number of lines in the source.
|
||||||
|
pub fn line_count(&self) -> usize {
|
||||||
|
self.line_starts.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Text of a 1-based line without its trailing newline.
|
||||||
|
pub fn line_text<'a>(&self, source: &'a str, line: usize) -> Option<&'a str> {
|
||||||
|
let start = self.line_start(line)?;
|
||||||
|
let end = self.line_starts.get(line).copied().unwrap_or(self.len);
|
||||||
|
let bytes = source.as_bytes();
|
||||||
|
let mut end = end.min(bytes.len());
|
||||||
|
if end > start && bytes.get(end - 1) == Some(&b'\n') {
|
||||||
|
end -= 1;
|
||||||
|
if end > start && bytes.get(end - 1) == Some(&b'\r') {
|
||||||
|
end -= 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
source.get(start..end)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 1-based line and 1-based byte column for a byte offset, clamped to the
|
||||||
|
/// file length. Column counts bytes, matching Core's presentation fields.
|
||||||
|
pub fn line_col(&self, byte: usize) -> (usize, usize) {
|
||||||
|
let byte = byte.min(self.len);
|
||||||
|
let line_index = match self.line_starts.binary_search(&byte) {
|
||||||
|
Ok(found) => found,
|
||||||
|
Err(insert) => insert.saturating_sub(1),
|
||||||
|
};
|
||||||
|
let line_start = self.line_starts[line_index];
|
||||||
|
(line_index + 1, byte - line_start + 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Byte offset → number of UTF-16 code units before it (JS string index).
|
||||||
|
pub fn utf16_offset(&self, source: &str, byte: usize) -> Option<usize> {
|
||||||
|
if byte > source.len() || !is_char_boundary(source.as_bytes(), byte) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(source[..byte].encode_utf16().count())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Byte offset for a UTF-16 offset, only when it lands on a boundary.
|
||||||
|
pub fn byte_for_utf16(&self, source: &str, utf16: usize) -> Option<usize> {
|
||||||
|
let mut units = 0usize;
|
||||||
|
for (byte, ch) in source.char_indices() {
|
||||||
|
if units == utf16 {
|
||||||
|
return Some(byte);
|
||||||
|
}
|
||||||
|
if units > utf16 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
units += ch.len_utf16();
|
||||||
|
}
|
||||||
|
if units == utf16 {
|
||||||
|
Some(source.len())
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True when an arbitrary `(line, column)` from a Core diagnostic is inside
|
||||||
|
/// the source index; line/column are presentation hints, spans are primary.
|
||||||
|
pub fn line_col_in_range(&self, line: u64, column: u64) -> bool {
|
||||||
|
let Ok(line) = usize::try_from(line) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let Ok(column) = usize::try_from(column) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
if line == 0 || column == 0 || line > self.line_starts.len() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let start = self.line_starts[line - 1];
|
||||||
|
let end = self.line_starts.get(line).copied().unwrap_or(self.len);
|
||||||
|
start + column - 1 <= end
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_char_boundary(bytes: &[u8], offset: usize) -> bool {
|
||||||
|
if offset == 0 || offset >= bytes.len() {
|
||||||
|
return offset <= bytes.len();
|
||||||
|
}
|
||||||
|
// UTF-8 continuation bytes start with 0b10.
|
||||||
|
bytes[offset] & 0b1100_0000 != 0b1000_0000
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn maps_multibyte_and_emoji_offsets() {
|
||||||
|
let source = "中文\nemoji🙂x\r\nlast";
|
||||||
|
let index = SourceIndex::new(source);
|
||||||
|
let emoji_byte = source.find('🙂').unwrap();
|
||||||
|
assert_eq!(index.line_col(emoji_byte), (2, 6));
|
||||||
|
let utf16 = index.utf16_offset(source, emoji_byte).unwrap();
|
||||||
|
assert_eq!(index.byte_for_utf16(source, utf16), Some(emoji_byte));
|
||||||
|
// Inside the emoji is not a char boundary.
|
||||||
|
assert!(index.utf16_offset(source, emoji_byte + 1).is_none());
|
||||||
|
let span = SourceSpan::new(emoji_byte as u64, (emoji_byte + 4) as u64);
|
||||||
|
assert_eq!(index.source_text(source, span), Some("🙂"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_out_of_range_and_misaligned_spans() {
|
||||||
|
let source = "# 数学";
|
||||||
|
let index = SourceIndex::new(source);
|
||||||
|
assert!(
|
||||||
|
index.validate_span_bytes(source.as_bytes(), SourceSpan::new(0, source.len() as u64))
|
||||||
|
);
|
||||||
|
assert!(!index.validate_span_bytes(
|
||||||
|
source.as_bytes(),
|
||||||
|
SourceSpan::new(0, source.len() as u64 + 1)
|
||||||
|
));
|
||||||
|
assert!(!index.validate_span_bytes(source.as_bytes(), SourceSpan::new(2, 1)));
|
||||||
|
// 2 is the middle of the 3-byte 字/数? Either way it is not a boundary
|
||||||
|
// for the CJK character starting at 2..5; check the interior byte 3.
|
||||||
|
assert!(!index.validate_span_bytes(source.as_bytes(), SourceSpan::new(3, 5)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn digest_is_exact_bytes() {
|
||||||
|
assert_eq!(
|
||||||
|
sha256_hex(b""),
|
||||||
|
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
sha256_prefixed(b"a"),
|
||||||
|
"sha256:ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bom_is_still_indexed() {
|
||||||
|
let source = "\u{feff}# hi";
|
||||||
|
let index = SourceIndex::new(source);
|
||||||
|
assert_eq!(index.bom_len(), 3);
|
||||||
|
assert_eq!(index.line_col(3), (1, 4));
|
||||||
|
assert_eq!(
|
||||||
|
index.source_text(source, SourceSpan::new(0, 3)),
|
||||||
|
Some("\u{feff}")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Controlled project root, path boundary and document source access.
|
||||||
|
//
|
||||||
|
// All production/HTTP/Export/tests use these functions; there is no second
|
||||||
|
// path validator (RFC-VIEW-0002 §5.2/§6.8).
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
use crate::error::{ViewError, ViewResult};
|
use crate::error::{ViewError, ViewResult};
|
||||||
use crate::source_map::sha256_hex;
|
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
/// Hard cap on one source document, matching the Core read limit family.
|
/// Hard cap on one source document, matching the Core read limit family.
|
||||||
@@ -306,86 +589,6 @@ impl Project {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Optional View-only site configuration (`view.json`).
|
|
||||||
///
|
|
||||||
/// This is **not** a Marqdo language protocol and cannot grant execution: only
|
|
||||||
/// the fields below are read, and the welcome path is still subject to the same
|
|
||||||
/// project-root boundary (RFC-VIEW-0001 §9.4).
|
|
||||||
#[derive(Debug, Clone, Default)]
|
|
||||||
pub struct ViewConfig {
|
|
||||||
pub welcome: Option<SafeRelativePath>,
|
|
||||||
pub site_title: Option<String>,
|
|
||||||
pub theme: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ViewConfig {
|
|
||||||
pub fn load(root: &Path) -> ViewResult<Self> {
|
|
||||||
let path = root.join("view.json");
|
|
||||||
let metadata = match std::fs::metadata(&path) {
|
|
||||||
Ok(metadata) => metadata,
|
|
||||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Self::default()),
|
|
||||||
Err(err) => return Err(ViewError::io(&format!("stat {}", path.display()), err)),
|
|
||||||
};
|
|
||||||
if !metadata.is_file() || metadata.len() > 64 * 1024 {
|
|
||||||
return Err(ViewError::PathForbidden {
|
|
||||||
detail: "view.json must be a regular file under 64 KiB".to_string(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
let bytes = std::fs::read(&path)
|
|
||||||
.map_err(|err| ViewError::io(&format!("read {}", path.display()), err))?;
|
|
||||||
#[derive(serde::Deserialize)]
|
|
||||||
struct RawConfig {
|
|
||||||
#[serde(default)]
|
|
||||||
schema: String,
|
|
||||||
#[serde(default)]
|
|
||||||
schema_version: u32,
|
|
||||||
#[serde(default)]
|
|
||||||
welcome: Option<String>,
|
|
||||||
#[serde(default)]
|
|
||||||
site_title: Option<String>,
|
|
||||||
#[serde(default)]
|
|
||||||
theme: Option<String>,
|
|
||||||
}
|
|
||||||
let raw: RawConfig = serde_json::from_slice(&bytes).map_err(|err| ViewError::Io {
|
|
||||||
detail: format!("view.json is not valid JSON: {err}"),
|
|
||||||
})?;
|
|
||||||
if raw.schema != "marqdo.view-config" || raw.schema_version != 1 {
|
|
||||||
return Err(ViewError::ProtocolIncompatible {
|
|
||||||
detail: format!(
|
|
||||||
"unsupported view.json schema {:?} version {}; expected marqdo.view-config v1",
|
|
||||||
raw.schema, raw.schema_version
|
|
||||||
),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
let welcome = match raw.welcome {
|
|
||||||
Some(path) => Some(SafeRelativePath::parse(&path)?),
|
|
||||||
None => None,
|
|
||||||
};
|
|
||||||
if let Some(welcome) = &welcome {
|
|
||||||
if !root.join(welcome.to_path()).is_file() {
|
|
||||||
return Err(ViewError::PathForbidden {
|
|
||||||
detail: format!(
|
|
||||||
"view.json welcome file {welcome} does not exist under the project root"
|
|
||||||
),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let site_title = raw
|
|
||||||
.site_title
|
|
||||||
.map(|title| title.trim().to_string())
|
|
||||||
.filter(|title| !title.is_empty() && title.chars().count() <= 80);
|
|
||||||
let theme = raw
|
|
||||||
.theme
|
|
||||||
.map(|theme| theme.trim().to_string())
|
|
||||||
.filter(|theme| theme == "botanical" || theme == "paper");
|
|
||||||
Ok(Self {
|
|
||||||
welcome,
|
|
||||||
site_title,
|
|
||||||
theme,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Discover the project root for a source file: nearest ancestor with
|
/// Discover the project root for a source file: nearest ancestor with
|
||||||
/// `marqdo.yaml`, else the file's directory. The file itself is canonical.
|
/// `marqdo.yaml`, else the file's directory. The file itself is canonical.
|
||||||
pub fn discover_project_root(file: &Path) -> PathBuf {
|
pub fn discover_project_root(file: &Path) -> PathBuf {
|
||||||
@@ -434,7 +637,7 @@ fn canonicalize(path: &Path, what: &str) -> ViewResult<PathBuf> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod path_tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||