From d0f1834e9860edd77cf0212d89d2072175b6a4f9 Mon Sep 17 00:00:00 2001 From: cflmy Date: Sun, 22 Nov 2026 12:46:05 +0800 Subject: [PATCH 01/21] docs(PR-00): adopt RFC-VIEW-0002 baseline, legacy and frozen-CLI audits - move RFC-0001 to docs/architecture and ADRs to docs/decisions; add ADR-0007 - add static legacy View audit with KEEP_ASSET/REIMPLEMENT/DROP/UNKNOWN and LEGACY_RUNTIME_UNVERIFIED declaration - add frozen CLI black-box contract audit (check/run/call, function-name resolution, JSON envelopes, Trace v2 binding, Tool v1 dispatch) - add living CONFORMANCE matrix and refresh STATUS with remaining 0002 gaps - mark 0001 ACCEPTANCE as historical evidence, not 0002 release gate --- CHANGELOG.md | 14 + COMPATIBILITY.md | 2 +- README.md | 18 +- docs/ACCEPTANCE.md | 6 + docs/CONFORMANCE.md | 119 ++ docs/STATUS.md | 128 +- docs/{ => architecture}/RFC-VIEW-0001.md | 0 docs/architecture/RFC-VIEW-0002.md | 1030 +++++++++++++++++ docs/audits/legacy-view.md | 136 +++ docs/audits/protocol-contract-0002.md | 222 ++++ .../0001-single-package-single-pipeline.md | 0 .../0002-embedded-assets-tool-protocol.md | 0 ...0003-heading-prefix-and-anchor-identity.md | 0 .../0004-explicit-run-csrf-and-cache.md | 0 docs/{ADR => decisions}/0005-static-export.md | 0 .../{ADR => decisions}/0006-rfc-deviations.md | 0 .../0007-rfc-view-0002-rebaseline.md | 73 ++ 17 files changed, 1686 insertions(+), 62 deletions(-) create mode 100644 docs/CONFORMANCE.md rename docs/{ => architecture}/RFC-VIEW-0001.md (100%) create mode 100644 docs/architecture/RFC-VIEW-0002.md create mode 100644 docs/audits/legacy-view.md create mode 100644 docs/audits/protocol-contract-0002.md rename docs/{ADR => decisions}/0001-single-package-single-pipeline.md (100%) rename docs/{ADR => decisions}/0002-embedded-assets-tool-protocol.md (100%) rename docs/{ADR => decisions}/0003-heading-prefix-and-anchor-identity.md (100%) rename docs/{ADR => decisions}/0004-explicit-run-csrf-and-cache.md (100%) rename docs/{ADR => decisions}/0005-static-export.md (100%) rename docs/{ADR => decisions}/0006-rfc-deviations.md (100%) create mode 100644 docs/decisions/0007-rfc-view-0002-rebaseline.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 30cb894..776a277 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,20 @@ Protocol axes (Tool v1, Analysis v2, Trace v2) are versioned separately. ## [Unreleased] +### 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 - PR-00: legacy View static audit (`docs/audits/legacy-render-paths.md`), visual diff --git a/COMPATIBILITY.md b/COMPATIBILITY.md index 8074734..e7d4bd7 100644 --- a/COMPATIBILITY.md +++ b/COMPATIBILITY.md @@ -4,7 +4,7 @@ | 轴 | 本 View 值 | 说明 | |---|---|---| -| View 产品版本 | `0.1.0` | 独立 SemVer,与 CLI 不共用 | +| View 产品版本 | `0.1.0`(目标 `0.2.0`,RFC-VIEW-0002 PR-01 升级) | 独立 SemVer,与 CLI 不共用 | | `marqdo` 产品范围 | `>=3.0.0-beta.1,<4.0.0` | 安装与分发时由 CLI 强制校验 | | CLI Tool Protocol | `1` | `tool.json` 清单/整包摘要/分发 | | Analysis | `2` | 未知 major 直接拒绝,不回退 | diff --git a/README.md b/README.md index 8ede561..19e0f3a 100644 --- a/README.md +++ b/README.md @@ -5,11 +5,16 @@ Marqdo View 是一个独立的可执行文档阅读器:以**原始 Markdown 附着回原文,而不是把文档翻译成另一套语言。 - 状态(唯一现状来源):[`docs/STATUS.md`](docs/STATUS.md) -- 验收结果与证据:[`docs/ACCEPTANCE.md`](docs/ACCEPTANCE.md) -- 架构规范:[`docs/RFC-VIEW-0001.md`](docs/RFC-VIEW-0001.md) -- 旧 View 静态审计:[`docs/audits/legacy-render-paths.md`](docs/audits/legacy-render-paths.md) -- 协议一致性:[`docs/audits/protocol-conformance.md`](docs/audits/protocol-conformance.md) +- **实施规范(当前)**:[`docs/architecture/RFC-VIEW-0002.md`](docs/architecture/RFC-VIEW-0002.md) +- 0002 合规矩阵:[`docs/CONFORMANCE.md`](docs/CONFORMANCE.md) +- 历史基础设计:[`docs/architecture/RFC-VIEW-0001.md`](docs/architecture/RFC-VIEW-0001.md) +- 旧 View 静态审计:[`docs/audits/legacy-view.md`](docs/audits/legacy-view.md) +- 冻结 CLI 合同审计:[`docs/audits/protocol-contract-0002.md`](docs/audits/protocol-contract-0002.md) - 兼容性:[`COMPATIBILITY.md`](COMPATIBILITY.md) / 变更:[`CHANGELOG.md`](CHANGELOG.md) +- 决策记录:[`docs/decisions/`](docs/decisions/) + +> **当前开发状态**:仓库正按 RFC-VIEW-0002 迭代(PR-00~PR-06)。下方能力表与 +> 限制按实际实现更新;未完成项以 `docs/STATUS.md` 为准,不宣称 0002 已完成。 ## 能力 @@ -18,11 +23,12 @@ Marqdo View 是一个独立的可执行文档阅读器:以**原始 Markdown | 原始 Markdown + GFM 阅读、源码态、文档态 | ✅ | | Analysis v2 静态语义(函数/Unit/签名/诊断/导入/引用/资源) | ✅ 严格校验,span 无效则降级 | | 本机 Live 阅读(默认 `127.0.0.1`,只读 API) | ✅ | -| 用户确认后运行 + 真实 Trace v2 可视化(`pure` 模式) | ✅ 需要页面内确认 + CSRF | +| 用户确认后运行 + 真实 Trace v2 可视化(`pure` 模式) | ✅(0001 同步模型;0002 的 SSE 异步闭环开发中) | | 纯只读静态导出(离线 `file://`、manifest/哈希、原子发布) | ✅ | +| 单函数参数表单 + 受控 `project` fs grants | 🚧 RFC-VIEW-0002 PR-03/04 | +| SSE 状态推送 / 取消 / 断线重放(禁止轮询) | 🚧 RFC-VIEW-0002 PR-04(MVP 阻塞项) | | 逐语句变量值 / 参数值 / 内存快照 | ❌ UNSUPPORTED(协议不提供,绝不伪造) | | 知识“已证明” / Prove / Lint / 调试器 | ❌ 非目标/等待独立协议 | -| `project`/`strict` 运行、SSE、多运行历史 | ❌ 未实现(首版仅 `pure`) | ## 安装 diff --git a/docs/ACCEPTANCE.md b/docs/ACCEPTANCE.md index be73d1f..782343d 100644 --- a/docs/ACCEPTANCE.md +++ b/docs/ACCEPTANCE.md @@ -1,5 +1,11 @@ # 验收状态(RFC-VIEW-0001 §18) +> **历史证据说明(2026-11-22)**:本文件的 PASS 是 **RFC-VIEW-0001 时期** +> 的验收结论,用作已实现能力的证据来源,**不是 RFC-VIEW-0002 的发布门禁**。 +> 0002 要求 SSE、7 路由、单函数调用、project grants、0.2.0 发行包与新的浏览器 +> 矩阵;这些将在 PR-04~PR-06 重新验收并更新本文件(见 `docs/CONFORMANCE.md`)。 + + > 结论:首个 Beta 的 **P0 门禁全部 PASS**(由真实冻结 CLI + 真实 Chromium 生成, > 见 `docs/evidence/2c7c4f31e7a388d3fcfa717a77067e696ed13854/manifest.json`)。 > P1 视觉/交互门禁大部分 PASS,**U-01 像素级人工比对与 U-04 动态曲线侧注未完成/未实现**, diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md new file mode 100644 index 0000000..d0306bd --- /dev/null +++ b/docs/CONFORMANCE.md @@ -0,0 +1,119 @@ +# RFC-VIEW-0002 合规矩阵(CONFORMANCE) + +> 活文档:每完成一个 PR 更新。状态值: +> `PASS`(本仓库实现 + 可复现证据)、`PARTIAL`(部分实现/证据待补)、 +> `PENDING`(未开始)、`N/A`(0002 明确非目标/删除项)。 +> 证据列写测试/脚本文档;不得以视觉相似代替测试。 + +最后更新:2026-11-22(PR-00) + +## 1. §0 核心不可妥协条件 + +| # | 条款 | 状态 | 实现位置 / 证据 | +|---|---|---|---| +| M1 | 独立构建/测试/打包/安装;不改/不重编译 CLI;无私有 crate/Git/path 依赖 | PASS(0001 基线) | `Cargo.toml`、`tests/no_coupling.rs`、`tools/acceptance.sh`(SHA 前后一致) | +| M2 | 语言真相=Analysis v2;运行真相=`run/call --json`+Trace v2;原文=`.mq.md`;Markdown 不判语义 | PARTIAL | 已实现 Analysis 严格校验与 Trace 绑定;`call` 入口与请求合同待 PR-03/04 | +| M3 | 打开/刷新/搜索/切换/导出/预览/目录/诊断绝不运行 | PASS(0001 证据,待 0002 复核) | `tests/http_live.rs`、`tests/export.rs`、浏览器证据 | +| M4 | 单一 Read Model / HTML 组件 / CSS / JS;Live=Export | PASS(0001 证据) | `src/render.rs`、`src/assets.rs`、`tests/no_coupling.rs`、`tests/asset_integrity.rs` | +| M5 | 原生执行只经 `MARQDO_BIN run/call` 子进程;无第二运行时 | PARTIAL | 子进程已有;`call` 与取消/状态机待 PR-03/04 | +| M6 | Tool 是普通进程;不得宣称 OS 沙箱 | PARTIAL | 文档已声明;UI 文案待 PR-04/06 复核 | +| M7 | 不开发 lint/knowledge/prove;无硬依赖 | N/A(合规) | 无相关目录/依赖 | +| M8 | 可见按钮必须有效;无公开数据/执行能力的面板删除 | PARTIAL | 现 UI 仍有“变量/内存不支持”入口(解释性);PR-04 复核 | + +## 2. §1.2 功能范围(MVP 强制项) + +| 功能 | 状态 | 计划/证据 | +|---|---|---| +| Markdown/GFM 阅读 | PASS | `src/document.rs`、`src/render.rs`、浏览器证据 | +| `@exec`/`@knowledge` 轻量标识(依 Analysis) | PASS | `src/semantic.rs`、`tests/rendering.rs` | +| 源码态 | PASS | `src/render.rs`、`tests/unicode_spans.rs` | +| 函数清单/导航 | PASS | `src/presentation.rs`、`src/render.rs` | +| 单函数参数填写 + 调用 | **PENDING** | PR-03 请求合同 + PR-04 前端表单 | +| 文档入口 `main` 执行 | PARTIAL | 同步 pure 已存在;需改为 SSE 异步任务(PR-04) | +| 运行结果(返回/stdout/stderr/错误) | PARTIAL | 0001 已有;需 0002 JSON→UI 映射与安全文本展示复核(PR-04/05) | +| Trace v2 调用/判断/循环/副作用 | PARTIAL | `src/trace.rs` 已有;需 SSE 后动态标注与 stale 规则(PR-04/05) | +| 执行确认/取消/超时/单任务 | **PENDING** | PR-03/04 | +| **SSE 状态与终态(禁止轮询)** | **PENDING(阻塞)** | PR-04 | +| 独立 Tool 安装/调用 | PASS(0001) | PR-01 迁移到 0.2.0/scripts | +| 静态 HTML 导出 | PARTIAL | 已实现;PR-06 复核零执行/离线 | +| 暖纸/品牌/樱花/侧注/Dock | PARTIAL | 已有;PR-05 视觉矩阵 | +| 搜索 + 目录 | PASS | 浏览器证据 | +| 有选择的 Observed 侧注/退化 | PARTIAL | 内联 chip 已有;SSE 后按本次运行更新(PR-04/05) | +| 深色主题/字号/显示设置 | PARTIAL | 已有字号/标注开关/print;深色待 PR-05 | +| project fs read/write grants | **PENDING** | PR-03/04(MVP CONTROLLED) | +| net/process/env/plugin 等授权 | N/A(DEFERRED,必须拒绝并提示 CLI) | PR-03 校验 | +| 变量/内存/Notebook/调试/Session/AI/Kernel | N/A(REMOVED) | 禁止出现 DOM/路由/状态 | + +## 3. §5 架构与目录 + +| 条款 | 状态 | 说明 | +|---|---|---| +| 唯一 Reader+Controller+CLI;无 DocumentService→Execution 隐式调用 | PARTIAL | 现同步架构无隐式执行;SSE 后复核 | +| 层间数据结构(SourceDocument/AnalysisArtifact/SemanticAnchor/ExecutionRecord/PresentationModel) | PARTIAL | 现有类型可映射;PR-02/03 重整 | +| §5.3 目标目录(protocol/reader/execution/server/scripts/tests 树) | **PENDING** | PR-01/02/04 迁移 | +| §5.4 单一渲染流水线;Export 类型边界不可执行 | PASS(0001) | `src/export.rs` 不依赖执行层;PR-06 复核 | +| 无第二 Markdown AST/解释器/主题/JS 入口 | PASS | `tests/no_coupling.rs`、`tests/asset_integrity.rs` | + +## 4. §6 HTTP / SSE / 执行合同 + +| 条款 | 状态 | 计划 | +|---|---|---| +| 7 条最小路由 | **PENDING** | PR-04 | +| POST /api/runs 两阶段确认请求体(document/target/parameters/analysis_digest/mode/grants/client_request_id) | **PENDING** | PR-03/04 | +| 校验顺序(会话→CSRF/Origin/Host→大小/schema→containment→check→digest→函数/参数→模式/grants→并发→202) | **PENDING** | PR-03/04 | +| 同 `client_request_id` 幂等/不同 payload 409 | **PENDING** | PR-04 | +| SSE 帧合同(事件类型/seq/id/schema/心跳) | **PENDING** | PR-04 | +| Last-Event-ID 重放、快照、128 缓冲、TTL、≤2 连接/任务 | **PENDING** | PR-04 | +| 单活动任务、409 run.busy、后台执行不阻塞 SSE | **PENDING** | PR-03/04 | +| 进程组取消(TERM→2s→KILL)、墙钟上限、有界输出 | **PENDING** | PR-03 | +| 显式预算参数 | **PENDING** | PR-03 | +| 会话 Cookie(HttpOnly/SameSite=Strict)+ X-View-CSRF + Origin/Host | **PENDING** | PR-04 | +| loopback only、请求体≤64KiB、CSP、路径 containment | PARTIAL | 大部分已有;会话 Cookie 待 PR-04 | +| SSE 按会话隔离、跨站读取拒绝 | **PENDING** | PR-04 | + +## 5. §8 里程碑 + +| PR | 状态 | 提交 | +|---|---|---| +| PR-00 取证/基线 | **完成** | 待提交(本提交) | +| PR-01 Tool/打包/scripts/CI/0.2.0 | PENDING | — | +| PR-02 Reader/Analysis 结构与只读路由 | PENDING | — | +| PR-03 执行层/请求/进程/控制器 | PENDING | — | +| PR-04 SSE/路由/会话/前端闭环 | PENDING | — | +| PR-05 Trace 绑定/标注/浏览器回归 | PENDING | — | +| PR-06 导出/发布/文档闭环 | PENDING | — | + +## 6. §9 验收测试矩阵(E01–E16 / N01–N22) + +| 组 | 状态 | 说明 | +|---|---|---| +| E01 Tool 安装/卸载/分发 | PASS(0001 证据;PR-01 重跑) | `tools/acceptance.sh` | +| E02 打开 knowledge+exec 文件不运行 | PASS | `tests/http_live.rs` | +| E03 Source/Document 切换 | PASS | 浏览器证据 | +| E04 中文/Emoji/表格/公式 span | PASS | `tests/unicode_spans.rs`、golden | +| E05 main 运行 run --json --trace-file | PARTIAL | 同步路径有;SSE 终态待 PR-04 | +| E06 H2 Exec n=5 call | **PENDING** | PR-03/04 | +| E07 文本/列表常量参数 | **PENDING** | PR-03/04 | +| E08 无 main 不自动运行别的函数 | PARTIAL | 现有 `can_offer_run` 逻辑;PR-04 复核 | +| E09 Trace 事件映射不伪造变量 | PARTIAL | `src/trace.rs`;SSE 后复核 | +| E10 SSE text/event-stream 无 polling | **PENDING** | PR-04 | +| E11 Last-Event-ID 重连 | **PENDING** | PR-04 | +| E12 长任务心跳/GET 不重启 | **PENDING** | PR-04 | +| E13 取消终止进程树 | **PENDING** | PR-03/04 | +| E14 静态导出零联网/相对链接 | PARTIAL | 已实现;PR-06 复核 | +| E15 刷新/重开不自动执行 | PASS | `tests/http_live.rs` | +| E16 运行后改源码 → stale 无高亮 | PARTIAL | 现有 stale;PR-05 复核 | +| N01–N22 | PARTIAL | 0001 已覆盖部分(路径/XSS/跨站/digest/超时/打包完整性);SSE/去重/取消/会话项待 PR-04 补齐,逐项记录在 PR-05/06 证据 | + +## 7. §10 发布门禁 + +| 门禁 | 状态 | +|---|---| +| 1. PR-00~06 + P0 检验,无伪交付 | PENDING | +| 2. Tool 独立安装;CLI 无 View 核心提交;SHA 不变 | PARTIAL(0001 已证 SHA 不变,需 0.2.0 重跑) | +| 3. 打开/刷新/导出零副作用;执行仅来自显式 POST;跨站/CSRF 全绿 | PARTIAL(同步模型已覆盖,SSE 模型待补) | +| 4. SSE 生命周期/心跳/序号/重连/有界重放;无轮询 | **PENDING** | +| 5. 真值来自 CLI/Analysis/Trace;无假变量/内存/证明 | PASS(设计) | +| 6. Live/Export 同一 HTML/CSS/JS;无旧叠层 | PASS(0001 证据) | +| 7. Linux x86_64 可重现包;README/帮助/限制一致 | PENDING(PR-06) | +| 8. N01–N22 至少覆盖;失败不执行不泄漏不提升权限 | PENDING | diff --git a/docs/STATUS.md b/docs/STATUS.md index 3257479..bb8c125 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -1,81 +1,99 @@ # marqdo-view 现状(STATUS) -> 唯一现状来源。设计/规范见 RFC 与 ADR;本文只记录**实际完成、证据与限制**。 -> 最后更新:2026-11-22(PR-06 完成) +> 唯一现状来源。规范见 `docs/architecture/RFC-VIEW-0002.md`;本文只记录 +> **实际完成、证据与限制**。最后更新:2026-11-22(RFC-VIEW-0002 PR-00 完成) ## 版本与基线 | 项 | 值 | |---|---| -| View 版本 | `0.1.0` | +| View 产品版本 | `0.1.0`(目标 `0.2.0`,PR-01 升级) | +| 实施规范 | `docs/architecture/RFC-VIEW-0002.md`(2026-11-22) | | 目标 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`) | -| 协议 | Tool v1 / Analysis v2 / Trace v2 / markdown profile `marqdo.md.v1` | -| 目标平台 | Linux x86_64 glibc(正式);其他平台未验证 | -| 视觉基准 | `docs/design/reference-old-view-reader.png`(1664×920) | -| 验收证据 | `docs/evidence//manifest.json`(由 `tools/acceptance.sh` 真实命令生成) | +| 协议 | Tool v1 / Analysis v2 / Trace v2 / `marqdo.md.v1` | +| 目标平台 | Linux x86_64 glibc(正式);其他平台不支持/未验证 | +| 视觉基准 | `docs/design/reference-old-view-reader.png`(**2048×1133**) | -## 分阶段进度 +## RFC-VIEW-0002 里程碑 | 阶段 | 状态 | 证据 | |---|---|---| -| PR-00 基线与旧 View 静态取证 | **完成** | `docs/audits/legacy-render-paths.md`、`docs/design/*`、ADR-0001/0002 | -| PR-01 Tool v1 安装闭环 | **完成** | `tool.json`、`tools/package.sh`、`tools/install-smoke.sh`、`tests/core_contract.rs`、`tests/no_coupling.rs` | -| PR-02 DocumentModel + Analysis v2 浏览 | **完成** | `src/document.rs`、`src/semantic.rs`、`src/presentation.rs`、`src/render.rs`、`src/server.rs`、冻结 Analysis golden | -| PR-03 Reader 视觉重建 | **完成(像素级人工比对未执行)** | 单一 `assets/reader.css`/`reader.js`;真实 Chromium 7 宽度/无 JS/打印/运行 PASS;`docs/evidence/PR-03/` | -| PR-04 Trace v2 运行可视化 | **完成** | `src/trace.rs`、CSRF/确认运行 API、真实 Trace golden、`tests/trace_contract.rs`、ADR-0004 | -| PR-05 Live 安全 + 静态导出 | **完成** | `src/export.rs`、`tools/test-export.sh`、`tools/test-security.sh`、`tests/export.rs`、ADR-0005 | -| PR-06 冻结 CLI 端到端验收 | **完成(CI 远端未运行)** | `tools/acceptance.sh` 全部 PASS;`docs/evidence//manifest.json`;`docs/ACCEPTANCE.md`;ADR-0006 | +| PR-00 基线、旧 View 取证、冻结 CLI 合同 | **完成** | `docs/audits/legacy-view.md`、`docs/audits/protocol-contract-0002.md`、`docs/decisions/0007` | +| PR-01 Tool v1 打包/安装/调度、0.2.0、scripts/、CI | 待开始 | — | +| PR-02 Reader/Analysis 只读面与目标目录结构 | 待开始(现有 0001 实现可迁移) | `src/document.rs`、`src/semantic.rs`、`src/render.rs`、`src/server.rs` | +| PR-03 执行层:request/process/controller、pure + project grants | 待开始(现有同步 `pure` 执行可迁移) | `src/core_client.rs`、`src/app.rs` | +| PR-04 SSE 任务生命周期、取消、7 路由、会话 Cookie/CSRF | **未实现(MVP 阻塞项)** | — | +| PR-05 Trace 绑定/原文标注/浏览器回归 | 待开始(现有 Trace 校验可迁移) | `src/trace.rs` | +| PR-06 静态导出/发布包/文档闭环 | 待开始(现有导出可迁移) | `src/export.rs` | -## 能力现状 +## 继承自 0001 的可用资产(不等于 0002 验收通过) -| 能力 | 状态 | +以下能力已实现并有测试/证据,但需在 0002 架构下迁移、补路由/SSE 与重新验收: + +| 能力 | 现状 | |---|---| -| 原始 Markdown 阅读(GFM 表/任务列表/引用/围栏/数学原文) | 已实现 | -| 文档态 / 源码态(原文逐行,含标记) | 已实现 | -| Analysis v2 静态语义(Unit/Function/Signature/诊断/导入/引用/资源) | 已实现,严格校验 + 无效 span 降级 | +| 原始 Markdown/GFM 阅读、源码态、搜索/设置/打印 | 已实现(单一 `assets/reader.css`/`assets/reader.js`) | +| Analysis v2 严格校验、函数/Unit/签名/诊断/导入/引用/资源投影 | 已实现(无效 span 降级) | | 单一 `ReaderRenderer`,Live/Export 共用 | 已实现(门禁测试) | -| Live 只读 API(`/`、`/file`、`/assets`、`/api/document`、`/api/health`) | 已实现 | -| 显式确认运行 + Trace v2 可视化(`pure` 模式) | 已实现(CSRF/Origin/单活动/超时) | -| 静态离线导出(纯只读、manifest/哈希、原子发布) | 已实现 | -| 搜索/导航/设置/打印/无 JS/响应式 | 已实现(真实浏览器验收) | -| `view verify`(CLI/Analysis/source 绑定,无执行) | 已实现 | -| 逐语句变量值 / 参数实际值 / 内存快照 | **UNSUPPORTED**(Trace v2 不提供,绝不伪造) | -| 知识“已证明” / Prove / Knowledge / Lint | **UNSUPPORTED**(等待独立协议) | -| 调试器/断点/单步、Notebook、旧 2.x 语法 | **不实现**(非目标) | -| `project`/`strict` 运行与 grants 授权界面 | **未实现**(首版仅 `pure`,拒绝其他模式) | -| SSE 流式输出、多运行历史、取消运行 | **未实现**(运行完成后整页重载) | -| SVG 曲线侧注 | **未实现**(使用内联 keyed chip,U-04 PARTIAL) | -| 像素级视觉比对 | **UNVERIFIED**(人工复核待办,U-01) | -| 远端 CI 实际运行 | **UNVERIFIED**(`.woodpecker.yml` 已提供;本地可复现证据已生成) | +| 显式确认后同步运行 `pure` + Trace v2 校验与展示 | 已实现,但**不是 0002 的异步 SSE 闭环** | +| 静态离线导出(无执行、manifest/哈希、原子发布) | 已实现,待按 0002 重新验收 | +| Tool v1 打包/安装/分发、冻结 CLI SHA 前后一致 | 已实现,待迁移至 `scripts/` 与 0.2.0 | +| HTTP 安全(Host/Origin/CSRF/路径 containment/CSP) | 部分实现;缺**会话 Cookie**模型与 7 路由合同 | +| 真实 Chromium 视觉/交互/无 JS/打印 | 已有证据(0001 时期),待按 0002 宽度矩阵重跑 | -## 验收证据 +## 与 RFC-VIEW-0002 的已知差距(全部必须关闭) -- 一键:`MARQDO_BIN=/abs/path/marqdo tools/acceptance.sh` -- 全链路结果:`fmt/clippy/test/build/bundle/archive_install/view_help/verify/export/browse/real_run/export_suite/security_suite/browser/core_sha` 全部 PASS。 -- 冻结核心 SHA-256 在验收前后完全相同(`062cb56e…`),View 从未重编译/链接 CLI。 -- 安装来自 `.tar.gz` 发布归档解包到临时目录;不读取 CLI 源码或旧仓库运行代码。 -- 浏览器:Chromium Headless Shell 131(Playwright 1.49),7 个宽度、无外部请求、无 console 错误、无 JS 可读、打印、恶意 fixture、显式运行。 -- 详见 `docs/ACCEPTANCE.md` 与 `docs/evidence/`。 +1. **SSE 执行闭环缺失**:当前是 POST 同步运行后整页重载;0002 要求 + `POST /api/runs` → 202 → `GET /api/runs/{id}/events` SSE(无轮询)→ + accepted/running/终态;断线 `Last-Event-ID` 重放、128 事件环形缓冲、终态 TTL。 +2. **路由未收敛**:现为 `/api/run`、`/api/clear-run`、`/api/document`、 + `/api/health`;0002 只允许 + `GET /`、`GET /file`、`GET /assets/...`、`GET /api/documents`、 + `POST /api/runs`、`GET /api/runs/{id}/events`、`POST /api/runs/{id}/cancel`。 +3. **无单函数调用表单**:函数目前只有跳转列表;缺基于 Analysis 签名的参数填写、 + 命令预览、`--arg` 常量表达式提交。 +4. **无 project grants**:0002 要求受控 fs read/write glob(明确二次确认), + 其它 net/process/env/plugin 一律拒绝并引导 CLI。 +5. **无运行会话 Cookie**:CSRF 目前是进程级 token;0002 要求 + `HttpOnly; SameSite=Strict` 随机会话 Cookie + 每会话 CSRF,且 SSE 按会话隔离。 +6. **无取消/单任务状态机/重复请求去重**:缺 `cancel_requested`、唯一终态、 + `client_request_id` 幂等/409、409 run.busy。 +7. **执行预算未按 0002**:默认 30s(最大 120s)、`--fuel 1000000`、 + `--max-output 1048576`、`--trace-max-events 10000`、`--trace-max-bytes 4194304`、 + JSON/Trace/日志 4 MiB 有界读取与 `view.output_limit` 未实现。 +8. **目录/测试/脚本/示例未按 0002 §5.3**:缺 `src/protocol`、`src/reader`、 + `src/execution`、`src/server`、`tests/{contract,integration,security,browser, + fixtures,golden}`、`scripts/`、`examples/{welcome,branch-loop,function-params, + knowledge-only,unsafe-side-effect}.mq.md`、`.github/workflows/ci.yml`。 +9. **版本与文档**:View 仍为 0.1.0;README/COMPATIBILITY/ACCEPTANCE 仍以 0001 + 为口径,需在 PR-06 前全部更新。 +10. **视觉回归矩阵**:0002 要求 2048×1133 源参考与 1664×920/1440×900/1024×768/ + 768×1024/390×844 宽度;现有截图集合不完整。 -## 已知限制与偏差 +## 明确 UNSUPPORTED / 非目标(不得伪造) -- 测试按 crate 根级集成测试文件组织,而非 RFC 建议的子目录树;职责与门禁不变(ADR-0006)。 -- 运行完成后整页重载;不实现 SSE/取消/历史。 -- 静态导出每个文档执行一次 `check`(非执行),无增量导出。 -- 首版运行仅 `pure`;`project`/`strict` grants 需要未来独立授权 UI。 -- 平台:仅 Linux x86_64 glibc 正式验证;macOS/Windows 未验证。 -- 视觉:几何/颜色/响应式/无外部资源自动化 PASS,但像素级人工比对未执行。 +- 逐语句变量值、参数实际值、内存快照/地址寄存器:Trace v2 不提供,永远显示 + “不支持”,不得用 `value` 代替。 +- 知识“已证明”/Prove、Lint、Knowledge 编译:独立仓库/未来版本化报告。 +- Notebook/Run All/持久内核、断点/单步/调用栈/时间旅行、Session/journal/snapshot。 +- AI/Agent/LLM Token 流、插件市场/热插拔、数据库/账号/多租户。 +- 第二套 Markdown AST/解释器/`inspect --ir` 解析:FORBIDDEN。 +- Windows/macOS 发行、`strict` 模式按钮、net/process/env/foreign 授权 UI:首版不做。 + +## 复现与证据 + +- 冻结 CLI 合同与实测:`docs/audits/protocol-contract-0002.md` +- 旧 View 取证:`docs/audits/legacy-view.md`(静态;运行时 `LEGACY_RUNTIME_UNVERIFIED`) +- 0002 条款映射:`docs/CONFORMANCE.md` +- 验收(0001 时期,历史):`docs/ACCEPTANCE.md`、`docs/evidence/` +- 0001 时期一键验收脚本:`tools/acceptance.sh`(PR-01 后迁移为 `scripts/` 口径) ## 复现文档 -- 一分钟使用:`README.md` -- 规范:`docs/RFC-VIEW-0001.md` +- 使用/安装:`README.md` +- 规范:`docs/architecture/RFC-VIEW-0002.md`(当前)、`RFC-VIEW-0001.md`(历史) - 兼容性:`COMPATIBILITY.md` - 变更:`CHANGELOG.md` -- 旧 View 审计:`docs/audits/legacy-render-paths.md` -- 协议一致性:`docs/audits/protocol-conformance.md` -- 验收:`docs/ACCEPTANCE.md` -- 决策:`docs/ADR/0001..0006` +- 决策:`docs/decisions/0001..0007` diff --git a/docs/RFC-VIEW-0001.md b/docs/architecture/RFC-VIEW-0001.md similarity index 100% rename from docs/RFC-VIEW-0001.md rename to docs/architecture/RFC-VIEW-0001.md diff --git a/docs/architecture/RFC-VIEW-0002.md b/docs/architecture/RFC-VIEW-0002.md new file mode 100644 index 0000000..853df4f --- /dev/null +++ b/docs/architecture/RFC-VIEW-0002.md @@ -0,0 +1,1030 @@ +# RFC-VIEW-0002:Marqdo View 3.0 交互式执行闭环与产品精简实施规范 + +> **状态**:Proposed / 具备直接实施所需的设计、约束、测试和验收定义;并非完成声明。 +> **目标仓库**:独立 `marqdo-view`,建议路径 `docs/architecture/RFC-VIEW-0002.md`。 +> **发布日期/审查基线**:2026-11-22。 +> **CLI 唯一公开核心**:`https://github.com/cflmy/marqdo-cli`,审查 `master@eeea01d672c07b6be7d6444031d1619309dc88ab`;首个公开 Beta 源码为 `v3.0.0-beta.1@2c7c4f31e7a388d3fcfa717a77067e696ed13854`。 +> **旧产品,仅供视觉/历史取证**:`https://github.com/cflmy/marqdo`,参考 `main@1c55baabd570e18b9da8f9057cef2f848e176690`。 +> **原始视觉基准**:`docs/design/reference-old-view-reader.png`(2048×1133;截图本身来自用户提供);开发包随附同名图。 +> **公开接口**:Marqdo CLI 3.0.0-beta.1,Tool Protocol v1、Analysis v2、Trace v2;首要支持平台 Linux x86_64。 +> **文档性质**:这是**完整且自足的实施 RFC**。若已有 RFC-VIEW-0001,以本文件有关执行、功能范围、安全、简化后的页面及发布门禁的规定为准;**不能要求开发者先阅读 0001 或历史聊天才能实施**。 + +--- + +## 0. 如何使用本文、证据分级与强制规则 + +本文把“已经存在的核心能力”和“要求新 View 开发的能力”明确分开: + +- **CORE-EXISTS**:已从指定 `marqdo-cli` 提交中的 `spec/` 或 Rust 源码核实,如 `marqdo tool install`、`check --emit`、`run/call --json --trace-file`。仅意味着接口存在,不代表本项目的调用/包装已经测试通过。 +- **LEGACY-OBSERVED**:已从旧 `marqdo` 仓库源码审计发现的入口、CSS/JS、渲染路径。这是迁移风险证据,不等于旧截图与 HEAD 产物已经经过浏览器逐像素复验。 +- **VIEW-REQUIRED**:本 RFC 新规定的 `marqdo-view` 功能、类型、路由、测试和性能/安全边界,需由开发者实现。 +- **VIEW-DEFERRED / REMOVED**:必须推迟或直接删除的旧功能,不能为了“功能还原”偷偷加入范围。 + +**决策优先级**:发布 CLI 的真实黑盒行为及同 tag 规范 > 本文所列核心事实摘要 > 本文针对新 View 的设计决定 > 旧 View 源码与截图的视觉线索。若 Beta CLI 的精确语法/参数与本文示例不符,先用其 `--help`、`spec/` 和黑盒测试确认差异;更新本文及 fixture,**绝不修改 CLI、添加第二解释器或伪造一次成功运行**。 + +**核心不可妥协条件(MUST)**: + +1. 新仓库独立构建、测试、打包、安装;**不更改和不重新编译** `marqdo-cli`,也不依赖其私有 Rust crate、Git/path 依赖或内部 IR。 +2. 所有语言真相来自官方 `check` 输出的 **Analysis v2**;运行真相来自官方 `run/call` 的 **JSON** 和 **Trace v2**;原始文档内容直接读取 `.mq.md`;Markdown 渲染器只管排版,**不判断可执行语义**。 +3. 打开、刷新、搜索、切换文件、静态导出、预览、生成目录和检查诊断**绝不运行程序**。运行必须是用户显式操作,且命令、函数、参数、权限清楚可见。 +4. **单一 Read Model、单一 HTML 组件体系、单一 CSS 主题入口、单一 JS 入口**。Live 和 Export 共用渲染代码;只改变链接策略和运行控件启用状态。 +5. 原生交互执行只允许通过 `MARQDO_BIN` 的 `run` 或 `call` 子进程;不引入 Jupyter/Notebook/REPL、隐式 session kernel、浏览器端表达式求值器、另一个 Host 或运行时状态机。 +6. Tool 本身是普通操作系统进程;CLI `pure`/`project` 不是 OS 沙箱,Worker 也不是 OS 安全沙箱。不得声称浏览器运行天然隔离。 +7. 不开发 `marqdo-lint`、`marqdo-knowledge`、`marqdo-prove`;未来只通过版本化可选报告叠加信息,不设硬依赖。 +8. 每个可见按钮必须实际有效;暂时不具备公开数据和执行能力的面板**直接删掉**,禁止灰色假按钮占据主界面。 + +### 0.1 一句话产品定义 + +> **Marqdo View 是一个“默认只读、显式调用、结果就地呈现”的可执行 Markdown 阅读器**。它不是 IDE,不是 Notebook,不是第二套 Marqdo 编译器,也不是知识/证明/AI 管理平台。 + +### 0.2 成功的用户任务 + +1. 用户执行 `marqdo view index.mq.md`,打开温暖、连续、原生 Markdown 阅读页面;**零程序副作用**。 +2. 用户在函数标题旁点击“调用”,从 Analysis v2 获得参数名/类型/是否必填,填入值,确认命令与权限,CLI 通过 `call` 执行,View 显示**真实返回值、标准输出、错误、Trace**。 +3. 用户点击底部金色“运行”,明确运行入口 `main`,结果同样回到当前阅读页。没有 `main` 则解释原因并建议选择函数;绝不自动找别的函数替代。 +4. 用户看到一次已执行的调用、判断和循环事件,能通过准确的源码位置阅读相关内容;不存在逐语句赋值值时不伪造。 +5. 用户执行 `marqdo view export . --out site/`,得到离线可读的静态 HTML,**无一次运行、无外部网络请求、无改写源项目**。 +6. 完全离线、只安装已发布的 `marqdo` 和新 View 的机器即可运行上述流程,完全不需要历史 Marqdo 工作树。 + +### 0.3 明确不承诺 + +不承诺旧版 View 的调用帧参数值/逐句变量值/内存状态;不承诺实时 LLM Token 流、持久内核、断点和单步调试;但交互式执行的状态与结果必须通过 SSE 推送,禁止浏览器轮询;不承诺未知外部扩展安全;不承诺跨平台发行或对任意旧 `.mq.md` 自动升级。所有缺失项需在 UI 中以“未提供/不可用/不支持”表示,**不可当成不存在的运行事实**。 + +--- + +## 1. 为什么需要交互执行,为什么必须精简 + +### 1.1 交互执行是区别于普通 Markdown 阅读器的关键 + +Marqdo 的价值不是把源码染上颜色,而是使自然语言叙述、可调用函数和计算结果共享同一个文档上下文。单纯显示静态 Analysis 只能解释**可能怎样运行**,无法展示**这次确实做了什么**。一旦读者明确选择函数、填入参数、触发运行、查看返回及事件,就能在科研、教学、算法验证、领域 SKILL 阅读中形成实际闭环。 + +但必须防止旧版本的错误演进:View 因承载 Notebook、debug、知识编译、证明、事件总线、Agent、内存和会话等职责,产生多套 DOM 模板、重复 CSS/JS 和执行权限模糊。新 View 的价值来自**一个具体闭环的完成度**,不是功能数量。 + +### 1.2 产品功能范围(此表具有强制验收效力) + +| 功能 | 判定 | 原因 / 处理方式 | +|---|---|---| +| 普通 Markdown/GFM 阅读 | **MVP MUST** | View 的主体。保留段落、标题、列表、表格、代码围栏、公式、链接等原文顺序 | +| `@exec` 函数与 `@knowledge` 单元的轻量标识 | **MVP MUST** | 依据 Analysis;不推断未公开的完整 H3 有效模式 | +| 源码态(纯文本,准确映射) | **MVP MUST** | 证明代码即文档;只读,不内置编辑器 | +| 函数清单与函数导航 | **MVP MUST** | 支持发现可调用 H2;不展示复杂的变量图 | +| 单函数参数填写 + 调用 | **MVP MUST** | 直接验证 `marqdo call` 与 Analysis 签名 | +| 文档入口 `main` 执行 | **MVP MUST** | 直接验证 `marqdo run`;须显式操作 | +| 运行结果(返回、stdout、stderr、错误) | **MVP MUST** | 官方 `--json` 真值,用户最需要的反馈 | +| Trace v2 的调用/判断/循环/副作用事件 | **MVP MUST** | 官方的真实运行证据;无数据时安全降级 | +| 执行确认、取消、超时与单任务约束 | **MVP MUST** | 防误执行和资源泄漏,不是增加 Notebook | +| **SSE 实时执行状态与终态结果** | **MVP MUST** | 使用 POST 建立任务、GET SSE 接收状态/结果、POST 取消;**禁止轮询**,不承诺逐指令或 Token 实时流 | +| 独立 Tool 安装/调用 | **MVP MUST** | 验证内核与外围完全解耦 | +| 静态 HTML 导出 | **MVP MUST** | 文档价值可脱离本地服务;无执行副作用 | +| 暖纸色、品牌、樱花、轻量侧注、底部 Dock | **MVP MUST** | 保留给定截图的识别度,删除旧主题叠层 | +| 基础文内搜索和目录 | **MVP MUST** | 文档必要可达性;不做跨仓全文数据库 | +| 有选择地在侧注显示“本次确实发生的事件” | **MVP MUST** | 让结果回到原文,拥挤时退化为行内摘要 | +| 深色主题、字号与显示设置 | **MVP SMALL** | 可提供简单开关;不引入主题框架或在线皮肤市场 | +| 高级项目权限:选定 fs read/write glob | **MVP CONTROLLED** | 只在明确确认后 `--mode project`;按限制逐项允许 | +| 网络、进程、环境访问授权 | **DEFERRED** | 风险和 UI 复杂度较高,首版只能提示改用 CLI;不得静默授权 | +| Plugin/Provider/Foreign 可视化安装、授权、热插拔 | **DEFERRED** | 已有 CLI 可用,但 View 不应成为扩展管理器 | +| 变量面板(入口最终变量全集) | **REMOVED** | Trace v2 不提供;不能以老私有捕获替代 | +| 内存检查器、内存网格、地址寄存器 GUI | **REMOVED** | 是调试工具职责,不是阅读工具 | +| Notebook Cell / Run All / Restart Kernel | **REMOVED** | 需要持久内核,与一次 `run/call` 不同 | +| 断点、单步、调用栈、堆栈帧、时间旅行 | **REMOVED** | 需要独立调试协议,不属于 View 第一阶段 | +| Session / journal / snapshot replay / cell persistence | **REMOVED** | 引入第二个状态管理系统且无法使用现行公开协议实现 | +| AI 对话框、实时 LLM token 流、Agent 控制台 | **REMOVED** | 交给未来独立 Agent/Tool;CLI 暂无对应稳定协议 | +| View 内编译 Knowledge/Prove | **REMOVED** | 对应工具独立仓库,避免再次耦合 | +| 可视化格式修正和完整 Linter | **DEFERRED** | 后续独立 `marqdo-lint`;本版仅呈现 CLI diagnostics | +| 数据库、账号、多租户、工作台、知识后台、插件市场 | **REMOVED** | 不是本产品 | +| 第二套 Markdown AST / 解释器 / `inspect --ir` 解析 | **FORBIDDEN** | 破坏 3.0 语义单一权威 | + +**MVP CONTROLLED** 是首版需提供的安全受限项目运行:只接受相对项目根的精确 fs read/write grants,暂不把 `--allow-net/--allow-process/--allow-env/--allow-foreign/--plugin/--provider/--kernel/--trust-native-plugin` 暴露到浏览器中。完整高级执行由用户在终端运行 CLI。若项目已声明第三方扩展,Core 可能拒绝 `pure`;View 解释错误并引导外部 CLI,而不是猜测缺失的 grants 或自动降级到 `project`。 + +### 1.3 首版页面删减决策 + +给定截图旧顶部是 `文档 / 函数 / 变量 / 内存 / 运行`。新版本**只保留 `文档 / 函数 / 运行` 三项**;`源码`作为页面上的切换或“更多”中的明确入口,不占据新的一级后台式菜单。变量、内存两项**不显示**,也不留空壳。 + +旧 Dock 保留五个视觉元素,但必须严格重定义:**刷新**=仅重新读取与检查;**设置**=字体/主题/轨迹显示;**运行**=执行 `main`,无 main 则打开函数选择;**清理**=清除当前会话结果与临时工件,**不删除项目文件或 lock**;**更多**=源码、导出、版本/帮助。除此不增加常驻按钮。界面默认的首屏高度、文档连续性优先于调试信息密度。 + +### 1.4 明确不同的“执行”概念 + +- **静态结构**:来自 Analysis v2 的函数、语句、分支、循环,未运行时可展示结构,但不得暗示已经执行。 +- **本次运行**:来自一个经确认的 CLI `run/call`;用户能看到运行目标、参数、模式、命令及结果。 +- **轨迹证据**:Trace v2 的事件,能说明发生过哪些分支/调用/循环/副作用;不是完整调试器,也不是证明证书。 +- **领域正确性/数学证明**:不属于 View 或 `check` 成功的含义;未来 Prove 独立提供并验证。 + +--- + +## 2. 已审查的公开 CLI 合同:外部开发者无需猜测 + +本节是开发必需的公开接口摘要,实施时用指定发布版二进制运行本节黑盒命令。**不要把本节作为发明新核心选项的许可。** + +### 2.1 版本及来源 + +| 版本轴 | 当前实际值 | 使用原则 | +|---|---|---| +| Marqdo 产品 | `3.0.0-beta.1` | Tool 兼容声明使用 `>=3.0.0-beta.1,<4.0.0`,Beta 期间须复测 | +| CLI Tool Protocol | v1 | 外部工具用 `tool.json` 安装,核心分发未知顶层命令 | +| Analysis | v2 | 静态语义、函数签名、源码 byte spans,唯一公开结构化编译结果 | +| Trace | v2 | `run/call --trace-file` 的静态来源关联事件 | +| Markdown Profile | `marqdo.md.v1` | 公共 Markdown 解析档案,不等于旧版本的语句语义 | +| 锁文件 | v4 | 项目身份与依赖;View 不更改锁文件 | +| 旧项目 | Marqdo 2.x | 不兼容,不提供 legacy mapper | + +CLI 发布 tag 对应源码记录:`2c7c4f31e7a388d3fcfa717a77067e696ed13854`。当前 `master` 可能在此 tag 之后继续更新;**测试始终以实际安装的发行二进制 `--version`、SHA-256、`RELEASE_INFO.json` 和对应 `spec/` 为准**。若未下载到发行包,明确记 `BASELINE_UNAVAILABLE`,不可伪称跨仓通过。 + +### 2.2 外挂 Tool 安装:实际支持,不需要改核心 + +发布 bundle(不是源仓库根的假模板)应具有: + +```text +marqdo-view-package/ + tool.json + bin/ + marqdo-view # 真实可执行文件;Linux x86_64 + assets/ # 如果没有全部内嵌,则仅打包已校验文件 + reader.css + reader.js + ... +``` + +`tool.json` 内容: + +```json +{ + "schema": "marqdo.cli-tool", + "schema_version": 1, + "name": "marqdo-view", + "version": "0.2.0", + "command": "view", + "entrypoint": "bin/marqdo-view", + "compatibility": { + "marqdo": ">=3.0.0-beta.1,<4.0.0", + "analysis": [2], + "trace": [2] + } +} +``` + +**`0.2.0` 是建议的独立 View 产品版本,不是 CLI 产品版本,也不是现有发布的事实**。安装及分发: + +```bash +export MARQDO_BIN=/absolute/path/to/released/marqdo +"$MARQDO_BIN" --version +"$MARQDO_BIN" tool install /absolute/path/to/marqdo-view-package/tool.json +"$MARQDO_BIN" tool list +"$MARQDO_BIN" view --help +"$MARQDO_BIN" view index.mq.md +"$MARQDO_BIN" tool remove view +``` + +核心注册表会将未知顶层 `view` 分发至**外部独立二进制**,不会添加 `Command::View`。工具执行进程继承普通 cwd/stdin/stdout/stderr,并获得:`MARQDO_BIN`、`MARQDO_TOOL_PROTOCOL=1`、`MARQDO_PROTOCOL_ANALYSIS=2`、`MARQDO_PROTOCOL_TRACE=2`(在兼容协商成功时)。工具**不得**用 PATH 猜测另一个 `marqdo`,也不得把这几个环境变量当作用户已授予的执行权限。 + +当前 Tool 的包安装会检查目录/工件清单并重新校验整体摘要;所有发布文件必须在打包后保持字节稳定。任何插件/资产修改之后都应**重建并重新安装工具包**,不能用“开发时直接替换已安装文件”绕过完整性。 + +### 2.3 静态检查与 Analysis v2 + +```bash +"$MARQDO_BIN" check index.mq.md --emit /private/tmp/analysis.json +# --refs 为可选的链接检查:可能产生额外报错,不应被误作语言编译错误 +"$MARQDO_BIN" check index.mq.md --refs --emit /private/tmp/analysis.json +``` + +成功时读取文件中的准确 JSON 字节,`schema="marqdo.analysis"`、`schema_version=2`,再计算 `sha256:...`。`modules[]` 包括 `id`、`relative_path`、`source_digest`、`units`、`functions`、`imports`、`references`、`calls`、`resources`。`functions[].signature.params[]` 包括 `name`、`required`、`type`、`default`;`functions[].id`、`namespace`、`local_name` 提供定位。`units[].kind` 是 `root|namespace|function|knowledge|section`,但 Analysis v2 **没有公开所有 H3+ 的最终 EffectiveMode 字段**。诊断位于顶层 `diagnostics[]`,标记 UTF-8 字节范围。 + +Core `check` **不执行目标程序**。失败时不要读取曾经的 `analysis.json` 作为成功产物;Core 会清除 stale emit,View 亦必须清除自己的旧缓存。可读取 `check --json` 仅用于展示真实错误,但不能从错误推断尚未公开的 IR。 + +### 2.4 运行:`run` 与 `call` 不等价 + +`run` 默认调用当前入口文件的 `main`,不接收命名函数的参数: + +```bash +"$MARQDO_BIN" run index.mq.md --mode pure --json \ + --trace-file /private/tmp/trace.json \ + --timeout 30 --fuel 1000000 --max-output 1048576 \ + --trace-max-events 10000 --trace-max-bytes 4194304 +``` + +单函数调用通过 `call FILE FUNCTION --arg name=CONSTANT`: + +```bash +"$MARQDO_BIN" call index.mq.md main \ + --arg n=5 \ + --mode pure --json --trace-file /private/tmp/trace.json +``` + +**开发者必须保留两个按钮的语义差别**:底部 Run 仅表示 `run main`;在“函数”面板选择 `compute` 是 `call compute`。没有 `main` 时底部按钮不能偷偷运行“第一个函数”,应打开函数列表或解释原因。 + +`--mode` 在核心中支持 `pure|project|strict`,**CLI 自身的默认是 `project`,但 View 必须显式发送 `--mode pure`**,绝不能遗漏后使用核心默认。`strict` 是 Linux probe-gated 的独立模式;本 View 第一版不提供 strict 的保证或按钮。Project 模式并非 OS 沙箱。 + +Core 还支持一组 grants(`--allow-read`、`--allow-write`、`--allow-net`、`--allow-env`、`--allow-process`、`--allow-random`、`--plugin`、`--allow-plugin`、`--kernel`、`--allow-foreign`、`--provider`、`--allow-provider`、`--trust-native-plugin`);**这里只陈述 Core 存在这些选项,View 首版仅允许用户显式选择 read/write glob 作为项目权限**,其他全部拒绝并提示通过终端调用 Core。这是刻意缩小安全面,而非误以为 Core 缺少扩展能力。 + +### 2.5 `--json` 成功与失败包络 + +在 CLI `crates/cli/src/commands/run.rs` 中,成功结果具有 `command`、`success:true`、`value`(`marqdo_value::to_wire(...)`,不是任意普通字符串)、`stdout`、`stderr`、`diagnostics`、`trace`;失败常见 `success:false`、`error` 或 `diagnostics`,并可能包含 stdout/stderr/trace。**处理器应接受某些失败路径缺少 `value`/`trace`/`stdout`,不要直接 unwrap**。 + +`value` 是 CLI 自己定义的版本相关 Wire Value;首版 View 仅进行**结构化安全展示**:优先呈现已识别的安全标量值,其他保留为折叠的、安全转义 JSON,不推导未公开的具体运行状态。stdout/stderr 完全视为用户数据,**不能赋值给 `innerHTML`**。 + +### 2.6 运行来源和 Trace v2 + +```bash +"$MARQDO_BIN" run index.mq.md \ + --mode pure --json --trace-file /private/tmp/trace.json +``` + +`trace.json` 顶层:`schema:"marqdo.trace"`、`schema_version:2`、`run {id,entry,status}`、`source {root_id,analysis_digest}`、`limits`、`truncated`、`events[]`。事件种类包括 `call.enter`、`call.exit`、`return`、`branch.eval`、`loop.iteration`、`effect`、`trace.truncated`。每条有源位置的事件必须指定真实 `module_id` 和 UTF-8 `span`。未来新增事件类型按协议忽略或保守显示。 + +**绑定规则(不能简化)**:将 `trace.source.analysis_digest` 与同一源码、同一检查配置所得到的 **Analysis JSON 文件的原始字节**的 SHA-256 比较,而不是反序列化再序列化后做哈希。还须核对 `source.root_id`、相关 `module_id` 和 `span` 的边界。Trace 的 `truncated` 或 `trace.truncated` 代表观测预算耗尽,不代表程序终止。Trace v2 **不记录参数值、逐语句赋值后的变量值、Handle、文件内容和秘密**。 + +### 2.7 三种载荷外观,不能恢复旧语法绑定 + +3.0 中 `@exec/@knowledge` 区分语义区域;在有效 Exec 位置,`**语句**`、`*语句*`、行内 `` `语句` `` 均能携带一条语句,实际执行分类由语句里的 `if/else/while/end/return/params`、赋值/表达式决定。H2 Exec 才是函数,H1 仅命名空间,H3+ 仅节。标题若没有模式声明则继承最近祖先模式;文档根是 Knowledge。 + +**这不授权 View 解析/推断 Exec**:渲染原始 Markdown 是合法的;表示“此处有函数/语句”必须来自 Analysis;`@knowledge` 不是“已数学证明”,`@exec` 不是“这次实际执行”。对于 H3 的模式继承,Analysis 未公开完全有效模式时只能显示准确的语义索引和显式源文本,不得把自行重建的 Mode 算法宣称为编译器真实状态。 + +### 2.8 开发者对应阅读的权威文件(本 RFC 已给出实施摘要) + +位于 `cflmy/marqdo-cli`:`spec/tool-v1.md`、`spec/analysis-v2.md`、`spec/trace-v2.md`、`spec/mapping.md`、`spec/expression.ebnf`、`spec/schemas/{tool-v1,analysis-v2,trace-v2}.schema.json`、`docs/developers/{tools,analysis-trace,compatibility,release-limits}.md`、`crates/cli/src/{main,args,analysis,trace,tool}.rs`、`crates/cli/src/commands/run.rs`。本文不要求开发者另找设计资料或阅读历史聊天,但如正式协议有新提交,以**确切发布版**为最终权威。 + +--- + +## 3. 旧 View 的混乱必须有证据地去掉,不做整体代码移植 + +### 3.1 从旧源码直接确认的结构风险 + +在旧 `cflmy/marqdo@1c55baa`: + +| 路径 | 已观察到的事实 | 新版裁决 | +|---|---|---| +| `src/main.rs` | `View`、`ViewAction::Output/Capture/Document`、`Debug` 是不同 CLI 路径;`ViewAction::Document` 还有 Workbench HTML 输出 | 不复制旧命令树,只保留一套新 View 命令 | +| `src/view/html.rs` | 包含庞大的 `stylesheet()` 和 `notebook_ui()`,同时在 `layout()` 又嵌入 `reader.css` / `reader.js` | **彻底废弃旧 CSS 叠层;保留视觉 token 重新实现** | +| `src/view/reader.css` | 暖纸/樱花/羽毛/衬线/五按钮 Dock/侧注曲线的重要样式来源 | 只抽取设计特征/必要资产,不原样复制整个文件后再覆盖 | +| `src/view/reader.js` | 以 `/welcome/` 文件名匹配注入 Hero;布局侧注 SVG 曲线和交互 | Hero 改明确页面配置;曲线保留为可降级小模块 | +| `src/view/debug_page.rs` | 独立暗色调试页面、调试工具、断点 | **删除**,不是新的 reader 模式 | +| `src/view/mod.rs` | Live page 与 Debug 走不同路由;还存在很多 Session/Notebook/API 路由 | 新服务仅留纯阅读与用户主动运行 API | +| `src/view/output.rs` | Live/Export 的页面模板有重用,但执行抓取路径与 `--no-exec` 控制相互交错 | 导出构造器**从类型边界不能取得**运行能力 | +| `src/view/knowledge_*` | 依赖旧 `SemanticProject`、知识编译结构 | 全部不迁移;3.x 专用 Knowledge/Prove 未来独立仓库 | +| `src/view/render.rs` | 依赖旧 AST 与 Strong/Emph/列表的语义映射 | 不能作为 3.0 执行语义真相 | + +**审计限定**:以上说明旧代码存在多条页面生成路径和样式覆盖,并不等于已经在浏览器里证明有“两套完整 View 同时竞争路由”。随附截图是**视觉验收依据**,不是源码实现证据。旧项目能否编译/对应什么样的运行 DOM 仍须单独记录 `LEGACY_RUNTIME_VERIFIED` 或 `LEGACY_RUNTIME_UNVERIFIED`,禁止把未经复现的历史印象当作软件事实。 + +### 3.2 必须记录的取证文件 + +新仓库创建 `docs/audits/legacy-view.md`,列出旧命令到入口函数、页面模板、CSS 注入顺序、JS 初始化、执行调用的连线。对每个可用资源标记 `KEEP_ASSET / REIMPLEMENT / DROP / UNKNOWN`;经审计批准后再将必要 Logo、樱花、羽毛放进本仓库并记录许可证、SHA-256 和来源提交。不能对旧 `marqdo` 建立任何 Git/path/Cargo 依赖。 + +最少调查命令(只读,可在旧源码 checkout 中运行): + +```bash +rg -n 'ViewAction|Commands::View|page_file|page_debug|layout_debug|serve_debug' src/main.rs src/view +rg -n 'stylesheet\(|notebook_ui\(|reader\.css|reader\.js|notebook-page|reader-page' src/view +rg -n 'build_file_view|run_file_capture|write_static|no_exec' src/view +rg -n 'reader-hero|reader-dock|reader-connectors|annot-band' src/view +``` + +### 3.3 应当真正删除的旧目录与功能概念 + +新仓库**禁止创建** `src/notebook/`、`src/debug/`、`src/memory_inspector/`、`src/session_kernel/`、`src/knowledge_compiler/`、`src/proof_engine/`、`src/agent/`、`src/legacy_compat/`。也禁止“先复制再隐藏”的做法:没有相应 DOM、路由、状态容器、请求处理器和测试假依赖,才叫删除。代码审查必须拒绝因为 UI 复刻而在 View 中内嵌旧 AST 或旧 `RunCapture`。 + +--- + +## 4. 新产品信息架构与视觉标准:删到刚好够用 + +### 4.1 给定截图的视觉特征 + +**本次交付的参考图片文件尺寸为 2048×1133**;可确认暖白纸色画布、左上粉色樱花枝、顶部居中 Marqdo 标识及小字、副标题与衬线字体、五项旧导航、金色欢迎大标题和羽毛、连续阅读区、金色函数竖标、轻边框表格以及底部居中椭圆浮动操作栏。右侧的黑色短线和竖线不能据此判定是必要设计元素,**不复刻任何未知划线 artifact**。 + +新 View 继续保持其**文档阅读的温度**,但删掉旧的 Variables/Memory 标签、满屏 Notebook 工具条、技术字段表、默认巨大执行日志。普通 `.mq.md` 的第一页直接显示作者文档,不自动加一个巨大 Welcome Hero。只在明确的 `welcome` 配置或独立欢迎页面显示装饰性大 Hero。 + +### 4.2 唯一页面骨架 + +```text +┌──────────────────────────────────────────────────┐ +│ 菜单 Marqdo 搜索 │ +│ 文档 函数 运行 │ +├──────────────────────────────────────────────────┤ +│ │ +│ 文章标题 / 可选 Welcome │ +│ 文档段落、图、表格、公式、函数原文 │ +│ [函数标题 · 调用] │ +│ [可选:本次事件侧注] │ +│ │ +│ [独立的运行结果面板,默认折叠] │ +│ │ +│ ⌜刷新 设置 ▶运行 清理 更多⌟ │ +└──────────────────────────────────────────────────┘ +``` + +- `文档`:主视图,始终原文顺序;默认选中,滚动是连续阅读,不是可执行卡片列表。 +- `函数`:列表/抽屉,而不是替代正文的后台页面;点击导航到原文 H2,点击调用打开单函数表单。 +- `运行`:仅显示当前会话运行历史(首版最近 1 次)和事件;默认不占据文章前部,不代替文档。 +- `源码`:通过“更多”或正文上的局部切换显示纯源码/复制按钮;**没有内建源码编辑器或保存操作**。 +- `Dock`:五个按钮有单一行为,执行按钮因没有 main 应引导选择函数,不应变成“运行所有”。 +- 用户可选择隐藏所有语义侧注,恢复与普通 Markdown 阅读器基本相同的页面。 + +### 4.3 风格 token / 资产约束 + +建议以旧 `reader.css` 的核心色感为初始:`--paper:#fcf9f5`、`--surface:#fffcf8`、`--ink:#29251f`、`--muted:#847565`、`--line:#e7ddce`、`--gold:#b88a45`、`--olive:#52603a`。正式主题只有 `assets/reader.css`,唯一入口 `assets/reader.js`;其他细分 CSS/JS 如果存在,必须在构建中合并成一份显式顺序产物,且没有旧 `.notebook-page` 皮肤覆盖。 + +主文字使用本机衬线字体族,不从 CDN 下载字体。桌面正文可读宽度约 720–900 CSS px,侧注只有宽屏才靠两侧排布。≤900 px 侧注转正文;≤600 px 单栏且 Dock 不遮挡末尾;打印隐藏装饰/交互控制。响应 `prefers-reduced-motion`、键盘焦点和触屏尺寸。 + +### 4.4 侧注:保留审美,不恢复虚假的值快照 + +侧注可分为 `Static`(参数、函数、源链接)和 `Observed`(本次 Trace 的调用/分支/循环/副作用);只有后者允许标记“已发生”。旁注最多保持合理密度(建议同一段默认 ≤3 个),重叠时折叠为有编号的就地注释,不能让线穿越正文。连接线可用简洁 SVG 弯曲路径;失败时**降级为行内关联**。它们是增强,不是布局生存条件;静态导出与禁 JS 阅读都不能丢失核心说明。 + +### 4.5 不允许假装拥有的旧工作台视图 + +不得提供“变量”“内存”空标签,不得用 `value` 的最终返回冒充所有赋值结果,不得显示未由 Trace 提供的所谓实时函数栈。网页也没有实际生效的 `Run All`、`Restart Kernel`、`Step`、`Breakpoint` 和 `Stream Token` 控制。若未来有正式公开调试协议,再另开 RFC,**不能先设计空 UI 等接口**。 + +--- +## 5. 唯一架构:Reader + Controller + CLI,禁止第二运行框架 + +### 5.1 模块职责及不可逆依赖方向 + +```text + 用户浏览器(只读首屏) + ┌──────────────────────────────────────┐ + │ Reader UI / Document / Function / Run│ + │ reader.js:仅 DOM、表单、SSE 状态 │ + └─────┬───────────────────┬────────────┘ + │ GET 静态页 │ POST /api/runs(用户主动) + │ │ GET /events(SSE) + ▼ ▼ + ┌────────────────┐ ┌────────────────────────┐ + │ DocumentService│ │ ExecutionController │ + │ Markdown renderer│ │ 单任务、取消、超时、缓存│ + └──────┬─────────┘ └───────────┬────────────┘ + │ │ + ┌──────▼─────────┐ ┌───────▼────────────┐ + │ AnalysisClient │ │ CliProcessAdapter │ + │ marqdo check │ │ marqdo run/call │ + └──────┬─────────┘ └────────┬───────────┘ + │ │ + └───────────┬───────────────┘ + ▼ + MARQDO_BIN:冻结发行版 + Analysis v2 / Trace v2 + + ↓ 合并到唯一数据模型 ↓ + PresentationModel + ↓ + Renderer(Live/Export 共用) +``` + +绝对禁止任何 `DocumentService → ExecutionController` 隐式调用;`GET /`、`GET /file`、`GET /api/documents`、目录扫描、前端刷新、静态导出不能形成执行边。运行命令仅从 `POST /api/runs` 的服务端处理器显式产生。**浏览器端任何代码都不能直接组装系统命令或执行语言表达式。** + +### 5.2 层间数据结构(供实现与单测固定) + +推荐 Rust 单 crate: + +```rust +// 类型草图;字段语义是合同,具体序列化通过新仓库 serde 定义。 +struct SourceDocument { + relative_path: String, // 相对于受控项目根目录 + raw_utf8: Vec, // 精确保留换行和 BOM 的原始字节 + source_sha256: String, +} +struct AnalysisArtifact { + bytes: Vec, // 原始 check --emit 文件字节 + digest: String, // "sha256:" + hex(SHA256(bytes)) + schema_version: u32, // 必须 == 2 + root_id: String, +} +struct SemanticAnchor { + module_id: String, + start: usize, + end: usize, + kind: String, // 仅来自公开 Analysis 节点 +} +struct ExecutionRecord { + run_id: String, + state: RunState, + source_analysis_digest: String, + target: String, + mode: String, + started_at: Option, + finished_at: Option, + result: Option, + trace: Option, + stale: bool, +} +struct PresentationModel { + source: SourceDocument, + analysis: Option, + diagnostics: Vec, + anchors: Vec, + execution: Option, +} +``` + +`SafeCliResult` 不保存环境变量、原始权限令牌、密钥,也不假定 `value` 一定存在。字段类型在实现中采用显式 DTO,禁止把内部 JSON 对象直接送入 HTML 模板作为信任值。View 的动态数据模型只表示用户**发起的一次外部调用及其完成记录**,不代表解释器的持久状态。 + +### 5.3 仓库结构:仅一个应用、一个主题、一个渲染入口 + +```text +marqdo-view/ +├── Cargo.toml # 一个主 binary crate;禁止复制 marqdo workspace +├── Cargo.lock +├── tool.json # 随发行包输出,command=view +├── README.md # 安装、使用、限制、截图和开发入口 +├── LICENSE-MIT / LICENSE-APACHE # 与实际使用的源码/资产许可证对应 +├── docs/ +│ ├── architecture/ +│ │ ├── RFC-VIEW-0001.md # 历史基础设计(可选归档) +│ │ └── RFC-VIEW-0002.md # 本文件(最终执行规范) +│ ├── audits/legacy-view.md +│ ├── decisions/ # 仅记录确实发生的设计权衡 +│ └── design/reference-old-view-reader.png +├── src/ +│ ├── main.rs # 唯一 composition root +│ ├── cli.rs # 参数解析:view/export/version +│ ├── config.rs # 本工具配置;不定义语言语义 +│ ├── core_client.rs # 唯一 MARQDO_BIN 运行入口 +│ ├── protocol/ +│ │ ├── analysis_v2.rs # 公共 JSON schema / 校验 +│ │ ├── trace_v2.rs # 公共 JSON schema / 校验 +│ │ └── tool_v1.rs +│ ├── reader/ +│ │ ├── source.rs # 受控文件读取与 byte span +│ │ ├── markdown.rs # 单一 GFM 渲染器;无语义执行 +│ │ ├── model.rs # PresentationModel +│ │ ├── assemble.rs # 静态/运行产物合并与过期判定 +│ │ └── render.rs # 唯一 HTML 渲染入口 +│ ├── execution/ +│ │ ├── request.rs # 目标、参数、权限验证 +│ │ ├── controller.rs # Job 生命周期与并发 +│ │ ├── process.rs # 可取消 CLI 子进程与输出限制 +│ │ └── events.rs # SSE 帧、重放缓冲、状态机 +│ ├── server/ +│ │ ├── mod.rs # 本地单用户 HTTP +│ │ ├── routes.rs # 固定最小路由清单 +│ │ ├── security.rs # Origin/Host/CSRF/Cookie +│ │ └── sse.rs # 单向长连接,不含业务引擎 +│ └── export.rs # 静态导出:仅 Reader,不含执行模块 +├── assets/ +│ ├── reader.css # 唯一最终 CSS 入口 +│ ├── reader.js # 唯一最终浏览器 JS 入口 +│ ├── logo.svg / blossom.webp / feather.webp +│ └── LICENSES.md +├── examples/ # 全部 3.0 新语法,不能复制旧代码 +│ ├── welcome.mq.md +│ ├── branch-loop.mq.md +│ ├── function-params.mq.md +│ ├── knowledge-only.mq.md +│ └── unsafe-side-effect.mq.md +├── tests/ +│ ├── contract/ # 冻结 CLI 发布二进制黑盒 +│ ├── integration/ # 独立 Tool install/dispatch + SSE +│ ├── security/ # 无意外执行、恶意路径/HTML/授权 +│ ├── browser/ # screenshot、键盘、SSE reconnect +│ ├── fixtures/ # Analysis/Trace 固定有效/无效样例 +│ └── golden/ # HTML / 屏幕宽度视觉基线 +├── scripts/ +│ ├── package.sh # 生成 tool.json+bin+assets 的不可变包 +│ └── verify-frozen-cli.sh # 核心 SHA 前后必须相同 +└── .github/workflows/ci.yml +``` + +不允许以“可扩展”为理由先拆 5~10 个独立 Rust crate;如未来存在真实复用需求,先给出衡量结果和 ADR。`protocol/` 表示 View 消费的公共格式,不是重新实现公共协议的发布源。`assets/reader.css` 与 `reader.js` 各只有一个发布入口;构建期模块化可以存在,但必须明确、可追踪地合并,不能通过多个历史 stylesheet 的偶然顺序覆盖。 + +### 5.4 唯一渲染流水线 + +```text +SourceDocument + ├─> Markdown renderer ──────────────────────┐ + ├─> AnalysisClient.check ─> AnalysisArtifact ├─> assemble ─> PresentationModel + └─> optional Verified ExecutionRecord ──────┘ │ + ▼ + render(model, RenderMode::Live | Export) +``` + +`RenderMode::Export` 类型中**没有** `ExecutionController`、`CliProcessAdapter` 或 HTTP client:从编译依赖结构就不能执行用户代码。Live 页面首次装载使用同一个 renderer,但可以接收后续执行记录;Renderer 仅更新运行区与关联锚点,不重新创建整个语义树。源文档变更导致模型旧状态失效,应清理观察性标注,不能把上一轮运行的关联硬套到新源码。 + +--- + +## 6. 交互式执行:SSE 是必需传输协议,但不是 Token/VM 事件系统 + +### 6.1 采用 SSE 而非轮询的原因及严格边界 + +- 浏览器需要及时接收任务开始、运行中、完成、失败、超时、取消和已验证 Trace 就绪状态;以固定频率 GET 轮询会制造空请求、延迟与脆弱的竞争状态。因此本产品**禁止任何周期性状态轮询 API**。 +- SSE 是浏览器内置的单向长连接,能自动重连并携带 `Last-Event-ID`;比此场景下双向 WebSocket 更简单,且不需要复制旧 EventBus。 +- **SSE 只保证“View 一旦知道状态变化,就立即推送”。** 3.0.0-beta.1 的 `run/call --json` 在结束时才产生结构化结果,Trace v2 也在运行后写出。View 可以实时知道**进程已启动、仍运行、收到取消、已退出**;不可承诺每条 stdout token、内部函数调用、每次赋值立刻推送。 +- 第一版不实现增量 `stdout.chunk`:为得到可靠的 `value`/`error`,CLI 使用 `--json`,完整 JSON 要在退出时解析。不要为了边跑边展示 stdout 改用文本模式,却丢弃结构化返回值,更不可偷偷双重执行获取两份结果。 +- 将来 CLI 有新公开流协议时,只在 `CoreClient` adapter 增加可信事件来源和版本协商,不改变 Viewer 的事件模型或通过私有 crate 绕过协议。 + +### 6.2 最小 HTTP API(MVP 强制;其他路由需 ADR) + +| 方法和路径 | 唯一职责 | 允许执行? | +|---|---|---| +| `GET /` | 主页/默认文档 | 否 | +| `GET /file?path=...` | 受控路径的单文件阅读 | 否 | +| `GET /assets/...` | 固定打包 CSS/JS/图片,无任意路径映射 | 否 | +| `GET /api/documents` | 搜索/目录/文档结构(只读) | 否 | +| `POST /api/runs` | 验证用户明确提交的执行请求并建立任务 | **是,唯一启动入口** | +| `GET /api/runs/{run_id}/events` | SSE 推送此任务生命周期与终态数据;断线重放 | 否(仅观察) | +| `POST /api/runs/{run_id}/cancel` | 幂等地请求取消;不启动其他进程 | 否(控制已启动任务) | + +不建立 `GET /api/run?command=...`、`POST /api/eval`、Notebook REST 兼容层、`/api/session/*`、通用 shell 命令执行端点,也不因未来引入 Prove/Knowledge 增加直通 CLI 私有接口。内部 job 查询可以由 Controller 对象直接提供,不代表必须公开 HTTP status-poll 路由。 + +### 6.3 请求定义:两阶段显式确认,不允许隐式运行 + +浏览器先由 Analysis 得到候选 H2 Exec 函数签名,打开表单并生成**命令预览**。用户点击“确认执行”才 POST: + +```json +{ + "document": "index.mq.md", + "target": {"kind": "function", "function_id": ""}, + "parameters": [{"name": "n", "expression": "5"}], + "analysis_digest": "sha256:<本次 check --emit 字节摘要>", + "mode": "pure", + "grants": {"read": [], "write": []}, + "client_request_id": "" +} +``` + +`target.kind` 只能为 `entry`(运行 `main`)或 `function`(运行 `call`);`function` 必须从**当前选中文件的入口模块** Analysis 函数表中选取,不能直接把依赖模块的函数 ID 当作 CLI `call FILE FUNCTION` 可运行目标。`function_id` 必须服务端按 Analysis 精确解析为 CLI 所接受的函数名,不能把客户端字符串原样拼接成任意参数。 + +`parameters[].expression` 是核心支持的常量表达式源文本,如 `5`、`"小明"`、`[1,2]`;服务器应做长度/字符/参数名/重复检查,**最后由 CLI 自身进行语法和类型验证**。无隐式裸文本转字符串。若复杂类型不具备被证实的可靠转换,首版以“高级常量表达式”原样输入、显示真实 CLI 错误,不做 JSON→Marqdo 文本的猜测转换。 + +响应 `202 Accepted`: + +```json +{ + "run_id": "", + "state": "accepted", + "events_url": "/api/runs//events", + "cancel_url": "/api/runs//cancel" +} +``` + +如果同一 `client_request_id` 被重复提交且请求体摘要相同,返回同一个 `run_id`;同 ID 不同 payload 一律 `409 Conflict`。这避免双击按钮、浏览器重试造成二次执行。对已过期 ID 返回明确错误,不能默认再执行。 + +**在接受前的服务端检查顺序**:会话 Cookie/CSRF/Origin/Host → 大小与 JSON schema → 文档真实路径 containment → 重新静态 `check`(只读)→ Analysis SHA 比对 → 精确函数/参数解析 → 允许的模式及 grants → 同时运行数预算 → 创建任务并入队 → 202。任一失败不得启动用户程序,也不得为错误请求生成“成功执行”的 UI。 + +### 6.4 SSE 帧合同(本仓库自有协议 `marqdo.view-run-events` v1) + +`GET /api/runs/{id}/events` 使用 `Content-Type: text/event-stream; charset=utf-8`、`Cache-Control: no-store`、`X-Accel-Buffering: no`,不启用跨域共享,也不允许缓存或压缩缓冲导致延迟。每帧: + +```text +event: run.state +id: 2 +data: {"schema":"marqdo.view-run-events","schema_version":1,"run_id":"","seq":2,"state":"running","at":"2026-11-22T00:00:00Z"} + +``` + +`id` 是**任务内严格递增整数**,与 `data.seq` 一致;`run_id` 是全局随机 ID。事件为 `run.state`、`run.complete`、`run.error`、`run.snapshot` 四种(所有数据按下表定义),另外心跳为 SSE 注释 `: heartbeat`,不占用事件序号: + +| SSE `event` | data 必需内容 | 触发条件 | +|---|---|---| +| `run.state` | `schema/schema_version/run_id/seq/state/at` | `accepted`、`running`、`cancel_requested` | +| `run.complete` | 通用字段 + `state:"succeeded"` + `result` + `trace` 验证结果 | 子进程成功退出且 JSON 合法;Trace 仅在校验后附上引用或安全摘要 | +| `run.error` | 通用字段 + `state` + `error {code,message}` + 可选安全 `result` | `failed`、`cancelled`、`timed_out`、`unavailable` 等终态 | +| `run.snapshot` | 通用字段 + 当前权威 `state` + 可用的安全结果 | SSE 重连请求的历史事件已被截断时进行状态同步 | + +对于 `succeeded`,若 Trace 缺失/无效但 `--json` 成功,**不得伪装 Trace 存在**。可标记结果成功、Trace `unavailable` 或 `invalid`(根据当前协议要求是否应将缺失 Trace 视作整体任务失败,在测试中固定);源摘要不匹配不得在原文上画执行高亮。`run.complete` 的 `result` 包括已解析的 JSON 返回值与裁剪后的 stdout/stderr;**前端只按文本节点展示**,绝不执行数据里的 HTML/JS。 + +建议每 15 秒写 `: heartbeat\n\n` 保持中间连接存活;心跳**不是轮询**,不查询 Core 运行状态、不发起新命令。SSE 实时推送是服务端对已有进程状态的响应,前端 `EventSource` 不调用定时器反复请求状态。服务端状态转移必须先写 Job 状态和环形缓冲,再通知 SSE 订阅者;即使客户端暂时没有连接,执行完成事件仍可重放。 + +### 6.5 SSE 断线重连、缓存和背压 + +- 内存中每个 job 保留最近 **128 个状态事件**(预计正常任务远少于该数量),并保留独立的最终结果快照;终态保留建议 15 分钟,超过后安全删除。 +- 允许 `Last-Event-ID`:仅在同一 job 下按 id/seq 重放 `> last_id` 的事件;若客户端游标太旧,直接发送最新 `run.snapshot`,不得发送不连续的伪历史。新的连接不提供游标时先发送当前状态快照,再订阅后续事件,要求“读取快照+注册订阅”在同一 Controller 锁中原子化,避免竞态漏事件。 +- 每任务**最多 2 个并发 SSE 连接**;超过限制返回 `429`。单个发送队列有界,慢客户端被断开而不阻塞 CLI 子进程;重连后可获取最终状态。 +- 客户端对 `seq` 去重、拒绝任务 ID 不匹配、忽略旧序号;终态后主动关闭 EventSource,不再自动重连。页面导航/关闭仅断开观察通道,**不自动取消正在运行的外部进程**,除非显式用户操作。 +- 禁止无限历史、没有 TTL 的 Job map、向浏览器公开所有工作区运行历史,也禁止 SSE 未鉴权读取终态结果。 + +### 6.6 任务状态机:所有终态一次且仅一次 + +```text + accepted ────────> running ────────────────> succeeded + │ │ └───────────────> failed + │ ├──cancel_requested─> cancelled + │ └───────────────────> timed_out + └─(无法启动)─────────────────────────────> unavailable +``` + +`cancel_requested` 不是终态;竞态中若进程已成功退出,允许最终落到 `succeeded`,但不能同时发出 `cancelled` 和 `succeeded` 两个终态。任何 terminal 事件必须有唯一 `run_id`/`seq`,并由单一 `ExecutionController` 负责终态转移。 + +第一版**每个 View 服务进程最多同时运行 1 个用户 CLI 任务**,可拒绝第二任务 `409 run.busy`,而非暗中无限排队。上限是刻意简化,并非语言执行引擎的能力限制。接受后须在后台执行 CLI 子进程,HTTP handler 不得同步阻塞 SSE 服务线程。 + +### 6.7 可取消的 CLI 子进程与执行预算 + +由 `CoreClient` 按参数数组调用,不经过 shell: + +```text +MARQDO_BIN run + --mode pure --json --trace-file + --timeout 30 --fuel 1000000 --max-output 1048576 + --trace-max-events 10000 --trace-max-bytes 4194304 +``` + +单函数:`MARQDO_BIN call --arg n=5 ...`。运行时 cwd 应设置为已确认的项目根目录,**不允许客户端传入 cwd、任意二进制路径、额外 CLI flags 或 shell 文本**。每次执行都产生独立、权限最小的系统临时目录;Analysis、Trace、结果日志和任何抽取文件均在此目录内,结束后按 TTL 删除;不得在项目文件夹中留下 `.view-*` 运行产物。 + +- `--timeout` 是 Core 内的运行限制;View 另设**独立墙钟上限**,不依赖 Core 自愿终止。默认建议 30 秒,最大 120 秒,且两者配置须明确一致或 View 更严格。 +- 最大 JSON 响应读取 4 MiB,最多 10000 条 Trace 事件、Trace 文件 4 MiB;超限停止接收并报 `view.output_limit`,不得无界缓冲或 `stdout` 管道死锁。`stderr` 同样有界,不能因小管道无人读而阻塞子进程。 +- Linux 优先用新进程组执行和取消:先发温和终止信号,约 2 秒后仍存活则强制结束进程组;父进程 wait/reap 并回收句柄。不能只 kill shell(因为**不使用 shell**)或仅移除 UI Job。Windows/macOS 不在当前 Beta 发布支持声明中,可对应平台独立实现或明确 fail-closed。 +- 取消本身要鉴权,与启动路由相同的会话作用域;重复取消幂等。Server 进程异常退出时应有子进程清理策略(Linux 进程组/watchdog;需要黑盒验证),不得遗留孤儿长任务。 +- **纯模式默认**。用户要在首版 `project` 中使用 read/write,必须再次确认每个相对项目根的 glob,并执行白名单验证后映射为明确 `--allow-read`/`--allow-write`;禁止从 `marqdo.yaml` 自动把“请求”提升成“授权”。`strict`、Foreign/Plugin/Provider、网络、进程、环境授权和 Native 信任按钮全部不在首版 UI 中。 + +### 6.8 SSE 安全模型:本地服务也必须保护执行端点 + +SSE `EventSource` 默认不能附加自定义认证头,因此推荐以本地会话 Cookie 进行 SSE GET 授权:`HttpOnly; SameSite=Strict; Path=/`,且绑定随机会话 ID;当服务基于 HTTPS 时加 `Secure`,本地 loopback HTTP 不允许假冒 HTTPS。初次打开页面时服务端发放随机 session 与防 CSRF 值;POST 请求要求自定义 `X-View-CSRF` 与同源 `Origin`、合法 `Host`。`GET /events` 仅允许已认证的会话读取**本会话**启动的 `run_id`。拒绝跨站 CORS、拒绝 query token 泄漏、禁止将密钥写入 SSE URL。 + +- 默认监听 **`127.0.0.1`,随机可用端口或用户指定本机端口**;首版不支持 `0.0.0.0` 公网监听,也不提供无认证远程执行模式。 +- HTTP 读取与 POST 设置严格体积上限(建议 64 KiB 以内),只接受 `application/json`,拒绝浏览器自动表单造成的跨站请求;`Origin` 不匹配直接拒绝,`Sec-Fetch-Site` 可作为额外信号而非唯一保障。 +- Web 页面上不加载 CDN、不启用任意前端脚本、Markdown HTML 必须经过安全策略处理。服务端 `Content-Security-Policy` 建议 `default-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'`;如 JS/CSS 内联,须使用 nonce/hash 而非退回全局 `unsafe-inline`。 +- `file?path` 与 `document` 必须规范化并检查真实路径在受控根之下;拒绝 `..`、绝对路径、符号链接越界、URL 编码双重解码逃逸;Markdown 的链接只能用于正常导航,不能成为任意本地文件读取 API。 +- **Tool 自身是用户启动的普通程序**,`project`/`pure`/Worker 不是对不可信源代码的 OS 级沙箱。任何 UI 字样均不得把显式运行描述为“安全运行”。 + +--- + +## 7. 运行结果如何返回同一文档,而非变成 Notebook + +### 7.1 前端最小状态 + +```text +ReaderState: + selected_document + view_mode = Document | Source + active_tab = Document | Functions | Run + display_settings = Theme + FontSize + ShowAnnotations + current_run_id? # 仅用户发起的当前任务 + current_run_state? # SSE 驱动,不做周期轮询 + current_result? # 安全的终态视图 +``` + +刷新页面先做只读分析。先前任务如果尚有服务端记录,只能在本地会话明确选择“恢复查看结果”后连接 SSE;**绝不因为重新加载页面自动发起 POST**。浏览器 localStorage 只能保存阅读偏好,不持久化密钥或危险授权。普通运行结果默认内存保留,首版不实现数据库或跨浏览器持久执行历史。 + +### 7.2 `--json` 结果到 UI 的可验证映射 + +| CLI 数据 | 页面展示 | 禁止行为 | +|---|---|---| +| `success: true` | 成功状态与耗时/返回类型(可知时) | 将成功等同于数学证明 | +| `value` | 按 Wire Value 安全展示;未知类型折叠为 JSON | 用 `value` 伪造所有变量值 | +| `stdout` | 转义后的普通文本输出 | 当 HTML 执行 | +| `stderr` | 错误/信息区,裁剪后可复制 | 当作可信 HTML / 自动脚本 | +| `error` / `diagnostics` | 代码、错误信息、源范围,帮助定位 | 从缺少字段猜测成功 | +| `Trace v2` | 经过 digest 关联的调用、分支、循环、effect | 展示不存在的每步变量/参数快照 | +| `trace.truncated` | “本次轨迹不完整”提示 | 宣称全部路径已观察 | +| `analysis_digest` 不符 | “结果与当前源码不一致” | 把事件侧注映射到当前源码 | + +成功与失败的终态应在原文附近的独立轻量执行面板展现,不能为了日志把读者踢到另一套 IDE 页面。默认可见最重要的一行状态与返回值;点击展开stdout、stderr、轨迹。静态导出不包含执行控制按钮;若未来允许快照导出,应另立契约并清楚标“历史快照、来源及时间”,**不属于 0002 必需范围**。 + +### 7.3 精确源位置映射 + +View 渲染原始 Markdown,但只能用 Analysis/Trace 产生语义标识。对有 span 的事件: + +1. 检查 `module_id` 是该 Analysis 的 `modules[]` 成员,且所用 source 是此模块的真实源码; +2. 检查 `start <= end <= raw_utf8.len()`、UTF-8 边界合法; +3. 验证模块 `source_digest` 是当前真实 source bytes 的 SHA-256; +4. 验证 Trace 整体 `source.analysis_digest`/`root_id`; +5. 根据字节 span 关联 Markdown 渲染节点,**不要用行号猜匹配**; +6. 无法精确定位时退化为结构化事件列表,绝不随意在最相近的文本画连接线。 + +如果读取不到依赖包的真实源码,仍可展示模块 ID 和事件列表,但不能把依赖包事件画到入口文件的正文里。样例覆盖中文、Emoji、组合 Unicode、CRLF、不同换行、源文件热修改和同名函数的模块歧义。 + +### 7.4 侧注规则与渐进降级 + +先渲染完整阅读文档,再叠加来源明确的最小侧注:`StaticFunction`(静态函数声明)、`ObservedCall`、`ObservedBranch`、`ObservedLoop`、`ObservedEffect`。每类标注带 `source=analysis|trace`,实际未运行时只能展示静态信息。显示 CSS/SVG 弯曲引出线时以锚点和注释实际矩形计算,避开文字;若容纳空间不足、打印、禁 JS 或来源匹配失败,改成正文下有编号的短注释。**先实现准确关联,再追求曲线审美**;禁止复活旧 `reader.js` 里整套 Notebook 状态监听器。 + +--- + +## 8. 具体开发里程碑:逐 PR、文件、测试和退出条件 + +### PR-00:冻结来源、证据与旧 View 清理表 + +**输入**:本 RFC、旧截图、两个指定仓库源码、官方 `v3.0.0-beta.1` release archive。 + +**工作**:创建 `docs/audits/legacy-view.md`;记录真实 HTML 主入口、reader CSS 最终覆盖、旧 notebook/debug CSS 冲突、运行副作用;给每个图片/样式片段写迁移裁决。记录 CLI 二进制版本、SHA、平台、实际 `--help` 和协议。创建独立仓库骨架,**不得引用旧源码为 Git 依赖**。 + +**通过**:证据文件列出 `src/view/html.rs`、`reader.css`、`reader.js`、`debug_page.rs` 的具体入口和 CSS 优先级;未经浏览器复现的旧行为标记 UNVERIFIED;截图独立保留。没有任何 UI 实现前即可执行 `cargo metadata`,并确认依赖图不含核心私有 crate。 + +### PR-01:Tool v1 的独立打包、安装和调度 + +**工作**:Rust binary、CLI 参数和 `tool.json`;`scripts/package.sh` 创建包含真实执行文件的发布目录;支持 `marqdo view --help`、`marqdo view FILE`、`marqdo view export PATH --out DIR`(后者可先建立拒绝的占位命令,但不得向用户声称已可用)。写一个无需改 Core 的黑盒注册测试。 + +**通过**:冻结 `MARQDO_BIN` 的 SHA 前后相同;`marqdo tool install ./dist/.../tool.json` 成功;运行 `marqdo view --help` 分发到外部程序;篡改 assets 或 executable 后 Core 拒绝分发;卸载成功。仓库不添加 `Command::View`、不编译 Core。 + +### PR-02:只读文档面与准确 Analysis v2 + +**工作**:`reader/source.rs` 的路径/UTF-8/源摘要安全、`protocol/analysis_v2.rs`、`core_client.check`、`reader/markdown.rs`、`reader/assemble.rs`、`reader/render.rs`;通过只读页面显示 Markdown/GFM、公式、H2 Exec 函数、Knowledge、Analysis diagnostics 和源代码视图。创建一套唯一 `reader.css`、`reader.js`;旧截图作为视觉参考但不能成为第二 DOM 模板。 + +**通过**:开页 10 次没有任意被标记的程序副作用;脚本无法执行来自 Markdown 的 HTML;语义错误能读原文与诊断;同 SHA Analysis 稳定、不同源码 stale 标记正确;中文跨度无错位;浅/深色和移动端可读;不出现变量/内存/调试占位 tab。 + +### PR-03:交互式调用表单与执行策略 + +**工作**:`execution/request.rs`、`core_client` 的 `run/call` argv 构造、`execution/controller.rs`;参数来自 Analysis,带命令预览和显式权限确认。实现纯模式和受控 project fs grants。每任务专用临时目录、并发上限、独立超时、完整 `--json` 解析。 + +**通过**:能调用单函数、带 Int/Text/List 常量值,并得到真正 Wire Value;无 main 不启动意外函数;没有授权无法访问读取/写入效果;已声明第三方 extension 的 pure 请求明确拒绝,不自动升级模式;点击其他 UI 控件不会运行;恶意参数不能进行 shell 注入。 + +### PR-04:**SSE 任务生命周期、取消和终态结果(MVP 不可省略)** + +**工作**:`server/routes.rs` 最小 7 个路由;`execution/events.rs` 的有界 Job 事件重放;`server/sse.rs` 以 EventSource 支持即时状态与终态推送;`execution/process.rs` 进程组取消、超时、JSON 大小预算。实施同源 Cookie + Origin/CSRF 并锁定 loopback。 + +**通过**:POST 返回 202 与 run_id;SSE 不靠定时轮询就接收到 accepted→running→terminal;不管执行耗时多久都能收到心跳;浏览器断线后 `Last-Event-ID` 重放、事件去重、终态唯一;取消后无残留子进程;恶意跨站请求不能启动执行;没有 Token 流,不引入旧 EventBus。 + +### PR-05:Trace v2 证据绑定、原文标注与浏览器回归 + +**工作**:`protocol/trace_v2.rs`、`reader/assemble.rs` 把真实 run 和 trace 联系起来;实现函数/分支/循环/副作用侧注和降级。运行表单/结果面板/时间线清楚区分静态与动态,完整简洁的截图视觉迭代。测试窄屏/打印/无 JS/断网。 + +**通过**:源摘要改变或 Analysis/Trace 不匹配不会画本次执行连接线;Truncated 正确显示;不显示未公开的参数值或逐语句变量值;截图与参考的视觉结构接近,但在已批准的“文档/函数/运行”简化导航下不要求完全像素相同;CSS 唯一入口和无远程 CDN 均满足。 + +### PR-06:静态导出、发布包、全项目回归和文档闭环 + +**工作**:`export.rs` 调用纯 Reader 模型,生成离线相对链接、单页入口及各文档页,默认绝不执行;提供 README、使用指南、受支持版本/平台、安全限制。CI 使用冻结发布 CLI 进行正向/负向测试,输出双端 SHA 和平台证明。 + +**通过**:导出前后程序副作用标记不存在;离线打开所有 HTML 不请求外网;从不同目录执行发行工具无需 Core checkout;取消/超时/冲突/断流恢复/恶意路径安全测试绿;文档提到的命令全可黑盒运行;没有“旧版兼容”或伪造功能。 + +### 8.1 必须固定的开发原则 + +- 每一个 PR 只能引入本阶段必要层;不允许提前创建未来 Proof/Knowledge/Lint/Notebook 目录;不存在“先占位、以后实现”的按钮。 +- `PR-04` 的 SSE 是**首版必须通过的产品合同**,不是 UI 优化可选项;若当前 CLI 尚不支持内部实时 event,仍能依靠子进程生命周期正确完成 SSE。 +- 首个发布版本不以旧 `marqdo` 的 `view` 运行结果作为语言语义金标准;它只能用于视觉取证。所有计算金标准来自冻结 3.0 CLI。 + +--- + +## 9. 验收测试:可直接转为 CI 测试矩阵 + +### 9.1 正向端到端测试 + +| ID | 测试动作 | 预期可断言结果 | +|---|---|---| +| E01 | Tool v1 安装/卸载/分发 `view` | 从独立包加载,不需要 Core 源码 | +| E02 | 打开含 `@knowledge` 与 H2 `@exec` 的文件 | 原文、函数、知识单元正确显示;没有启动 run/call | +| E03 | Source/Document 切换 | Source 字节保真;Document Markdown 完整,语义只依 Analysis | +| E04 | 含中文/Emoji 的表格、段落、公式 | 断行和源码 byte-span 对应正确 | +| E05 | 显式 `main` 运行 | 真正 CLI `run --json --trace-file`;Run 区收到返回和 stdout | +| E06 | H2 Exec 的 `n=5` 调用 | CLI `call` 接受 `--arg n=5`,显示真实结果 | +| E07 | 文本/列表常量参数 | 正确封装引号/数组;不插值进 shell | +| E08 | 无 main 的普通库文档 | Doc 仍可读;底部 Run 引导函数选择,不运行第一函数 | +| E09 | 执行 if/while 源码 | Trace v2 事件在有来源时能映射,过程图不假装有变量值 | +| E10 | `GET /api/runs//events` | `text/event-stream`,accepted/running/terminal;没有前端 polling | +| E11 | SSE 断开后携带 Last-Event-ID 重连 | 有序重放、无重复展示;过期缓冲 snapshot 正确 | +| E12 | 一个长任务运行期间 SSE 长连 | 心跳正常、浏览器保持连接;任务不可被 GET 重启 | +| E13 | 取消当前运行 | 进程树终止、唯一终态、资源回收 | +| E14 | 导出静态 HTML | 无执行/无联网;页面间相对链接正确 | +| E15 | 页面刷新/重新打开 | 完全不自动执行,用户无确认不会发生副作用 | +| E16 | 源码在运行后被编辑 | 结果可见但标记 stale,原文上绝无错误高亮 | + +### 9.2 必测失败与安全回归 + +| ID | 输入/故障注入 | 强制响应 | +|---|---|---| +| N01 | 假 Analysis schema v3 / 缺失 modules | 明确 unsupported;不伪造语义或执行成功 | +| N02 | `check --emit` 失败但旧 analysis 文件残留 | 删除/忽略旧文件;文档阅读可安全降级 | +| N03 | Trace digest/root_id/module_id 不匹配 | 不绑定执行侧注,解释 stale/error | +| N04 | UTF-8 边界错误、span 越界 | 安全丢弃标注并报告协议诊断 | +| N05 | 恶意 Markdown ` - + 跳到正文 "##, presentation_version = model.version, @@ -205,7 +205,7 @@ impl ReaderRenderer { html: &mut String, model: &PresentationModel, _ctx: &RenderContext, - navigation: &crate::presentation::Navigation, + navigation: &crate::reader::model::Navigation, ) { let active = model .navigation @@ -254,7 +254,7 @@ impl ReaderRenderer { ); } - fn render_welcome(&self, html: &mut String, navigation: &crate::presentation::Navigation) { + fn render_welcome(&self, html: &mut String, navigation: &crate::reader::model::Navigation) { let _ = write!( html, r##"
@@ -509,6 +509,7 @@ impl ReaderRenderer {

阅读设置

  • +
@@ -519,8 +520,7 @@ impl ReaderRenderer {
  • -
  • -
  • +
  • @@ -918,7 +918,7 @@ fn resolve_heading_unit( model: &PresentationModel, heading_span: SourceSpan, level: u8, -) -> Option<&crate::semantic::SemanticUnit> { +) -> Option<&crate::protocol::analysis_v2::SemanticUnit> { let projection = model.semantic.as_ref()?; // A function heading maps to its function unit exactly; never borrow the // ancestor function for H3/H4 sections (that would duplicate DOM ids). @@ -945,7 +945,7 @@ fn resolve_heading_unit( fn display_heading_content( content: &[Inline], - unit: Option<&crate::semantic::SemanticUnit>, + unit: Option<&crate::protocol::analysis_v2::SemanticUnit>, ) -> (Option<(&'static str, &'static str)>, Vec) { let Some(unit) = unit else { return (None, content.to_vec()); diff --git a/src/project.rs b/src/reader/source.rs similarity index 59% rename from src/project.rs rename to src/reader/source.rs index f0db180..05851e9 100644 --- a/src/project.rs +++ b/src/reader/source.rs @@ -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 -//! second path validator (RFC-VIEW-0001 §14.4). +//! Core Analysis/Trace spans are half-open UTF-8 **byte** offsets into the +//! 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> { + 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, + /// 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 { + 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 { + 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 { + 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::source_map::sha256_hex; use std::path::{Path, PathBuf}; /// 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, - pub site_title: Option, - pub theme: Option, -} - -impl ViewConfig { - pub fn load(root: &Path) -> ViewResult { - 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, - #[serde(default)] - site_title: Option, - #[serde(default)] - theme: Option, - } - 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 /// `marqdo.yaml`, else the file's directory. The file itself is canonical. pub fn discover_project_root(file: &Path) -> PathBuf { @@ -434,7 +637,7 @@ fn canonicalize(path: &Path, what: &str) -> ViewResult { } #[cfg(test)] -mod tests { +mod path_tests { use super::*; #[test] diff --git a/src/server.rs b/src/server.rs index 42b5f22..3351bd7 100644 --- a/src/server.rs +++ b/src/server.rs @@ -4,15 +4,15 @@ //! exposed until the explicit-run flow lands; every response carries a strict //! CSP and the Host header is validated to blunt DNS-rebinding. -use crate::app::AppContext; -use crate::assets::AssetBundle; use crate::cli::RuntimeOpts; use crate::error::{ViewError, ViewResult}; -use crate::presentation::PresentationModel; -use crate::project::SafeRelativePath; -use crate::render::{ReaderRenderer, RenderContext}; -use crate::source_map::sha256_hex; -use crate::trace::VerifiedRun; +use crate::protocol::trace_v2::VerifiedRun; +use crate::reader::assemble::DocumentService; +use crate::reader::assets::AssetBundle; +use crate::reader::model::PresentationModel; +use crate::reader::render::{ReaderRenderer, RenderContext}; +use crate::reader::source::sha256_hex; +use crate::reader::source::SafeRelativePath; use std::collections::HashMap; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; @@ -22,7 +22,7 @@ const MAX_URL_BYTES: usize = 2048; const MAX_QUERY_BYTES: usize = 4096; const MAX_BODY_BYTES: usize = 16 * 1024; -pub fn serve(ctx: AppContext, opts: &RuntimeOpts) -> ViewResult { +pub fn serve(ctx: DocumentService, opts: &RuntimeOpts) -> ViewResult { let address = format!("{}:{}", opts.host, opts.port); let server = Server::http(&address).map_err(|err| ViewError::Io { detail: format!("listen on {address}: {err}"), @@ -89,7 +89,7 @@ pub fn serve(ctx: AppContext, opts: &RuntimeOpts) -> ViewResult { } struct ServerState { - ctx: AppContext, + ctx: DocumentService, csrf_token: String, renderer: ReaderRenderer, cache: Mutex>, @@ -291,7 +291,7 @@ fn handle(state: &ServerState, request: Request) -> ViewResult<()> { Err(err) => serve_error_page(request, &err, is_head), } } - "/api/document" => { + "/api/documents" => { let relative = match query_param(query, "path") .and_then(|raw| percent_decode(&raw)) .map(|decoded| SafeRelativePath::parse(&decoded)) @@ -303,7 +303,7 @@ fn handle(state: &ServerState, request: Request) -> ViewResult<()> { None => state.ctx.project().entry().relative.clone(), }; match state.load_for_page(&relative, query_param(query, "run").as_deref()) { - Ok(model) => serve_document_json(request, &model), + Ok(model) => serve_documents_json(state, request, &relative, &model), Err(err) => respond_json_error(request, StatusCode(500), &err), } } @@ -326,9 +326,9 @@ fn handle(state: &ServerState, request: Request) -> ViewResult<()> { "version": state.ctx.core_version(), }, "protocols": { - "tool": crate::version::TOOL_PROTOCOL, - "analysis": crate::version::ANALYSIS_PROTOCOL, - "trace": crate::version::TRACE_PROTOCOL, + "tool": crate::protocol::tool_v1::TOOL_PROTOCOL, + "analysis": crate::protocol::tool_v1::ANALYSIS_PROTOCOL, + "trace": crate::protocol::tool_v1::TRACE_PROTOCOL, }, "documents": documents, "run_api": true, @@ -684,7 +684,7 @@ fn serve_page( is_head: bool, ) -> ViewResult<()> { let ctx = RenderContext { - links: crate::render::LinkPolicy::LocalServer, + links: crate::reader::render::LinkPolicy::LocalServer, live: true, csrf_token: Some(state.csrf_token.clone()), run_available: state.ctx.core().is_some() && model.can_offer_run(), @@ -703,55 +703,84 @@ fn serve_error_page(request: Request, err: &ViewError, is_head: bool) -> ViewRes respond_html(request, html.into_bytes(), is_head) } -fn serve_document_json(request: Request, model: &PresentationModel) -> ViewResult<()> { +fn serve_documents_json( + state: &ServerState, + request: Request, + relative: &SafeRelativePath, + model: &PresentationModel, +) -> ViewResult<()> { let semantic = model.semantic.as_ref(); + let documents = state + .ctx + .project() + .list_documents() + .unwrap_or_default() + .into_iter() + .map(|path| { + serde_json::json!({ + "path": path.as_str(), + "active": path == *relative, + }) + }) + .collect::>(); + let functions = model + .outline + .iter() + .filter(|entry| entry.kind == crate::reader::model::OutlineKind::Function) + .map(|entry| { + serde_json::json!({ + "label": entry.label, + "anchor": entry.anchor, + "detail": entry.detail, + }) + }) + .collect::>(); let doc = serde_json::json!({ - "schema": "marqdo.view-document", + "schema": "marqdo.view-documents", "schema_version": 1, - "title": model.title, - "document": { + "entry": state.ctx.project().entry().relative.as_str(), + "documents": documents, + "current": { "relative_path": model.document.identity.relative_path, "module_id": model.document.identity.module_id, + "title": model.title, "source_sha256": sha256_hex(model.document.source.as_bytes()), + "source_status": model.source_status.data_value(), + "semantics_usable": model.source_status.semantics_usable(), + "analysis": semantic.map(|projection| serde_json::json!({ + "digest": projection.analysis_digest, + "schema_version": crate::protocol::tool_v1::ANALYSIS_PROTOCOL, + "producer_version": projection.producer_version, + "project_root_id": projection.project_root_id, + "functions": projection.functions.len(), + "units": projection.units.len(), + "diagnostics": projection.diagnostics.len(), + })), + "outline": model.outline.iter().map(|entry| serde_json::json!({ + "label": entry.label, + "anchor": entry.anchor, + "detail": entry.detail, + "kind": match entry.kind { + crate::reader::model::OutlineKind::Function => "function", + crate::reader::model::OutlineKind::Knowledge => "knowledge", + crate::reader::model::OutlineKind::Section => "section", + }, + })).collect::>(), + "functions": functions, + "run": model.run.as_ref().map(|run| serde_json::json!({ + "state": run.state.data_value(), + "label": run.state.label(), + "run_id": run.run_id, + "run_status": run.run_status, + "exit_code": run.exit_code, + "event_count": run.counts.total(), + "entry_event_count": run.entry_event_count, + "truncated": run.truncated.as_ref().map(|truncated| truncated.label()), + "has_result_value": run.result_value.is_some(), + })), + "can_offer_run": model.can_offer_run(), }, - "source_status": model.source_status.data_value(), - "semantics_usable": model.source_status.semantics_usable(), - "analysis": semantic.map(|projection| serde_json::json!({ - "digest": projection.analysis_digest, - "schema_version": crate::version::ANALYSIS_PROTOCOL, - "producer_version": projection.producer_version, - "project_root_id": projection.project_root_id, - "functions": projection.functions.len(), - "units": projection.units.len(), - "diagnostics": projection.diagnostics.len(), - })), - "outline": model.outline.iter().map(|entry| serde_json::json!({ - "label": entry.label, - "anchor": entry.anchor, - "detail": entry.detail, - "kind": match entry.kind { - crate::presentation::OutlineKind::Function => "function", - crate::presentation::OutlineKind::Knowledge => "knowledge", - crate::presentation::OutlineKind::Section => "section", - }, - })).collect::>(), - "navigation": { - "documents": model.navigation.documents.iter().map(|doc| doc.as_str()).collect::>(), - "welcome": model.navigation.welcome, - }, - "run": model.run.as_ref().map(|run| serde_json::json!({ - "state": run.state.data_value(), - "label": run.state.label(), - "run_id": run.run_id, - "run_status": run.run_status, - "exit_code": run.exit_code, - "event_count": run.counts.total(), - "entry_event_count": run.entry_event_count, - "truncated": run.truncated.as_ref().map(|truncated| truncated.label()), - "has_result_value": run.result_value.is_some(), - })), - "can_offer_run": model.can_offer_run(), - "note": "Read-only PresentationModel summary; this page load never executes the document.", + "note": "Read-only document structure; this request never executes the document.", }); respond_json(request, StatusCode(200), &doc) } diff --git a/src/source_map.rs b/src/source_map.rs deleted file mode 100644 index 34c14ba..0000000 --- a/src/source_map.rs +++ /dev/null @@ -1,281 +0,0 @@ -//! Exact UTF-8 byte ↔ line/column ↔ JavaScript UTF-16 offset mapping. -//! -//! Core Analysis/Trace spans are half-open UTF-8 **byte** offsets into the -//! 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> { - 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, - /// 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 { - 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 { - 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 { - 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}") - ); - } -} diff --git a/tests/asset_integrity.rs b/tests/contract/asset_integrity.rs similarity index 97% rename from tests/asset_integrity.rs rename to tests/contract/asset_integrity.rs index 6ecdc4b..6d15158 100644 --- a/tests/asset_integrity.rs +++ b/tests/contract/asset_integrity.rs @@ -49,7 +49,7 @@ fn reused_assets_match_their_recorded_hashes() { #[test] fn embedded_asset_bundle_matches_disk_and_has_one_theme() { - let bundle = marqdo_view::assets::AssetBundle::get(); + let bundle = marqdo_view::reader::assets::AssetBundle::get(); let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); let css = std::fs::read(root.join("assets/reader.css")).unwrap(); assert_eq!(sha256_hex(&css), bundle.css().sha256); diff --git a/tests/cli_surface.rs b/tests/contract/cli_surface.rs similarity index 97% rename from tests/cli_surface.rs rename to tests/contract/cli_surface.rs index 21f8e37..3ce6c6e 100644 --- a/tests/cli_surface.rs +++ b/tests/contract/cli_surface.rs @@ -1,7 +1,7 @@ //! CLI surface tests: this program owns its own help/subcommands and refuses //! unsafe defaults. Exit codes follow RFC-VIEW-0001 §10.2. -mod common; +use crate::common; use common::run_view; @@ -76,7 +76,7 @@ fn degradation_without_core_keeps_prose_readable() { project.marqdo_project("# @knowledge 标题\n\n正文 **加粗**。\n"); // Explicitly point at a missing core so the test is independent of the // caller environment (acceptance scripts export MARQDO_BIN). - let context = marqdo_view::app::AppContext::open( + let context = marqdo_view::reader::assemble::DocumentService::open( &project.dir, Some(std::path::Path::new("/definitely/missing/marqdo-frozen")), ) diff --git a/tests/core_contract.rs b/tests/contract/core_contract.rs similarity index 99% rename from tests/core_contract.rs rename to tests/contract/core_contract.rs index 23da80e..da42b04 100644 --- a/tests/core_contract.rs +++ b/tests/contract/core_contract.rs @@ -4,11 +4,11 @@ //! The fake core is a shell script, not a mocked Rust trait, so everything at //! the process boundary is exercised for real. -mod common; +use crate::common; use common::{minimal_analysis, sha256_hex, FakeCore, TempProject}; use marqdo_view::core_client::{CheckOptions, CheckResponse, CoreClient, RunOptions}; -use marqdo_view::project::Project; +use marqdo_view::reader::source::Project; fn fixture(name: &str) -> (TempProject, FakeCore) { let project = TempProject::new(name); diff --git a/tests/contract/main.rs b/tests/contract/main.rs new file mode 100644 index 0000000..6355ef1 --- /dev/null +++ b/tests/contract/main.rs @@ -0,0 +1,12 @@ +//! Contract suite: the frozen CLI black-box process contract, Analysis v2 / +//! Trace v2 validation, the View CLI surface, and architecture/asset gates. + +#[path = "../common/mod.rs"] +mod common; + +mod asset_integrity; +mod cli_surface; +mod core_contract; +mod no_coupling; +mod presentation_states; +mod trace_contract; diff --git a/tests/no_coupling.rs b/tests/contract/no_coupling.rs similarity index 100% rename from tests/no_coupling.rs rename to tests/contract/no_coupling.rs diff --git a/tests/presentation_states.rs b/tests/contract/presentation_states.rs similarity index 82% rename from tests/presentation_states.rs rename to tests/contract/presentation_states.rs index c34f90b..7479158 100644 --- a/tests/presentation_states.rs +++ b/tests/contract/presentation_states.rs @@ -1,11 +1,11 @@ //! Degradation/state matrix contract (RFC-VIEW-0001 S-05..S-07, §12.3): //! prose stays readable while semantics become explicitly unusable. -mod common; +use crate::common; use common::{minimal_analysis, sha256_hex, FakeCore, TempProject}; -use marqdo_view::app::AppContext; -use marqdo_view::presentation::SourceStatus; +use marqdo_view::reader::assemble::DocumentService; +use marqdo_view::reader::model::SourceStatus; fn project(name: &str) -> (TempProject, FakeCore) { let project = TempProject::new(name); @@ -24,7 +24,7 @@ fn failed_check_keeps_prose_and_shows_core_diagnostics() { core.set_check_json( r#"{"command":"check","success":false,"errors":1,"diagnostics":[{"code":"sem.unclosed_control","column":1,"file":"/home/secret/index.mq.md","line":3,"message":"`if` is not closed by `end`","module":"root:fixture@0.1.0::index.mq.md","severity":"error"}]}"#, ); - let context = AppContext::open(&project.dir, Some(&core.script)).unwrap(); + let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap(); let relative = context.project().entry().relative.clone(); let model = context.load(&relative).unwrap(); assert_eq!(model.source_status, SourceStatus::CoreError); @@ -46,7 +46,7 @@ fn failed_check_keeps_prose_and_shows_core_diagnostics() { fn source_digest_mismatch_degrades_instead_of_misbinding() { let (project, core) = project("state-source-mismatch"); core.set_analysis(&minimal_analysis("index.mq.md", &"0".repeat(64), 2)); - let context = AppContext::open(&project.dir, Some(&core.script)).unwrap(); + let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap(); let relative = context.project().entry().relative.clone(); let model = context.load(&relative).unwrap(); assert_eq!(model.source_status, SourceStatus::SourceMismatch); @@ -59,7 +59,7 @@ fn unknown_analysis_schema_is_a_hard_protocol_error() { let (project, core) = project("state-protocol"); let source = std::fs::read(project.path("index.mq.md")).unwrap(); core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 3)); - let context = AppContext::open(&project.dir, Some(&core.script)).unwrap(); + let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap(); let relative = context.project().entry().relative.clone(); let err = context.load(&relative).unwrap_err(); assert_eq!(err.code(), "view.protocol_incompatible"); @@ -78,7 +78,7 @@ fn invalid_core_span_is_dropped_with_an_explicit_warning() { "span": {"start": 0, "end": 999_999} }]); core.set_analysis(&serde_json::to_string(&analysis).unwrap()); - let context = AppContext::open(&project.dir, Some(&core.script)).unwrap(); + let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap(); let relative = context.project().entry().relative.clone(); let model = context.load(&relative).unwrap(); assert_eq!(model.source_status, SourceStatus::StaticOk); @@ -105,30 +105,36 @@ fn run_attached_to_changed_source_becomes_stale() { let analysis = std::fs::read(repo_root.join("tests/golden/analysis-v2/control-flow.json")).unwrap(); core.set_analysis(std::str::from_utf8(&analysis).unwrap()); - let context = AppContext::open(&project.dir, Some(&core.script)).unwrap(); + let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap(); let relative = context.project().entry().relative.clone(); // Build a verified run directly from the golden trace + golden analysis. - let source_index = marqdo_view::source_map::SourceIndex::new(&source); - let verified_analysis = - marqdo_view::semantic::verify_analysis(&analysis, &source, &source_index, "index.mq.md") - .unwrap(); + let source_index = marqdo_view::reader::source::SourceIndex::new(&source); + let verified_analysis = marqdo_view::protocol::analysis_v2::verify_analysis( + &analysis, + &source, + &source_index, + "index.mq.md", + ) + .unwrap(); let trace = std::fs::read(repo_root.join("tests/golden/trace-v2/control-flow.trace.json")).unwrap(); let run_json: serde_json::Value = serde_json::from_slice( &std::fs::read(repo_root.join("tests/golden/trace-v2/control-flow.run.json")).unwrap(), ) .unwrap(); - let run = marqdo_view::trace::verify_trace(marqdo_view::trace::TraceVerificationInput { - trace_bytes: &trace, - analysis_bytes: &analysis, - semantic: &verified_analysis.projection, - modules: &verified_analysis.projection.modules, - source: &source, - source_index: &source_index, - run_json: &run_json, - exit_code: 0, - }) + let run = marqdo_view::protocol::trace_v2::verify_trace( + marqdo_view::protocol::trace_v2::TraceVerificationInput { + trace_bytes: &trace, + analysis_bytes: &analysis, + semantic: &verified_analysis.projection, + modules: &verified_analysis.projection.modules, + source: &source, + source_index: &source_index, + run_json: &run_json, + exit_code: 0, + }, + ) .unwrap(); let attached = context.load_with_run(&relative, Some(&run)).unwrap(); assert_eq!(attached.run_state().data_value(), "succeeded"); diff --git a/tests/trace_contract.rs b/tests/contract/trace_contract.rs similarity index 97% rename from tests/trace_contract.rs rename to tests/contract/trace_contract.rs index a672f58..ce2d7aa 100644 --- a/tests/trace_contract.rs +++ b/tests/contract/trace_contract.rs @@ -2,9 +2,9 @@ //! goldens bind to the committed Analysis v2 bytes by digest, so a changed //! source cannot silently reuse an old trace. -use marqdo_view::semantic; -use marqdo_view::source_map::{sha256_prefixed, SourceIndex}; -use marqdo_view::trace::{verify_trace, RunDisplayState, TraceVerificationInput}; +use marqdo_view::protocol::analysis_v2 as semantic; +use marqdo_view::protocol::trace_v2::{verify_trace, RunDisplayState, TraceVerificationInput}; +use marqdo_view::reader::source::{sha256_prefixed, SourceIndex}; use serde_json::Value; struct Fixture { @@ -43,7 +43,7 @@ fn verify( trace_golden: &str, run_golden: &str, exit_code: i32, -) -> marqdo_view::trace::VerifiedRun { +) -> marqdo_view::protocol::trace_v2::VerifiedRun { let trace = golden_bytes(trace_golden); let run_json = golden_json(run_golden); verify_trace(TraceVerificationInput { diff --git a/tests/export.rs b/tests/integration/export.rs similarity index 99% rename from tests/export.rs rename to tests/integration/export.rs index cae30bd..cf00e9f 100644 --- a/tests/export.rs +++ b/tests/integration/export.rs @@ -1,7 +1,7 @@ //! Static export contract tests: pure read-only, same renderer, offline assets, //! safe output paths and no execution (RFC-VIEW-0001 §11.3, R-02, X-04). -mod common; +use crate::common; use common::{run_view, sha256_hex, FakeCore, TempProject}; use std::path::{Path, PathBuf}; @@ -124,7 +124,7 @@ fn exports_offline_site_with_shared_renderer_and_relative_links() { assert_eq!(sha256_hex(&bytes), entry["sha256"].as_str().unwrap()); } // Assets are exactly the embedded bundle bytes. - let bundle = marqdo_view::assets::AssetBundle::get(); + let bundle = marqdo_view::reader::assets::AssetBundle::get(); let css = std::fs::read(out.join("assets").join(bundle.hashed_css_name())).unwrap(); assert_eq!(css, bundle.css_bytes()); diff --git a/tests/http_live.rs b/tests/integration/http_live.rs similarity index 95% rename from tests/http_live.rs rename to tests/integration/http_live.rs index ea2a9dd..81e4069 100644 --- a/tests/http_live.rs +++ b/tests/integration/http_live.rs @@ -2,7 +2,7 @@ //! The server is a real child process so startup, URL output, routing, security //! headers, CSRF and the explicit-run flow are exercised end to end. -mod common; +use crate::common; use common::{run_view, FakeCore}; use std::io::{BufRead, BufReader, Read, Write}; @@ -567,3 +567,23 @@ fn cli_verify_output_contract_still_holds_for_installed_style_invocation() { assert_eq!(json["executed"], false); assert_eq!(json["analysis"]["schema_version"], 2); } + +#[test] +fn documents_api_is_a_read_only_structure_and_old_route_is_gone() { + let server = start_server(); + let response = http_get(server.port, None, "/api/documents"); + assert_eq!(response.status, 200); + let body = json_body(&response.body); + assert_eq!(body["schema"], "marqdo.view-documents"); + assert_eq!(body["schema_version"], 1); + assert!(body["documents"].is_array()); + assert!(body["documents"].as_array().unwrap().len() >= 2); + assert!(body["current"]["relative_path"].is_string()); + assert!(body["current"]["outline"].is_array()); + assert!(body["current"]["note"].is_null() || body["current"]["note"].is_string()); + assert!(body["note"].as_str().unwrap().contains("never executes")); + + // The old singular route is not part of the target API surface. + let old = http_get(server.port, None, "/api/document?path=index.mq.md"); + assert_eq!(old.status, 404); +} diff --git a/tests/integration/main.rs b/tests/integration/main.rs new file mode 100644 index 0000000..271dc80 --- /dev/null +++ b/tests/integration/main.rs @@ -0,0 +1,10 @@ +//! Integration suite: the Live HTTP surface, the one renderer, Unicode span +//! mapping and the static export path. + +#[path = "../common/mod.rs"] +mod common; + +mod export; +mod http_live; +mod rendering; +mod unicode_spans; diff --git a/tests/rendering.rs b/tests/integration/rendering.rs similarity index 87% rename from tests/rendering.rs rename to tests/integration/rendering.rs index cac6c27..f1c9af6 100644 --- a/tests/rendering.rs +++ b/tests/integration/rendering.rs @@ -1,15 +1,15 @@ //! Rendering contract tests: one renderer, safe Markdown, exact source view, //! verified semantic annotations and Live/Export link differences. -mod common; +use marqdo_view::config::ViewConfig; +use marqdo_view::protocol::analysis_v2 as semantic; +use marqdo_view::reader::assemble::{self as assemble, BuildInput}; +use marqdo_view::reader::markdown::{DocumentIdentity, DocumentModel}; +use marqdo_view::reader::model::{Navigation, SourceStatus}; +use marqdo_view::reader::render::{ReaderRenderer, RenderContext}; +use marqdo_view::reader::source::{Project, SafeRelativePath}; -use marqdo_view::document::{DocumentIdentity, DocumentModel}; -use marqdo_view::presentation::{self, BuildInput, Navigation, SourceStatus}; -use marqdo_view::project::{Project, SafeRelativePath, ViewConfig}; -use marqdo_view::render::{ReaderRenderer, RenderContext}; -use marqdo_view::semantic; - -fn example(name: &str) -> (marqdo_view::presentation::PresentationModel, String) { +fn example(name: &str) -> (marqdo_view::reader::model::PresentationModel, String) { let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("examples") .join(name); @@ -29,7 +29,7 @@ fn example(name: &str) -> (marqdo_view::presentation::PresentationModel, String) .unwrap_or_else(|err| panic!("golden does not verify for {name}: {err}")); let config = ViewConfig::load(project.root()).unwrap_or_default(); let navigation = Navigation::from_project(&project, &config, &entry); - let model = presentation::build(BuildInput { + let model = assemble::build(BuildInput { document, analysis: Some(&verified), status: SourceStatus::StaticOk, @@ -42,13 +42,13 @@ fn example(name: &str) -> (marqdo_view::presentation::PresentationModel, String) (model, source) } -fn render_live(model: &marqdo_view::presentation::PresentationModel) -> String { +fn render_live(model: &marqdo_view::reader::model::PresentationModel) -> String { ReaderRenderer::new() .render(model, &RenderContext::live()) .html } -fn render_static(model: &marqdo_view::presentation::PresentationModel, depth: usize) -> String { +fn render_static(model: &marqdo_view::reader::model::PresentationModel, depth: usize) -> String { ReaderRenderer::new() .render(model, &RenderContext::static_site(depth)) .html @@ -203,7 +203,7 @@ fn malicious_markdown_cannot_inject_markup_or_scripts() { &config, &SafeRelativePath::parse("index.mq.md").unwrap(), ); - let model = presentation::build(BuildInput { + let model = assemble::build(BuildInput { document, analysis: None, status: SourceStatus::CoreUnavailable, @@ -250,3 +250,14 @@ fn run_controls_are_explicitly_unavailable_before_pr04() { assert!(!html.contains("data-run-state=\"running\"")); assert!(!html.contains("data-run-state=\"succeeded\"")); } + +#[test] +fn reader_exposes_simple_theme_toggle_and_no_variable_or_memory_tabs() { + let (model, _source) = example("welcome"); + let html = render_live(&model); + assert!(html.contains("data-theme=\"light\"")); + assert!(html.contains("data-action=\"theme\"")); + assert!(!html.contains("data-action=\"variables\"")); + assert!(!html.contains("data-action=\"memory\"")); + assert!(html.contains("data-action=\"unsupported\"")); +} diff --git a/tests/unicode_spans.rs b/tests/integration/unicode_spans.rs similarity index 88% rename from tests/unicode_spans.rs rename to tests/integration/unicode_spans.rs index 5ded0e4..3d78246 100644 --- a/tests/unicode_spans.rs +++ b/tests/integration/unicode_spans.rs @@ -1,12 +1,14 @@ //! Unicode/CRLF/duplicate-text span contract (RFC-VIEW-0001 S-04). //! Goldens are emitted by the frozen CLI from the exact fixture bytes. -use marqdo_view::document::{DocumentIdentity, DocumentModel}; -use marqdo_view::presentation::{self, BuildInput, Navigation, SourceStatus}; -use marqdo_view::project::{Project, SafeRelativePath, ViewConfig}; -use marqdo_view::render::{ReaderRenderer, RenderContext}; -use marqdo_view::semantic; -use marqdo_view::source_map::sha256_hex; +use marqdo_view::config::ViewConfig; +use marqdo_view::protocol::analysis_v2 as semantic; +use marqdo_view::reader::assemble::{self as assemble, BuildInput}; +use marqdo_view::reader::markdown::{DocumentIdentity, DocumentModel}; +use marqdo_view::reader::model::{Navigation, SourceStatus}; +use marqdo_view::reader::render::{ReaderRenderer, RenderContext}; +use marqdo_view::reader::source::sha256_hex; +use marqdo_view::reader::source::{Project, SafeRelativePath}; fn repo_root() -> std::path::PathBuf { std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) @@ -15,7 +17,7 @@ fn repo_root() -> std::path::PathBuf { fn load(path: &str, golden: &str) -> (String, Vec, semantic::VerifiedAnalysis) { let root = repo_root(); let source = std::fs::read_to_string(root.join(path)).unwrap(); - let index = marqdo_view::source_map::SourceIndex::new(&source); + let index = marqdo_view::reader::source::SourceIndex::new(&source); let analysis = std::fs::read(root.join(golden)).unwrap(); let relative = std::path::Path::new(path) .file_name() @@ -32,7 +34,7 @@ fn render(verified: &semantic::VerifiedAnalysis, source: &str, relative: &str) - let entry = SafeRelativePath::parse(relative).unwrap(); let document = DocumentModel::parse(source.to_string(), DocumentIdentity::placeholder(&entry)); let navigation = Navigation::from_project(&project, &ViewConfig::default(), &entry); - let model = presentation::build(BuildInput { + let model = assemble::build(BuildInput { document, analysis: Some(verified), status: SourceStatus::StaticOk, @@ -67,7 +69,7 @@ fn unicode_spans_are_exact_and_duplicate_returns_get_distinct_anchors() { let first = returns[0].span; let second = returns[1].span; assert_ne!(first, second); - let index = marqdo_view::source_map::SourceIndex::new(&source); + let index = marqdo_view::reader::source::SourceIndex::new(&source); // Core statement spans cover the whole carrier node (including markers). assert_eq!(index.source_text(&source, first), Some("`return 1`")); assert_eq!(index.source_text(&source, second), Some("`return 1`")); @@ -106,7 +108,7 @@ fn crlf_source_keeps_exact_digest_and_line_mapping() { verified.projection.source_digest, sha256_hex(source.as_bytes()) ); - let index = marqdo_view::source_map::SourceIndex::new(&source); + let index = marqdo_view::reader::source::SourceIndex::new(&source); let function = &verified.projection.functions[0]; for (_, statement) in verified .projection @@ -137,7 +139,7 @@ fn knowledge_emphasis_never_becomes_an_execution_anchor() { let project = Project::open(&root.join("examples/mixed-modes")).unwrap(); let entry = project.entry().relative.clone(); let source = project.read_source_text(&entry).unwrap(); - let index = marqdo_view::source_map::SourceIndex::new(&source); + let index = marqdo_view::reader::source::SourceIndex::new(&source); let analysis = std::fs::read(root.join("tests/golden/analysis-v2/mixed-modes.json")).unwrap(); let verified = semantic::verify_analysis(&analysis, &source, &index, entry.as_str()).unwrap(); assert_eq!( @@ -146,7 +148,7 @@ fn knowledge_emphasis_never_becomes_an_execution_anchor() { ); let document = DocumentModel::parse(source.clone(), DocumentIdentity::placeholder(&entry)); let navigation = Navigation::from_project(&project, &ViewConfig::default(), &entry); - let model = presentation::build(BuildInput { + let model = assemble::build(BuildInput { document, analysis: Some(&verified), status: SourceStatus::StaticOk, From e13c1828a4619d86d7afdcde908fbe0be5717845 Mon Sep 17 00:00:00 2001 From: cflmy Date: Sun, 22 Nov 2026 13:39:17 +0800 Subject: [PATCH 04/21] feat(PR-03): execution controller, cancellable process adapter and budgets MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - add src/execution/{request,process,controller,events}.rs implementing RFC-0002 §6.3 request validation, function_id->CLI name resolution, single-job lifecycle, dedupe by client_request_id+payload digest, 409 busy/conflict, unique terminal states, idempotent cancel and Trace v2 binding against the exact pre-run Analysis bytes - route all Core subprocess spawning through one bounded, cancelable adapter with process-group TERM->2s->KILL, spawn hook, 4 MiB output caps and explicit --fuel/--max-output/--timeout/trace budgets; CoreClient check/--version reuse it - add marqdo.view-run-events v1 event log: 128 frame ring, Last-Event-ID replay or authoritative snapshot, numeric seq/id, heartbeat constant - add bounded --run-timeout (default 30s, max 120s - add ADR-0008 (lifecycle/cancel race/trace-missing semantics) and PR-03 evidence; execution tests use a real fake-Core executable - unit 58 + contract 41 + integration 42 pass; clippy clean --- CHANGELOG.md | 23 +- docs/ACCEPTANCE.md | 2 +- docs/CONFORMANCE.md | 20 +- docs/STATUS.md | 19 +- docs/decisions/0008-execution-lifecycle.md | 68 ++ docs/evidence/0001-pr03/README.md | 23 + .../control-flow-run-1664x920.png | Bin .../{PR-03 => 0001-pr03}/welcome-1664x920.png | Bin .../{PR-03 => 0001-pr03}/welcome-390x844.png | Bin docs/evidence/PR-03/README.md | 72 +- src/cli.rs | 21 + src/core_client.rs | 181 ++- src/error.rs | 50 +- src/execution/controller.rs | 1046 +++++++++++++++++ src/execution/events.rs | 430 +++++++ src/execution/mod.rs | 15 + src/execution/process.rs | 293 +++++ src/execution/request.rs | 594 ++++++++++ src/lib.rs | 1 + src/reader/assemble.rs | 89 +- tests/common/mod.rs | 8 +- tests/integration/execution.rs | 514 ++++++++ tests/integration/main.rs | 1 + 23 files changed, 3312 insertions(+), 158 deletions(-) create mode 100644 docs/decisions/0008-execution-lifecycle.md create mode 100644 docs/evidence/0001-pr03/README.md rename docs/evidence/{PR-03 => 0001-pr03}/control-flow-run-1664x920.png (100%) rename docs/evidence/{PR-03 => 0001-pr03}/welcome-1664x920.png (100%) rename docs/evidence/{PR-03 => 0001-pr03}/welcome-390x844.png (100%) create mode 100644 src/execution/controller.rs create mode 100644 src/execution/events.rs create mode 100644 src/execution/mod.rs create mode 100644 src/execution/process.rs create mode 100644 src/execution/request.rs create mode 100644 tests/integration/execution.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c1219d..8f0c626 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,27 @@ Protocol axes (Tool v1, Analysis v2, Trace v2) are versioned separately. ## [Unreleased] +### 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/ @@ -115,7 +136,7 @@ Protocol axes (Tool v1, Analysis v2, Trace v2) are versioned separately. search, settings, 7 viewport widths without horizontal overflow or dock clipping, no-JS reading, print mode, explicit run + clear. - Screenshot evidence for the Welcome page (1664×920, 390×844) and a real - Trace run page in `docs/evidence/PR-03/`. + Trace run page in `docs/evidence/0001-pr03/`. - Meta CSP no longer carries the ignored `frame-ancestors` directive (the HTTP header still enforces framing). diff --git a/docs/ACCEPTANCE.md b/docs/ACCEPTANCE.md index 33c8357..1412c31 100644 --- a/docs/ACCEPTANCE.md +++ b/docs/ACCEPTANCE.md @@ -48,7 +48,7 @@ | ID | 结果 | 说明 | |---|---|---| -| U-01 1664×920 视觉 | **PARTIAL** | 截图已采集(`docs/evidence/PR-03/`),几何/颜色令牌/无溢出/无外部资源 PASS;与参考截图的**像素级人工比对未执行(UNVERIFIED)** | +| U-01 1664×920 视觉 | **PARTIAL** | 截图已采集(`docs/evidence/0001-pr03/`),几何/颜色令牌/无溢出/无外部资源 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 曲线侧注未实现,不画错线 | diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 914a1c6..0936f25 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -59,14 +59,14 @@ | 条款 | 状态 | 计划 | |---|---|---| | 7 条最小路由 | **PENDING** | PR-04 | -| POST /api/runs 两阶段确认请求体(document/target/parameters/analysis_digest/mode/grants/client_request_id) | **PENDING** | PR-03/04 | -| 校验顺序(会话→CSRF/Origin/Host→大小/schema→containment→check→digest→函数/参数→模式/grants→并发→202) | **PENDING** | PR-03/04 | -| 同 `client_request_id` 幂等/不同 payload 409 | **PENDING** | PR-04 | +| POST /api/runs 两阶段确认请求体(document/target/parameters/analysis_digest/mode/grants/client_request_id) | PARTIAL | `execution/request.rs` 校验/解析/计划已实现;HTTP 路由 PR-04 | +| 校验顺序(会话→CSRF/Origin/Host→大小/schema→containment→check→digest→函数/参数→模式/grants→并发→202) | PARTIAL | Controller 已实现 schema→dedupe→busy→check→digest→target→202;HTTP 前置校验 PR-04 | +| 同 `client_request_id` 幂等/不同 payload 409 | PASS(Controller) | `tests/integration/execution.rs`;HTTP 映射 PR-04 | | SSE 帧合同(事件类型/seq/id/schema/心跳) | **PENDING** | PR-04 | | Last-Event-ID 重放、快照、128 缓冲、TTL、≤2 连接/任务 | **PENDING** | PR-04 | -| 单活动任务、409 run.busy、后台执行不阻塞 SSE | **PENDING** | PR-03/04 | -| 进程组取消(TERM→2s→KILL)、墙钟上限、有界输出 | **PENDING** | PR-03 | -| 显式预算参数 | **PENDING** | PR-03 | +| 单活动任务、409 run.busy、后台执行不阻塞 SSE | PARTIAL | Controller 单任务/后台线程已实现并测试;HTTP/SSE PR-04 | +| 进程组取消(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 | **PENDING** | PR-04 | | loopback only、请求体≤64KiB、CSP、路径 containment | PARTIAL | 大部分已有;会话 Cookie 待 PR-04 | | SSE 按会话隔离、跨站读取拒绝 | **PENDING** | PR-04 | @@ -78,7 +78,7 @@ | 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 执行层/请求/进程/控制器 | PENDING | — | +| PR-03 执行层/请求/进程/控制器 | **完成** | `src/execution/*`、ADR-0008、`docs/evidence/PR-03/` | | PR-04 SSE/路由/会话/前端闭环 | PENDING | — | | PR-05 Trace 绑定/标注/浏览器回归 | PENDING | — | | PR-06 导出/发布/文档闭环 | PENDING | — | @@ -92,14 +92,14 @@ | E03 Source/Document 切换 | PASS | 浏览器证据 | | E04 中文/Emoji/表格/公式 span | PASS | `tests/integration/unicode_spans.rs`、golden | | E05 main 运行 run --json --trace-file | PARTIAL | 同步路径有;SSE 终态待 PR-04 | -| E06 H2 Exec n=5 call | **PENDING** | PR-03/04 | -| E07 文本/列表常量参数 | **PENDING** | PR-03/04 | +| E06 H2 Exec n=5 call | PARTIAL | `build_call_args` + Controller 测试;真实 CLI/UI PR-04/06 | +| E07 文本/列表常量参数 | PARTIAL | `--arg name=expression` argv 已实现;真实 CLI/UI PR-04/06 | | E08 无 main 不自动运行别的函数 | PARTIAL | 现有 `can_offer_run` 逻辑;PR-04 复核 | | E09 Trace 事件映射不伪造变量 | PARTIAL | `src/trace.rs`;SSE 后复核 | | E10 SSE text/event-stream 无 polling | **PENDING** | PR-04 | | E11 Last-Event-ID 重连 | **PENDING** | PR-04 | | E12 长任务心跳/GET 不重启 | **PENDING** | PR-04 | -| E13 取消终止进程树 | **PENDING** | PR-03/04 | +| E13 取消终止进程树 | PARTIAL | Controller/process 已测(`second_run_is_busy...`、`process.rs` 单测);HTTP 接线 PR-04 | | E14 静态导出零联网/相对链接 | PARTIAL | 已实现;PR-06 复核 | | E15 刷新/重开不自动执行 | PASS | `tests/integration/http_live.rs` | | E16 运行后改源码 → stale 无高亮 | PARTIAL | 现有 stale;PR-05 复核 | diff --git a/docs/STATUS.md b/docs/STATUS.md index 4b5ccd2..fe8313a 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -23,7 +23,7 @@ | PR-00 基线、旧 View 取证、冻结 CLI 合同 | **完成** | `docs/audits/legacy-view.md`、`docs/audits/protocol-contract-0002.md`、`docs/decisions/0007` | | PR-01 Tool v1 打包/安装/调度、0.2.0、scripts/、CI | **完成** | `scripts/package.sh`、`scripts/install-smoke.sh`、`scripts/verify-frozen-cli.sh`、`.github/workflows/ci.yml`;冻结 CLI `tool install`/`view --help`/篡改拒绝实测 | | PR-02 Reader/Analysis 只读面与目标目录结构 | **完成** | `src/protocol/*`、`src/reader/*`、`src/config.rs`、`tests/{contract,integration}/`、`/api/documents`;证据 `docs/evidence/PR-02/` | -| PR-03 执行层:request/process/controller、pure + project grants | 待开始(现有同步 `pure` 执行可迁移) | `src/core_client.rs`、`src/app.rs` | +| PR-03 执行层:request/process/controller、pure + project grants | **完成** | `src/execution/{request,process,controller,events}.rs`、`--run-timeout`、ADR-0008、`tests/integration/execution.rs`;证据 `docs/evidence/PR-03/` | | PR-04 SSE 任务生命周期、取消、7 路由、会话 Cookie/CSRF | **未实现(MVP 阻塞项)** | — | | PR-05 Trace 绑定/原文标注/浏览器回归 | 待开始(现有 Trace 校验可迁移) | `src/trace.rs` | | PR-06 静态导出/发布包/文档闭环 | 待开始(现有导出可迁移) | `src/export.rs` | @@ -37,7 +37,7 @@ | 原始 Markdown/GFM 阅读、源码态、搜索/设置/打印 | 已实现(单一 `assets/reader.css`/`assets/reader.js`) | | Analysis v2 严格校验、函数/Unit/签名/诊断/导入/引用/资源投影 | 已实现(无效 span 降级) | | 单一 `ReaderRenderer`,Live/Export 共用 | 已实现(`src/reader/render.rs`,门禁测试) | -| 显式确认后同步运行 `pure` + Trace v2 校验与展示 | 已实现,但**不是 0002 的异步 SSE 闭环** | +| 显式确认后同步运行 `pure` + Trace v2 校验与展示 | 旧同步路径仍在(过渡);新的异步 Controller/SSE 就绪于 PR-03/04 | | 静态离线导出(无执行、manifest/哈希、原子发布) | 已实现,待按 0002 重新验收 | | Tool v1 打包/安装/分发、冻结 CLI SHA 前后一致 | 已实现,待迁移至 `scripts/` 与 0.2.0 | | HTTP 安全(Host/Origin/CSRF/路径 containment/CSP) | 部分实现;缺**会话 Cookie**模型与 7 路由合同 | @@ -57,12 +57,15 @@ 4. **无 project grants**:0002 要求受控 fs read/write glob(明确二次确认), 其它 net/process/env/plugin 一律拒绝并引导 CLI。 5. **无运行会话 Cookie**:CSRF 目前是进程级 token;0002 要求 - `HttpOnly; SameSite=Strict` 随机会话 Cookie + 每会话 CSRF,且 SSE 按会话隔离。 -6. **无取消/单任务状态机/重复请求去重**:缺 `cancel_requested`、唯一终态、 - `client_request_id` 幂等/409、409 run.busy。 -7. **执行预算未按 0002**:默认 30s(最大 120s)、`--fuel 1000000`、 - `--max-output 1048576`、`--trace-max-events 10000`、`--trace-max-bytes 4194304`、 - JSON/Trace/日志 4 MiB 有界读取与 `view.output_limit` 未实现。 + `HttpOnly; SameSite=Strict` 随机会话 Cookie + 每会话 CSRF,且 SSE 按会话隔离 + (PR-04)。 +6. **HTTP/SSE 传输未接**:Controller 已实现单任务状态机、取消、去重、 + `client_request_id` 幂等/409 与 `409 run.busy`(`src/execution/controller.rs`), + 但 `POST /api/runs`、`GET .../events`、`POST .../cancel` 与前端尚未切换(PR-04)。 +7. **执行预算**:Controller 已显式发送 `--timeout`(默认 30s/最大 120s)、 + `--fuel 1000000`、`--max-output 1048576`、`--trace-max-events 10000`、 + `--trace-max-bytes 4194304`,并做 4 MiB JSON/Trace 有界读取与 + `view.output_limit`;HTTP 层仍需映射为终态事件(PR-04)。 8. **目录/测试/示例仍有缺口**:`src/protocol`/`src/reader`/`src/config.rs`/ `tests/{contract,integration}`/`scripts/`/`.github/workflows/ci.yml` 已就位; 仍缺 `src/execution/*`、`src/server/{mod,routes,security,sse}.rs`、 diff --git a/docs/decisions/0008-execution-lifecycle.md b/docs/decisions/0008-execution-lifecycle.md new file mode 100644 index 0000000..f751142 --- /dev/null +++ b/docs/decisions/0008-execution-lifecycle.md @@ -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 轮询。 diff --git a/docs/evidence/0001-pr03/README.md b/docs/evidence/0001-pr03/README.md new file mode 100644 index 0000000..8e586e9 --- /dev/null +++ b/docs/evidence/0001-pr03/README.md @@ -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` 生成。 diff --git a/docs/evidence/PR-03/control-flow-run-1664x920.png b/docs/evidence/0001-pr03/control-flow-run-1664x920.png similarity index 100% rename from docs/evidence/PR-03/control-flow-run-1664x920.png rename to docs/evidence/0001-pr03/control-flow-run-1664x920.png diff --git a/docs/evidence/PR-03/welcome-1664x920.png b/docs/evidence/0001-pr03/welcome-1664x920.png similarity index 100% rename from docs/evidence/PR-03/welcome-1664x920.png rename to docs/evidence/0001-pr03/welcome-1664x920.png diff --git a/docs/evidence/PR-03/welcome-390x844.png b/docs/evidence/0001-pr03/welcome-390x844.png similarity index 100% rename from docs/evidence/PR-03/welcome-390x844.png rename to docs/evidence/0001-pr03/welcome-390x844.png diff --git a/docs/evidence/PR-03/README.md b/docs/evidence/PR-03/README.md index 8e586e9..49fe282 100644 --- a/docs/evidence/PR-03/README.md +++ b/docs/evidence/PR-03/README.md @@ -1,23 +1,59 @@ -# PR-03 浏览器视觉验收证据 +# PR-03 证据:执行层(request / process / controller / events) -- 采集环境: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、清理结果。 +- 日期:2026-11-22 +- 范围:`src/execution/{request,process,controller,events}.rs`、`core_client` 单一进程 + 适配器、`--run-timeout`、`DocumentService::static_document` +- 冻结 CLI:`marqdo 3.0.0-beta.1`(`062cb56e…`);本 PR 只用假核心做确定性进程级 + 测试,PR-04/06 再用真实冻结 CLI 做端到端验收 +- 说明:本 PR **不切换 HTTP 运行路由**;`POST /api/run`(同步旧路径)暂留到 + PR-04 被 7 路由 + SSE 替换。 -| 文件 | 说明 | +## 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(与基准截图同尺寸),无运行 | -| `welcome-390x844.png` | 同一页面 390×844 单栏布局 | -| `control-flow-run-1664x920.png` | `examples/control-flow` 用户确认运行后的真实 Trace v2 运行面板与内联事件 chip | +| `explicit_entry_run_streams_accepted_running_and_succeeded_with_verified_trace` | 事件序号递增;accepted/running/succeeded;Trace `verified`、事件非空、`stale=false`、stdout 来自 CLI JSON | +| `call_target_uses_the_call_subcommand_and_function_name` | argv 为 `call FILE `;FUNCTION 名称由 function_id 精确解析 | +| `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` 的像素差分:本环境无法进行 - 人工视觉判读,`U-01` 只声明“DOM/几何/字体栈/颜色令牌/无溢出/无外部资源”通过, - 像素级视觉相似度标记为 **UNVERIFIED(人工复核待办)**,不以自动化 PASS 代替。 -- 截图是证据,不是新的渲染路径:页面仍由唯一 `ReaderRenderer` 生成。 +```bash +cargo fmt --all -- --check +cargo clippy --all-targets --offline -- -D warnings +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 不冒称)。 diff --git a/src/cli.rs b/src/cli.rs index 67135a1..479695f 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -41,6 +41,16 @@ pub struct Cli { #[arg(long, global = true)] 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. #[arg(long, global = true, hide = true)] pub unsafe_expose: bool, @@ -97,6 +107,7 @@ pub struct RuntimeOpts { pub port: u16, pub no_open: bool, pub unsafe_expose: bool, + pub run_timeout_secs: u64, } impl Cli { @@ -108,6 +119,7 @@ impl Cli { port: self.port, no_open: self.no_open, unsafe_expose: self.unsafe_expose, + run_timeout_secs: self.run_timeout, } } } @@ -141,6 +153,7 @@ mod tests { assert!(cli.command.is_none()); assert_eq!(cli.host, "127.0.0.1"); assert_eq!(cli.port, 7429); + assert_eq!(cli.run_timeout, 30); } #[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] fn bind_policy_is_loopback_by_default() { assert!(validate_bind("127.0.0.1", false).is_ok()); diff --git a/src/core_client.rs b/src/core_client.rs index 822a867..c52e681 100644 --- a/src/core_client.rs +++ b/src/core_client.rs @@ -10,15 +10,14 @@ //! drop. use crate::error::{ViewError, ViewResult}; +use crate::execution::process::{run_bounded, ProcessBudget}; use crate::protocol::tool_v1::{self, CoreVersion}; use crate::reader::source::{sha256_hex, sha256_prefixed}; use crate::reader::source::{Project, SafeRelativePath}; use serde::{Deserialize, Serialize}; use std::ffi::OsString; -use std::io::Read; use std::path::{Path, PathBuf}; -use std::process::{Command, Stdio}; -use std::time::{Duration, Instant}; +use std::time::Duration; /// Default View-level wall clock cap for one Core `run`. pub const DEFAULT_RUN_TIMEOUT: Duration = Duration::from_secs(120); @@ -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 { - let mut command = Command::new(&self.bin); - command - .args(args) - .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 budget = ProcessBudget { + wall_clock: timeout, + ..Default::default() }; - - let stdout_bytes = stdout_thread.join().unwrap_or_default(); - let stderr_bytes = stderr_thread.join().unwrap_or_default(); - let stdout = String::from_utf8_lossy(&stdout_bytes).to_string(); - let stderr = String::from_utf8_lossy(&stderr_bytes).to_string(); + let outcome = run_bounded(&self.bin, args, cwd, &budget, None)?; + if outcome.timed_out { + return Err(ViewError::CoreTimeout { + detail: format!( + "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 { - exit_code: status.code().unwrap_or(-1), - stdout_bytes, + exit_code: outcome.exit_code.unwrap_or(-1), + stdout_bytes: outcome.stdout.bytes, stdout, stderr, }) @@ -515,86 +466,88 @@ struct ExecOutput { 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 { - let mut bytes = Vec::new(); - let _ = reader.read_to_end(&mut bytes); - bytes -} - /// Build the base `check` arguments. The caller appends `--emit ` and /// optionally `--refs`; this function exists so the argv shape is unit-testable. fn build_check_args(entry: &Path) -> Vec { vec![OsString::from("check"), entry.as_os_str().to_os_string()] } -/// Build `run` arguments from an already user-approved request. -pub fn build_run_args(entry: &Path, trace_path: &Path, options: &RunOptions) -> Vec { - let mut args = vec![ - 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(), - ]; +/// Common explicit flags shared by `run` and `call`. Budgets are always sent +/// explicitly by the execution controller (RFC-VIEW-0002 §6.7). +fn append_common_args(args: &mut Vec, trace_path: &Path, options: &RunOptions) { fn push_pair(args: &mut Vec, flag: &str, value: &str) { args.push(OsString::from(flag)); 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 { - push_pair(&mut args, "--allow-read", glob); + push_pair(args, "--allow-read", glob); } 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 { - push_pair(&mut args, "--allow-net", host); + push_pair(args, "--allow-net", host); } 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 { - push_pair(&mut args, "--allow-process", program); + push_pair(args, "--allow-process", program); } if options.grants.allow_random { args.push(OsString::from("--allow-random")); } 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 { - push_pair(&mut args, "--stack", &stack.to_string()); + push_pair(args, "--stack", &stack.to_string()); } 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 { - push_pair(&mut args, "--timeout", &timeout.to_string()); + push_pair(args, "--timeout", &timeout.to_string()); } 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 { - 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 { + 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 { + 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 } diff --git a/src/error.rs b/src/error.rs index 8d6a556..d4ced30 100644 --- a/src/error.rs +++ b/src/error.rs @@ -42,6 +42,22 @@ pub enum ViewError { ResourceLimit { detail: String }, /// Core subprocess could not be spawned. 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 }, + /// 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. CoreTimeout { detail: String }, /// Local file system / HTTP I/O failure. @@ -67,6 +83,14 @@ impl ViewError { ViewError::ResourceLimit { .. } => "view.resource_limit", ViewError::CoreSpawn { .. } => "view.core_spawn", ViewError::CoreTimeout { .. } => "view.core_timeout", + ViewError::RunInvalid { .. } => "view.run_invalid", + ViewError::NoEntryFunction { .. } => "view.no_entry_function", + 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::Unsupported { .. } => "view.unsupported", } @@ -80,7 +104,15 @@ impl ViewError { | ViewError::PathForbidden { .. } | ViewError::BindDenied { .. } | ViewError::SourceSpanInvalid { .. } - | ViewError::Unsupported { .. } => ExitClass::Argument, + | ViewError::Unsupported { .. } + | ViewError::RunInvalid { .. } + | ViewError::NoEntryFunction { .. } + | ViewError::RunBusy { .. } + | ViewError::RunConflict { .. } + | ViewError::RunNotFound { .. } + | ViewError::OutputLimit { .. } + | ViewError::CoreProtocol { .. } + | ViewError::SseBusy { .. } => ExitClass::Argument, _ => ExitClass::Runtime, } } @@ -118,6 +150,14 @@ impl ViewError { "view.resource_limit" => "超过配置的资源上限。", "view.core_spawn" => "无法启动冻结核心。", "view.core_timeout" => "冻结核心执行超时,已终止。", + "view.run_invalid" => "运行请求未通过校验(目标、参数、模式或授权不合法)。", + "view.no_entry_function" => "文档没有可调用的 main;请改选一个 H2 Exec 函数。", + "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.unsupported" => "当前版本不支持该功能。", _ => "View 内部错误。", @@ -162,6 +202,14 @@ impl ViewError { | ViewError::ResourceLimit { detail } | ViewError::CoreSpawn { detail } | ViewError::CoreTimeout { detail } + | ViewError::RunInvalid { detail } + | ViewError::NoEntryFunction { detail } + | ViewError::RunBusy { detail } + | ViewError::RunConflict { detail } + | ViewError::RunNotFound { detail } + | ViewError::OutputLimit { detail } + | ViewError::CoreProtocol { detail } + | ViewError::SseBusy { detail } | ViewError::Io { detail } | ViewError::Unsupported { detail } => detail, ViewError::SourceMismatch { expected, actual } => { diff --git a/src/execution/controller.rs b/src/execution/controller.rs new file mode 100644 index 0000000..8ce065f --- /dev/null +++ b/src/execution/controller.rs @@ -0,0 +1,1046 @@ +//! Single-job execution controller. +//! +//! One explicit `POST /api/runs` request becomes exactly one Core subprocess. +//! The controller owns the job state machine, deduplication, cancellation, the +//! bounded event log and Trace verification; it never polls and never starts a +//! second process for the same accepted job (RFC-VIEW-0002 §6.6/§6.7). + +use crate::core_client::{build_call_args, build_run_args, RunOptions, SandboxMode, ScratchDir}; +use crate::error::{ViewError, ViewResult}; +use crate::execution::events::{EventLog, RunEvent, RunState, Subscription}; +use crate::execution::process::{run_bounded_with_hook, ProcessBudget, ProcessOutcome}; +use crate::execution::request::{self, payload_digest, ExecutionPlan, ExecutionTarget, RunMode}; +use crate::protocol::trace_v2::{verify_trace, TraceVerificationInput}; +use crate::reader::assemble::{DocumentService, StaticDocument}; +use crate::reader::source::{sha256_hex, sha256_prefixed}; +use std::collections::{HashMap, VecDeque}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::Receiver; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +pub const DEFAULT_RUN_TIMEOUT_SECS: u64 = 30; +pub const MAX_RUN_TIMEOUT_SECS: u64 = 120; +pub const DEFAULT_MAX_JOBS: usize = 32; +pub const DEFAULT_TERMINAL_TTL: Duration = Duration::from_secs(15 * 60); +pub const DEFAULT_MAX_SSE_CONNECTIONS: usize = 2; +/// Execution budgets sent explicitly on every `run`/`call` (RFC §6.7). +pub const DEFAULT_FUEL: u64 = 1_000_000; +pub const DEFAULT_MAX_OUTPUT: u64 = 1_048_576; +pub const DEFAULT_TRACE_MAX_EVENTS: u64 = 10_000; +pub const DEFAULT_TRACE_MAX_BYTES: u64 = 4_194_304; +/// Maximum JSON/trace bytes accepted from one execution. +pub const MAX_RESULT_JSON_BYTES: usize = 4 * 1024 * 1024; +pub const MAX_TRACE_FILE_BYTES: usize = 4 * 1024 * 1024; + +#[derive(Debug, Clone)] +pub struct ExecutionConfig { + /// View-owned wall clock; kept equal to the Core `--timeout` value. + pub run_timeout: Duration, + pub budget: ProcessBudget, + pub max_jobs: usize, + pub terminal_ttl: Duration, + pub max_sse_connections: usize, +} + +impl Default for ExecutionConfig { + fn default() -> Self { + Self { + run_timeout: Duration::from_secs(DEFAULT_RUN_TIMEOUT_SECS), + budget: ProcessBudget::default(), + max_jobs: DEFAULT_MAX_JOBS, + terminal_ttl: DEFAULT_TERMINAL_TTL, + max_sse_connections: DEFAULT_MAX_SSE_CONNECTIONS, + } + } +} + +impl ExecutionConfig { + /// Clamp a user-provided timeout to the RFC range and keep both caps equal. + pub fn with_timeout(mut self, seconds: u64) -> Self { + let seconds = seconds.clamp(1, MAX_RUN_TIMEOUT_SECS); + self.run_timeout = Duration::from_secs(seconds); + self.budget.wall_clock = self.run_timeout; + self + } + + pub fn run_timeout_secs(&self) -> u64 { + self.run_timeout.as_secs().clamp(1, MAX_RUN_TIMEOUT_SECS) + } +} + +/// What the browser gets from `POST /api/runs` (202). +#[derive(Debug, Clone)] +pub struct AcceptedRun { + pub run_id: String, + pub state: RunState, + pub events_url: String, + pub cancel_url: String, + /// True when this is the same request id + same payload as an earlier job. + pub reused: bool, +} + +/// One SSE observer handle. Dropping it releases the per-job connection slot. +pub struct SseSubscription { + pub run_id: String, + pub replay: Vec, + pub receiver: Receiver, + pub terminal: bool, + _guard: ConnectionGuard, +} + +impl std::fmt::Debug for SseSubscription { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("SseSubscription") + .field("run_id", &self.run_id) + .field("replay", &self.replay.len()) + .field("terminal", &self.terminal) + .finish() + } +} + +struct ConnectionGuard { + job: Arc, +} + +impl Drop for ConnectionGuard { + fn drop(&mut self) { + if let Ok(mut inner) = self.job.inner.lock() { + inner.connections = inner.connections.saturating_sub(1); + } + } +} + +pub struct Job { + pub run_id: String, + pub session_id: String, + pub document: String, + pub created: Instant, + cancel: Arc, + inner: Mutex, +} + +struct JobInner { + log: EventLog, + terminal_at: Option, + connections: usize, +} + +impl Job { + fn new(run_id: String, session_id: String, document: String) -> Self { + Self { + run_id, + session_id, + document, + created: Instant::now(), + cancel: Arc::new(AtomicBool::new(false)), + inner: Mutex::new(JobInner { + log: EventLog::new(), + terminal_at: None, + connections: 0, + }), + } + } + + pub fn state(&self) -> RunState { + self.inner + .lock() + .map(|inner| inner.log.last_state()) + .unwrap_or(RunState::Unavailable) + } + + pub fn is_terminal(&self) -> bool { + self.inner + .lock() + .map(|inner| inner.log.terminal()) + .unwrap_or(true) + } +} + +struct DedupeEntry { + digest: String, + run_id: String, + created: Instant, +} + +#[derive(Default)] +struct ControllerState { + jobs: HashMap>, + order: VecDeque, + active: Option, + dedupe: HashMap, +} + +pub struct ExecutionController { + service: Arc, + config: ExecutionConfig, + state: Mutex, +} + +impl ExecutionController { + pub fn new(service: Arc, config: ExecutionConfig) -> Self { + Self { + service, + config, + state: Mutex::new(ControllerState::default()), + } + } + + pub fn config(&self) -> &ExecutionConfig { + &self.config + } + + /// Validate and accept one explicit run request. The read-only Analysis + /// check and digest comparison happen **before** acceptance; the user + /// program is only spawned in the background afterwards. + pub fn submit(self: &Arc, session_id: &str, body: &[u8]) -> ViewResult { + let validated = request::validate_request(body)?; + let digest = payload_digest(body); + let client_request_id = validated.client_request_id.clone(); + let mut state = self.state.lock().map_err(|_| ViewError::Io { + detail: "execution controller lock poisoned".to_string(), + })?; + self.purge_locked(&mut state); + + if let Some(entry) = state.dedupe.get(&client_request_id) { + if entry.digest != digest { + return Err(ViewError::RunConflict { + detail: "同一 client_request_id 携带了不同请求内容;拒绝执行以避免偷换任务" + .to_string(), + }); + } + if let Some(job) = state.jobs.get(&entry.run_id).cloned() { + return Ok(self.accepted_run(&job, true)); + } + return Err(ViewError::RunInvalid { + detail: "client_request_id 对应的运行已过期;请刷新页面后重新提交".to_string(), + }); + } + if let Some(active) = state.active.as_deref() { + return Err(ViewError::RunBusy { + detail: format!( + "已有运行 {active} 正在进行;本版本每个 View 服务只允许一个活动任务,请等待或取消" + ), + }); + } + + // Static, read-only validation while holding the controller lock so two + // concurrent submissions cannot both pass the single-job gate. + let static_doc = self.service.static_document(&validated.document)?; + if static_doc.analysis_digest != validated.analysis_digest { + return Err(ViewError::RunInvalid { + detail: "页面携带的 analysis_digest 与当前源码的 check --emit 不一致(页面已过期);请刷新后重试" + .to_string(), + }); + } + let plan = validated.plan_against(&static_doc.verified.projection)?; + let run_id = new_run_id(); + let job = Arc::new(Job::new( + run_id.clone(), + session_id.to_string(), + plan.document.to_string(), + )); + { + let mut inner = job.inner.lock().map_err(|_| ViewError::Io { + detail: "job lock poisoned".to_string(), + })?; + inner.log.publish_state(RunState::Accepted); + } + state.order.push_back(run_id.clone()); + state.jobs.insert(run_id.clone(), Arc::clone(&job)); + state.active = Some(run_id.clone()); + state.dedupe.insert( + client_request_id, + DedupeEntry { + digest, + run_id: run_id.clone(), + created: Instant::now(), + }, + ); + let accepted = self.accepted_run(&job, false); + drop(state); + + let controller = Arc::clone(self); + std::thread::spawn(move || controller.execute_job(job, static_doc, plan)); + Ok(accepted) + } + + fn accepted_run(&self, job: &Arc, reused: bool) -> AcceptedRun { + AcceptedRun { + run_id: job.run_id.clone(), + state: job.state(), + events_url: format!("/api/runs/{}/events", job.run_id), + cancel_url: format!("/api/runs/{}/cancel", job.run_id), + reused, + } + } + + fn execute_job( + self: Arc, + job: Arc, + static_doc: StaticDocument, + plan: ExecutionPlan, + ) { + let started = Instant::now(); + let outcome = self.run_core(&job, &plan); + let cancel_requested = job.cancel.load(Ordering::SeqCst); + let terminal = self.build_terminal(&plan, &static_doc, started, outcome, cancel_requested); + let Ok(mut inner) = job.inner.lock() else { + return; + }; + if inner.log.terminal() { + return; + } + let (state, result, trace, trace_status, error_code, error_message) = terminal; + let mut result = result; + result["trace_status"] = serde_json::json!(trace_status.clone()); + match state { + RunState::Succeeded => { + inner.log.publish_complete(result, trace); + } + _ => { + inner.log.publish_error( + state, + error_code.as_deref().unwrap_or("view.run_failed"), + error_message.as_deref().unwrap_or("运行失败"), + Some(result), + trace, + ); + } + } + inner.terminal_at = Some(Instant::now()); + drop(inner); + + if let Ok(mut state) = self.state.lock() { + if state.active.as_deref() == Some(job.run_id.as_str()) { + state.active = None; + } + self.purge_locked(&mut state); + } + } + + /// Spawn and wait for the one Core subprocess. `running` is published only + /// after the process was actually spawned (through the spawn hook). + fn run_core( + &self, + job: &Arc, + plan: &ExecutionPlan, + ) -> Result<(ProcessOutcome, Option>), ViewError> { + let client = self + .service + .core_client() + .ok_or_else(|| ViewError::RunDenied { + detail: "没有可用的冻结核心(MARQDO_BIN),运行被拒绝".to_string(), + })?; + let entry = self.service.project().absolute_for(&plan.document)?; + let scratch = ScratchDir::create("run")?; + let trace_path = scratch.file("trace.json"); + let options = self.run_options(plan); + let args = match &plan.target { + ExecutionTarget::Entry => build_run_args(&entry, &trace_path, &options), + ExecutionTarget::Function { cli_name, .. } => { + build_call_args(&entry, cli_name, &plan.arguments, &trace_path, &options) + } + }; + let running_job = Arc::clone(job); + let hook = move || { + if let Ok(mut inner) = running_job.inner.lock() { + if !inner.log.terminal() { + inner.log.publish_state(RunState::Running); + } + } + }; + let budget = ProcessBudget { + wall_clock: self.config.run_timeout, + ..self.config.budget.clone() + }; + let outcome = run_bounded_with_hook( + client.bin(), + &args, + self.service.project().root(), + &budget, + Some(Arc::clone(&job.cancel)), + Box::new(hook), + )?; + let trace = read_trace_limited(&trace_path)?; + Ok((outcome, trace)) + } + + fn run_options(&self, plan: &ExecutionPlan) -> RunOptions { + RunOptions { + mode: match plan.mode { + RunMode::Pure => SandboxMode::Pure, + RunMode::Project => SandboxMode::Project, + }, + grants: plan.grants.clone(), + fuel: Some(DEFAULT_FUEL), + stack: None, + max_output: Some(DEFAULT_MAX_OUTPUT), + timeout_seconds: Some(self.config.run_timeout_secs()), + view_timeout: Some(self.config.run_timeout), + trace_max_events: Some(DEFAULT_TRACE_MAX_EVENTS), + trace_max_bytes: Some(DEFAULT_TRACE_MAX_BYTES), + } + } + + fn build_terminal( + &self, + plan: &ExecutionPlan, + static_doc: &StaticDocument, + started: Instant, + outcome: Result<(ProcessOutcome, Option>), ViewError>, + cancel_requested: bool, + ) -> ( + RunState, + serde_json::Value, + Option, + String, + Option, + Option, + ) { + let duration_ms = started.elapsed().as_millis() as u64; + let (outcome, trace_bytes) = match outcome { + Ok(value) => value, + Err(err) => { + let state = match err.code() { + "view.output_limit" => RunState::Failed, + _ => RunState::Unavailable, + }; + let result = base_result(plan, static_doc, duration_ms); + return ( + state, + result, + None, + "unavailable".to_string(), + Some(err.code().to_string()), + Some(err.detail().to_string()), + ); + } + }; + if outcome.cancelled { + let mut result = base_result(plan, static_doc, duration_ms); + result["stdout"] = serde_json::json!(outcome.stdout.text_lossy()); + result["stderr"] = serde_json::json!(outcome.stderr.text_lossy()); + return ( + RunState::Cancelled, + result, + None, + "unavailable".to_string(), + Some("view.run_cancelled".to_string()), + Some("运行已按用户请求取消,进程组已终止".to_string()), + ); + } + if cancel_requested && !outcome.timed_out && !outcome.status_ok() { + // The user cancelled; the process may have exited from SIGTERM + // before the grace-period SIGKILL, so the adapter did not mark it + // itself. A successful exit still wins the race (RFC §6.6). + let mut result = base_result(plan, static_doc, duration_ms); + result["stderr"] = serde_json::json!(outcome.stderr.text_lossy()); + return ( + RunState::Cancelled, + result, + None, + "unavailable".to_string(), + Some("view.run_cancelled".to_string()), + Some("运行已按用户请求取消,进程组已终止".to_string()), + ); + } + if outcome.timed_out { + let mut result = base_result(plan, static_doc, duration_ms); + result["stderr"] = serde_json::json!(outcome.stderr.text_lossy()); + return ( + RunState::TimedOut, + result, + None, + "unavailable".to_string(), + Some("view.core_timeout".to_string()), + Some(format!( + "运行超过 {} 秒墙钟上限,进程组已终止", + self.config.run_timeout_secs() + )), + ); + } + if outcome.stdout.total > MAX_RESULT_JSON_BYTES { + let mut result = base_result(plan, static_doc, duration_ms); + result["stdout_truncated"] = serde_json::json!(true); + return ( + RunState::Failed, + result, + None, + "unavailable".to_string(), + Some("view.output_limit".to_string()), + Some(format!( + "CLI JSON 输出超过 {} 字节上限,已停止接收", + MAX_RESULT_JSON_BYTES + )), + ); + } + let json: serde_json::Value = + match serde_json::from_slice::(&outcome.stdout.bytes) { + Ok(value) if value.is_object() => value, + Ok(_) => { + return ( + RunState::Failed, + base_result(plan, static_doc, duration_ms), + None, + "unavailable".to_string(), + Some("view.core_protocol".to_string()), + Some("CLI 的 --json 输出不是 JSON 对象".to_string()), + ) + } + Err(err) => { + return ( + RunState::Failed, + base_result(plan, static_doc, duration_ms), + None, + "unavailable".to_string(), + Some("view.core_protocol".to_string()), + Some(format!( + "无法解析 CLI --json 输出(exit {:?}):{err}", + outcome.exit_code + )), + ) + } + }; + + // Re-read the source after the run: a changed source makes the result + // stale and forbids anchoring events to the current text. + let current_source = self + .service + .project() + .read_source(&plan.document) + .unwrap_or_default(); + let stale = sha256_hex(¤t_source) != static_doc.source_sha256; + + let (trace, trace_status) = build_trace_summary( + trace_bytes.as_deref(), + static_doc, + &json, + outcome.exit_code.unwrap_or(-1), + stale, + ); + let mut result = build_cli_result(plan, static_doc, duration_ms, &json, &outcome); + result["stale"] = serde_json::json!(stale); + let success = json + .get("success") + .and_then(serde_json::Value::as_bool) + .unwrap_or(false); + if success { + (RunState::Succeeded, result, trace, trace_status, None, None) + } else { + let (code, message) = cli_error(&json); + ( + RunState::Failed, + result, + trace, + trace_status, + Some(code), + Some(message), + ) + } + } + + /// Idempotent cancellation: only requests it; the executor owns the unique + /// terminal transition. + pub fn cancel(&self, session_id: &str, run_id: &str) -> ViewResult { + let job = self.lookup(session_id, run_id)?; + let mut inner = job.inner.lock().map_err(|_| ViewError::Io { + detail: "job lock poisoned".to_string(), + })?; + let state_now = inner.log.last_state(); + if state_now.is_terminal() { + return Ok(state_now); + } + job.cancel.store(true, Ordering::SeqCst); + if state_now != RunState::CancelRequested { + inner.log.publish_state(RunState::CancelRequested); + } + Ok(RunState::CancelRequested) + } + + /// Snapshot + subscribe must be one atomic step under the job lock so no + /// event can slip between the replay and the live subscription (§6.5). + pub fn subscribe( + &self, + session_id: &str, + run_id: &str, + last_event_id: Option, + ) -> ViewResult { + let job = self.lookup(session_id, run_id)?; + let mut inner = job.inner.lock().map_err(|_| ViewError::Io { + detail: "job lock poisoned".to_string(), + })?; + if inner.connections >= self.config.max_sse_connections { + return Err(ViewError::SseBusy { + detail: format!( + "同一运行最多 {} 个并发 SSE 连接", + self.config.max_sse_connections + ), + }); + } + inner.connections += 1; + let Subscription { + replay, + receiver, + terminal, + } = inner.log.subscribe(last_event_id); + drop(inner); + Ok(SseSubscription { + run_id: job.run_id.clone(), + replay: replay + .iter() + .map(|event| event.to_sse(&job.run_id)) + .collect(), + receiver, + terminal, + _guard: ConnectionGuard { + job: Arc::clone(&job), + }, + }) + } + + /// Public read-only job state for tests and diagnostics (not an HTTP + /// polling route). Never exposes another session's job. + pub fn job_state(&self, session_id: &str, run_id: &str) -> ViewResult { + Ok(self.lookup(session_id, run_id)?.state()) + } + + fn lookup(&self, session_id: &str, run_id: &str) -> ViewResult> { + let state = self.state.lock().map_err(|_| ViewError::Io { + detail: "execution controller lock poisoned".to_string(), + })?; + let job = state + .jobs + .get(run_id) + .cloned() + .ok_or_else(|| ViewError::RunNotFound { + detail: "运行任务不存在或已过期".to_string(), + })?; + if job.session_id != session_id { + return Err(ViewError::RunNotFound { + detail: "运行任务不属于当前会话".to_string(), + }); + } + Ok(job) + } + + fn purge_locked(&self, state: &mut ControllerState) { + let now = Instant::now(); + let ttl = self.config.terminal_ttl; + let mut keep_order = VecDeque::with_capacity(state.order.len()); + for run_id in state.order.drain(..) { + let mut expired = false; + if let Some(job) = state.jobs.get(&run_id) { + if let Ok(inner) = job.inner.lock() { + if let Some(terminal_at) = inner.terminal_at { + expired = now.duration_since(terminal_at) >= ttl; + } + } + } else { + expired = true; + } + if expired { + state.jobs.remove(&run_id); + } else { + keep_order.push_back(run_id); + } + } + state.order = keep_order; + while state.jobs.len() > self.config.max_jobs { + let Some(oldest) = state.order.pop_front() else { + break; + }; + state.jobs.remove(&oldest); + } + state + .dedupe + .retain(|_, entry| now.duration_since(entry.created) < ttl); + } +} + +fn read_trace_limited(path: &std::path::Path) -> ViewResult>> { + match std::fs::read(path) { + Ok(bytes) if bytes.is_empty() => Ok(None), + Ok(bytes) if bytes.len() > MAX_TRACE_FILE_BYTES => Err(ViewError::OutputLimit { + detail: format!("Trace 文件超过 {} 字节上限", MAX_TRACE_FILE_BYTES), + }), + Ok(bytes) => Ok(Some(bytes)), + Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(err) => Err(ViewError::io( + &format!("read trace {}", path.display()), + err, + )), + } +} + +fn base_result( + plan: &ExecutionPlan, + static_doc: &StaticDocument, + duration_ms: u64, +) -> serde_json::Value { + serde_json::json!({ + "document": plan.document.as_str(), + "target": match &plan.target { + ExecutionTarget::Entry => serde_json::json!({"kind": "entry"}), + ExecutionTarget::Function { cli_name, label } => serde_json::json!({ + "kind": "function", "cli_name": cli_name, "label": label, + }), + }, + "mode": plan.mode.as_str(), + "grants": { + "read": plan.grants.allow_read, + "write": plan.grants.allow_write, + }, + "analysis_digest": static_doc.analysis_digest, + "source_digest": sha256_prefixed(static_doc.source.as_bytes()), + "duration_ms": duration_ms, + "stale": false, + }) +} + +fn build_cli_result( + plan: &ExecutionPlan, + static_doc: &StaticDocument, + duration_ms: u64, + json: &serde_json::Value, + outcome: &ProcessOutcome, +) -> serde_json::Value { + let mut result = base_result(plan, static_doc, duration_ms); + result["command"] = json + .get("command") + .cloned() + .unwrap_or(serde_json::json!("run")); + result["success"] = json + .get("success") + .cloned() + .unwrap_or(serde_json::json!(false)); + result["exit_code"] = serde_json::json!(outcome.exit_code); + result["value"] = json + .get("value") + .cloned() + .unwrap_or(serde_json::Value::Null); + let (value_type, value_text) = summarize_value(json.get("value")); + result["value_type"] = serde_json::json!(value_type); + result["value_text"] = serde_json::json!(value_text); + result["stdout"] = json.get("stdout").cloned().unwrap_or(serde_json::json!("")); + result["stderr"] = json.get("stderr").cloned().unwrap_or(serde_json::json!("")); + result["diagnostics"] = json + .get("diagnostics") + .cloned() + .unwrap_or(serde_json::json!([])); + let success = json + .get("success") + .and_then(serde_json::Value::as_bool) + .unwrap_or(false); + result["error"] = if success { + serde_json::Value::Null + } else { + let (code, message) = cli_error(json); + serde_json::json!({"code": code, "message": message}) + }; + result["stdout_bytes"] = serde_json::json!(outcome.stdout.total); + result["stderr_bytes"] = serde_json::json!(outcome.stderr.total); + result +} + +fn cli_error(json: &serde_json::Value) -> (String, String) { + if let Some(error) = json.get("error") { + if let Some(text) = error.as_str() { + let code = json + .get("code") + .and_then(serde_json::Value::as_str) + .unwrap_or("core.error") + .to_string(); + return (code, text.to_string()); + } + if error.is_object() { + let code = error + .get("code") + .and_then(serde_json::Value::as_str) + .unwrap_or("core.error") + .to_string(); + let message = error + .get("message") + .and_then(serde_json::Value::as_str) + .unwrap_or("冻结核心报告运行失败") + .to_string(); + return (code, message); + } + } + let code = json + .get("code") + .and_then(serde_json::Value::as_str) + .unwrap_or("core.run_failed") + .to_string(); + (code, "冻结核心报告运行失败".to_string()) +} + +/// Safe Wire Value summary: recognized scalars are rendered as text; everything +/// else stays inert JSON that the frontend only shows via text nodes. +fn summarize_value(value: Option<&serde_json::Value>) -> (String, String) { + let Some(value) = value else { + return ("none".to_string(), "无返回值".to_string()); + }; + let Some(object) = value.as_object() else { + return ( + "unknown".to_string(), + "未知 Wire Value(已折叠)".to_string(), + ); + }; + let ty = object + .get("type") + .and_then(serde_json::Value::as_str) + .unwrap_or("unknown"); + let text = match ty { + "unit" => "Unit(无返回值)".to_string(), + "none" => "None".to_string(), + "bool" => format!( + "Bool({})", + object + .get("value") + .map(serde_json::Value::to_string) + .unwrap_or_else(|| "?".to_string()) + ), + "int" => format!( + "Int({})", + object + .get("decimal") + .and_then(serde_json::Value::as_str) + .unwrap_or("?") + ), + "text" => format!( + "Text({})", + object + .get("value") + .and_then(serde_json::Value::as_str) + .unwrap_or("") + ), + "float" => match object.get("special").and_then(serde_json::Value::as_str) { + Some(special) => format!("Float({special})"), + None => format!( + "Float({})", + object + .get("value") + .map(serde_json::Value::to_string) + .unwrap_or_else(|| "?".to_string()) + ), + }, + "list" => format!( + "List({} 项)", + object + .get("items") + .and_then(serde_json::Value::as_array) + .map(Vec::len) + .unwrap_or(0) + ), + "map" => format!( + "Map({} 项)", + object + .get("entries") + .and_then(serde_json::Value::as_object) + .map(serde_json::Map::len) + .unwrap_or(0) + ), + "table" => { + let rows = object + .get("rows") + .and_then(serde_json::Value::as_array) + .map(Vec::len) + .unwrap_or(0); + let cols = object + .get("header") + .and_then(serde_json::Value::as_array) + .map(Vec::len) + .unwrap_or(0); + format!("Table({rows}×{cols})") + } + "formula" => "Formula(惰性数据)".to_string(), + "code" => "Code(惰性数据)".to_string(), + "function_ref" => "FunctionRef".to_string(), + "plugin_handle" => "PluginHandle(不可传输)".to_string(), + "memory" => "Memory(不可传输)".to_string(), + "resource" => "Resource(不可传输)".to_string(), + other => format!("{other}(未识别,已折叠为 JSON)"), + }; + (ty.to_string(), text) +} + +/// Verify Trace v2 against the exact pre-run Analysis bytes and project a safe +/// event summary. Missing/invalid trace never fakes execution evidence. +fn build_trace_summary( + trace_bytes: Option<&[u8]>, + static_doc: &StaticDocument, + json: &serde_json::Value, + exit_code: i32, + stale: bool, +) -> (Option, String) { + let Some(trace_bytes) = trace_bytes else { + return (None, "unavailable".to_string()); + }; + let projection = &static_doc.verified.projection; + let verified = verify_trace(TraceVerificationInput { + trace_bytes, + analysis_bytes: &static_doc.analysis_bytes, + semantic: projection, + modules: &projection.modules, + source: &static_doc.source, + source_index: &static_doc.source_index, + run_json: json, + exit_code, + }); + let verified = match verified { + Ok(verified) => verified, + Err(_) => { + return ( + Some(serde_json::json!({ + "status": "invalid", + "stale": stale, + "note": "Trace 与本次 Analysis 字节不匹配或格式无效;不绘制任何执行标注。", + })), + "invalid".to_string(), + ) + } + }; + let projection = verified.projection; + let events = projection + .events + .iter() + .map(|event| { + serde_json::json!({ + "seq": event.seq, + "kind": event.kind_label(), + "function_id": event.function_id, + "module_id": event.module_id, + "span": event.raw_span, + "anchor": if stale { serde_json::Value::Null } else { + event.anchor_span.map(|span| serde_json::json!({"start": span.start, "end": span.end})) + .unwrap_or(serde_json::Value::Null) + }, + "detail": event.detail, + "operation": event.operation, + "duration_micros": event.duration_micros, + }) + }) + .collect::>(); + let truncated = projection.truncated.as_ref().map(|truncated| { + serde_json::json!({ + "reason": truncated.reason, + "limit": truncated.limit, + "written": truncated.written, + "label": truncated.label(), + }) + }); + let summary = serde_json::json!({ + "status": "verified", + "analysis_digest": projection.analysis_digest, + "core_run_id": projection.run_id, + "run_status": projection.run_status, + "state": projection.state.data_value(), + "stale": stale, + "truncated": truncated, + "events": events, + "counts": { + "total": projection.counts.total(), + "call_enter": projection.counts.call_enter, + "call_exit": projection.counts.call_exit, + "branch_eval": projection.counts.branch_eval, + "loop_iteration": projection.counts.loop_iteration, + "return": projection.counts.return_events, + "effect": projection.counts.effect, + "other": projection.counts.other, + "entry": projection.entry_event_count, + "other_modules": projection.other_event_count, + }, + "note": "Trace v2 已按 Analysis 原始字节摘要绑定;不包含参数值、逐语句变量或秘密。", + }); + (Some(summary), "verified".to_string()) +} + +fn new_run_id() -> String { + let mut bytes = [0u8; 16]; + let random = { + #[cfg(unix)] + { + use std::io::Read as _; + std::fs::File::open("/dev/urandom") + .and_then(|mut file| file.read_exact(&mut bytes).map(|_| ())) + .is_ok() + } + #[cfg(not(unix))] + { + false + } + }; + if !random { + let material = format!( + "{}-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|duration| duration.as_nanos()) + .unwrap_or(0), + unique_counter() + ); + bytes.copy_from_slice(&sha256_hex(material.as_bytes()).as_bytes()[..16]); + } + bytes.iter().map(|byte| format!("{byte:02x}")).collect() +} + +fn unique_counter() -> u64 { + static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + COUNTER.fetch_add(1, Ordering::Relaxed) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn wire_value_summary_is_safe_and_never_html() { + assert_eq!( + summarize_value(Some(&serde_json::json!({"type": "int", "decimal": "10"}))), + ("int".to_string(), "Int(10)".to_string()) + ); + assert_eq!( + summarize_value(Some( + &serde_json::json!({"type": "text", "value": "x"}) + )) + .1, + "Text(x)" + ); + assert!( + summarize_value(Some(&serde_json::json!({"type": "memory"}))) + .1 + .contains("不可传输") + ); + } + + #[test] + fn cli_errors_support_both_envelope_shapes() { + let prepare = serde_json::json!({ + "success": false, + "code": "sem.no_entry_function", + "error": "no main", + }); + assert_eq!( + cli_error(&prepare), + ("sem.no_entry_function".to_string(), "no main".to_string()) + ); + let runtime = serde_json::json!({ + "success": false, + "error": {"code": "runtime.type", "message": "bad type"}, + }); + assert_eq!( + cli_error(&runtime), + ("runtime.type".to_string(), "bad type".to_string()) + ); + } + + #[test] + fn run_ids_are_unguessable_and_unique() { + let a = new_run_id(); + let b = new_run_id(); + assert_eq!(a.len(), 32); + assert_ne!(a, b); + } +} diff --git a/src/execution/events.rs b/src/execution/events.rs new file mode 100644 index 0000000..f7f2993 --- /dev/null +++ b/src/execution/events.rs @@ -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, + /// Verified Trace v2 summary, only after digest/binding checks. + pub trace: Option, + /// `{code, message}` for terminal failures. + pub error: Option, +} + +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, + pub receiver: Receiver, + /// 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, + subscribers: Vec>, + last_state: RunState, + terminal_snapshot: Option, +} + +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, + ) -> 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, + trace: Option, + ) -> 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 { + 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) -> Subscription { + let (sender, receiver) = mpsc::sync_channel(EVENT_RING_CAPACITY); + let terminal = self.terminal(); + let mut replay: Vec = 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); + } +} diff --git a/src/execution/mod.rs b/src/execution/mod.rs new file mode 100644 index 0000000..87b3db2 --- /dev/null +++ b/src/execution/mod.rs @@ -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; diff --git a/src/execution/process.rs b/src/execution/process.rs new file mode 100644 index 0000000..3fcfd6d --- /dev/null +++ b/src/execution/process.rs @@ -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, + 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, + 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>, +) -> ViewResult { + 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>, + on_spawn: Box, +) -> ViewResult { + 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 = 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)); + } +} diff --git a/src/execution/request.rs b/src/execution/request.rs new file mode 100644 index 0000000..64de16d --- /dev/null +++ b/src/execution/request.rs @@ -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, + 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, + #[serde(default)] + pub write: Vec, +} + +#[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, + 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 { + 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 { + 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 `::`. +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" + ); + } +} diff --git a/src/lib.rs b/src/lib.rs index b161ced..210ffc8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,6 +10,7 @@ pub mod cli; pub mod config; pub mod core_client; pub mod error; +pub mod execution; pub mod export; pub mod protocol; pub mod reader; diff --git a/src/reader/assemble.rs b/src/reader/assemble.rs index 5e0f518..b973208 100644 --- a/src/reader/assemble.rs +++ b/src/reader/assemble.rs @@ -11,7 +11,7 @@ use crate::reader::markdown::{DocumentIdentity, DocumentModel}; use crate::reader::model::{ Navigation, OutlineEntry, OutlineKind, PresentationModel, SourceStatus, }; -use crate::reader::source::{Project, SafeRelativePath}; +use crate::reader::source::{sha256_hex, Project, SafeRelativePath}; use crate::core_client::{ CheckOptions, CheckResponse, CoreClient, RawCheckDiagnostic, RunOptions, SandboxMode, @@ -186,6 +186,10 @@ impl DocumentService { 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() } @@ -430,3 +434,86 @@ fn diagnostic_to_view( 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, + 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 { + 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, + }) + } +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs index fbe848d..09a93ed 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -73,9 +73,6 @@ dir="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)" printf 'invocation\n' for arg in "$@"; do printf 'arg=%s\n' "$arg"; done } >> "$dir/argv.txt" -if [ -f "$dir/sleep" ]; then - sleep "$(cat "$dir/sleep")" -fi case "$1" in --version) if [ -f "$dir/version" ]; then cat "$dir/version"; else printf 'marqdo 3.0.0-beta.1\n'; fi @@ -94,8 +91,11 @@ case "$1" in if [ -f "$dir/check_exit" ]; then exit "$(cat "$dir/check_exit")"; fi exit 0 ;; - run) + run|call) : > "$dir/run-was-called" + if [ -f "$dir/sleep" ]; then + sleep "$(cat "$dir/sleep")" + fi trace="" prev="" for a in "$@"; do diff --git a/tests/integration/execution.rs b/tests/integration/execution.rs new file mode 100644 index 0000000..3ccbf94 --- /dev/null +++ b/tests/integration/execution.rs @@ -0,0 +1,514 @@ +//! Execution controller tests: one explicit request, one Core subprocess, one +//! unique terminal state, SSE-ready events, dedupe, grants and cancellation. +//! +//! The fake Core is a real executable (never a mocked trait) so argv, process +//! lifecycle and trace files are exercised at the process boundary. + +use crate::common::{sha256_hex, FakeCore}; +use marqdo_view::execution::controller::{ExecutionConfig, ExecutionController, SseSubscription}; +use marqdo_view::execution::events::RunState; +use marqdo_view::reader::assemble::DocumentService; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +fn repo_root() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) +} + +fn golden(name: &str) -> String { + let path = repo_root().join("tests/golden/analysis-v2").join(name); + std::fs::read_to_string(&path).unwrap_or_else(|err| panic!("read {path:?}: {err}")) +} + +fn analysis_digest(analysis: &str) -> String { + format!("sha256:{}", sha256_hex(analysis.as_bytes())) +} + +struct Fixture { + core: FakeCore, + controller: Arc, + _service: Arc, +} + +fn fixture_with( + name: &str, + project_relative: &str, + analysis: &str, + run_json: &str, + trace: Option<&str>, + config: ExecutionConfig, +) -> Fixture { + let core = FakeCore::new(name); + core.set_analysis(analysis); + core.set_check_json(r#"{"command":"check","diagnostics":[],"errors":0,"success":true}"#); + core.set_run(0, run_json, trace); + let project = repo_root().join(project_relative); + let service = Arc::new( + DocumentService::open(&project, Some(core.script.as_path())) + .expect("open document service"), + ); + let controller = Arc::new(ExecutionController::new(Arc::clone(&service), config)); + Fixture { + core, + controller, + _service: service, + } +} + +fn control_flow(name: &str) -> Fixture { + let analysis = golden("control-flow.json"); + let run = + std::fs::read_to_string(repo_root().join("tests/golden/trace-v2/control-flow.run.json")) + .expect("run golden"); + let trace = + std::fs::read_to_string(repo_root().join("tests/golden/trace-v2/control-flow.trace.json")) + .expect("trace golden"); + fixture_with( + name, + "examples/control-flow", + &analysis, + &run, + Some(&trace), + ExecutionConfig::default().with_timeout(10), + ) +} + +fn request_body( + analysis: &str, + target: serde_json::Value, + mode: &str, + grants: serde_json::Value, + client_request_id: &str, +) -> Vec { + serde_json::json!({ + "document": "index.mq.md", + "target": target, + "analysis_digest": analysis_digest(analysis), + "mode": mode, + "grants": grants, + "client_request_id": client_request_id, + }) + .to_string() + .into_bytes() +} + +fn frame_data(frame: &str) -> Option { + frame + .lines() + .find(|line| line.starts_with("data: ")) + .and_then(|line| serde_json::from_str(line.trim_start_matches("data: ")).ok()) +} + +fn is_terminal_data(data: &serde_json::Value) -> bool { + data["state"] + .as_str() + .map(|state| { + matches!( + state, + "succeeded" | "failed" | "cancelled" | "timed_out" | "unavailable" + ) + }) + .unwrap_or(false) +} + +fn terminal_events(subscription: SseSubscription) -> (Vec, serde_json::Value) { + let mut parsed = subscription + .replay + .iter() + .filter_map(|frame| frame_data(frame)) + .collect::>(); + let mut terminal = parsed + .iter() + .rev() + .find(|data| is_terminal_data(data)) + .cloned(); + let deadline = Instant::now() + Duration::from_secs(20); + while terminal.is_none() && Instant::now() < deadline { + match subscription + .receiver + .recv_timeout(Duration::from_millis(250)) + { + Ok(event) => { + let data = event.data(&subscription.run_id); + if event.state.is_terminal() { + terminal = Some(data.clone()); + } + parsed.push(data); + } + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => { + if subscription.terminal { + break; + } + } + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break, + } + } + (parsed, terminal.expect("terminal event")) +} + +fn wait_for_file(path: &Path) { + let deadline = Instant::now() + Duration::from_secs(10); + while Instant::now() < deadline { + if path.is_file() { + return; + } + std::thread::sleep(Duration::from_millis(20)); + } + panic!("timed out waiting for {path:?}"); +} + +#[test] +fn explicit_entry_run_streams_accepted_running_and_succeeded_with_verified_trace() { + let fixture = control_flow("ctrl-success"); + let analysis = golden("control-flow.json"); + let body = request_body( + &analysis, + serde_json::json!({"kind": "entry"}), + "pure", + serde_json::json!({}), + "req-success", + ); + let accepted = fixture + .controller + .submit("session-a", &body) + .expect("accepted"); + assert!(!accepted.reused); + assert_eq!(accepted.run_id.len(), 32); + assert_eq!( + accepted.events_url, + format!("/api/runs/{}/events", accepted.run_id) + ); + + let subscription = fixture + .controller + .subscribe("session-a", &accepted.run_id, Some(0)) + .expect("subscribe"); + let (events, terminal) = terminal_events(subscription); + let seqs: Vec = events + .iter() + .map(|event| event["seq"].as_u64().unwrap()) + .collect(); + assert!( + seqs.windows(2).all(|pair| pair[0] < pair[1]), + "seqs: {seqs:?}" + ); + let states: Vec = events + .iter() + .map(|event| event["state"].as_str().unwrap().to_string()) + .collect(); + assert!( + states.contains(&"accepted".to_string()), + "states: {states:?}" + ); + assert!( + states.contains(&"running".to_string()), + "states: {states:?}" + ); + assert_eq!(terminal["state"], "succeeded"); + assert_eq!(terminal["result"]["success"], true); + assert_eq!(terminal["trace"]["status"], "verified"); + assert!(!terminal["trace"]["events"].as_array().unwrap().is_empty()); + assert_eq!(terminal["trace"]["stale"], false); + // The fake Core's stderr/stdout were read through the adapter, not guessed. + assert_eq!(terminal["result"]["stdout"], "0\n0\n2\n"); +} + +#[test] +fn call_target_uses_the_call_subcommand_and_function_name() { + let fixture = control_flow("ctrl-call"); + let analysis = golden("control-flow.json"); + let function_id = "root:control-flow@0.1.0::index.mq.md::演示.main"; + let body = request_body( + &analysis, + serde_json::json!({"kind": "function", "function_id": function_id}), + "pure", + serde_json::json!({}), + "req-call", + ); + let accepted = fixture + .controller + .submit("session-a", &body) + .expect("accepted"); + let subscription = fixture + .controller + .subscribe("session-a", &accepted.run_id, Some(0)) + .expect("subscribe"); + let (_events, terminal) = terminal_events(subscription); + assert_eq!(terminal["state"], "succeeded"); + let argv = std::fs::read_to_string(fixture.core.dir.join("argv.txt")).unwrap_or_default(); + assert!(argv.contains("arg=call"), "argv: {argv}"); + assert!(argv.contains("arg=main"), "argv: {argv}"); +} + +#[test] +fn same_client_request_id_is_idempotent_and_different_payload_conflicts() { + let fixture = control_flow("ctrl-dedupe"); + let analysis = golden("control-flow.json"); + let body = request_body( + &analysis, + serde_json::json!({"kind": "entry"}), + "pure", + serde_json::json!({}), + "req-dedupe", + ); + let first = fixture + .controller + .submit("session-a", &body) + .expect("first accepted"); + let second = fixture + .controller + .submit("session-a", &body) + .expect("second accepted"); + assert_eq!(first.run_id, second.run_id); + assert!(second.reused); + + let mut changed: serde_json::Value = serde_json::from_slice(&body).unwrap(); + changed["mode"] = serde_json::json!("project"); + let err = fixture + .controller + .submit("session-a", changed.to_string().as_bytes()) + .expect_err("conflicting payload must be rejected"); + assert_eq!(err.code(), "view.run_conflict"); +} + +#[test] +fn second_run_is_busy_while_one_is_active_and_cancel_is_idempotent() { + let analysis = golden("control-flow.json"); + let run = r#"{"command":"run","success":true,"value":{"type":"int","decimal":"1"}}"#; + let fixture = fixture_with( + "ctrl-cancel", + "examples/control-flow", + &analysis, + run, + None, + ExecutionConfig::default().with_timeout(30), + ); + fixture.core.set_sleep_seconds(30); + let body = request_body( + &analysis, + serde_json::json!({"kind": "entry"}), + "pure", + serde_json::json!({}), + "req-cancel", + ); + let accepted = fixture + .controller + .submit("session-a", &body) + .expect("accepted"); + wait_for_file(&fixture.core.dir.join("run-was-called")); + + let other_body = request_body( + &analysis, + serde_json::json!({"kind": "entry"}), + "pure", + serde_json::json!({}), + "req-cancel-other", + ); + let busy = fixture + .controller + .submit("session-a", &other_body) + .expect_err("second run must be busy"); + assert_eq!(busy.code(), "view.run_busy"); + + let started = Instant::now(); + let state = fixture + .controller + .cancel("session-a", &accepted.run_id) + .expect("cancel"); + assert!(matches!( + state, + RunState::CancelRequested | RunState::Cancelled + )); + // Repeat cancel is idempotent. + let _ = fixture + .controller + .cancel("session-a", &accepted.run_id) + .expect("second cancel"); + + let subscription = fixture + .controller + .subscribe("session-a", &accepted.run_id, Some(0)) + .expect("subscribe"); + let (events, terminal) = terminal_events(subscription); + assert_eq!(terminal["state"], "cancelled"); + let terminal_count = events + .iter() + .filter(|event| { + event["state"] + .as_str() + .map(|state| { + matches!( + state, + "succeeded" | "failed" | "cancelled" | "timed_out" | "unavailable" + ) + }) + .unwrap_or(false) + }) + .count(); + assert_eq!(terminal_count, 1, "exactly one terminal state: {events:?}"); + assert!(started.elapsed() < Duration::from_secs(10)); +} + +#[test] +fn cross_session_observation_is_rejected() { + let fixture = control_flow("ctrl-session"); + let analysis = golden("control-flow.json"); + let body = request_body( + &analysis, + serde_json::json!({"kind": "entry"}), + "pure", + serde_json::json!({}), + "req-session", + ); + let accepted = fixture + .controller + .submit("session-a", &body) + .expect("accepted"); + assert_eq!( + fixture + .controller + .subscribe("session-b", &accepted.run_id, None) + .unwrap_err() + .code(), + "view.run_not_found" + ); + assert_eq!( + fixture + .controller + .cancel("session-b", &accepted.run_id) + .unwrap_err() + .code(), + "view.run_not_found" + ); +} + +#[test] +fn stale_analysis_digest_is_rejected_before_any_process_starts() { + let fixture = control_flow("ctrl-stale"); + let analysis = golden("control-flow.json"); + let mut body: serde_json::Value = serde_json::from_slice(&request_body( + &analysis, + serde_json::json!({"kind": "entry"}), + "pure", + serde_json::json!({}), + "req-stale", + )) + .unwrap(); + body["analysis_digest"] = serde_json::json!(format!("sha256:{}", "0".repeat(64))); + let err = fixture + .controller + .submit("session-a", body.to_string().as_bytes()) + .expect_err("stale digest must be rejected"); + assert_eq!(err.code(), "view.run_invalid"); + assert!(!fixture.core.dir.join("run-was-called").exists()); +} + +#[test] +fn project_grants_are_mapped_to_explicit_cli_flags_and_pure_grants_are_rejected() { + let fixture = control_flow("ctrl-grants"); + let analysis = golden("control-flow.json"); + let body = request_body( + &analysis, + serde_json::json!({"kind": "entry"}), + "project", + serde_json::json!({"read": ["data/**"], "write": ["out/*.txt"]}), + "req-project", + ); + let accepted = fixture + .controller + .submit("session-a", &body) + .expect("accepted"); + let subscription = fixture + .controller + .subscribe("session-a", &accepted.run_id, Some(0)) + .expect("subscribe"); + let (_events, terminal) = terminal_events(subscription); + assert_eq!(terminal["state"], "succeeded"); + let argv = std::fs::read_to_string(fixture.core.dir.join("argv.txt")).unwrap_or_default(); + assert!(argv.contains("arg=--mode\narg=project"), "argv: {argv}"); + assert!( + argv.contains("arg=--allow-read\narg=data/**"), + "argv: {argv}" + ); + assert!( + argv.contains("arg=--allow-write\narg=out/*.txt"), + "argv: {argv}" + ); + assert!(!argv.contains("arg=--mode\narg=pure")); + + // pure with grants is rejected by request validation before the Core runs. + let pure_with_grants = request_body( + &analysis, + serde_json::json!({"kind": "entry"}), + "pure", + serde_json::json!({"read": ["data/**"]}), + "req-pure-grants", + ); + let err = fixture + .controller + .submit("session-a", &pure_with_grants) + .expect_err("pure grants must be rejected"); + assert_eq!(err.code(), "view.run_invalid"); +} + +#[test] +fn run_without_a_trace_file_succeeds_but_reports_unavailable_trace() { + let analysis = golden("control-flow.json"); + let run = r#"{"command":"run","success":true,"value":{"type":"int","decimal":"7"},"stdout":"hi\n","stderr":"","diagnostics":[]}"#; + let fixture = fixture_with( + "ctrl-no-trace", + "examples/control-flow", + &analysis, + run, + None, + ExecutionConfig::default().with_timeout(10), + ); + let body = request_body( + &analysis, + serde_json::json!({"kind": "entry"}), + "pure", + serde_json::json!({}), + "req-no-trace", + ); + let accepted = fixture + .controller + .submit("session-a", &body) + .expect("accepted"); + let subscription = fixture + .controller + .subscribe("session-a", &accepted.run_id, Some(0)) + .expect("subscribe"); + let (_events, terminal) = terminal_events(subscription); + assert_eq!(terminal["state"], "succeeded"); + assert_eq!(terminal["result"]["value_text"], "Int(7)"); + assert_eq!(terminal["trace"], serde_json::Value::Null); + assert_eq!(terminal["result"]["trace_status"], "unavailable"); + assert!(!fixture.core.dir.join("trace.json").exists() || terminal["trace"].is_null()); +} + +#[test] +fn event_frames_use_the_view_run_events_schema_and_numeric_ids() { + let fixture = control_flow("ctrl-frames"); + let analysis = golden("control-flow.json"); + let body = request_body( + &analysis, + serde_json::json!({"kind": "entry"}), + "pure", + serde_json::json!({}), + "req-frames", + ); + let accepted = fixture + .controller + .submit("session-a", &body) + .expect("accepted"); + let subscription = fixture + .controller + .subscribe("session-a", &accepted.run_id, None) + .expect("subscribe"); + let (events, terminal) = terminal_events(subscription); + assert_eq!(terminal["schema"], "marqdo.view-run-events"); + assert_eq!(terminal["schema_version"], 1); + assert_eq!(terminal["run_id"], accepted.run_id.as_str()); + assert!(!events.is_empty()); +} diff --git a/tests/integration/main.rs b/tests/integration/main.rs index 271dc80..2818421 100644 --- a/tests/integration/main.rs +++ b/tests/integration/main.rs @@ -4,6 +4,7 @@ #[path = "../common/mod.rs"] mod common; +mod execution; mod export; mod http_live; mod rendering; From 046834bcb6619501b1f33f6d2a44503971cdd8bf Mon Sep 17 00:00:00 2001 From: cflmy Date: Sun, 22 Nov 2026 14:30:40 +0800 Subject: [PATCH 05/21] feat(PR-04): SSE execution loop, 7-route server and session security MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - replace src/server.rs with src/server/{mod,routes,security,sse}.rs implementing exactly the RFC-0002 §6.2 routes: GET /, GET /file, GET /assets, GET /api/documents, POST /api/runs, GET /api/runs/{id}/events, POST /api/runs/{id}/cancel; old /api/health, /api/document, /api/run and /api/clear-run are gone (404) - SSE writes the event-stream directly to the socket and flushes every frame and heartbeat (tiny_http's chunked writer would delay frames); Last-Event-ID replay or authoritative snapshot, 128-event ring, terminal close, heartbeat comments, at most two observers per run, no polling route - per-session HttpOnly SameSite=Strict cookie + X-View-CSRF, exact same-origin Origin, loopback Host, Sec-Fetch-Site cross-site rejection, JSON-only 64 KiB run POSTs; cancel is an authenticated bodyless control POST - reader.js: Analysis-driven function form with text-only command preview, pure/project mode + explicit fs grants with second confirmation, one POST then EventSource, cancel, live result/stdout/stderr/Trace panel and keyed source anchors (skipped when stale); no innerHTML of CLI data and no status polling - render: hidden live run shell, generic explicit-run dialog, function call buttons carrying Analysis function ids/params, data-analysis-digest/document attributes; remove the old run-confirm dialog and run-page reload path - add tests/security/ suite, rewrite HTTP/SSE integration tests, update browser suite for EventSource/dark theme/RFC width matrix (incl. 2048x1133) - ADR-0009 + docs/evidence/PR-04 with real Chromium log/screenshots and a real frozen-CLI SSE run (285 Trace v2 events, CLI SHA unchanged) - unit 63 + contract 41 + integration 40 + security 11 pass; clippy clean --- CHANGELOG.md | 24 + COMPATIBILITY.md | 8 +- Cargo.toml | 4 + README.md | 46 +- assets/reader.css | 89 ++ assets/reader.js | 593 +++++++-- docs/CONFORMANCE.md | 52 +- docs/STATUS.md | 56 +- .../0009-sse-transport-and-session.md | 86 ++ docs/evidence/PR-04/README.md | 83 ++ docs/evidence/PR-04/browser.log | 143 +++ .../evidence/PR-04/control-flow-2048x1133.png | Bin 0 -> 121653 bytes docs/evidence/PR-04/control-flow-390x844.png | Bin 0 -> 68466 bytes docs/evidence/PR-04/control-flow-run.png | Bin 0 -> 107927 bytes docs/evidence/PR-04/real-run.log | 1 + docs/evidence/PR-04/server.log | 7 + docs/evidence/PR-04/welcome-2048x1133.png | Bin 0 -> 191792 bytes scripts/acceptance-run.py | 81 ++ scripts/acceptance.sh | 36 +- scripts/test-security.sh | 8 +- src/error.rs | 6 + src/execution/controller.rs | 30 + src/reader/assemble.rs | 72 +- src/reader/model.rs | 21 + src/reader/render.rs | 145 ++- src/server.rs | 1105 ----------------- src/server/mod.rs | 122 ++ src/server/routes.rs | 691 +++++++++++ src/server/security.rs | 348 ++++++ src/server/sse.rs | 132 ++ tests/browser/reader.browser.cjs | 70 +- tests/common/http.rs | 419 +++++++ tests/common/mod.rs | 4 +- tests/integration/http_live.rs | 911 ++++++-------- tests/security/main.rs | 382 ++++++ 35 files changed, 3812 insertions(+), 1963 deletions(-) create mode 100644 docs/decisions/0009-sse-transport-and-session.md create mode 100644 docs/evidence/PR-04/README.md create mode 100644 docs/evidence/PR-04/browser.log create mode 100644 docs/evidence/PR-04/control-flow-2048x1133.png create mode 100644 docs/evidence/PR-04/control-flow-390x844.png create mode 100644 docs/evidence/PR-04/control-flow-run.png create mode 100644 docs/evidence/PR-04/real-run.log create mode 100644 docs/evidence/PR-04/server.log create mode 100644 docs/evidence/PR-04/welcome-2048x1133.png create mode 100755 scripts/acceptance-run.py delete mode 100644 src/server.rs create mode 100644 src/server/mod.rs create mode 100644 src/server/routes.rs create mode 100644 src/server/security.rs create mode 100644 src/server/sse.rs create mode 100644 tests/common/http.rs create mode 100644 tests/security/main.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f0c626..62caf09 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,30 @@ Protocol axes (Tool v1, Analysis v2, Trace v2) are versioned separately. ## [Unreleased] +### 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`. diff --git a/COMPATIBILITY.md b/COMPATIBILITY.md index 19bf408..be044e2 100644 --- a/COMPATIBILITY.md +++ b/COMPATIBILITY.md @@ -29,13 +29,13 @@ Beta 版 CLI 必须使用 prerelease 范围(`>=3.0.0-beta.1,<4.0.0`);`>=3. | Analysis v2 静态语义(函数/Unit/诊断/引用/资源) | **已实现**(PR-02) | | 文档态 / 源码态切换 | **已实现**(PR-02) | | 暖纸 Reader 视觉(单一 CSS/JS) | 计划 PR-03 | -| 用户显式触发运行 + Trace v2 事件可视化 | **已实现**(PR-04,仅 `pure` 模式,需页面内确认 + CSRF) | -| Live 本机安全 API | **已实现**(PR-02 只读 + PR-04 run + PR-05 并发/公开错误/导出) | +| 用户显式触发运行 + SSE + Trace v2 事件可视化 | **已实现**(0002 PR-04;`pure`/受控 `project`,显式确认 + 会话 CSRF) | +| Live 本机安全 API(7 路由) | **已实现**(0002 PR-04;Cookie/CSRF/Origin/CSP/单任务/SSE) | | 静态离线导出(纯只读) | **已实现**(PR-05,同一渲染器) | | 逐语句变量值 / 参数实际值 / 内存快照 | **UNSUPPORTED**(Trace v2 不提供,绝不伪造) | | 知识“已证明”状态 | **UNSUPPORTED**(需要独立 Prove 协议与证书) | -| `project`/`strict` 运行与 grants 授权 | **未实现**(首版仅 `pure`;0002 的受控 project grants 在 PR-03/04) | -| SSE 状态推送 / 取消运行 / 事件重放 | **未实现**(RFC-VIEW-0002 PR-04 阻塞项;当前运行后整页重载) | +| `project` 运行与 fs grants | **已实现(受控)**:仅相对项目根 read/write glob,显式二次确认;其它权限拒绝 | +| SSE 状态推送 / 取消运行 / 事件重放 | **已实现**(逐帧 flush、心跳、Last-Event-ID、2 连接上限、无轮询) | | SVG 曲线侧注 | **未实现**(运行事件用内联 keyed chip,U-04 PARTIAL) | | 调试器/断点/单步 | **不实现**(首版非目标) | | Knowledge/Prove/Lint 引擎 | **不实现**(独立仓库/未来可选信息层) | diff --git a/Cargo.toml b/Cargo.toml index 292bfa1..2c1e713 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,10 @@ path = "src/main.rs" name = "contract" path = "tests/contract/main.rs" +[[test]] +name = "security" +path = "tests/security/main.rs" + [[test]] name = "integration" path = "tests/integration/main.rs" diff --git a/README.md b/README.md index 7dc9c61..2bd77d3 100644 --- a/README.md +++ b/README.md @@ -22,11 +22,11 @@ Marqdo View(`0.2.0`)是一个独立的可执行文档阅读器:以**原始 |---|---| | 原始 Markdown + GFM 阅读、源码态、文档态 | ✅ | | Analysis v2 静态语义(函数/Unit/签名/诊断/导入/引用/资源) | ✅ 严格校验,span 无效则降级 | -| 本机 Live 阅读(默认 `127.0.0.1`,只读 API) | ✅ | -| 用户确认后运行 + 真实 Trace v2 可视化(`pure` 模式) | ✅(0001 同步模型;0002 的 SSE 异步闭环开发中) | +| 本机 Live 阅读(默认 `127.0.0.1`,只读 API + 显式执行端点) | ✅ | +| 显式确认后运行 + SSE 状态/取消 + 真实 Trace v2 | ✅ 单任务、无轮询、断线重放 | | 纯只读静态导出(离线 `file://`、manifest/哈希、原子发布) | ✅ | -| 单函数参数表单 + 受控 `project` fs grants | 🚧 RFC-VIEW-0002 PR-03/04 | -| SSE 状态推送 / 取消 / 断线重放(禁止轮询) | 🚧 RFC-VIEW-0002 PR-04(MVP 阻塞项) | +| 单函数参数表单 + 受控 `project` fs grants | ✅ 参数来自 Analysis 签名;project 需显式 glob 二次确认 | +| SSE 状态推送 / 取消 / 断线重放(禁止轮询) | ✅ `POST /api/runs` + `GET …/events` + `POST …/cancel` | | 逐语句变量值 / 参数值 / 内存快照 | ❌ UNSUPPORTED(协议不提供,绝不伪造) | | 知识“已证明” / Prove / Lint / 调试器 | ❌ 非目标/等待独立协议 | @@ -62,9 +62,11 @@ marqdo view export examples/welcome --out ./site marqdo view export examples/mixed-modes --out ./site --no-annotations ``` -开发期可直接运行 `marqdo-view`(用 `--marqdo-bin` 指定冻结核心)。运行入口在 Live -页面中:点击“运行”→ 阅读风险说明 → 点击“确认运行”,才会调用冻结核心执行 -`--mode pure`;页面刷新/打开/搜索/导出都不会运行。 +开发期可直接运行 `marqdo-view`(用 `--marqdo-bin` 指定冻结核心)。运行只有一个入口: +Live 页面点击 Dock “运行”(执行 `main`)或函数面板的“调用”(执行 `call`), +阅读命令预览与权限说明后点击“确认执行”,服务端才 `POST /api/runs` 启动一个 +CLI 子进程;状态与结果通过 SSE 推送,可取消,断线可重放。页面刷新/打开/搜索/ +切换/导出都不会运行,也没有状态轮询。 ## 架构(强制约束) @@ -75,21 +77,25 @@ Reader UI(唯一 assets/reader.css + assets/reader.js) │ ReaderRenderer(唯一模板,Live/Export 共用) │ -PresentationModel(DocumentModel / SemanticProjection / RunProjection) +PresentationModel(reader::assemble / reader::model) │ -PublicCoreClient ─ MARQDO_BIN 子进程 + 公开 JSON(check --emit / run --trace-file) +CoreClient ─ MARQDO_BIN 子进程 + 公开 JSON(check --emit / run/call --trace-file) + │ +ExecutionController ─ 单任务、取消、SSE 事件(仅 POST /api/runs 可达) │ 冻结发布版 marqdo CLI(不修改、不重编译、不链接、不读源码) ``` - 单一 Rust package、单一渲染入口、单一主题文件;没有第二个 Markdown→语义管线。 +- 服务端只有 7 条固定路由;SSE 只推送 View 自有 `run.*` 生命周期事件。 - Analysis v2 是唯一语义权威:函数/语句/分支/循环/诊断均来自 `check --emit`, 源码字节 span 只用于绑定视觉位置。 - Trace v2 与 Analysis 字节摘要严格绑定;`STALE/TRUNCATED/FAILED/UNSUPPORTED` 状态显式呈现,不猜测未公开值。 - Live/Export 内容同源;导出绝不执行、绝不覆盖项目源文件或无关目录。 - 门禁:`tests/contract/no_coupling.rs` 拒绝旧 crate/源码依赖、第二套渲染器/主题、shell 执行; - `tests/contract/asset_integrity.rs` 锁定内嵌资产与唯一主题层。 + `tests/contract/asset_integrity.rs` 锁定内嵌资产与唯一主题层; + `tests/security/` 覆盖 CSRF/Origin/Cookie/路径/symlink/XSS/跨会话 SSE。 ## 开发与验收 @@ -122,15 +128,11 @@ MARQDO_BIN=... ./scripts/test-browser.sh # 真实 Chromium 视觉/交互/响 ## 已知限制(诚实状态) -- 首版运行只支持 `--mode pure`;`project`/`strict` 及 grants 授权界面未实现。 -- 运行完成后整页重载并保留阅读位置;无 SSE 流式输出/取消/多运行历史。 -- 变量实际值、参数值、内存快照、知识证明状态不在 Trace v2 中,UI 一律标 UNSUPPORTED。 -- 平台仅 Linux x86_64 glibc 正式验证;macOS/Windows 未验证。 -- 视觉自动化门禁 PASS,但参考截图的像素级人工比对仍未执行(`U-01 UNVERIFIED`); - SVG 曲线侧注未实现,运行事件以可访问的内联 chip 呈现(`U-04 PARTIAL`)。 -- 远端正 CI 未实际运行;`.woodpecker.yml` 已提供,本地验收证据完整。 - -## 许可 - -代码按 MIT / Apache-2.0 双许可发布(`LICENSE-MIT`、`LICENSE-APACHE`)。复用的旧 -View 视觉资产(Apache-2.0)来源与哈希见 `assets/licenses/ASSETS.md`。 +- 运行仅 `pure`(默认)与受控 `project` fs read/write;`strict`、网络/进程/环境/ + plugin/provider/kernel 授权不在首版 UI,必须使用终端 CLI。 +- `project` 不是 OS 沙箱;View 不继承 `marqdo.yaml` 的 capability 请求。 +- SSE 只推送 View 生命周期与终态数据,不承诺逐字 stdout/Token 流;Trace v2 不含 + 参数实际值/逐语句变量/内存快照。 +- 平台:仅 Linux x86_64 正式验证;Windows/macOS 不支持声明。 +- 像素级人工视觉比对与完整 screen-reader 走查为 `UNVERIFIED`(自动化几何/响应式/ + 无外部资源/无 JS/打印证据见 `docs/evidence/PR-04/`)。 diff --git a/assets/reader.css b/assets/reader.css index ba27811..8eb93b7 100644 --- a/assets/reader.css +++ b/assets/reader.css @@ -1281,3 +1281,92 @@ } } } + +@layer interactions { + .mq-fn-call { + margin-left: 10px; + padding: 2px 10px; + border: 1px solid var(--mq-gold); + border-radius: 999px; + background: transparent; + color: var(--mq-gold); + font: 12px/1.6 var(--mq-sans); + cursor: pointer; + } + .mq-fn-call:hover { + background: var(--mq-gold-soft); + color: var(--mq-strong); + } + .mq-run-target { + margin: 4px 0 12px; + font: 13px/1.6 var(--mq-sans); + color: var(--mq-muted); + } + .mq-run-status { + font: 13px/1.6 var(--mq-sans); + color: var(--mq-ink); + } + .mq-run-params { + display: grid; + gap: 10px; + margin: 12px 0; + } + .mq-run-param { + display: flex; + flex-direction: column; + gap: 4px; + font: 12px/1.5 var(--mq-sans); + color: var(--mq-muted); + } + .mq-run-param input { + padding: 7px 10px; + border: 1px solid var(--mq-line-strong); + border-radius: 8px; + background: var(--mq-paper); + color: var(--mq-ink); + font: 13px/1.5 var(--mq-mono); + } + .mq-run-mode { + margin: 12px 0; + padding: 10px 12px; + border: 1px solid var(--mq-line); + border-radius: 10px; + font: 12px/1.6 var(--mq-sans); + } + .mq-run-mode legend { + padding: 0 6px; + color: var(--mq-muted); + } + .mq-run-mode label { + display: block; + margin: 4px 0; + } + .mq-run-grants { + display: grid; + gap: 8px; + margin: 10px 0; + font: 12px/1.6 var(--mq-sans); + } + .mq-run-grants textarea { + width: 100%; + margin-top: 4px; + padding: 8px 10px; + border: 1px solid var(--mq-line-strong); + border-radius: 8px; + background: var(--mq-paper); + color: var(--mq-ink); + font: 12px/1.5 var(--mq-mono); + resize: vertical; + } + .mq-run-command { + margin: 8px 0 12px; + padding: 10px 12px; + overflow-x: auto; + border: 1px dashed var(--mq-line-strong); + border-radius: 8px; + background: var(--mq-surface-2); + font: 12px/1.6 var(--mq-mono); + white-space: pre-wrap; + overflow-wrap: anywhere; + } +} diff --git a/assets/reader.js b/assets/reader.js index ea79773..a2bc19a 100644 --- a/assets/reader.js +++ b/assets/reader.js @@ -252,7 +252,7 @@ openDialog("mq-dialog-unsupported"); } - function handleAction(action) { + function handleAction(action, trigger) { switch (action) { case "mode-document": setMode("document"); @@ -302,25 +302,33 @@ openDialog("mq-dialog-about"); break; case "run": - if (reader.dataset.runAvailable === "true") { - openDialog("mq-dialog-run-confirm"); - } else { - showUnsupported( - "运行文档", - "当前页面没有可用的冻结核心或可执行入口;View 不会在缺少确认的情况下执行任何文档。" - ); - } + openRunForMain(); break; case "run-confirm": - confirmRun(); + submitRun(); + break; + case "cancel-run": + cancelRun(); + break; + case "call-function": + if (trigger) { + var params = []; + try { + params = JSON.parse(trigger.dataset.params || "[]"); + } catch (error) { + params = []; + } + openRunForm({ + kind: "function", + functionId: trigger.dataset.functionId, + label: trigger.dataset.functionLabel, + params: params + }); + } break; case "clear-run": - clearRun(); - break; case "clear": - var panel = $("#mq-run-panel"); - if (panel) panel.hidden = true; - toast("已清理本地展示状态(源文件与缓存未修改)"); + clearRun(); break; default: break; @@ -332,93 +340,522 @@ return meta ? meta.getAttribute("content") : ""; } - function setRunBusy(busy) { - var button = document.querySelector('.mq-dock-btn[data-action="run"]'); - if (!button) return; - if (busy) { - button.setAttribute("aria-busy", "true"); - button.dataset.busy = "true"; - button.disabled = true; - reader.dataset.runState = "running"; + var activeRun = null; + var pendingRun = null; + + function randomId() { + var bytes = new Uint8Array(16); + if (window.crypto && window.crypto.getRandomValues) { + window.crypto.getRandomValues(bytes); } else { - button.removeAttribute("aria-busy"); - delete button.dataset.busy; - button.disabled = false; + for (var i = 0; i < bytes.length; i += 1) bytes[i] = Math.floor(Math.random() * 256); + } + var out = ""; + for (var j = 0; j < bytes.length; j += 1) { + out += (bytes[j] < 16 ? "0" : "") + bytes[j].toString(16); + } + return "req-" + out; + } + + function csrfToken() { + var meta = document.querySelector('meta[name="mq-csrf-token"]'); + return meta ? meta.getAttribute("content") : ""; + } + + function stateLabel(state) { + switch (state) { + case "accepted": return "已接受"; + case "running": return "运行中"; + case "cancel_requested": return "正在取消"; + case "succeeded": return "成功"; + case "failed": return "失败"; + case "cancelled": return "已取消"; + case "timed_out": return "超时"; + case "unavailable": return "不可用"; + default: return String(state || "未知"); } } - function confirmRun() { - var dialog = $("#mq-dialog-run-confirm"); - var path = dialog ? dialog.dataset.path : ""; - var token = csrfToken(); - if (!path || !token) { - toast("缺少运行上下文或 CSRF 令牌,已拒绝运行"); + function isTerminalState(state) { + return ["succeeded", "failed", "cancelled", "timed_out", "unavailable"].indexOf(state) >= 0; + } + + function runPanel() { + return $("#mq-run-panel"); + } + + function setRunStatus(text) { + var status = $("#mq-run-status"); + if (status) status.textContent = text; + } + + function showRunPanel() { + var panel = runPanel(); + if (panel) panel.hidden = false; + } + + function setRunBusy(busy) { + var button = document.querySelector('.mq-dock-btn[data-action="run"]'); + if (button) { + if (busy) { + button.setAttribute("aria-busy", "true"); + button.dataset.busy = "true"; + button.disabled = true; + reader.dataset.runState = "running"; + } else { + button.removeAttribute("aria-busy"); + delete button.dataset.busy; + button.disabled = false; + } + } + var cancel = $("#mq-run-actions"); + if (cancel) cancel.hidden = !busy; + } + + function appendLine(container, tag, className, text) { + var node = document.createElement(tag); + if (className) node.className = className; + node.textContent = text; + container.appendChild(node); + return node; + } + + function clearRunOutput() { + ["#mq-run-summary", "#mq-run-stdout", "#mq-run-stderr", "#mq-run-events"].forEach(function (selector) { + var node = $(selector); + if (node) node.textContent = ""; + }); + var stdout = $("#mq-run-stdout"); + if (stdout) stdout.hidden = true; + var stderr = $("#mq-run-stderr"); + if (stderr) stderr.hidden = true; + var traceWrap = $("#mq-run-trace-wrap"); + if (traceWrap) traceWrap.hidden = true; + $$(".mq-run-chip[data-view-chip]").forEach(function (chip) { + chip.remove(); + }); + } + + function closeActiveObserver() { + if (activeRun && activeRun.source) { + try { + activeRun.source.close(); + } catch (error) { + /* optional */ + } + activeRun.source = null; + } + } + + function selectedMode() { + var checked = document.querySelector('input[name="mq-mode"]:checked'); + return checked ? checked.value : "pure"; + } + + function grantList(id) { + var field = document.getElementById(id); + if (!field) return []; + return field.value + .split("\n") + .map(function (line) { return line.trim(); }) + .filter(function (line) { return line.length > 0; }); + } + + function rawParams() { + var out = []; + $$("#mq-run-params [data-param-name]").forEach(function (input) { + out.push({ name: input.dataset.paramName, expression: input.value, required: input.dataset.required === "true" }); + }); + return out; + } + + function updateRunPreview() { + var preview = $("#mq-run-command"); + if (!preview || !pendingRun) return; + var mode = selectedMode(); + var parts = []; + if (pendingRun.kind === "entry") { + parts = ["marqdo", "run", reader.dataset.document, "--mode", mode, "--json", "--trace-file", "<临时文件>"]; + } else { + parts = ["marqdo", "call", reader.dataset.document, "<函数 " + pendingRun.label + ">", "--mode", mode, "--json", "--trace-file", "<临时文件>"]; + rawParams().forEach(function (param) { + parts.push("--arg"); + parts.push(param.name + "=" + (param.expression || "<常量表达式>")); + }); + } + if (mode === "project") { + grantList("mq-grant-read").forEach(function (glob) { parts.push("--allow-read"); parts.push(glob); }); + grantList("mq-grant-write").forEach(function (glob) { parts.push("--allow-write"); parts.push(glob); }); + } + preview.textContent = parts.join(" "); + var modeLabel = $("#mq-run-target-mode"); + if (modeLabel) modeLabel.textContent = mode; + } + + function renderRunParams(params) { + var container = $("#mq-run-params"); + if (!container) return; + container.textContent = ""; + if (!params.length) { + appendLine(container, "p", "mq-colophon", "该目标没有参数。"); return; } + params.forEach(function (param) { + var label = document.createElement("label"); + label.className = "mq-run-param"; + var title = document.createElement("span"); + var type = param.type ? ": " + param.type : ""; + var required = param.required ? "(必填)" : "(可选)"; + title.textContent = param.name + type + " " + required; + var input = document.createElement("input"); + input.type = "text"; + input.dataset.paramName = param.name; + input.dataset.required = param.required ? "true" : "false"; + input.spellcheck = false; + input.placeholder = param.default ? "默认常量:" + param.default : "常量表达式,例如 5 或 \"text\""; + if (param.required) input.setAttribute("aria-required", "true"); + input.addEventListener("input", updateRunPreview); + label.appendChild(title); + label.appendChild(input); + container.appendChild(label); + }); + } + + function openRunForm(target) { + var dialog = $("#mq-dialog-run"); + if (!dialog) { + toast("当前页面没有可用的运行表单;请确认已安装冻结核心"); + return; + } + pendingRun = { + kind: target.kind, + functionId: target.functionId || "", + label: target.label || "入口 main", + clientRequestId: randomId(), + params: target.params || [] + }; + var label = $("#mq-run-target-label"); + if (label) label.textContent = target.kind === "entry" ? "入口 main" : "函数 " + (target.label || ""); + renderRunParams(pendingRun.params); + var mode = document.querySelector('input[name="mq-mode"][value="pure"]'); + if (mode) mode.checked = true; + var grants = $("#mq-run-grants"); + if (grants) grants.hidden = true; + updateRunPreview(); + openDialog("mq-dialog-run"); + } + + function openRunForMain() { + if (reader.dataset.coreAvailable !== "true") { + showUnsupported( + "运行文档", + "当前页面没有可用的冻结核心(MARQDO_BIN),无法通过 CLI 执行;打开、刷新与导出仍然零副作用。" + ); + return; + } + if (reader.dataset.hasMain !== "true") { + toast("本文档没有可执行的 main;请从函数面板选择一个 H2 Exec 函数"); + showFunctions(); + return; + } + openRunForm({ kind: "entry", label: "入口 main" }); + } + + function submitRun() { + if (!pendingRun) return; + var params = rawParams(); + for (var i = 0; i < params.length; i += 1) { + if (params[i].required && params[i].expression.trim() === "") { + toast("缺少必填参数:" + params[i].name); + return; + } + } + var mode = selectedMode(); + var grants = mode === "project" + ? { read: grantList("mq-grant-read"), write: grantList("mq-grant-write") } + : { read: [], write: [] }; + if (mode === "project" && grants.read.length === 0 && grants.write.length === 0) { + toast("project 模式必须至少声明一个相对项目根的 fs read/write glob"); + return; + } + if (mode === "project" && + !window.confirm("project 模式将按你填写的 glob 授予文件读写权限。它仍不是操作系统沙箱,是否继续?")) { + return; + } + var payload = { + document: reader.dataset.document, + target: pendingRun.kind === "entry" + ? { kind: "entry" } + : { kind: "function", function_id: pendingRun.functionId }, + parameters: params.map(function (param) { + return { name: param.name, expression: param.expression }; + }), + analysis_digest: reader.dataset.analysisDigest, + mode: mode, + grants: grants, + client_request_id: pendingRun.clientRequestId + }; + closeAllDialogs(); + clearRunOutput(); + showRunPanel(); setRunBusy(true); - fetch("/api/run", { + setRunStatus("正在提交运行请求…"); + fetch("/api/runs", { method: "POST", credentials: "same-origin", cache: "no-store", headers: { "Content-Type": "application/json", "Accept": "application/json", - "X-MQ-CSRF": token + "X-View-CSRF": csrfToken() }, - body: JSON.stringify({ path: path, mode: "pure", confirm: true }) + body: JSON.stringify(payload) }) .then(function (response) { - return response.json().then(function (data) { - return { ok: response.ok, data: data }; - }); + return response.json().then(function (data) { return { ok: response.ok, status: response.status, data: data }; }); }) .then(function (result) { - if (!result.ok || !result.data || !result.data.ok) { + if (!result.ok || !result.data || !result.data.run_id) { setRunBusy(false); - var reason = result.data && result.data.message - ? result.data.message - : "运行被拒绝或失败"; - toast("运行未完成:" + reason); + var reason = result.data && result.data.message ? result.data.message : "运行请求被拒绝"; + setRunStatus("运行未启动(" + result.status + "):" + reason); + toast("运行未启动:" + reason); return; } - try { - window.sessionStorage.setItem( - "marqdo.view.scroll", - String(window.scrollY || 0) - ); - } catch (error) { - /* storage is optional */ - } - window.location.assign(result.data.redirect); + subscribeRun(result.data, pendingRun ? pendingRun.label : "运行"); }) .catch(function (error) { setRunBusy(false); + setRunStatus("运行请求失败:" + error.message); toast("运行请求失败:" + error.message); }); } + function subscribeRun(job, targetLabel) { + closeActiveObserver(); + activeRun = { + runId: job.run_id, + eventsUrl: job.events_url, + cancelUrl: job.cancel_url, + source: null, + lastSeq: -1, + targetLabel: targetLabel || "运行", + terminal: false + }; + clearRunOutput(); + showRunPanel(); + setRunStatus("状态:已接受 · " + activeRun.targetLabel); + if (!window.EventSource) { + setRunBusy(false); + setRunStatus("浏览器不支持 EventSource,无法接收运行状态;请使用现代浏览器。"); + return; + } + var source = new EventSource(job.events_url, { withCredentials: true }); + activeRun.source = source; + function apply(event) { + var data; + try { + data = JSON.parse(event.data); + } catch (error) { + return; + } + if (!data || + data.schema !== "marqdo.view-run-events" || + data.schema_version !== 1 || + data.run_id !== job.run_id || + !Number.isSafeInteger(data.seq) || + data.seq <= activeRun.lastSeq) { + return; + } + activeRun.lastSeq = data.seq; + updateRunView(data); + } + ["run.state", "run.complete", "run.error", "run.snapshot"].forEach(function (kind) { + source.addEventListener(kind, apply); + }); + source.onerror = function () { + if (activeRun && !activeRun.terminal) { + setRunStatus("SSE 连接中断,正在自动恢复…(任务仍在服务端运行;不会重新执行)"); + } + }; + } + + function updateRunView(data) { + var panel = runPanel(); + if (panel) { + panel.hidden = false; + panel.dataset.runState = data.state; + } + reader.dataset.runState = data.state; + setRunStatus("状态:" + stateLabel(data.state) + (data.at ? " · " + data.at : "")); + if (!isTerminalState(data.state)) { + setRunBusy(true); + return; + } + if (activeRun) activeRun.terminal = true; + closeActiveObserver(); + setRunBusy(false); + if (data.result) renderRunResult(data.result, data.state, data.error); + else if (data.error) renderRunResult(null, data.state, data.error); + if (data.trace) renderTrace(data.trace); + else if (data.result && data.result.trace_status) renderTraceStatus(data.result.trace_status); + if (data.state === "succeeded") toast("运行完成"); + else toast("运行" + stateLabel(data.state)); + } + + function renderRunResult(result, state, error) { + var summary = $("#mq-run-summary"); + if (!summary) return; + summary.textContent = ""; + if (result) { + if (result.target) { + var label = result.target.kind === "entry" ? "入口 main" : "函数 " + (result.target.label || result.target.cli_name || ""); + appendLine(summary, "p", "mq-run-result", label + " · 模式 " + (result.mode || "pure") + + (typeof result.duration_ms === "number" ? " · " + result.duration_ms + " ms" : "") + + (result.exit_code === null || typeof result.exit_code === "undefined" ? "" : " · 退出码 " + result.exit_code)); + } + if (result.value_text) { + appendLine(summary, "p", "mq-run-result", "返回值:" + result.value_text); + } + if (result.stale) { + appendLine(summary, "p", "mq-run-warning", "源码在运行后发生变化:结果可见但标记为过期,不在当前正文上绘制执行标注。"); + } + if (result.stdout) { + var stdout = $("#mq-run-stdout"); + if (stdout) { + stdout.textContent = result.stdout; + stdout.hidden = false; + } + } + if (result.stderr) { + var stderr = $("#mq-run-stderr"); + if (stderr) { + stderr.textContent = result.stderr; + stderr.hidden = false; + } + } + if (Array.isArray(result.diagnostics) && result.diagnostics.length) { + appendLine(summary, "p", "mq-run-warning", "诊断:" + result.diagnostics.length + " 条(详见运行详情)"); + var list = document.createElement("ol"); + list.className = "mq-run-events"; + result.diagnostics.slice(0, 20).forEach(function (diagnostic) { + var code = diagnostic && diagnostic.code ? diagnostic.code : "diagnostic"; + var message = diagnostic && diagnostic.message ? diagnostic.message : ""; + appendLine(list, "li", "", code + ":" + message); + }); + summary.appendChild(list); + } + } + if (error && (error.code || error.message)) { + appendLine(summary, "p", "mq-run-error", (error.code || "error") + ":" + (error.message || "运行失败")); + } + if (state === "cancelled") { + appendLine(summary, "p", "mq-run-warning", "运行已按请求取消;进程组已终止。"); + } + } + + function renderTraceStatus(status) { + if (!status || status === "verified") return; + var summary = $("#mq-run-summary"); + if (!summary) return; + var message = status === "invalid" + ? "Trace 与本次 Analysis 不匹配或格式无效:不绘制执行标注,也不声称观察到完整过程。" + : "本次运行没有可用的 Trace v2(unavailable):只展示 CLI 返回值与输出。"; + appendLine(summary, "p", "mq-run-warning", message); + } + + function renderTrace(trace) { + var summary = $("#mq-run-summary"); + var wrap = $("#mq-run-trace-wrap"); + var list = $("#mq-run-events"); + if (!wrap || !list) return; + list.textContent = ""; + if (!trace || trace.status !== "verified") { + wrap.hidden = true; + renderTraceStatus(trace && trace.status ? trace.status : "unavailable"); + return; + } + wrap.hidden = false; + if (summary) { + if (trace.stale) { + appendLine(summary, "p", "mq-run-warning", "Trace 属于运行时的源码:当前源码已变化,本次不绘制执行标注。"); + } + if (trace.truncated) { + var label = trace.truncated.label || (trace.truncated.reason + "(上限 " + trace.truncated.limit + ")"); + appendLine(summary, "p", "mq-run-warning", "Trace 被截断:" + label + ";这不代表程序终止。"); + } + } + var entryEvents = Array.isArray(trace.events) ? trace.events : []; + entryEvents.slice(0, 200).forEach(function (event) { + var location = event.span ? "span " + event.span.start + "–" + event.span.end : (event.module_id || ""); + var detail = event.detail ? " · " + event.detail : ""; + var operation = event.operation ? " · " + event.operation : ""; + appendLine(list, "li", "", event.kind + " · " + location + detail + operation); + }); + if (entryEvents.length > 200) { + appendLine(list, "li", "mq-colophon", "仅显示前 200 条(共 " + entryEvents.length + " 条)。"); + } + if (!trace.stale) { + var bySource = {}; + $$("[data-source-id]").forEach(function (element) { + bySource[element.dataset.sourceId] = element; + }); + entryEvents.forEach(function (event) { + if (!event.source_id || !bySource[event.source_id]) return; + var chip = document.createElement("span"); + chip.className = "mq-run-chip"; + chip.dataset.viewChip = "1"; + chip.dataset.runSeq = String(event.seq); + chip.textContent = event.detail || event.kind; + bySource[event.source_id].appendChild(chip); + }); + } + } + + function cancelRun() { + if (!activeRun || activeRun.terminal) return; + setRunStatus("正在请求取消…"); + fetch(activeRun.cancelUrl, { + method: "POST", + credentials: "same-origin", + cache: "no-store", + headers: { "Accept": "application/json", "X-View-CSRF": csrfToken() } + }) + .then(function (response) { + return response.json().then(function (data) { return { ok: response.ok, status: response.status, data: data }; }); + }) + .then(function (result) { + if (!result.ok) { + var reason = result.data && result.data.message ? result.data.message : "取消失败"; + setRunStatus("取消请求被拒绝(" + result.status + "):" + reason); + return; + } + setRunStatus("已请求取消;等待唯一终态…"); + }) + .catch(function (error) { + setRunStatus("取消请求失败:" + error.message); + }); + } + function clearRun() { closeAllDialogs(); - try { - var url = new URL(window.location.href); - if (url.searchParams.has("run")) { - url.searchParams.delete("run"); - window.location.assign(url.toString()); - return; - } - } catch (error) { - /* fall through */ + closeActiveObserver(); + var panel = runPanel(); + if (panel) { + panel.hidden = true; + panel.dataset.runState = "idle"; } - var panel = $("#mq-run-panel"); - if (panel) panel.hidden = true; - toast("已清理本地展示状态(源文件与缓存未修改)"); + reader.dataset.runState = "idle"; + clearRunOutput(); + setRunStatus("尚未运行。点击 Dock 的“运行”执行 main,或在函数面板选择函数。"); + toast("已清理本地结果展示(未删除项目文件、lock 或服务端运行记录)"); } document.addEventListener("click", function (event) { var trigger = event.target.closest ? event.target.closest("[data-action]") : null; if (!trigger) return; event.preventDefault(); - handleAction(trigger.dataset.action); + handleAction(trigger.dataset.action, trigger); }); document.addEventListener("click", function (event) { @@ -440,6 +877,16 @@ if (event.target && event.target.id === "mq-search-input") { renderSearch(event.target.value); } + if (event.target && (event.target.id === "mq-grant-read" || event.target.id === "mq-grant-write" || event.target.dataset.paramName)) { + updateRunPreview(); + } + }); + document.addEventListener("change", function (event) { + if (event.target && event.target.name === "mq-mode") { + var grants = $("#mq-run-grants"); + if (grants) grants.hidden = event.target.value !== "project"; + updateRunPreview(); + } }); document.addEventListener("keydown", function (event) { @@ -492,22 +939,6 @@ setMode("document"); } - // Restore reading position after a run reload, without faking any result. - try { - var scroll = window.sessionStorage.getItem("marqdo.view.scroll"); - if (scroll && new URLSearchParams(window.location.search).has("run")) { - window.sessionStorage.removeItem("marqdo.view.scroll"); - var target = parseInt(scroll, 10); - if (!isNaN(target)) { - window.requestAnimationFrame(function () { - window.scrollTo(0, target); - }); - } - } - } catch (error) { - /* storage is optional */ - } - // Keep dock buttons visible above the last line on small screens. function syncDockInset() { var dock = $(".mq-dock"); diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 0936f25..6d8c3cb 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -5,7 +5,7 @@ > `PENDING`(未开始)、`N/A`(0002 明确非目标/删除项)。 > 证据列写测试/脚本文档;不得以视觉相似代替测试。 -最后更新:2026-11-22(PR-00) +最后更新:2026-11-22(PR-04) ## 1. §0 核心不可妥协条件 @@ -28,21 +28,21 @@ | `@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` | -| 单函数参数填写 + 调用 | **PENDING** | PR-03 请求合同 + PR-04 前端表单 | -| 文档入口 `main` 执行 | PARTIAL | 同步 pure 已存在;需改为 SSE 异步任务(PR-04) | -| 运行结果(返回/stdout/stderr/错误) | PARTIAL | 0001 已有;需 0002 JSON→UI 映射与安全文本展示复核(PR-04/05) | -| Trace v2 调用/判断/循环/副作用 | PARTIAL | `src/trace.rs` 已有;需 SSE 后动态标注与 stale 规则(PR-04/05) | -| 执行确认/取消/超时/单任务 | **PENDING** | PR-03/04 | -| **SSE 状态与终态(禁止轮询)** | **PENDING(阻塞)** | PR-04 | +| 单函数参数填写 + 调用 | 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 导出 | PARTIAL | 已实现;PR-06 复核零执行/离线 | | 暖纸/品牌/樱花/侧注/Dock | PARTIAL | 已有;PR-05 视觉矩阵 | | 搜索 + 目录 | PASS | 浏览器证据 | | 有选择的 Observed 侧注/退化 | PARTIAL | 内联 chip 已有;SSE 后按本次运行更新(PR-04/05) | | 深色主题/字号/显示设置 | PARTIAL | 已有字号/标注开关/print;深色待 PR-05 | -| project fs read/write grants | **PENDING** | PR-03/04(MVP CONTROLLED) | +| 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/路由/状态 | +| 变量/内存/Notebook/调试/Session/AI/Kernel | N/A(REMOVED) | 无路由/DOM/状态;仅一个明确 UNSUPPORTED 说明 | ## 3. §5 架构与目录 @@ -58,18 +58,18 @@ | 条款 | 状态 | 计划 | |---|---|---| -| 7 条最小路由 | **PENDING** | PR-04 | -| POST /api/runs 两阶段确认请求体(document/target/parameters/analysis_digest/mode/grants/client_request_id) | PARTIAL | `execution/request.rs` 校验/解析/计划已实现;HTTP 路由 PR-04 | -| 校验顺序(会话→CSRF/Origin/Host→大小/schema→containment→check→digest→函数/参数→模式/grants→并发→202) | PARTIAL | Controller 已实现 schema→dedupe→busy→check→digest→target→202;HTTP 前置校验 PR-04 | -| 同 `client_request_id` 幂等/不同 payload 409 | PASS(Controller) | `tests/integration/execution.rs`;HTTP 映射 PR-04 | -| SSE 帧合同(事件类型/seq/id/schema/心跳) | **PENDING** | PR-04 | -| Last-Event-ID 重放、快照、128 缓冲、TTL、≤2 连接/任务 | **PENDING** | PR-04 | -| 单活动任务、409 run.busy、后台执行不阻塞 SSE | PARTIAL | Controller 单任务/后台线程已实现并测试;HTTP/SSE PR-04 | +| 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 | **PENDING** | PR-04 | +| 会话 Cookie(HttpOnly/SameSite=Strict)+ X-View-CSRF + Origin/Host | PASS | `server/security.rs`、`tests/security/`、浏览器测试 | | loopback only、请求体≤64KiB、CSP、路径 containment | PARTIAL | 大部分已有;会话 Cookie 待 PR-04 | -| SSE 按会话隔离、跨站读取拒绝 | **PENDING** | PR-04 | +| SSE 按会话隔离、跨站读取拒绝 | PASS | 跨会话 404/401、Sec-Fetch-Site 拒绝 | ## 5. §8 里程碑 @@ -79,7 +79,7 @@ | 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/路由/会话/前端闭环 | PENDING | — | +| PR-04 SSE/路由/会话/前端闭环 | **完成** | `docs/evidence/PR-04/`(含真实 Chromium + 真实冻结 CLI) | | PR-05 Trace 绑定/标注/浏览器回归 | PENDING | — | | PR-06 导出/发布/文档闭环 | PENDING | — | @@ -91,15 +91,15 @@ | 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 | PARTIAL | 同步路径有;SSE 终态待 PR-04 | -| E06 H2 Exec n=5 call | PARTIAL | `build_call_args` + Controller 测试;真实 CLI/UI PR-04/06 | -| E07 文本/列表常量参数 | PARTIAL | `--arg name=expression` argv 已实现;真实 CLI/UI PR-04/06 | +| 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 不自动运行别的函数 | PARTIAL | 现有 `can_offer_run` 逻辑;PR-04 复核 | | E09 Trace 事件映射不伪造变量 | PARTIAL | `src/trace.rs`;SSE 后复核 | -| E10 SSE text/event-stream 无 polling | **PENDING** | PR-04 | -| E11 Last-Event-ID 重连 | **PENDING** | PR-04 | -| E12 长任务心跳/GET 不重启 | **PENDING** | PR-04 | -| E13 取消终止进程树 | PARTIAL | Controller/process 已测(`second_run_is_busy...`、`process.rs` 单测);HTTP 接线 PR-04 | +| E10 SSE text/event-stream 无 polling | PASS | 集成 + 浏览器请求记录 | +| E11 Last-Event-ID 重连 | PASS | 重放/伪造游标 snapshot 测试 | +| E12 长任务心跳/GET 不重启 | PASS | 心跳 + 2 连接 + GET 观察不启动任务 | +| E13 取消终止进程树 | PASS | Controller/process 单测 + HTTP 取消唯一终态 + 浏览器取消路径 | | E14 静态导出零联网/相对链接 | PARTIAL | 已实现;PR-06 复核 | | E15 刷新/重开不自动执行 | PASS | `tests/integration/http_live.rs` | | E16 运行后改源码 → stale 无高亮 | PARTIAL | 现有 stale;PR-05 复核 | diff --git a/docs/STATUS.md b/docs/STATUS.md index fe8313a..b880b6b 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -24,9 +24,9 @@ | PR-01 Tool v1 打包/安装/调度、0.2.0、scripts/、CI | **完成** | `scripts/package.sh`、`scripts/install-smoke.sh`、`scripts/verify-frozen-cli.sh`、`.github/workflows/ci.yml`;冻结 CLI `tool install`/`view --help`/篡改拒绝实测 | | PR-02 Reader/Analysis 只读面与目标目录结构 | **完成** | `src/protocol/*`、`src/reader/*`、`src/config.rs`、`tests/{contract,integration}/`、`/api/documents`;证据 `docs/evidence/PR-02/` | | PR-03 执行层:request/process/controller、pure + project grants | **完成** | `src/execution/{request,process,controller,events}.rs`、`--run-timeout`、ADR-0008、`tests/integration/execution.rs`;证据 `docs/evidence/PR-03/` | -| PR-04 SSE 任务生命周期、取消、7 路由、会话 Cookie/CSRF | **未实现(MVP 阻塞项)** | — | -| PR-05 Trace 绑定/原文标注/浏览器回归 | 待开始(现有 Trace 校验可迁移) | `src/trace.rs` | -| PR-06 静态导出/发布包/文档闭环 | 待开始(现有导出可迁移) | `src/export.rs` | +| PR-04 SSE 任务生命周期、取消、7 路由、会话 Cookie/CSRF | **完成** | `src/server/{mod,routes,security,sse}.rs`、`assets/reader.js` SSE/表单、`tests/integration/http_live.rs`、`tests/security/`、真实 Chromium + 真实冻结 CLI SSE 证据 `docs/evidence/PR-04/` | +| PR-05 Trace 绑定/原文标注/浏览器回归 | 待开始(SSE 后动态标注/宽度矩阵已基本具备) | `src/execution/controller.rs` Trace 摘要、浏览器证据 | +| PR-06 静态导出/发布包/文档闭环 | 待开始 | `src/export.rs`、`scripts/acceptance.sh`、`docs/ACCEPTANCE.md` | ## 继承自 0001 的可用资产(不等于 0002 验收通过) @@ -37,44 +37,30 @@ | 原始 Markdown/GFM 阅读、源码态、搜索/设置/打印 | 已实现(单一 `assets/reader.css`/`assets/reader.js`) | | Analysis v2 严格校验、函数/Unit/签名/诊断/导入/引用/资源投影 | 已实现(无效 span 降级) | | 单一 `ReaderRenderer`,Live/Export 共用 | 已实现(`src/reader/render.rs`,门禁测试) | -| 显式确认后同步运行 `pure` + Trace v2 校验与展示 | 旧同步路径仍在(过渡);新的异步 Controller/SSE 就绪于 PR-03/04 | +| 显式确认 + SSE 异步执行 + Trace v2 | 已实现(7 路由、单任务、取消、断线重放) | | 静态离线导出(无执行、manifest/哈希、原子发布) | 已实现,待按 0002 重新验收 | | Tool v1 打包/安装/分发、冻结 CLI SHA 前后一致 | 已实现,待迁移至 `scripts/` 与 0.2.0 | | HTTP 安全(Host/Origin/CSRF/路径 containment/CSP) | 部分实现;缺**会话 Cookie**模型与 7 路由合同 | | 真实 Chromium 视觉/交互/无 JS/打印 | 已有证据(0001 时期),待按 0002 宽度矩阵重跑 | -## 与 RFC-VIEW-0002 的已知差距(全部必须关闭) +## 与 RFC-VIEW-0002 的已知差距(剩余项) -1. **SSE 执行闭环缺失**:当前是 POST 同步运行后整页重载;0002 要求 - `POST /api/runs` → 202 → `GET /api/runs/{id}/events` SSE(无轮询)→ - accepted/running/终态;断线 `Last-Event-ID` 重放、128 事件环形缓冲、终态 TTL。 -2. **路由未收敛**:现为 `/api/run`、`/api/clear-run`、`/api/document`、 - `/api/health`;0002 只允许 - `GET /`、`GET /file`、`GET /assets/...`、`GET /api/documents`、 - `POST /api/runs`、`GET /api/runs/{id}/events`、`POST /api/runs/{id}/cancel`。 -3. **无单函数调用表单**:函数目前只有跳转列表;缺基于 Analysis 签名的参数填写、 - 命令预览、`--arg` 常量表达式提交。 -4. **无 project grants**:0002 要求受控 fs read/write glob(明确二次确认), - 其它 net/process/env/plugin 一律拒绝并引导 CLI。 -5. **无运行会话 Cookie**:CSRF 目前是进程级 token;0002 要求 - `HttpOnly; SameSite=Strict` 随机会话 Cookie + 每会话 CSRF,且 SSE 按会话隔离 - (PR-04)。 -6. **HTTP/SSE 传输未接**:Controller 已实现单任务状态机、取消、去重、 - `client_request_id` 幂等/409 与 `409 run.busy`(`src/execution/controller.rs`), - 但 `POST /api/runs`、`GET .../events`、`POST .../cancel` 与前端尚未切换(PR-04)。 -7. **执行预算**:Controller 已显式发送 `--timeout`(默认 30s/最大 120s)、 - `--fuel 1000000`、`--max-output 1048576`、`--trace-max-events 10000`、 - `--trace-max-bytes 4194304`,并做 4 MiB JSON/Trace 有界读取与 - `view.output_limit`;HTTP 层仍需映射为终态事件(PR-04)。 -8. **目录/测试/示例仍有缺口**:`src/protocol`/`src/reader`/`src/config.rs`/ - `tests/{contract,integration}`/`scripts/`/`.github/workflows/ci.yml` 已就位; - 仍缺 `src/execution/*`、`src/server/{mod,routes,security,sse}.rs`、 - `tests/security/` 套件、`examples/{welcome,branch-loop,function-params, - knowledge-only,unsafe-side-effect}.mq.md`、`docs/design` 0002 宽度截图矩阵。 -9. **文档口径**:README/COMPATIBILITY/ACCEPTANCE 仍含 0001 时期表述,需在 - PR-06 前全部更新为 0002 口径。 -10. **视觉回归矩阵**:0002 要求 2048×1133 源参考与 1664×920/1440×900/1024×768/ - 768×1024/390×844 宽度;现有截图集合不完整。 +PR-00~PR-04 已关闭 SSE、7 路由、单函数调用表单、受控 project grants、 +会话 Cookie/CSRF、取消/去重/单任务、执行预算与有界输出、目标目录/测试树/ +`scripts/`/CI/浏览器宽度矩阵。**剩余**: + +1. **PR-05**:Trace 事件到原文的锚点/侧注在 SSE 后已由前端按 `source_id` + 渲染 keyed chip;仍需固化 stale/截断/无 Trace 的浏览器回归与最终视觉矩阵 + 证据(含深色/打印/断网/无 JS)。 +2. **PR-06**:`examples/{welcome,branch-loop,function-params,knowledge-only, + unsafe-side-effect}.mq.md` 需按 RFC §13.3 创建并用冻结 CLI 实际 check/call + 记录;静态导出需按 0002 重新跑离线/零执行验收;更新 ACCEPTANCE/README/ + COMPATIBILITY/CHANGELOG 为 0002 口径并生成最终 evidence manifest。 +3. 0002 §9.2 N 系列须逐项在最终验收报告中登记(当前 HTTP/SSE/安全套件已覆盖 + 大部分:N01/N02/N03/N04/N05/N06/N07/N09/N10/N11/N12/N13/N14/N15/N16/N17/ + N19/N21/N22 有对应测试;N18/N20 在 PR-06 冻结 CLI/导出套件中登记)。 +4. 视觉/可达性的人工像素级比对与完整 screen-reader 走查仍标 `UNVERIFIED`, + 自动化几何/颜色/无外部资源/响应式证据已存在(`docs/evidence/PR-04/`)。 ## 明确 UNSUPPORTED / 非目标(不得伪造) diff --git a/docs/decisions/0009-sse-transport-and-session.md b/docs/decisions/0009-sse-transport-and-session.md new file mode 100644 index 0000000..630cb81 --- /dev/null +++ b/docs/decisions/0009-sse-transport-and-session.md @@ -0,0 +1,86 @@ +# 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)。 +- 页面通过 `` 获得**该会话**的 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/`)。 diff --git a/docs/evidence/PR-04/README.md b/docs/evidence/PR-04/README.md new file mode 100644 index 0000000..158542c --- /dev/null +++ b/docs/evidence/PR-04/README.md @@ -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 不能注入 +` - + 跳到正文 "##, presentation_version = model.version, @@ -170,6 +185,11 @@ impl ReaderRenderer { annotations = if ctx.annotations { "on" } else { "off" }, run_state = model.run_state().data_value(), run_available = if ctx.run_available { "true" } else { "false" }, + has_main = if has_main { "true" } else { "false" }, + core_available = if ctx.core_available { "true" } else { "false" }, + document = escape_attr(&relative_path), + analysis_digest = escape_attr(&analysis_digest), + run_timeout = ctx.run_timeout_secs, live = if ctx.live { "true" } else { "false" }, ); @@ -182,9 +202,13 @@ impl ReaderRenderer { } self.render_document_meta(&mut html, model); self.render_diagnostics(&mut html, model); - self.render_functions(&mut html, model); + self.render_functions(&mut html, model, ctx); self.render_document(&mut html, model, ctx); - self.render_run_panel(&mut html, model, ctx); + if ctx.live { + self.render_live_run_shell(&mut html, ctx); + } else { + self.render_run_panel(&mut html, model, ctx); + } self.render_source_pane(&mut html, model, ctx); self.render_footer(&mut html, model); let _ = write!(html, "\n"); @@ -361,7 +385,7 @@ impl ReaderRenderer { html.push_str("\n\n"); } - fn render_functions(&self, html: &mut String, model: &PresentationModel) { + fn render_functions(&self, html: &mut String, model: &PresentationModel, ctx: &RenderContext) { if model.outline.is_empty() { return; } @@ -375,12 +399,33 @@ impl ReaderRenderer { count = functions.len() ); for entry in functions { + let function = model.semantic.as_ref().and_then(|semantic| { + semantic.functions.iter().find(|function| { + anchor_for_span(function.heading_span.start, function.heading_span.end) + == entry.anchor + }) + }); + let (function_id, params, callable) = match function { + Some(function) => (function.id.clone(), function_params_json(function), true), + None => (String::new(), "[]".to_string(), false), + }; + let call_button = if callable && ctx.core_available { + format!( + "", + id = escape_attr(&function_id), + label = escape_attr(&entry.label), + params = escape_attr(¶ms) + ) + } else { + String::new() + }; let _ = write!( html, - "
  • {label}{detail}
  • \n", + "
  • {label}{detail}{call_button}
  • \n", anchor = escape_attr(&entry.anchor), label = escape_text(&entry.label), - detail = escape_text(&entry.detail) + detail = escape_text(&entry.detail), + call_button = call_button ); } html.push_str("\n\n"); @@ -457,8 +502,32 @@ impl ReaderRenderer { ); } + /// Empty, accessible run panel that the single reader script fills from + /// SSE events. It is never populated by the server for a live page: no run + /// exists until the user explicitly submits one (RFC-VIEW-0002 §7.1). + fn render_live_run_shell(&self, html: &mut String, _ctx: &RenderContext) { + html.push_str( + r##" +"##, + ); + } + fn render_dock(&self, html: &mut String, ctx: &RenderContext) { - let run_disabled = if ctx.run_available { + let run_disabled = if ctx.core_available { "" } else { " data-disabled=\"true\"" @@ -544,8 +613,8 @@ impl ReaderRenderer { "##, csrf = csrf, files = self.render_file_list(model, ctx), - run_dialog = if ctx.run_available { - render_run_confirm_dialog(model) + run_dialog = if ctx.core_available { + render_run_form_dialog(model, ctx) } else { String::new() }, @@ -1346,32 +1415,48 @@ fn render_run_chips(html: &mut String, model: &PresentationModel, statement_span ); } -fn render_run_confirm_dialog(model: &PresentationModel) -> String { - let function = model - .semantic - .as_ref() - .and_then(|semantic| { - semantic - .functions - .iter() - .find(|function| function.local_name == "main") - }) - .map(|function| function.local_name.clone()) - .unwrap_or_else(|| "main".to_string()); +fn function_params_json(function: &crate::protocol::analysis_v2::SemanticFunction) -> String { + serde_json::json!(function + .signature + .params + .iter() + .map(|param| serde_json::json!({ + "name": param.name, + "type": param.ty, + "required": param.required, + "default": param.default, + })) + .collect::>()) + .to_string() +} + +fn render_run_form_dialog(model: &PresentationModel, ctx: &RenderContext) -> String { + let path = &model.document.identity.relative_path; format!( - r##" -

    确认运行本文档

    -

    即将通过冻结核心执行入口函数 {function},沙箱模式 pure(无文件、网络、环境变量、进程权限)。

    -

    等价命令:marqdo run {path} --mode pure --json --trace-file <临时文件>

    -

    运行会在你的机器上真实执行文档中的 @exec 代码。Trace v2 不记录参数实际值、文件内容或敏感数据;View 不继承项目声明的 capabilities。

    -

    打开、刷新、搜索、导出都不会触发运行;只有本确认按钮会。

    + r##" +

    显式运行

    +

    入口 main · pure

    +
    +
    + 执行模式 + + +
    + +

    等价命令(点击“确认执行”后才会运行;<参数值> 由下方输入原样作为常量表达式提交):

    +
    
    +  

    墙钟上限 {timeout} 秒;结果通过 SSE 推送,不轮询。打开/刷新/导出不会执行。

    - +
    "##, - function = escape_text(&function), - path = escape_text(&model.document.identity.relative_path) + path = escape_attr(path), + timeout = ctx.run_timeout_secs ) } diff --git a/src/server.rs b/src/server.rs deleted file mode 100644 index 3351bd7..0000000 --- a/src/server.rs +++ /dev/null @@ -1,1105 +0,0 @@ -//! Localhost Live reader. -//! -//! Minimal, loopback-only surface (RFC-VIEW-0001 §11.1). Only read APIs are -//! exposed until the explicit-run flow lands; every response carries a strict -//! CSP and the Host header is validated to blunt DNS-rebinding. - -use crate::cli::RuntimeOpts; -use crate::error::{ViewError, ViewResult}; -use crate::protocol::trace_v2::VerifiedRun; -use crate::reader::assemble::DocumentService; -use crate::reader::assets::AssetBundle; -use crate::reader::model::PresentationModel; -use crate::reader::render::{ReaderRenderer, RenderContext}; -use crate::reader::source::sha256_hex; -use crate::reader::source::SafeRelativePath; -use std::collections::HashMap; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::{Arc, Mutex}; -use tiny_http::{Header, Method, Request, Response, Server, StatusCode}; - -const MAX_URL_BYTES: usize = 2048; -const MAX_QUERY_BYTES: usize = 4096; -const MAX_BODY_BYTES: usize = 16 * 1024; - -pub fn serve(ctx: DocumentService, opts: &RuntimeOpts) -> ViewResult { - let address = format!("{}:{}", opts.host, opts.port); - let server = Server::http(&address).map_err(|err| ViewError::Io { - detail: format!("listen on {address}: {err}"), - })?; - let bound = server.server_addr().to_ip().ok_or_else(|| ViewError::Io { - detail: "server address is not an IP socket".to_string(), - })?; - let port = bound.port(); - let display_host = match opts.host.as_str() { - "localhost" => "localhost".to_string(), - "::1" | "[::1]" => "[::1]".to_string(), - _ => "127.0.0.1".to_string(), - }; - let url = format!("http://{display_host}:{port}/"); - - eprintln!("marqdo view: {url}"); - eprintln!("root: {}", ctx.project().root().display()); - eprintln!( - "{} .mq.md document(s). Ctrl+C to stop.", - ctx.project() - .list_documents() - .map(|docs| docs.len()) - .unwrap_or(0) - ); - if ctx.core_version().is_some() { - eprintln!( - "core: marqdo {} (Analysis v2, Trace v2)", - ctx.core_version().unwrap_or_default() - ); - } else if let Some(note) = ctx.core_note() { - eprintln!("core: unavailable ({note})"); - } - if !opts.no_open { - open_browser(&url); - } - - let state = Arc::new(ServerState { - ctx, - csrf_token: random_token(), - renderer: ReaderRenderer::new(), - cache: Mutex::new(HashMap::new()), - allowed_hosts: allowed_hosts(port), - running: AtomicBool::new(false), - active_requests: std::sync::atomic::AtomicUsize::new(0), - run_cache: Mutex::new(HashMap::new()), - run_seq: AtomicU64::new(1), - }); - - loop { - let request = match server.recv() { - Ok(request) => request, - Err(err) => { - eprintln!("view: accept failed: {err}"); - continue; - } - }; - let state = Arc::clone(&state); - std::thread::spawn(move || { - if let Err(err) = handle(&state, request) { - eprintln!("view request error: {err}"); - } - }); - } -} - -struct ServerState { - ctx: DocumentService, - csrf_token: String, - renderer: ReaderRenderer, - cache: Mutex>, - allowed_hosts: Vec, - /// One active run per View session. - running: AtomicBool, - /// Bounded concurrent request handling. - active_requests: std::sync::atomic::AtomicUsize, - run_cache: Mutex>, - run_seq: AtomicU64, -} - -#[derive(Clone)] -struct CachedRun { - relative: String, - verified: VerifiedRun, -} - -struct CacheEntry { - source_digest: String, - model: PresentationModel, -} - -impl ServerState { - /// Load one document, reusing a cached model only while the exact source - /// bytes are unchanged (no path-only cache identity, RFC §6.5). - /// Load a page and attach a cached run when the URL names one. The run is - /// re-bound against freshly checked Analysis inside `load_with_run`. - fn load_for_page( - &self, - relative: &SafeRelativePath, - run_id: Option<&str>, - ) -> ViewResult { - if let Some(run_id) = run_id { - let cached = self - .run_cache - .lock() - .ok() - .and_then(|cache| cache.get(run_id).cloned()); - if let Some(cached) = cached { - if cached.relative == relative.as_str() { - return self.ctx.load_with_run(relative, Some(&cached.verified)); - } - } - } - self.load(relative) - } - - fn load(&self, relative: &SafeRelativePath) -> ViewResult { - let digest = self.ctx.project().source_digest(relative)?; - if let Ok(cache) = self.cache.lock() { - if let Some(entry) = cache.get(relative.as_str()) { - if entry.source_digest == digest { - return Ok(entry.model.clone()); - } - } - } - let model = self.ctx.load(relative)?; - if let Ok(mut cache) = self.cache.lock() { - if cache.len() < 64 { - cache.insert( - relative.as_str().to_string(), - CacheEntry { - source_digest: digest, - model: model.clone(), - }, - ); - } - } - Ok(model) - } -} - -fn handle(state: &ServerState, request: Request) -> ViewResult<()> { - if state.active_requests.fetch_add(1, Ordering::SeqCst) >= 32 { - state.active_requests.fetch_sub(1, Ordering::SeqCst); - return respond_text( - request, - StatusCode(503), - "text/plain; charset=utf-8", - "too many concurrent requests\n".as_bytes().to_vec(), - CacheKind::NoStore, - ); - } - let _active = ActiveRequestGuard(&state.active_requests); - let method = request.method().clone(); - let is_head = method == Method::Head; - let is_get = method == Method::Get; - - let raw_url = request.url().to_string(); - if raw_url.len() > MAX_URL_BYTES { - return respond_text( - request, - StatusCode(414), - "text/plain; charset=utf-8", - "request target too long\n".as_bytes().to_vec(), - CacheKind::NoStore, - ); - } - let (path_part, query) = split_url(&raw_url); - if query.len() > MAX_QUERY_BYTES { - return respond_text( - request, - StatusCode(414), - "text/plain; charset=utf-8", - "query too long\n".as_bytes().to_vec(), - CacheKind::NoStore, - ); - } - - if !host_is_allowed(&request, &state.allowed_hosts) { - return respond_text( - request, - StatusCode(400), - "text/plain; charset=utf-8", - "invalid Host header\n".as_bytes().to_vec(), - CacheKind::NoStore, - ); - } - - if method == Method::Post { - return match path_part { - "/api/run" => handle_run_post(state, request), - "/api/clear-run" => handle_clear_run_post(state, request), - _ => respond_text( - request, - StatusCode(405), - "text/plain; charset=utf-8", - "method not allowed\n".as_bytes().to_vec(), - CacheKind::NoStore, - ), - }; - } - if !is_get && !is_head { - return respond_text( - request, - StatusCode(405), - "text/plain; charset=utf-8", - "method not allowed\n".as_bytes().to_vec(), - CacheKind::NoStore, - ); - } - - if let Some(hashed_name) = path_part.strip_prefix("/assets/") { - return serve_asset(request, hashed_name, is_head); - } - - let run_id = query_param(query, "run"); - match path_part { - "/" | "/index.html" => { - let entry = state.ctx.project().entry().relative.clone(); - match state.load_for_page(&entry, run_id.as_deref()) { - Ok(model) => serve_page(state, request, &model, is_head), - Err(err) => serve_error_page(request, &err, is_head), - } - } - "/file" => { - let Some(raw_path) = query_param(query, "path") else { - return respond_text( - request, - StatusCode(400), - "text/plain; charset=utf-8", - "missing path\n".as_bytes().to_vec(), - CacheKind::NoStore, - ); - }; - let Some(decoded) = percent_decode(&raw_path) else { - return respond_text( - request, - StatusCode(400), - "text/plain; charset=utf-8", - "malformed path\n".as_bytes().to_vec(), - CacheKind::NoStore, - ); - }; - let relative = match SafeRelativePath::parse(&decoded) { - Ok(relative) => relative, - Err(err) => { - return respond_text( - request, - StatusCode(403), - "text/plain; charset=utf-8", - format!("{}\n", err.code()).into_bytes(), - CacheKind::NoStore, - ) - } - }; - if state.ctx.project().read_source(&relative).is_err() { - return respond_text( - request, - StatusCode(404), - "text/plain; charset=utf-8", - "document not found\n".as_bytes().to_vec(), - CacheKind::NoStore, - ); - } - match state.load_for_page(&relative, run_id.as_deref()) { - Ok(model) => serve_page(state, request, &model, is_head), - Err(err) => serve_error_page(request, &err, is_head), - } - } - "/api/documents" => { - let relative = match query_param(query, "path") - .and_then(|raw| percent_decode(&raw)) - .map(|decoded| SafeRelativePath::parse(&decoded)) - { - Some(Ok(relative)) => relative, - Some(Err(err)) => { - return respond_json_error(request, StatusCode(400), &err); - } - None => state.ctx.project().entry().relative.clone(), - }; - match state.load_for_page(&relative, query_param(query, "run").as_deref()) { - Ok(model) => serve_documents_json(state, request, &relative, &model), - Err(err) => respond_json_error(request, StatusCode(500), &err), - } - } - "/api/health" => { - let documents = state - .ctx - .project() - .list_documents() - .map(|documents| documents.len()) - .unwrap_or(0); - let health = serde_json::json!({ - "schema": "marqdo.view-health", - "schema_version": 1, - "ok": true, - "view": { - "name": "marqdo-view", - "version": env!("CARGO_PKG_VERSION"), - }, - "core": { - "version": state.ctx.core_version(), - }, - "protocols": { - "tool": crate::protocol::tool_v1::TOOL_PROTOCOL, - "analysis": crate::protocol::tool_v1::ANALYSIS_PROTOCOL, - "trace": crate::protocol::tool_v1::TRACE_PROTOCOL, - }, - "documents": documents, - "run_api": true, - }); - respond_json(request, StatusCode(200), &health) - } - _ => respond_text( - request, - StatusCode(404), - "text/plain; charset=utf-8", - "not found\n".as_bytes().to_vec(), - CacheKind::NoStore, - ), - } -} - -fn handle_run_post(state: &ServerState, mut request: Request) -> ViewResult<()> { - if !origin_is_allowed(&request, state) { - return respond_json_error( - request, - StatusCode(403), - &ViewError::RunDenied { - detail: "跨站来源被拒绝(Origin 校验失败)".to_string(), - }, - ); - } - if !content_type_is_json(&request) { - return respond_text( - request, - StatusCode(415), - "text/plain; charset=utf-8", - "expected application/json\n".as_bytes().to_vec(), - CacheKind::NoStore, - ); - } - let Some(token) = header_value(&request, "X-MQ-CSRF") else { - return respond_json_error( - request, - StatusCode(403), - &ViewError::RunDenied { - detail: "缺少 CSRF 令牌,运行被拒绝".to_string(), - }, - ); - }; - if !constant_time_eq(token.as_bytes(), state.csrf_token.as_bytes()) { - return respond_json_error( - request, - StatusCode(403), - &ViewError::RunDenied { - detail: "CSRF 令牌无效,运行被拒绝".to_string(), - }, - ); - } - let body = match read_body(&mut request, MAX_BODY_BYTES) { - Ok(body) => body, - Err(err) => return respond_json_error(request, StatusCode(413), &err), - }; - #[derive(serde::Deserialize)] - struct RunRequest { - #[serde(default)] - path: Option, - #[serde(default)] - mode: Option, - #[serde(default)] - confirm: Option, - } - let parsed: RunRequest = match serde_json::from_slice(&body) { - Ok(parsed) => parsed, - Err(err) => { - return respond_json_error( - request, - StatusCode(400), - &ViewError::RunDenied { - detail: format!("运行请求不是合法 JSON: {err}"), - }, - ) - } - }; - if parsed.confirm != Some(true) { - return respond_json_error( - request, - StatusCode(400), - &ViewError::RunDenied { - detail: "缺少显式用户确认,拒绝运行".to_string(), - }, - ); - } - if let Some(mode) = parsed.mode.as_deref() { - if mode != "pure" { - return respond_json_error( - request, - StatusCode(403), - &ViewError::RunDenied { - detail: format!( - "当前版本只允许最低权限 pure 模式(收到 {mode:?});project/strict grants 需要单独的授权界面" - ), - }, - ); - } - } - let relative = match parsed.path.as_deref() { - Some(path) => match SafeRelativePath::parse(path) { - Ok(relative) => relative, - Err(err) => return respond_json_error(request, StatusCode(403), &err), - }, - None => state.ctx.project().entry().relative.clone(), - }; - if state.ctx.project().read_source(&relative).is_err() { - return respond_text( - request, - StatusCode(404), - "text/plain; charset=utf-8", - "document not found\n".as_bytes().to_vec(), - CacheKind::NoStore, - ); - } - if state.running.swap(true, Ordering::SeqCst) { - return respond_json_error( - request, - StatusCode(409), - &ViewError::RunDenied { - detail: "已有一次运行正在进行;首版每个 View 会话只允许一个活动运行".to_string(), - }, - ); - } - let guard = RunningGuard(&state.running); - let outcome = state.ctx.run_document(&relative); - drop(guard); - let executed = match outcome { - Ok(executed) => executed, - Err(err) => { - return respond_json_error(request, run_error_status(&err), &err); - } - }; - let seq = state.run_seq.fetch_add(1, Ordering::Relaxed); - let sanitized = executed - .verified - .projection - .run_id - .chars() - .map(|ch| { - if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' { - ch - } else { - '-' - } - }) - .take(40) - .collect::(); - let run_id = format!("{seq}-{sanitized}"); - let entry = state.ctx.project().entry().relative.clone(); - let redirect = if relative == entry { - format!("/?run={run_id}") - } else { - format!("/file?path={}&run={run_id}", encode_path(relative.as_str())) - }; - let cached = CachedRun { - relative: relative.as_str().to_string(), - verified: executed.verified, - }; - if let Ok(mut cache) = state.run_cache.lock() { - if cache.len() >= 8 { - let oldest = cache - .keys() - .min_by_key(|key| { - key.split('-') - .next() - .and_then(|seq| seq.parse::().ok()) - .unwrap_or(u64::MAX) - }) - .cloned(); - if let Some(oldest) = oldest { - cache.remove(&oldest); - } - } - cache.insert(run_id.clone(), cached.clone()); - } - let projection = &cached.verified.projection; - let response = serde_json::json!({ - "ok": true, - "run_id": run_id, - "redirect": redirect, - "state": projection.state.data_value(), - "label": projection.state.label(), - "run_status": projection.run_status, - "exit_code": projection.exit_code, - "events": projection.counts.total(), - "entry_events": projection.entry_event_count, - "truncated": projection.truncated.as_ref().map(|truncated| truncated.label()), - "note": "本响应只来自冻结核心 run --json 与 Trace v2;参数值/内存/证明状态不提供。", - }); - respond_json(request, StatusCode(200), &response) -} - -fn handle_clear_run_post(state: &ServerState, mut request: Request) -> ViewResult<()> { - if !origin_is_allowed(&request, state) { - return respond_json_error( - request, - StatusCode(403), - &ViewError::RunDenied { - detail: "跨站来源被拒绝(Origin 校验失败)".to_string(), - }, - ); - } - if !content_type_is_json(&request) { - return respond_text( - request, - StatusCode(415), - "text/plain; charset=utf-8", - "expected application/json\n".as_bytes().to_vec(), - CacheKind::NoStore, - ); - } - let Some(token) = header_value(&request, "X-MQ-CSRF") else { - return respond_json_error( - request, - StatusCode(403), - &ViewError::RunDenied { - detail: "缺少 CSRF 令牌,清理缓存被拒绝".to_string(), - }, - ); - }; - if !constant_time_eq(token.as_bytes(), state.csrf_token.as_bytes()) { - return respond_json_error( - request, - StatusCode(403), - &ViewError::RunDenied { - detail: "CSRF 令牌无效,清理缓存被拒绝".to_string(), - }, - ); - } - let body = match read_body(&mut request, MAX_BODY_BYTES) { - Ok(body) => body, - Err(err) => return respond_json_error(request, StatusCode(413), &err), - }; - #[derive(serde::Deserialize)] - struct ClearRequest { - #[serde(default)] - run_id: Option, - } - let parsed: ClearRequest = - serde_json::from_slice(&body).unwrap_or(ClearRequest { run_id: None }); - if let Some(run_id) = parsed.run_id { - if let Ok(mut cache) = state.run_cache.lock() { - cache.remove(&run_id); - } - } - respond_json( - request, - StatusCode(200), - &serde_json::json!({ "ok": true, "note": "仅清理本 View 会话的运行展示缓存;未修改项目文件。" }), - ) -} - -struct ActiveRequestGuard<'a>(&'a std::sync::atomic::AtomicUsize); - -impl Drop for ActiveRequestGuard<'_> { - fn drop(&mut self) { - self.0.fetch_sub(1, Ordering::SeqCst); - } -} - -struct RunningGuard<'a>(&'a AtomicBool); - -impl Drop for RunningGuard<'_> { - fn drop(&mut self) { - self.0.store(false, Ordering::SeqCst); - } -} - -fn run_error_status(err: &ViewError) -> StatusCode { - match err.code() { - "view.run_denied" => StatusCode(403), - "view.trace_stale" => StatusCode(409), - "view.core_timeout" => StatusCode(504), - "view.protocol_incompatible" => StatusCode(502), - _ => StatusCode(500), - } -} - -fn read_body(request: &mut Request, max: usize) -> Result, ViewError> { - use std::io::Read as _; - let mut body = Vec::new(); - let mut reader = request.as_reader().take(max as u64 + 1); - reader.read_to_end(&mut body).map_err(|err| ViewError::Io { - detail: format!("read request body: {err}"), - })?; - if body.len() > max { - return Err(ViewError::ResourceLimit { - detail: format!("request body above {max} bytes"), - }); - } - Ok(body) -} - -fn header_value(request: &Request, name: &'static str) -> Option { - request - .headers() - .iter() - .find(|header| header.field.equiv(name)) - .map(|header| header.value.as_str().to_string()) -} - -fn content_type_is_json(request: &Request) -> bool { - header_value(request, "Content-Type") - .map(|value| value.to_ascii_lowercase().starts_with("application/json")) - .unwrap_or(false) -} - -fn origin_is_allowed(request: &Request, state: &ServerState) -> bool { - let Some(origin) = header_value(request, "Origin") else { - // Non-browser clients and same-origin `fetch` may omit Origin; the - // CSRF token is still mandatory in every case. - return true; - }; - let origin = origin.trim_end_matches('/').to_ascii_lowercase(); - state.allowed_hosts.iter().any(|host| { - let http = format!("http://{}", host.to_ascii_lowercase()); - origin == http - }) -} - -fn constant_time_eq(left: &[u8], right: &[u8]) -> bool { - if left.len() != right.len() { - return false; - } - let mut diff = 0u8; - for (a, b) in left.iter().zip(right.iter()) { - diff |= a ^ b; - } - diff == 0 -} - -fn encode_path(raw: &str) -> String { - let mut out = String::with_capacity(raw.len()); - for byte in raw.as_bytes() { - let unreserved = - byte.is_ascii_alphanumeric() || matches!(*byte, b'-' | b'_' | b'.' | b'~' | b'/'); - if unreserved { - out.push(*byte as char); - } else { - use std::fmt::Write as _; - let _ = write!(out, "%{byte:02X}"); - } - } - out -} - -fn serve_page( - state: &ServerState, - request: Request, - model: &PresentationModel, - is_head: bool, -) -> ViewResult<()> { - let ctx = RenderContext { - links: crate::reader::render::LinkPolicy::LocalServer, - live: true, - csrf_token: Some(state.csrf_token.clone()), - run_available: state.ctx.core().is_some() && model.can_offer_run(), - annotations: true, - }; - let page = state.renderer.render(model, &ctx); - respond_html(request, page.html.into_bytes(), is_head) -} - -fn serve_error_page(request: Request, err: &ViewError, is_head: bool) -> ViewResult<()> { - let html = format!( - "Marqdo View · 错误

    无法生成阅读页面

    {code}

    {message}

    返回入口

    ", - code = escape_html(err.code()), - message = escape_html(err.public_message()), - ); - respond_html(request, html.into_bytes(), is_head) -} - -fn serve_documents_json( - state: &ServerState, - request: Request, - relative: &SafeRelativePath, - model: &PresentationModel, -) -> ViewResult<()> { - let semantic = model.semantic.as_ref(); - let documents = state - .ctx - .project() - .list_documents() - .unwrap_or_default() - .into_iter() - .map(|path| { - serde_json::json!({ - "path": path.as_str(), - "active": path == *relative, - }) - }) - .collect::>(); - let functions = model - .outline - .iter() - .filter(|entry| entry.kind == crate::reader::model::OutlineKind::Function) - .map(|entry| { - serde_json::json!({ - "label": entry.label, - "anchor": entry.anchor, - "detail": entry.detail, - }) - }) - .collect::>(); - let doc = serde_json::json!({ - "schema": "marqdo.view-documents", - "schema_version": 1, - "entry": state.ctx.project().entry().relative.as_str(), - "documents": documents, - "current": { - "relative_path": model.document.identity.relative_path, - "module_id": model.document.identity.module_id, - "title": model.title, - "source_sha256": sha256_hex(model.document.source.as_bytes()), - "source_status": model.source_status.data_value(), - "semantics_usable": model.source_status.semantics_usable(), - "analysis": semantic.map(|projection| serde_json::json!({ - "digest": projection.analysis_digest, - "schema_version": crate::protocol::tool_v1::ANALYSIS_PROTOCOL, - "producer_version": projection.producer_version, - "project_root_id": projection.project_root_id, - "functions": projection.functions.len(), - "units": projection.units.len(), - "diagnostics": projection.diagnostics.len(), - })), - "outline": model.outline.iter().map(|entry| serde_json::json!({ - "label": entry.label, - "anchor": entry.anchor, - "detail": entry.detail, - "kind": match entry.kind { - crate::reader::model::OutlineKind::Function => "function", - crate::reader::model::OutlineKind::Knowledge => "knowledge", - crate::reader::model::OutlineKind::Section => "section", - }, - })).collect::>(), - "functions": functions, - "run": model.run.as_ref().map(|run| serde_json::json!({ - "state": run.state.data_value(), - "label": run.state.label(), - "run_id": run.run_id, - "run_status": run.run_status, - "exit_code": run.exit_code, - "event_count": run.counts.total(), - "entry_event_count": run.entry_event_count, - "truncated": run.truncated.as_ref().map(|truncated| truncated.label()), - "has_result_value": run.result_value.is_some(), - })), - "can_offer_run": model.can_offer_run(), - }, - "note": "Read-only document structure; this request never executes the document.", - }); - respond_json(request, StatusCode(200), &doc) -} - -fn serve_asset(request: Request, hashed_name: &str, is_head: bool) -> ViewResult<()> { - let bundle = AssetBundle::get(); - if hashed_name == bundle.hashed_css_name() { - return respond_asset( - request, - bundle.css_bytes().to_vec(), - "text/css; charset=utf-8", - is_head, - ); - } - let Some(asset) = bundle.by_path(hashed_name) else { - return respond_text( - request, - StatusCode(404), - "text/plain; charset=utf-8", - "asset not found\n".as_bytes().to_vec(), - CacheKind::NoStore, - ); - }; - respond_asset(request, asset.bytes.to_vec(), asset.mime, is_head) -} - -enum CacheKind { - NoStore, - Immutable, -} - -fn respond_html(request: Request, body: Vec, is_head: bool) -> ViewResult<()> { - respond_with( - request, - StatusCode(200), - "text/html; charset=utf-8", - if is_head { Vec::new() } else { body }, - CacheKind::NoStore, - ) -} - -fn respond_asset( - request: Request, - body: Vec, - content_type: &str, - is_head: bool, -) -> ViewResult<()> { - respond_with( - request, - StatusCode(200), - content_type, - if is_head { Vec::new() } else { body }, - CacheKind::Immutable, - ) -} - -fn respond_json(request: Request, status: StatusCode, value: &serde_json::Value) -> ViewResult<()> { - let body = serde_json::to_vec_pretty(value).unwrap_or_else(|_| b"{}".to_vec()); - respond_with( - request, - status, - "application/json; charset=utf-8", - body, - CacheKind::NoStore, - ) -} - -fn respond_json_error(request: Request, status: StatusCode, err: &ViewError) -> ViewResult<()> { - respond_json(request, status, &err.to_public_json()) -} - -fn respond_text( - request: Request, - status: StatusCode, - content_type: &str, - body: Vec, - cache: CacheKind, -) -> ViewResult<()> { - respond_with(request, status, content_type, body, cache) -} - -fn respond_with( - request: Request, - status: StatusCode, - content_type: &str, - body: Vec, - cache: CacheKind, -) -> ViewResult<()> { - let length = body.len(); - let mut response = Response::from_data(body).with_status_code(status); - if let Ok(header) = Header::from_bytes(&b"Content-Type"[..], content_type.as_bytes()) { - response.add_header(header); - } - for (name, value) in security_headers() { - if let Ok(header) = Header::from_bytes(name.as_bytes(), value.as_bytes()) { - response.add_header(header); - } - } - let cache_value = match cache { - CacheKind::NoStore => "no-store", - CacheKind::Immutable => "public, max-age=31536000, immutable", - }; - if let Ok(header) = Header::from_bytes(&b"Cache-Control"[..], cache_value.as_bytes()) { - response.add_header(header); - } - let _ = length; - request.respond(response).map_err(|err| ViewError::Io { - detail: format!("write response: {err}"), - }) -} - -fn security_headers() -> Vec<(&'static str, &'static str)> { - vec![ - ( - "Content-Security-Policy", - "default-src 'none'; style-src 'self'; script-src 'self' file:; img-src 'self' data:; font-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'; object-src 'none'", - ), - ("X-Content-Type-Options", "nosniff"), - ("Referrer-Policy", "no-referrer"), - ("X-Frame-Options", "DENY"), - ("Cross-Origin-Resource-Policy", "same-origin"), - ("Cross-Origin-Opener-Policy", "same-origin"), - ] -} - -fn split_url(url: &str) -> (&str, &str) { - match url.split_once('?') { - Some((path, query)) => (path, query), - None => (url, ""), - } -} - -fn query_param(query: &str, key: &str) -> Option { - for pair in query.split('&') { - let (name, value) = match pair.split_once('=') { - Some(parts) => parts, - None => (pair, ""), - }; - if name == key { - return Some(value.to_string()); - } - } - None -} - -/// Decode `%XX` exactly once. Rejects malformed escapes, NUL, other control -/// characters and non-UTF-8 results (RFC §11.2.4). -fn percent_decode(raw: &str) -> Option { - let bytes = raw.as_bytes(); - let mut out = Vec::with_capacity(bytes.len()); - let mut index = 0; - while index < bytes.len() { - match bytes[index] { - b'%' => { - if index + 2 >= bytes.len() { - return None; - } - let high = hex_value(*bytes.get(index + 1)?)?; - let low = hex_value(*bytes.get(index + 2)?)?; - out.push(high * 16 + low); - index += 3; - } - b'+' => { - // Query strings here are paths, not form data: keep a literal +. - out.push(b'+'); - index += 1; - } - byte => { - out.push(byte); - index += 1; - } - } - } - if out.contains(&0) || out.iter().any(|byte| *byte < 0x20 || *byte == 0x7f) { - return None; - } - String::from_utf8(out).ok() -} - -fn hex_value(byte: u8) -> Option { - match byte { - b'0'..=b'9' => Some(byte - b'0'), - b'a'..=b'f' => Some(byte - b'a' + 10), - b'A'..=b'F' => Some(byte - b'A' + 10), - _ => None, - } -} - -fn allowed_hosts(port: u16) -> Vec { - vec![ - format!("127.0.0.1:{port}"), - format!("localhost:{port}"), - format!("[::1]:{port}"), - ] -} - -fn host_is_allowed(request: &Request, allowed: &[String]) -> bool { - let mut host: Option<&str> = None; - for header in request.headers() { - if header.field.equiv("Host") { - host = Some(header.value.as_str()); - break; - } - } - match host { - Some(value) => allowed - .iter() - .any(|allowed| allowed.eq_ignore_ascii_case(value)), - None => false, - } -} - -fn escape_html(raw: &str) -> String { - let mut out = String::with_capacity(raw.len()); - for ch in raw.chars() { - match ch { - '&' => out.push_str("&"), - '<' => out.push_str("<"), - '>' => out.push_str(">"), - '"' => out.push_str("""), - '\'' => out.push_str("'"), - _ => out.push(ch), - } - } - out -} - -fn random_token() -> String { - #[cfg(unix)] - { - use std::io::Read as _; - if let Ok(mut file) = std::fs::File::open("/dev/urandom") { - let mut bytes = [0u8; 32]; - if file.read_exact(&mut bytes).is_ok() { - return hex_encode(&bytes); - } - } - } - // Fallback: still unique per process/session, never a constant. - let material = format!( - "{}-{}-{:?}", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0), - std::thread::current().id() - ); - sha256_hex(material.as_bytes()) -} - -fn hex_encode(bytes: &[u8]) -> String { - let mut out = String::with_capacity(bytes.len() * 2); - for byte in bytes { - use std::fmt::Write as _; - let _ = write!(out, "{byte:02x}"); - } - out -} - -fn open_browser(url: &str) { - let program = if cfg!(target_os = "macos") { - "open" - } else if cfg!(target_os = "windows") { - "cmd" - } else { - "xdg-open" - }; - let mut command = std::process::Command::new(program); - if cfg!(target_os = "windows") { - command.args(["/C", "start", ""]); - } - command.arg(url); - command - .stdin(std::process::Stdio::null()) - .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()); - if command.spawn().is_err() { - eprintln!("view: could not open a browser; open {url} manually"); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn percent_decode_is_single_pass_and_strict() { - assert_eq!(percent_decode("a%20b").as_deref(), Some("a b")); - assert_eq!(percent_decode("100%25").as_deref(), Some("100%")); - assert_eq!(percent_decode("a+b").as_deref(), Some("a+b")); - assert!(percent_decode("%2e%2e%2fsecret").is_some()); - assert!(percent_decode("%zz").is_none()); - assert!(percent_decode("%2").is_none()); - assert!(percent_decode("a%00b").is_none()); - assert!(percent_decode("%0a").is_none()); - assert!(percent_decode("%ff").is_none()); - } - - #[test] - fn query_params_are_parsed_without_form_plus_rules() { - assert_eq!(query_param("path=a%2Fb", "path").as_deref(), Some("a%2Fb")); - assert_eq!(query_param("x=1&path=y", "path").as_deref(), Some("y")); - assert_eq!(query_param("", "path"), None); - } - - #[test] - fn allowed_hosts_include_loopback_and_port() { - let hosts = allowed_hosts(7429); - assert!(hosts.contains(&"127.0.0.1:7429".to_string())); - assert!(hosts.contains(&"localhost:7429".to_string())); - assert!(!hosts.contains(&"127.0.0.1:7428".to_string())); - } - - #[test] - fn random_token_is_64_hex_chars_and_unique() { - let a = random_token(); - let b = random_token(); - assert_eq!(a.len(), 64); - assert_ne!(a, b); - } -} diff --git a/src/server/mod.rs b/src/server/mod.rs new file mode 100644 index 0000000..09dae9c --- /dev/null +++ b/src/server/mod.rs @@ -0,0 +1,122 @@ +//! Local single-user Live server. +//! +//! Loopback-only, fixed minimal routes, one explicit execution entry. The +//! server module contains no business engine: pages come from the one Reader, +//! run jobs from the ExecutionController, and SSE only transports already +//! sequenced View events (RFC-VIEW-0002 §5.1). + +pub mod routes; +pub mod security; +pub mod sse; + +use crate::cli::RuntimeOpts; +use crate::error::{ViewError, ViewResult}; +use crate::execution::controller::{ExecutionConfig, ExecutionController}; +use crate::reader::assemble::DocumentService; +use crate::reader::render::ReaderRenderer; +use routes::ServerState; +use std::collections::HashMap; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use tiny_http::Server; + +pub fn serve(service: DocumentService, opts: &RuntimeOpts) -> ViewResult { + let address = format!("{}:{}", opts.host, opts.port); + let server = Server::http(&address).map_err(|err| ViewError::Io { + detail: format!("listen on {address}: {err}"), + })?; + let bound = server.server_addr().to_ip().ok_or_else(|| ViewError::Io { + detail: "server address is not an IP socket".to_string(), + })?; + let port = bound.port(); + let display_host = match opts.host.as_str() { + "localhost" => "localhost".to_string(), + "::1" | "[::1]" => "[::1]".to_string(), + _ => "127.0.0.1".to_string(), + }; + let url = format!("http://{display_host}:{port}/"); + + let service = Arc::new(service); + let controller = Arc::new(ExecutionController::new( + Arc::clone(&service), + ExecutionConfig::default().with_timeout(opts.run_timeout_secs), + )); + let state = Arc::new(ServerState { + service, + controller, + renderer: ReaderRenderer::new(), + cache: Mutex::new(HashMap::new()), + security: crate::server::security::SecurityState::new(port), + active_requests: AtomicUsize::new(0), + }); + + eprintln!("marqdo view: {url}"); + eprintln!("root: {}", state.service.project().root().display()); + eprintln!( + "{} .mq.md document(s). Ctrl+C to stop.", + state + .service + .project() + .list_documents() + .map(|documents| documents.len()) + .unwrap_or(0) + ); + if let Some(version) = state.service.core_version() { + eprintln!("core: marqdo {version} (Analysis v2, Trace v2)"); + } else if let Some(note) = state.service.core_note() { + eprintln!("core: unavailable ({note})"); + } + eprintln!( + "run: explicit only (pure by default, one active job, {}s wall clock)", + opts.run_timeout_secs + ); + if !opts.no_open { + open_browser(&url); + } + + loop { + let request = match server.recv() { + Ok(request) => request, + Err(err) => { + eprintln!("view: accept failed: {err}"); + continue; + } + }; + let active = state.active_requests.fetch_add(1, Ordering::SeqCst); + if active >= 48 { + state.active_requests.fetch_sub(1, Ordering::SeqCst); + let _ = request.respond(tiny_http::Response::empty(503)); + continue; + } + let state = Arc::clone(&state); + std::thread::spawn(move || { + let result = routes::handle(&state, request); + state.active_requests.fetch_sub(1, Ordering::SeqCst); + if let Err(err) = result { + eprintln!("view request error: {err}"); + } + }); + } +} + +fn open_browser(url: &str) { + let program = if cfg!(target_os = "macos") { + "open" + } else if cfg!(target_os = "windows") { + "cmd" + } else { + "xdg-open" + }; + let mut command = std::process::Command::new(program); + if cfg!(target_os = "windows") { + command.args(["/C", "start", ""]); + } + command.arg(url); + command + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()); + if command.spawn().is_err() { + eprintln!("view: could not open a browser; open {url} manually"); + } +} diff --git a/src/server/routes.rs b/src/server/routes.rs new file mode 100644 index 0000000..bb6ff99 --- /dev/null +++ b/src/server/routes.rs @@ -0,0 +1,691 @@ +//! The fixed minimal HTTP route table (RFC-VIEW-0002 §6.2). +//! +//! | route | executes? | +//! |---|---| +//! | `GET /` | no | +//! | `GET /file?path=...` | no | +//! | `GET /assets/...` | no | +//! | `GET /api/documents` | no | +//! | `POST /api/runs` | **yes — the only execution entry** | +//! | `GET /api/runs/{id}/events` | no (observe only) | +//! | `POST /api/runs/{id}/cancel` | no (control of an existing job) | +//! +//! Anything else is 404. Page loads, refreshes, searches, document switches and +//! the static export path can never form an execution edge. + +use crate::error::{ViewError, ViewResult}; +use crate::execution::controller::ExecutionController; +use crate::reader::assemble::DocumentService; +use crate::reader::assets::AssetBundle; +use crate::reader::model::PresentationModel; +use crate::reader::render::{ReaderRenderer, RenderContext}; +use crate::reader::source::{sha256_hex, SafeRelativePath}; +use crate::server::security::{ + header, SecurityState, MAX_POST_BODY_BYTES, MAX_QUERY_BYTES, MAX_URL_BYTES, +}; +use crate::server::sse; +use std::collections::HashMap; +use std::io::Read; +use std::sync::atomic::AtomicUsize; +use std::sync::{Arc, Mutex}; +use tiny_http::{Header, Method, Request, Response, StatusCode}; + +pub struct ServerState { + pub service: Arc, + pub controller: Arc, + pub renderer: ReaderRenderer, + pub cache: Mutex>, + pub security: SecurityState, + pub active_requests: AtomicUsize, +} + +#[derive(Clone)] +pub struct CacheEntry { + source_digest: String, + model: PresentationModel, +} + +impl ServerState { + /// Load one document, reusing a cached model only while the exact source + /// bytes are unchanged. This path performs the read-only `check` only. + pub fn load(&self, relative: &SafeRelativePath) -> ViewResult { + let digest = self.service.project().source_digest(relative)?; + if let Ok(cache) = self.cache.lock() { + if let Some(entry) = cache.get(relative.as_str()) { + if entry.source_digest == digest { + return Ok(entry.model.clone()); + } + } + } + let model = self.service.load(relative)?; + if let Ok(mut cache) = self.cache.lock() { + if cache.len() < 64 { + cache.insert( + relative.as_str().to_string(), + CacheEntry { + source_digest: digest, + model: model.clone(), + }, + ); + } + } + Ok(model) + } +} + +pub fn handle(state: &ServerState, request: Request) -> ViewResult<()> { + let method = request.method().clone(); + let raw_url = request.url().to_string(); + if raw_url.len() > MAX_URL_BYTES { + return respond_text( + request, + StatusCode(414), + "request target too long\n", + CacheKind::NoStore, + ); + } + let (path, query) = split_url(&raw_url); + if query.len() > MAX_QUERY_BYTES { + return respond_text( + request, + StatusCode(414), + "query too long\n", + CacheKind::NoStore, + ); + } + if let Err(err) = state.security.check_host(&request) { + return respond_error(request, StatusCode(400), &err); + } + + let is_get = method == Method::Get || method == Method::Head; + if is_get { + if let Some(hashed_name) = path.strip_prefix("/assets/") { + return serve_asset(request, hashed_name); + } + if path == "/" || path == "/index.html" { + return serve_page(state, request, None); + } + if path == "/file" { + return serve_file(state, request, query); + } + if path == "/api/documents" { + return serve_documents(state, request, query); + } + if let Some(run_id) = matched_run_route(path, "/events") { + return serve_events(state, request, run_id); + } + return respond_text(request, StatusCode(404), "not found\n", CacheKind::NoStore); + } + + if method == Method::Post { + if path == "/api/runs" { + return submit_run(state, request); + } + if let Some(run_id) = matched_run_route(path, "/cancel") { + return cancel_run(state, request, run_id); + } + return respond_text( + request, + StatusCode(405), + "method not allowed\n", + CacheKind::NoStore, + ); + } + respond_text( + request, + StatusCode(405), + "method not allowed\n", + CacheKind::NoStore, + ) +} + +/// Match `/api/runs/` without accepting nested paths. +fn matched_run_route<'a>(path: &'a str, suffix: &str) -> Option<&'a str> { + let rest = path.strip_prefix("/api/runs/")?; + let run_id = rest.strip_suffix(suffix)?; + if run_id.is_empty() + || run_id.len() > 128 + || !run_id + .chars() + .all(|ch| ch.is_ascii_alphanumeric() || ch == '-' || ch == '_') + || path.contains("//") + { + return None; + } + Some(run_id) +} + +fn serve_page( + state: &ServerState, + request: Request, + relative: Option, +) -> ViewResult<()> { + let relative = match relative { + Some(relative) => relative, + None => state.service.project().entry().relative.clone(), + }; + let model = match state.load(&relative) { + Ok(model) => model, + Err(err) => return serve_error_page(request, &err), + }; + let (session, set_cookie) = state.security.page_session(&request); + let ctx = RenderContext { + links: crate::reader::render::LinkPolicy::LocalServer, + live: true, + csrf_token: Some(session.csrf), + run_available: state.service.core().is_some() && model.can_offer_run(), + annotations: true, + run_timeout_secs: state.controller.config().run_timeout_secs(), + core_available: state.service.core().is_some(), + }; + let page = state.renderer.render(&model, &ctx); + let mut headers = Vec::new(); + if let Some(cookie) = set_cookie { + if let Ok(header) = Header::from_bytes(&b"Set-Cookie"[..], cookie.as_bytes()) { + headers.push(header); + } + } + respond_bytes( + request, + StatusCode(200), + "text/html; charset=utf-8", + page.html.into_bytes(), + CacheKind::NoStore, + headers, + ) +} + +fn serve_file(state: &ServerState, request: Request, query: &str) -> ViewResult<()> { + let Some(raw_path) = query_param(query, "path") else { + return respond_text( + request, + StatusCode(400), + "missing path\n", + CacheKind::NoStore, + ); + }; + let Some(decoded) = percent_decode(&raw_path) else { + return respond_text( + request, + StatusCode(400), + "malformed path\n", + CacheKind::NoStore, + ); + }; + let relative = match SafeRelativePath::parse(&decoded) { + Ok(relative) => relative, + Err(err) => { + return respond_text( + request, + StatusCode(403), + &format!("{}\n", err.code()), + CacheKind::NoStore, + ) + } + }; + if state.service.project().read_source(&relative).is_err() { + return respond_text( + request, + StatusCode(404), + "document not found\n", + CacheKind::NoStore, + ); + } + serve_page(state, request, Some(relative)) +} + +fn serve_documents(state: &ServerState, request: Request, query: &str) -> ViewResult<()> { + if let Err(err) = state.security.check_same_origin(&request) { + return respond_error(request, StatusCode(403), &err); + } + let relative = match query_param(query, "path").and_then(|raw| percent_decode(&raw)) { + Some(decoded) => match SafeRelativePath::parse(&decoded) { + Ok(relative) => relative, + Err(err) => return respond_error(request, StatusCode(400), &err), + }, + None => state.service.project().entry().relative.clone(), + }; + let model = match state.load(&relative) { + Ok(model) => model, + Err(err) => return respond_error(request, StatusCode(500), &err), + }; + let semantic = model.semantic.as_ref(); + let documents = state + .service + .project() + .list_documents() + .unwrap_or_default() + .into_iter() + .map(|path| { + serde_json::json!({ + "path": path.as_str(), + "active": path == relative, + }) + }) + .collect::>(); + let functions = model + .outline + .iter() + .filter(|entry| entry.kind == crate::reader::model::OutlineKind::Function) + .map(|entry| { + serde_json::json!({ + "label": entry.label, + "anchor": entry.anchor, + "detail": entry.detail, + }) + }) + .collect::>(); + let doc = serde_json::json!({ + "schema": "marqdo.view-documents", + "schema_version": 1, + "entry": state.service.project().entry().relative.as_str(), + "documents": documents, + "current": { + "relative_path": model.document.identity.relative_path, + "module_id": model.document.identity.module_id, + "title": model.title, + "source_sha256": sha256_hex(model.document.source.as_bytes()), + "source_status": model.source_status.data_value(), + "semantics_usable": model.source_status.semantics_usable(), + "analysis": semantic.map(|projection| serde_json::json!({ + "schema_version": crate::protocol::tool_v1::ANALYSIS_PROTOCOL, + "digest": projection.analysis_digest, + "producer_version": projection.producer_version, + "project_root_id": projection.project_root_id, + "functions": projection.functions.len(), + "units": projection.units.len(), + "diagnostics": projection.diagnostics.len(), + })), + "outline": model.outline.iter().map(|entry| serde_json::json!({ + "label": entry.label, + "anchor": entry.anchor, + "detail": entry.detail, + "kind": match entry.kind { + crate::reader::model::OutlineKind::Function => "function", + crate::reader::model::OutlineKind::Knowledge => "knowledge", + crate::reader::model::OutlineKind::Section => "section", + }, + })).collect::>(), + "functions": functions, + "can_offer_run": model.can_offer_run(), + }, + "note": "Read-only document structure; this request never executes the document.", + }); + respond_json(request, StatusCode(200), &doc) +} + +/// The only execution entry in the whole product. +fn submit_run(state: &ServerState, mut request: Request) -> ViewResult<()> { + let session = match state.security.authenticate_post(&request) { + Ok(session) => session, + Err(err) => return respond_error(request, status_for(&err), &err), + }; + let body = match read_body(&mut request, MAX_POST_BODY_BYTES) { + Ok(body) => body, + Err(err) => { + let status = match err.code() { + "view.resource_limit" | "view.output_limit" => StatusCode(413), + _ => status_for(&err), + }; + return respond_error(request, status, &err); + } + }; + match state.controller.submit(&session.id, &body) { + Ok(accepted) => respond_json( + request, + StatusCode(202), + &serde_json::json!({ + "schema": "marqdo.view-run-accepted", + "schema_version": 1, + "run_id": accepted.run_id, + "state": accepted.state.data_value(), + "events_url": accepted.events_url, + "cancel_url": accepted.cancel_url, + "reused": accepted.reused, + }), + ), + Err(err) => respond_error(request, status_for(&err), &err), + } +} + +fn serve_events(state: &ServerState, request: Request, run_id: &str) -> ViewResult<()> { + let session = match state.security.require_session(&request) { + Ok(session) => session, + Err(err) => return respond_error(request, status_for(&err), &err), + }; + if let Err(err) = state.security.check_same_origin(&request) { + return respond_error(request, StatusCode(403), &err); + } + let last_event_id = + header(&request, "Last-Event-ID").and_then(|value| value.parse::().ok()); + match state + .controller + .subscribe(&session.id, run_id, last_event_id) + { + Ok(subscription) => sse::respond(request, subscription), + Err(err) => respond_error(request, status_for(&err), &err), + } +} + +fn cancel_run(state: &ServerState, request: Request, run_id: &str) -> ViewResult<()> { + let session = match state.security.authenticate_control(&request) { + Ok(session) => session, + Err(err) => return respond_error(request, status_for(&err), &err), + }; + match state.controller.cancel(&session.id, run_id) { + Ok(state_value) => respond_json( + request, + StatusCode(200), + &serde_json::json!({ + "schema": "marqdo.view-run-cancel", + "schema_version": 1, + "run_id": run_id, + "state": state_value.data_value(), + }), + ), + Err(err) => respond_error(request, status_for(&err), &err), + } +} + +fn serve_asset(request: Request, hashed_name: &str) -> ViewResult<()> { + let bundle = AssetBundle::get(); + if hashed_name == bundle.hashed_css_name() { + return respond_bytes( + request, + StatusCode(200), + "text/css; charset=utf-8", + bundle.css_bytes().to_vec(), + CacheKind::Immutable, + Vec::new(), + ); + } + let Some(asset) = bundle.by_path(hashed_name) else { + return respond_text( + request, + StatusCode(404), + "asset not found\n", + CacheKind::NoStore, + ); + }; + respond_bytes( + request, + StatusCode(200), + asset.mime, + asset.bytes.to_vec(), + CacheKind::Immutable, + Vec::new(), + ) +} + +fn serve_error_page(request: Request, err: &ViewError) -> ViewResult<()> { + let html = format!( + "Marqdo View · 错误

    无法生成阅读页面

    {code}

    {message}

    返回入口

    ", + code = escape_html(err.code()), + message = escape_html(err.public_message()), + ); + respond_html(request, html.into_bytes()) +} + +fn status_for(err: &ViewError) -> StatusCode { + match err.code() { + "view.session_required" => StatusCode(401), + "view.run_denied" => StatusCode(403), + "view.run_invalid" | "view.no_entry_function" => StatusCode(400), + "view.run_busy" | "view.run_conflict" => StatusCode(409), + "view.run_not_found" => StatusCode(404), + "view.sse_busy" | "view.resource_limit" => StatusCode(429), + "view.output_limit" => StatusCode(413), + "view.analysis_failed" => StatusCode(422), + "view.core_missing" | "view.core_spawn" => StatusCode(503), + "view.core_timeout" => StatusCode(504), + "view.protocol_incompatible" | "view.core_protocol" => StatusCode(502), + "view.unsupported" => StatusCode(415), + _ => StatusCode(500), + } +} + +fn read_body(request: &mut Request, max: usize) -> Result, ViewError> { + let mut body = Vec::new(); + let mut reader = request.as_reader().take(max as u64 + 1); + reader.read_to_end(&mut body).map_err(|err| ViewError::Io { + detail: format!("read request body: {err}"), + })?; + if body.len() > max { + return Err(ViewError::ResourceLimit { + detail: format!("request body above {max} bytes"), + }); + } + Ok(body) +} + +enum CacheKind { + NoStore, + Immutable, +} + +fn respond_html(request: Request, body: Vec) -> ViewResult<()> { + respond_bytes( + request, + StatusCode(200), + "text/html; charset=utf-8", + body, + CacheKind::NoStore, + Vec::new(), + ) +} + +fn respond_text( + request: Request, + status: StatusCode, + body: &str, + cache: CacheKind, +) -> ViewResult<()> { + respond_bytes( + request, + status, + "text/plain; charset=utf-8", + body.as_bytes().to_vec(), + cache, + Vec::new(), + ) +} + +fn respond_json(request: Request, status: StatusCode, value: &serde_json::Value) -> ViewResult<()> { + let body = serde_json::to_vec_pretty(value).unwrap_or_else(|_| b"{}".to_vec()); + respond_bytes( + request, + status, + "application/json; charset=utf-8", + body, + CacheKind::NoStore, + Vec::new(), + ) +} + +fn respond_error(request: Request, status: StatusCode, err: &ViewError) -> ViewResult<()> { + let mut headers = Vec::new(); + if let Ok(header) = + Header::from_bytes(&b"WWW-Authenticate"[..], b"Session realm=\"marqdo-view\"") + { + if err.code() == "view.run_denied" && status.0 == 401 { + headers.push(header); + } + } + let value = serde_json::json!({ + "schema": "marqdo.view-error", + "schema_version": 1, + "code": err.code(), + "source": "view", + "message": err.public_message(), + }); + let body = serde_json::to_vec_pretty(&value).unwrap_or_else(|_| b"{}".to_vec()); + respond_bytes( + request, + status, + "application/json; charset=utf-8", + body, + CacheKind::NoStore, + headers, + ) +} + +fn respond_bytes( + request: Request, + status: StatusCode, + content_type: &str, + body: Vec, + cache: CacheKind, + extra_headers: Vec
    , +) -> ViewResult<()> { + let mut response = Response::from_data(body).with_status_code(status); + if let Ok(header) = Header::from_bytes(&b"Content-Type"[..], content_type.as_bytes()) { + response.add_header(header); + } + for (name, value) in crate::server::security::security_headers() { + if let Ok(header) = Header::from_bytes(name.as_bytes(), value.as_bytes()) { + response.add_header(header); + } + } + let cache_value = match cache { + CacheKind::NoStore => "no-store", + CacheKind::Immutable => "public, max-age=31536000, immutable", + }; + if let Ok(header) = Header::from_bytes(&b"Cache-Control"[..], cache_value.as_bytes()) { + response.add_header(header); + } + for header in extra_headers { + response.add_header(header); + } + request.respond(response).map_err(|err| ViewError::Io { + detail: format!("write response: {err}"), + }) +} + +fn split_url(url: &str) -> (&str, &str) { + match url.split_once('?') { + Some((path, query)) => (path, query), + None => (url, ""), + } +} + +pub fn query_param(query: &str, key: &str) -> Option { + for pair in query.split('&') { + let (name, value) = match pair.split_once('=') { + Some(parts) => parts, + None => (pair, ""), + }; + if name == key { + return Some(value.to_string()); + } + } + None +} + +/// Decode `%XX` exactly once; reject malformed escapes, NUL, controls and +/// non-UTF-8 results. +pub fn percent_decode(raw: &str) -> Option { + let bytes = raw.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut index = 0; + while index < bytes.len() { + match bytes[index] { + b'%' => { + if index + 2 >= bytes.len() { + return None; + } + let high = hex_value(*bytes.get(index + 1)?)?; + let low = hex_value(*bytes.get(index + 2)?)?; + out.push(high * 16 + low); + index += 3; + } + b'+' => { + out.push(b'+'); + index += 1; + } + byte => { + out.push(byte); + index += 1; + } + } + } + if out.contains(&0) || out.iter().any(|byte| *byte < 0x20 || *byte == 0x7f) { + return None; + } + String::from_utf8(out).ok() +} + +fn hex_value(byte: u8) -> Option { + match byte { + b'0'..=b'9' => Some(byte - b'0'), + b'a'..=b'f' => Some(byte - b'a' + 10), + b'A'..=b'F' => Some(byte - b'A' + 10), + _ => None, + } +} + +fn escape_html(raw: &str) -> String { + let mut out = String::with_capacity(raw.len()); + for ch in raw.chars() { + match ch { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + _ => out.push(ch), + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn run_route_matching_is_strict() { + assert_eq!( + matched_run_route("/api/runs/abc/events", "/events"), + Some("abc") + ); + assert_eq!( + matched_run_route("/api/runs/abc/cancel", "/cancel"), + Some("abc") + ); + assert_eq!(matched_run_route("/api/runs//events", "/events"), None); + assert_eq!(matched_run_route("/api/runs/a/b/events", "/events"), None); + assert_eq!(matched_run_route("/api/runs/abc/events/", "/events"), None); + } + + #[test] + fn percent_decode_is_single_pass_and_strict() { + assert_eq!(percent_decode("a%20b").as_deref(), Some("a b")); + assert_eq!(percent_decode("100%25").as_deref(), Some("100%")); + assert_eq!(percent_decode("a+b").as_deref(), Some("a+b")); + assert!(percent_decode("%zz").is_none()); + assert!(percent_decode("a%00b").is_none()); + assert!(percent_decode("%ff").is_none()); + } + + #[test] + fn status_mapping_covers_execution_errors() { + assert_eq!( + status_for(&ViewError::RunBusy { + detail: String::new() + }), + StatusCode(409) + ); + assert_eq!( + status_for(&ViewError::RunNotFound { + detail: String::new() + }), + StatusCode(404) + ); + assert_eq!( + status_for(&ViewError::RunDenied { + detail: String::new() + }), + StatusCode(403) + ); + } +} diff --git a/src/server/security.rs b/src/server/security.rs new file mode 100644 index 0000000..976ab9a --- /dev/null +++ b/src/server/security.rs @@ -0,0 +1,348 @@ +//! Local-session, CSRF, Origin/Host and response-header security. +//! +//! The Live server is loopback-only but still guards the one execution endpoint +//! (RFC-VIEW-0002 §6.8): an HttpOnly `SameSite=Strict` session cookie, a +//! per-session CSRF token required as `X-View-CSRF`, an exact same-origin +//! `Origin`, a valid loopback `Host`, JSON-only bounded POSTs and a strict CSP. + +use crate::error::{ViewError, ViewResult}; +use std::collections::HashMap; +use std::sync::Mutex; +use std::time::{Duration, Instant}; +use tiny_http::Request; + +pub const SESSION_COOKIE: &str = "mq_view_session"; +pub const CSRF_HEADER: &str = "X-View-CSRF"; +pub const MAX_SESSIONS: usize = 64; +pub const SESSION_TTL: Duration = Duration::from_secs(12 * 60 * 60); +pub const MAX_POST_BODY_BYTES: usize = 64 * 1024; +pub const MAX_URL_BYTES: usize = 2048; +pub const MAX_QUERY_BYTES: usize = 4096; + +#[derive(Debug, Clone)] +pub struct SessionView { + pub id: String, + pub csrf: String, +} + +struct Session { + csrf: String, + last_seen: Instant, +} + +pub struct SecurityState { + sessions: Mutex>, + allowed_hosts: Vec, + origin: String, +} + +impl SecurityState { + pub fn new(port: u16) -> Self { + let host = format!("127.0.0.1:{port}"); + Self { + sessions: Mutex::new(HashMap::new()), + allowed_hosts: vec![host.clone(), format!("localhost:{port}")], + origin: format!("http://{host}"), + } + } + + pub fn allowed_hosts(&self) -> &[String] { + &self.allowed_hosts + } + + /// Validate `Host` for every request (DNS-rebinding defence). + pub fn check_host(&self, request: &Request) -> ViewResult<()> { + let host = header(request, "Host").ok_or_else(|| ViewError::RunDenied { + detail: "missing Host header".to_string(), + })?; + if self + .allowed_hosts + .iter() + .any(|allowed| allowed.eq_ignore_ascii_case(host.trim())) + { + Ok(()) + } else { + Err(ViewError::RunDenied { + detail: "invalid Host header".to_string(), + }) + } + } + + /// Browser page load: reuse a valid cookie or mint a new session. Returns + /// the session plus the `Set-Cookie` value when a new one was created. + pub fn page_session(&self, request: &Request) -> (SessionView, Option) { + let now = Instant::now(); + let mut sessions = self + .sessions + .lock() + .unwrap_or_else(|poison| poison.into_inner()); + sessions.retain(|_, session| now.duration_since(session.last_seen) < SESSION_TTL); + if let Some(id) = cookie_value(request, SESSION_COOKIE) { + if let Some(session) = sessions.get_mut(&id) { + session.last_seen = now; + return ( + SessionView { + id, + csrf: session.csrf.clone(), + }, + None, + ); + } + } + let id = random_hex(32); + let csrf = random_hex(32); + sessions.insert( + id.clone(), + Session { + csrf: csrf.clone(), + last_seen: now, + }, + ); + while sessions.len() > MAX_SESSIONS { + let oldest = sessions + .iter() + .min_by_key(|(_, session)| session.last_seen) + .map(|(id, _)| id.clone()); + match oldest { + Some(id) => { + sessions.remove(&id); + } + None => break, + } + } + let cookie = + format!("{SESSION_COOKIE}={id}; HttpOnly; SameSite=Strict; Path=/; Max-Age=43200"); + (SessionView { id, csrf }, Some(cookie)) + } + + /// Authenticated GET (page/SSE): an existing session cookie is required. + pub fn require_session(&self, request: &Request) -> ViewResult { + let id = + cookie_value(request, SESSION_COOKIE).ok_or_else(|| ViewError::SessionRequired { + detail: "缺少本地会话 Cookie;请刷新阅读页面后重试".to_string(), + })?; + let now = Instant::now(); + let mut sessions = self + .sessions + .lock() + .unwrap_or_else(|poison| poison.into_inner()); + let session = sessions + .get_mut(&id) + .ok_or_else(|| ViewError::SessionRequired { + detail: "本地会话已过期;请刷新阅读页面".to_string(), + })?; + if now.duration_since(session.last_seen) >= SESSION_TTL { + sessions.remove(&id); + return Err(ViewError::SessionRequired { + detail: "本地会话已过期;请刷新阅读页面".to_string(), + }); + } + session.last_seen = now; + Ok(SessionView { + id, + csrf: session.csrf.clone(), + }) + } + + /// Authenticated JSON POST (run submission). + pub fn authenticate_post(&self, request: &Request) -> ViewResult { + self.authenticate_post_impl(request, true) + } + + /// Authenticated control POST without a JSON body (cancel is a bare POST). + pub fn authenticate_control(&self, request: &Request) -> ViewResult { + self.authenticate_post_impl(request, false) + } + + fn authenticate_post_impl( + &self, + request: &Request, + require_json: bool, + ) -> ViewResult { + self.check_host(request)?; + let origin = header(request, "Origin").ok_or_else(|| ViewError::RunDenied { + detail: "缺少 Origin,跨站来源被拒绝".to_string(), + })?; + if !origin + .trim_end_matches('/') + .eq_ignore_ascii_case(&self.origin) + { + return Err(ViewError::RunDenied { + detail: "Origin 与本地服务不一致,跨站请求被拒绝".to_string(), + }); + } + if let Some(site) = header(request, "Sec-Fetch-Site") { + if site.eq_ignore_ascii_case("cross-site") { + return Err(ViewError::RunDenied { + detail: "Sec-Fetch-Site 表示跨站请求,已拒绝".to_string(), + }); + } + } + if require_json + && !header(request, "Content-Type") + .map(|value| value.to_ascii_lowercase().starts_with("application/json")) + .unwrap_or(false) + { + return Err(ViewError::Unsupported { + detail: "运行请求必须是 application/json".to_string(), + }); + } + let session = self.require_session(request)?; + let csrf = header(request, CSRF_HEADER).ok_or_else(|| ViewError::RunDenied { + detail: "缺少 X-View-CSRF,运行被拒绝".to_string(), + })?; + if !constant_time_eq(csrf.as_bytes(), session.csrf.as_bytes()) { + return Err(ViewError::RunDenied { + detail: "X-View-CSRF 无效,运行被拒绝".to_string(), + }); + } + Ok(session) + } + + /// Origin check for read-only JSON APIs (no CSRF needed, no state change). + pub fn check_same_origin(&self, request: &Request) -> ViewResult<()> { + if let Some(origin) = header(request, "Origin") { + if !origin + .trim_end_matches('/') + .eq_ignore_ascii_case(&self.origin) + { + return Err(ViewError::RunDenied { + detail: "跨站读取被拒绝".to_string(), + }); + } + } + Ok(()) + } +} + +pub fn header(request: &Request, name: &'static str) -> Option { + request + .headers() + .iter() + .find(|header| header.field.equiv(name)) + .map(|header| header.value.as_str().trim().to_string()) +} + +pub fn cookie_value(request: &Request, name: &str) -> Option { + let raw = header(request, "Cookie")?; + for pair in raw.split(';') { + let (key, value) = pair.split_once('=')?; + if key.trim() == name { + let value = value.trim(); + if !value.is_empty() + && value + .chars() + .all(|ch| ch.is_ascii_alphanumeric() || ch == '-' || ch == '_') + { + return Some(value.to_string()); + } + return None; + } + } + None +} + +pub fn constant_time_eq(left: &[u8], right: &[u8]) -> bool { + if left.len() != right.len() { + return false; + } + let mut diff = 0u8; + for (a, b) in left.iter().zip(right.iter()) { + diff |= a ^ b; + } + diff == 0 +} + +/// Random lowercase hex from `/dev/urandom` (with a non-constant fallback). +pub fn random_hex(bytes: usize) -> String { + let mut buffer = vec![0u8; bytes]; + #[cfg(unix)] + { + use std::io::Read as _; + if let Ok(mut file) = std::fs::File::open("/dev/urandom") { + if file.read_exact(&mut buffer).is_ok() { + return hex_encode(&buffer); + } + } + } + let thread = format!("{:?}", std::thread::current().id()); + let material = format!( + "{}-{}-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|duration| duration.as_nanos()) + .unwrap_or(0), + thread, + fallback_counter() + ); + crate::reader::source::sha256_hex(material.as_bytes())[..bytes * 2].to_string() +} + +fn fallback_counter() -> u64 { + static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed) +} + +fn hex_encode(bytes: &[u8]) -> String { + let mut out = String::with_capacity(bytes.len() * 2); + for byte in bytes { + use std::fmt::Write as _; + let _ = write!(out, "{byte:02x}"); + } + out +} + +/// HTTP security headers for every response (RFC-VIEW-0002 §6.8). +pub fn security_headers() -> Vec<(&'static str, &'static str)> { + vec![ + ( + "Content-Security-Policy", + "default-src 'self'; connect-src 'self'; style-src 'self'; script-src 'self'; img-src 'self' data:; font-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'", + ), + ("X-Content-Type-Options", "nosniff"), + ("Referrer-Policy", "no-referrer"), + ("X-Frame-Options", "DENY"), + ("Cross-Origin-Resource-Policy", "same-origin"), + ("Cross-Origin-Opener-Policy", "same-origin"), + ("Cache-Control", "no-store"), + ] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn constant_time_eq_is_strict() { + assert!(constant_time_eq(b"abc", b"abc")); + assert!(!constant_time_eq(b"abc", b"abd")); + assert!(!constant_time_eq(b"abc", b"ab")); + } + + #[test] + fn random_tokens_are_lower_hex_and_unique() { + let a = random_hex(32); + let b = random_hex(32); + assert_eq!(a.len(), 64); + assert_ne!(a, b); + assert!(a.chars().all(|ch| ch.is_ascii_hexdigit())); + } + + #[test] + fn session_cookie_is_parsed_from_a_real_request() { + let request: tiny_http::Request = tiny_http::TestRequest::new() + .with_header( + tiny_http::Header::from_bytes( + &b"Cookie"[..], + &b"a=b; mq_view_session=ok_1; other=x"[..], + ) + .unwrap(), + ) + .into(); + assert_eq!( + cookie_value(&request, SESSION_COOKIE).as_deref(), + Some("ok_1") + ); + } +} diff --git a/src/server/sse.rs b/src/server/sse.rs new file mode 100644 index 0000000..bf81541 --- /dev/null +++ b/src/server/sse.rs @@ -0,0 +1,132 @@ +//! One-way SSE transport for View-owned run events. +//! +//! We write the HTTP response directly to the socket (via tiny_http's writer) +//! instead of going through its buffered chunked writer: SSE requires each +//! frame and heartbeat to be flushed immediately, not when a buffer fills. +//! This module only transports already-sequenced events; it never queries the +//! Core, starts work or implements a polling loop (RFC-VIEW-0002 §6.4/§6.5). + +use crate::error::ViewResult; +use crate::execution::controller::SseSubscription; +use crate::execution::events::{HEARTBEAT_FRAME, HEARTBEAT_INTERVAL_SECS}; +use std::io::Write; +use std::sync::mpsc::RecvTimeoutError; +use std::time::{Duration, Instant}; +use tiny_http::Request; + +pub fn heartbeat_interval() -> Duration { + // Test/dev override only; production default is the RFC 15 seconds. + if let Ok(raw) = std::env::var("MARQDO_VIEW_SSE_HEARTBEAT_SECS") { + if let Ok(seconds) = raw.parse::() { + if seconds > 0 { + return Duration::from_secs(seconds); + } + } + } + Duration::from_secs(HEARTBEAT_INTERVAL_SECS) +} + +/// Send a `200 text/event-stream` response and block while the client observes +/// it. Each frame is flushed immediately; the stream closes after the single +/// terminal event so the browser never re-runs anything. +pub fn respond(request: Request, subscription: SseSubscription) -> ViewResult<()> { + let run_id = subscription.run_id.clone(); + let replay = subscription.replay.clone(); + let terminal = subscription.terminal; + let receiver = subscription.receiver; + let mut writer = request.into_writer(); + + let head = concat!( + "HTTP/1.1 200 OK\r\n", + "Content-Type: text/event-stream; charset=utf-8\r\n", + "Cache-Control: no-store\r\n", + "X-Accel-Buffering: no\r\n", + "X-Content-Type-Options: nosniff\r\n", + "Referrer-Policy: no-referrer\r\n", + "Connection: close\r\n", + "\r\n" + ); + if write_frame(&mut writer, head.as_bytes()).is_err() { + return Ok(()); + } + for frame in &replay { + if write_frame(&mut writer, frame.as_bytes()).is_err() { + return Ok(()); + } + } + let _ = run_id; + if terminal { + let _ = writer.flush(); + return Ok(()); + } + + let heartbeat = heartbeat_interval(); + let mut next_heartbeat = Instant::now() + heartbeat; + loop { + let now = Instant::now(); + let timeout = next_heartbeat.saturating_duration_since(now); + match receiver.recv_timeout(timeout) { + Ok(event) => { + let is_terminal = event.state.is_terminal(); + let frame = event.to_sse(&subscription.run_id); + if write_frame(&mut writer, frame.as_bytes()).is_err() { + return Ok(()); + } + if is_terminal { + let _ = writer.flush(); + return Ok(()); + } + } + Err(RecvTimeoutError::Timeout) => { + if write_frame(&mut writer, HEARTBEAT_FRAME.as_bytes()).is_err() { + return Ok(()); + } + next_heartbeat = Instant::now() + heartbeat; + } + Err(RecvTimeoutError::Disconnected) => { + let _ = writer.flush(); + return Ok(()); + } + } + if Instant::now() >= next_heartbeat { + if write_frame(&mut writer, HEARTBEAT_FRAME.as_bytes()).is_err() { + return Ok(()); + } + next_heartbeat = Instant::now() + heartbeat; + } + } +} + +fn write_frame(writer: &mut Box, frame: &[u8]) -> std::io::Result<()> { + writer.write_all(frame)?; + writer.flush() +} + +/// Kept as a named constant for the transport tests/documentation. +pub fn headers() -> [(&'static str, &'static str); 4] { + [ + ("Content-Type", "text/event-stream; charset=utf-8"), + ("Cache-Control", "no-store"), + ("X-Accel-Buffering", "no"), + ("X-Content-Type-Options", "nosniff"), + ] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn heartbeat_interval_is_fifteen_seconds_by_default() { + std::env::remove_var("MARQDO_VIEW_SSE_HEARTBEAT_SECS"); + assert_eq!(heartbeat_interval(), Duration::from_secs(15)); + } + + #[test] + fn headers_are_the_sse_contract() { + let headers = headers(); + assert_eq!(headers[0].1, "text/event-stream; charset=utf-8"); + assert_eq!(headers[1].1, "no-store"); + assert_eq!(headers[2].1, "no"); + } +} diff --git a/tests/browser/reader.browser.cjs b/tests/browser/reader.browser.cjs index 19eaec5..ce0103a 100644 --- a/tests/browser/reader.browser.cjs +++ b/tests/browser/reader.browser.cjs @@ -166,15 +166,28 @@ function localHostOnly(url) { check("GFM table rendered", (await page.locator(".mq-document table").count()) >= 1); } + // Simple theme switch (RFC §1.2 MVP SMALL) persists and stays readable. + await page.click('.mq-dock-btn[data-action="settings"]'); + await page.click('#mq-dialog-settings [data-action="theme"]'); + check("dark theme applied", (await page.getAttribute("body", "data-theme")) === "dark"); + await page.reload({ waitUntil: "networkidle" }); + check( + "theme preference persisted", + (await page.getAttribute("body", "data-theme")) === "dark" + ); + await page.click('.mq-dock-btn[data-action="settings"]'); + await page.click('#mq-dialog-settings [data-action="theme"]'); + check("paper theme restored", (await page.getAttribute("body", "data-theme")) === "light"); + // Responsive geometry: no horizontal overflow; dock inside viewport. + // RFC-VIEW-0002 §9.3 visual matrix: the source reference is 2048x1133. const widths = [ - [390, 844], - [600, 800], - [900, 768], - [1280, 800], + [2048, 1133], [1664, 920], - [1920, 1080], - [2560, 1440], + [1440, 900], + [1024, 768], + [768, 1024], + [390, 844], ]; for (const [width, height] of widths) { await page.setViewportSize({ width, height }); @@ -206,7 +219,11 @@ function localHostOnly(url) { await nojsPage.goto(base, { waitUntil: "load" }); const nojsText = await nojsPage.locator(".mq-document").innerText(); check("no-JS document remains readable", nojsText.trim().length > 20); - check("no-JS has no fake run panel", (await nojsPage.locator("#mq-run-panel").count()) === 0); + check( + "no-JS exposes no active run UI", + !(await nojsPage.locator("#mq-run-panel").isVisible()) && + (await nojsPage.locator('.mq-dock-btn[data-action="run"]').count()) === 1 + ); await nojs.close(); // Print hides chrome but keeps prose. @@ -219,31 +236,44 @@ function localHostOnly(url) { // Explicit run flow, only against the control-flow example. if (projectName === "control-flow") { + const runRequests = []; + page.on("request", (request) => { + if (request.url().includes("/api/runs")) runRequests.push(request.url()); + }); await page.click('.mq-dock-btn[data-action="run"]'); - check("run confirm dialog opens", await page.locator("#mq-dialog-run-confirm").isVisible()); - const dialogText = await page.locator("#mq-dialog-run-confirm").innerText(); - check("confirm mentions pure mode", dialogText.includes("pure")); + check("run dialog opens", await page.locator("#mq-dialog-run").isVisible()); + const dialogText = await page.locator("#mq-dialog-run").innerText(); + check("run dialog mentions pure mode", dialogText.includes("pure")); + check( + "run dialog previews the command", + (await page.locator("#mq-run-command").innerText()).includes("marqdo run") + ); await page.click('[data-action="run-confirm"]'); - await page.waitForURL(/run=/, { timeout: 30000 }); - await page.waitForLoadState("networkidle"); - check("run state succeeded", (await page.getAttribute("body", "data-run-state")) === "succeeded"); - check("run panel rendered", await page.locator("#mq-run-panel").isVisible()); + await page.waitForSelector('body[data-run-state="succeeded"]', { timeout: 30000 }); + // SSE delivered the terminal state without a page reload. + check("run state succeeded via SSE", (await page.getAttribute("body", "data-run-state")) === "succeeded"); + check("run panel visible", await page.locator("#mq-run-panel").isVisible()); check("run chips anchored", (await page.locator(".mq-run-chip").count()) > 0); check( "trace event list rendered", - (await page.locator(".mq-run-events li").count()) > 0 + (await page.locator("#mq-run-events li").count()) > 0 ); check( "stdout rendered escaped", - (await page.locator(".mq-stdout").first().innerText()).includes("0") + (await page.locator("#mq-run-stdout").innerText()).includes("0") + ); + check( + "no polling API was used", + runRequests.every((url) => !url.includes("status")), + runRequests.join(", ") ); if (screenshotDir) { await page.screenshot({ path: path.join(screenshotDir, "control-flow-run.png") }); } - // Clear run removes the display and the URL marker. - await page.click('[data-action="clear-run"]'); - await page.waitForURL((url) => !url.searchParams.has("run"), { timeout: 15000 }); - check("clear run removes panel", (await page.locator("#mq-run-panel").count()) === 0); + // Clear run hides the display and keeps the project untouched. + await page.click('.mq-dock-btn[data-action="clear"]'); + check("clear hides run panel", !(await page.locator("#mq-run-panel").isVisible())); + check("page was never reloaded by the run", (await page.title()).includes("Marqdo")); } await browser.close(); diff --git a/tests/common/http.rs b/tests/common/http.rs new file mode 100644 index 0000000..5e5120d --- /dev/null +++ b/tests/common/http.rs @@ -0,0 +1,419 @@ +//! Raw HTTP/1.1 test client for the Live server (no extra dependencies). +//! +//! Provides one-shot requests and a chunked SSE reader, so integration and +//! security suites exercise the real server process, real cookies, real +//! headers and the real `text/event-stream` transport. + +#![allow(dead_code)] + +use super::{view_bin, FakeCore}; +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::TcpStream; +use std::process::{Child, Command, Stdio}; +use std::time::{Duration, Instant}; + +pub struct TestServer { + pub child: Child, + pub port: u16, + pub core: FakeCore, +} + +impl Drop for TestServer { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +/// Start the real `marqdo-view` binary on an OS-chosen loopback port with a +/// scripted fake Core. Golden Analysis must match the project's exact source. +pub fn start( + project: &str, + analysis_golden: &str, + run_golden: Option<&str>, + trace_golden: Option<&str>, +) -> TestServer { + start_with_env(project, analysis_golden, run_golden, trace_golden, &[]) +} + +pub fn start_with_env( + project: &str, + analysis_golden: &str, + run_golden: Option<&str>, + trace_golden: Option<&str>, + envs: &[(&str, &str)], +) -> TestServer { + use std::sync::atomic::{AtomicUsize, Ordering}; + static NEXT: AtomicUsize = AtomicUsize::new(0); + let seq = NEXT.fetch_add(1, Ordering::Relaxed); + let repo_root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let core = FakeCore::new(&format!("http-core-{seq}")); + let golden = std::fs::read(repo_root.join(analysis_golden)).unwrap(); + core.set_analysis(std::str::from_utf8(&golden).unwrap()); + if let Some(run_golden) = run_golden { + let run = std::fs::read_to_string(repo_root.join(run_golden)).unwrap(); + let trace = + trace_golden.map(|trace| std::fs::read_to_string(repo_root.join(trace)).unwrap()); + core.set_run(0, &run, trace.as_deref()); + } + + let mut command = Command::new(view_bin()); + command + .current_dir(&repo_root) + .args([project, "--port", "0", "--no-open", "--marqdo-bin"]) + .arg(&core.script) + .env_remove("MARQDO_BIN") + .env_remove("MARQDO_TOOL_PROTOCOL") + .env_remove("MARQDO_PROTOCOL_ANALYSIS") + .env_remove("MARQDO_PROTOCOL_TRACE") + .stdout(Stdio::null()) + .stderr(Stdio::piped()); + for (key, value) in envs { + command.env(key, value); + } + let mut child = command.spawn().expect("spawn marqdo-view"); + let stderr = child.stderr.take().expect("piped stderr"); + let mut reader = BufReader::new(stderr); + let deadline = Instant::now() + Duration::from_secs(10); + let mut url: Option = None; + while Instant::now() < deadline { + let mut line = String::new(); + if reader.read_line(&mut line).unwrap_or(0) == 0 { + break; + } + if let Some(rest) = line.trim().strip_prefix("marqdo view: ") { + url = Some(rest.to_string()); + break; + } + } + let url = url.expect("server printed its URL"); + let port: u16 = url + .trim_end_matches('/') + .rsplit(':') + .next() + .expect("port in url") + .parse() + .expect("numeric port"); + let debug = std::env::var("MQ_TEST_DEBUG").is_ok(); + std::thread::spawn(move || { + if debug { + for line in reader.lines().map_while(Result::ok) { + eprintln!("[server] {line}"); + } + } else { + let mut sink = String::new(); + let _ = reader.read_to_string(&mut sink); + } + }); + TestServer { child, port, core } +} + +#[derive(Debug)] +pub struct HttpResponse { + pub status: u16, + pub headers: String, + pub body: String, +} + +impl HttpResponse { + pub fn header(&self, name: &str) -> Option { + self.headers.lines().find_map(|line| { + let (key, value) = line.split_once(':')?; + if key.eq_ignore_ascii_case(name) { + Some(value.trim().to_string()) + } else { + None + } + }) + } + + pub fn json(&self) -> serde_json::Value { + serde_json::from_str(&self.body) + .unwrap_or_else(|err| panic!("json body {err}: {}", self.body)) + } + + pub fn set_cookie(&self) -> Option { + self.header("Set-Cookie") + } +} + +pub fn get(port: u16, path: &str) -> HttpResponse { + request(port, "GET", path, &[], None) +} + +pub fn get_with_host(port: u16, path: &str, host: &str) -> HttpResponse { + let mut stream = TcpStream::connect(("127.0.0.1", port)).expect("connect"); + let head = format!("GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n"); + stream.write_all(head.as_bytes()).expect("write request"); + let mut raw = Vec::new(); + stream.read_to_end(&mut raw).expect("read response"); + parse_response(&raw) +} + +pub fn post(port: u16, path: &str, headers: &[(&str, String)], body: Option<&str>) -> HttpResponse { + request(port, "POST", path, headers, body) +} + +pub fn request( + port: u16, + method: &str, + path: &str, + headers: &[(&str, String)], + body: Option<&str>, +) -> HttpResponse { + let mut stream = TcpStream::connect(("127.0.0.1", port)).expect("connect"); + let host = format!("127.0.0.1:{port}"); + write_request(&mut stream, &host, method, path, headers, body, true); + let mut raw = Vec::new(); + stream.read_to_end(&mut raw).expect("read response"); + parse_response(&raw) +} + +fn parse_response(raw: &[u8]) -> HttpResponse { + let text = String::from_utf8_lossy(raw).to_string(); + let (head, body) = text.split_once("\r\n\r\n").unwrap_or((&text, "")); + let status = head + .lines() + .next() + .and_then(|line| line.split_whitespace().nth(1)) + .and_then(|code| code.parse().ok()) + .unwrap_or(0); + HttpResponse { + status, + headers: head.to_string(), + body: body.to_string(), + } +} + +fn write_request( + stream: &mut TcpStream, + host: &str, + method: &str, + path: &str, + headers: &[(&str, String)], + body: Option<&str>, + close: bool, +) { + let mut head = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nAccept: */*\r\n"); + if close { + head.push_str("Connection: close\r\n"); + } + for (name, value) in headers { + head.push_str(&format!("{name}: {value}\r\n")); + } + if let Some(body) = body { + head.push_str(&format!("Content-Length: {}\r\n", body.len())); + } + head.push_str("\r\n"); + stream.write_all(head.as_bytes()).expect("write headers"); + if let Some(body) = body { + stream.write_all(body.as_bytes()).expect("write body"); + } + stream.flush().expect("flush request"); +} + +/// One parsed SSE frame (or heartbeat comment). +#[derive(Debug, Clone)] +pub struct SseFrame { + pub event: String, + pub id: Option, + pub data: Option, +} + +pub struct SseReader { + reader: BufReader, + pending: String, + pub headers: String, + pub status: u16, +} + +impl SseReader { + pub fn open(port: u16, path: &str, headers: &[(&str, String)]) -> SseReader { + let mut stream = TcpStream::connect(("127.0.0.1", port)).expect("connect sse"); + stream + .set_read_timeout(Some(Duration::from_secs(15))) + .expect("read timeout"); + let host = format!("127.0.0.1:{port}"); + write_request(&mut stream, &host, "GET", path, headers, None, false); + let mut reader = BufReader::new(stream); + let mut head = String::new(); + loop { + let mut line = String::new(); + reader.read_line(&mut line).expect("read sse header"); + if line == "\r\n" || line == "\n" { + break; + } + head.push_str(&line); + } + let status = head + .lines() + .next() + .and_then(|line| line.split_whitespace().nth(1)) + .and_then(|code| code.parse().ok()) + .unwrap_or(0); + SseReader { + reader, + pending: String::new(), + headers: head, + status, + } + } + + pub fn header(&self, name: &str) -> Option { + self.headers.lines().find_map(|line| { + let (key, value) = line.split_once(':')?; + if key.eq_ignore_ascii_case(name) { + Some(value.trim().to_string()) + } else { + None + } + }) + } + + /// Next frame/heartbeat; `None` on stream end or read failure. + pub fn next_frame(&mut self) -> Option { + loop { + let mut line = String::new(); + match self.reader.read_line(&mut line) { + Ok(0) => return None, + Ok(_) => {} + Err(_) => return None, + } + let trimmed = line.trim_end_matches(['\r', '\n']); + if trimmed.is_empty() { + if self.pending.is_empty() { + continue; + } + let frame = std::mem::take(&mut self.pending); + let mut event = "message".to_string(); + let mut id = None; + let mut data_lines: Vec = Vec::new(); + for line in frame.lines() { + if let Some(value) = line.strip_prefix("event: ") { + event = value.trim().to_string(); + } else if let Some(value) = line.strip_prefix("id: ") { + id = value.trim().parse::().ok(); + } else if let Some(value) = line.strip_prefix("data: ") { + data_lines.push(value.to_string()); + } else if line.starts_with(':') { + event = "heartbeat".to_string(); + } + } + let data = if data_lines.is_empty() { + None + } else { + serde_json::from_str(&data_lines.join("\n")).ok() + }; + return Some(SseFrame { event, id, data }); + } + self.pending.push_str(&line); + } + } +} + +/// One authenticated browser session: cookie + CSRF + current Analysis digest. +pub struct Session { + pub cookie: String, + pub csrf: String, + pub digest: String, +} + +pub fn open_session(server: &TestServer, path: &str) -> (Session, HttpResponse) { + let page = get(server.port, path); + assert_eq!(page.status, 200, "body: {}", page.body); + let cookie = page + .set_cookie() + .and_then(|cookie| cookie.split(';').next().map(str::to_string)) + .expect("Set-Cookie"); + let csrf = page + .body + .split("name=\"mq-csrf-token\" content=\"") + .nth(1) + .and_then(|rest| rest.split('"').next()) + .expect("csrf meta") + .to_string(); + let digest = page + .body + .split("data-analysis-digest=\"") + .nth(1) + .and_then(|rest| rest.split('"').next()) + .expect("analysis digest attr") + .to_string(); + ( + Session { + cookie, + csrf, + digest, + }, + page, + ) +} + +pub fn run_body( + document: &str, + digest: &str, + target: serde_json::Value, + client_id: &str, +) -> String { + serde_json::json!({ + "document": document, + "target": target, + "parameters": [], + "analysis_digest": digest, + "mode": "pure", + "grants": {"read": [], "write": []}, + "client_request_id": client_id, + }) + .to_string() +} + +pub fn post_headers( + server: &TestServer, + session: &Session, + json: bool, +) -> Vec<(&'static str, String)> { + let mut headers = vec![ + ("Cookie", session.cookie.clone()), + ("Origin", format!("http://127.0.0.1:{}", server.port)), + ("X-View-CSRF", session.csrf.clone()), + ]; + if json { + headers.push(("Content-Type", "application/json".to_string())); + } + headers +} + +pub fn submit(server: &TestServer, session: &Session, body: &str) -> HttpResponse { + post( + server.port, + "/api/runs", + &post_headers(server, session, true), + Some(body), + ) +} + +pub fn collect_until_terminal(reader: &mut SseReader) -> Vec { + let mut frames = Vec::new(); + let deadline = Instant::now() + Duration::from_secs(20); + while Instant::now() < deadline { + let Some(frame) = reader.next_frame() else { + break; + }; + let terminal = frame + .data + .as_ref() + .and_then(|data| data["state"].as_str()) + .map(|state| { + matches!( + state, + "succeeded" | "failed" | "cancelled" | "timed_out" | "unavailable" + ) + }) + .unwrap_or(false); + frames.push(frame); + if terminal { + break; + } + } + frames +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 09a93ed..25c5f80 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -1,4 +1,4 @@ -//! Shared test helpers for integration tests. +//! Shared test helpers for integration and security suites. //! //! Fake cores are real executables (never mocked Rust traits at the process //! boundary) so argv, exit codes, stderr and temp artifacts are all exercised. @@ -236,3 +236,5 @@ pub fn sha256_hex(bytes: &[u8]) -> String { } out } + +pub mod http; diff --git a/tests/integration/http_live.rs b/tests/integration/http_live.rs index 81e4069..237d34e 100644 --- a/tests/integration/http_live.rs +++ b/tests/integration/http_live.rs @@ -1,30 +1,30 @@ -//! Live server tests over a raw TCP HTTP/1.1 client (no extra deps). -//! The server is a real child process so startup, URL output, routing, security -//! headers, CSRF and the explicit-run flow are exercised end to end. +//! Live HTTP/SSE integration tests over a raw HTTP client. +//! +//! The server is a real child process, the fake Core is a real executable and +//! every assertion goes through real cookies, CSRF headers, Origin checks and +//! the chunked `text/event-stream` transport. -use crate::common; - -use common::{run_view, FakeCore}; -use std::io::{BufRead, BufReader, Read, Write}; -use std::net::TcpStream; -use std::process::{Child, Command, Stdio}; +use crate::common::http::{ + self, collect_until_terminal, open_session, post_headers, run_body, submit, SseFrame, + TestServer, +}; use std::time::{Duration, Instant}; -struct LiveServer { - child: Child, - port: u16, - _core: FakeCore, +const RUN_GOLDEN: &str = "tests/golden/trace-v2/control-flow.run.json"; +const TRACE_GOLDEN: &str = "tests/golden/trace-v2/control-flow.trace.json"; +const ANALYSIS_GOLDEN: &str = "tests/golden/analysis-v2/control-flow.json"; + +fn control_flow() -> TestServer { + http::start( + "examples/control-flow", + ANALYSIS_GOLDEN, + Some(RUN_GOLDEN), + Some(TRACE_GOLDEN), + ) } -impl Drop for LiveServer { - fn drop(&mut self) { - let _ = self.child.kill(); - let _ = self.child.wait(); - } -} - -fn start_server() -> LiveServer { - start_server_with( +fn welcome() -> TestServer { + http::start( "examples/welcome", "tests/golden/analysis-v2/welcome.json", None, @@ -32,558 +32,409 @@ fn start_server() -> LiveServer { ) } -fn start_server_with( - project: &str, - analysis_golden: &str, - run_golden: Option<&str>, - trace_golden: Option<&str>, -) -> LiveServer { - use std::sync::atomic::{AtomicUsize, Ordering}; - static NEXT: AtomicUsize = AtomicUsize::new(0); - let seq = NEXT.fetch_add(1, Ordering::Relaxed); - let repo_root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let core = FakeCore::new(&format!("live-core-{seq}")); - let golden = std::fs::read(repo_root.join(analysis_golden)).unwrap(); - core.set_analysis(std::str::from_utf8(&golden).unwrap()); - if let Some(run_golden) = run_golden { - let run = std::fs::read_to_string(repo_root.join(run_golden)).unwrap(); - let trace = - trace_golden.map(|trace| std::fs::read_to_string(repo_root.join(trace)).unwrap()); - core.set_run(0, &run, trace.as_deref()); - } - - let mut child = Command::new(common::view_bin()) - .current_dir(&repo_root) - .args([project, "--port", "0", "--no-open", "--marqdo-bin"]) - .arg(&core.script) - .env_remove("MARQDO_BIN") - .env_remove("MARQDO_TOOL_PROTOCOL") - .env_remove("MARQDO_PROTOCOL_ANALYSIS") - .env_remove("MARQDO_PROTOCOL_TRACE") - .stdout(Stdio::null()) - .stderr(Stdio::piped()) - .spawn() - .expect("spawn marqdo-view"); - - let stderr = child.stderr.take().expect("piped stderr"); - let mut reader = BufReader::new(stderr); - let deadline = Instant::now() + Duration::from_secs(10); - let mut url: Option = None; - while Instant::now() < deadline { - let mut line = String::new(); - if reader.read_line(&mut line).unwrap_or(0) == 0 { - break; - } - if let Some(rest) = line.trim().strip_prefix("marqdo view: ") { - url = Some(rest.to_string()); - break; - } - } - let url = url.expect("server printed its URL"); - let port: u16 = url - .trim_end_matches('/') - .rsplit(':') - .next() - .expect("port in url") - .parse() - .expect("numeric port"); - // Keep draining stderr so the child never blocks on a full pipe. - std::thread::spawn(move || { - let mut sink = String::new(); - let _ = reader.read_to_string(&mut sink); - }); - - LiveServer { - child, - port, - _core: core, - } -} - -struct HttpResponse { - status: u16, - headers: String, - body: String, -} - -fn http_get(port: u16, host: Option<&str>, path: &str) -> HttpResponse { - http_request(port, host, "GET", path, &[], None) -} - -fn http_post(port: u16, path: &str, headers: &[(&str, String)], body: &str) -> HttpResponse { - http_request(port, None, "POST", path, headers, Some(body)) -} - -fn http_request( - port: u16, - host: Option<&str>, - method: &str, - path: &str, - headers: &[(&str, String)], - body: Option<&str>, -) -> HttpResponse { - let mut stream = TcpStream::connect(("127.0.0.1", port)).expect("connect"); - let host = host - .map(str::to_string) - .unwrap_or_else(|| format!("127.0.0.1:{port}")); - let mut request = - format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\nAccept: */*\r\n"); - for (name, value) in headers { - request.push_str(&format!("{name}: {value}\r\n")); - } - if let Some(body) = body { - request.push_str(&format!("Content-Length: {}\r\n", body.len())); - } - request.push_str("\r\n"); - if let Some(body) = body { - request.push_str(body); - } - stream.write_all(request.as_bytes()).expect("write request"); - let mut raw = Vec::new(); - stream.read_to_end(&mut raw).expect("read response"); - let text = String::from_utf8_lossy(&raw).to_string(); - let (head, body) = text.split_once("\r\n\r\n").unwrap_or((&text, "")); - let status = head - .lines() - .next() - .and_then(|line| line.split_whitespace().nth(1)) - .and_then(|code| code.parse().ok()) - .unwrap_or(0); - HttpResponse { - status, - headers: head.to_string(), - body: body.to_string(), - } -} - -fn csrf_token(page: &str) -> String { - page.split("name=\"mq-csrf-token\" content=\"") - .nth(1) - .and_then(|rest| rest.split('"').next()) - .expect("csrf meta token") - .to_string() -} - -fn json_body(page: &str) -> serde_json::Value { - serde_json::from_str(page).expect("json body") -} - #[test] -fn live_server_serves_pages_assets_and_health() { - let server = start_server(); - let page = http_get(server.port, None, "/"); +fn pages_issue_a_session_cookie_and_never_execute_the_document() { + let server = welcome(); + let (session, page) = open_session(&server, "/"); assert_eq!(page.status, 200); assert!(page.headers.contains("Content-Type: text/html")); assert!(page.headers.contains("Content-Security-Policy")); - assert!(page.headers.contains("X-Content-Type-Options: nosniff")); + assert!(page.headers.contains("default-src 'self'")); + assert!(page.headers.contains("connect-src 'self'")); assert!(page.body.contains("mq-reader")); - assert!(page.body.contains("欢迎来到 Marqdo")); assert!(page.body.contains("data-live=\"true\"")); + assert!(page + .body + .contains(&format!("data-analysis-digest=\"{}\"", session.digest))); assert!(page.body.contains("mq-csrf-token")); - assert!(page.body.contains("data-run-available=\"false\"")); + assert!(page.body.contains("data-action=\"run\"")); + assert!(page.body.contains("mq-dialog-run\"")); + assert!(!page.body.contains("/api/run\"")); + // Repeated page loads with the same cookie must never run the document. + for _ in 0..10 { + let repeated = http::request( + server.port, + "GET", + "/", + &[("Cookie", session.cookie.clone())], + None, + ); + assert_eq!(repeated.status, 200); + } + assert!(!server.core.dir.join("run-was-called").exists()); +} + +#[test] +fn read_only_routes_are_the_target_contract_and_old_routes_are_gone() { + let server = welcome(); + let documents = http::get(server.port, "/api/documents"); + assert_eq!(documents.status, 200); + let body = documents.json(); + assert_eq!(body["schema"], "marqdo.view-documents"); + assert_eq!(body["schema_version"], 1); + assert!(body["documents"].as_array().unwrap().len() >= 2); + assert!(body["note"].as_str().unwrap().contains("never executes")); + + for stale in ["/api/health", "/api/document?path=index.mq.md", "/api/run"] { + let response = http::get(server.port, stale); + assert_eq!(response.status, 404, "{stale} must be gone"); + } + let run_get = http::get(server.port, "/api/runs/deadbeef/events"); + assert_eq!(run_get.status, 401, "SSE requires a session"); +} + +#[test] +fn assets_are_immutable_and_carry_strict_headers() { + let server = welcome(); + let (_, page) = open_session(&server, "/"); let css_path = page .body .split("href=\"/assets/") .nth(1) .and_then(|rest| rest.split('"').next()) .expect("css link"); - let css = http_get(server.port, None, &format!("/assets/{css_path}")); + let css = http::get(server.port, &format!("/assets/{css_path}")); assert_eq!(css.status, 200); assert!(css.headers.contains("text/css")); - assert!(css.body.contains("@layer tokens")); assert!(css.headers.contains("immutable")); + assert!(css.headers.contains("X-Content-Type-Options: nosniff")); - let health = http_get(server.port, None, "/api/health"); - assert_eq!(health.status, 200); - let health = json_body(&health.body); - assert_eq!(health["schema"], "marqdo.view-health"); - assert_eq!(health["protocols"]["analysis"], 2); - assert_eq!(health["run_api"], true); - - let document = http_get(server.port, None, "/file?path=guide.mq.md"); - assert_eq!(document.status, 200); - assert!(document.body.contains("阅读指南")); -} - -#[test] -fn live_server_rejects_dns_rebinding_and_path_escape() { - let server = start_server(); - let bad_host = http_get(server.port, Some("attacker.example"), "/"); - assert_eq!(bad_host.status, 400); - - for path in [ - "/file?path=../secret.mq.md", - "/file?path=%2e%2e%2fsecret.mq.md", - "/file?path=/etc/passwd", - "/file?path=..%2f..%2fetc%2fpasswd", - ] { - let response = http_get(server.port, None, path); - assert!( - response.status == 403 || response.status == 404, - "path {path} returned {}", - response.status - ); - } - - let missing = http_get(server.port, None, "/file?path=missing.mq.md"); + let missing = http::get(server.port, "/assets/nope.css"); assert_eq!(missing.status, 404); - let unknown = http_get(server.port, None, "/api/run"); - assert_eq!(unknown.status, 404); } #[test] -fn live_server_rejects_unknown_methods_and_bad_assets() { - let server = start_server(); - let mut stream = TcpStream::connect(("127.0.0.1", server.port)).expect("connect"); - let request = format!( - "PUT /api/run HTTP/1.1\r\nHost: 127.0.0.1:{}\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}", - server.port +fn explicit_run_streams_sse_accepted_running_and_terminal_with_verified_trace() { + let server = control_flow(); + let (session, _) = open_session(&server, "/"); + let body = run_body( + "index.mq.md", + &session.digest, + serde_json::json!({"kind": "entry"}), + "req-sse", ); - stream.write_all(request.as_bytes()).unwrap(); - let mut raw = Vec::new(); - stream.read_to_end(&mut raw).unwrap(); - let text = String::from_utf8_lossy(&raw); - assert!(text.starts_with("HTTP/1.1 405"), "{text}"); + let accepted = submit(&server, &session, &body); + assert_eq!(accepted.status, 202, "body: {}", accepted.body); + let accepted = accepted.json(); + let run_id = accepted["run_id"].as_str().expect("run id").to_string(); + assert_eq!(accepted["state"], "accepted"); + assert_eq!(accepted["events_url"], format!("/api/runs/{run_id}/events")); + assert_eq!(accepted["cancel_url"], format!("/api/runs/{run_id}/cancel")); + assert_eq!(accepted["reused"], false); - let bad_asset = http_get(server.port, None, "/assets/../../etc/passwd"); - assert_eq!(bad_asset.status, 404); -} - -#[test] -fn opening_and_refreshing_never_runs_the_document() { - // R-01: ten page loads must produce zero Core `run` invocations. - let server = start_server_with( - "examples/control-flow", - "tests/golden/analysis-v2/control-flow.json", - Some("tests/golden/trace-v2/control-flow.run.json"), - Some("tests/golden/trace-v2/control-flow.trace.json"), + let mut reader = http::SseReader::open( + server.port, + &format!("/api/runs/{run_id}/events"), + &[("Cookie", session.cookie.clone())], ); - for _ in 0..10 { - let page = http_get(server.port, None, "/"); - assert_eq!(page.status, 200); - assert!(page.body.contains("data-run-state=\"not-run\"")); - assert!(!page.body.contains("mq-run-panel")); - } - let args = server._core.argv_lines(); - let run_calls = args + assert_eq!(reader.status, 200); + assert!(reader + .header("Content-Type") + .unwrap() + .contains("text/event-stream")); + assert!(reader.header("Cache-Control").unwrap().contains("no-store")); + let frames = collect_until_terminal(&mut reader); + assert!(!frames.is_empty()); + let mut ids = frames .iter() - .filter(|line| line.as_str() == "arg=run") - .count(); - assert_eq!(run_calls, 0, "page loads must never call Core run"); -} - -fn run_and_get_page(server: &LiveServer) -> (String, String) { - let page = http_get(server.port, None, "/"); - let token = csrf_token(&page.body); - let response = http_post( - server.port, - "/api/run", - &[ - ("Content-Type", "application/json".to_string()), - ("X-MQ-CSRF", token.clone()), - ], - r#"{"path":"index.mq.md","mode":"pure","confirm":true}"#, - ); - assert_eq!(response.status, 200, "body: {}", response.body); - let json = json_body(&response.body); - assert_eq!(json["ok"], true); - let redirect = json["redirect"].as_str().expect("redirect").to_string(); - let run_page = http_get(server.port, None, &redirect); - assert_eq!(run_page.status, 200); - (token, run_page.body) -} - -#[test] -fn explicit_run_requires_csrf_and_confirm_then_renders_real_trace() { - let server = start_server_with( - "examples/control-flow", - "tests/golden/analysis-v2/control-flow.json", - Some("tests/golden/trace-v2/control-flow.run.json"), - Some("tests/golden/trace-v2/control-flow.trace.json"), - ); - let (_, page) = run_and_get_page(&server); - assert!(page.contains("mq-run-panel")); - assert!(page.contains("data-run-state=\"succeeded\"")); - assert!(page.contains("真实 Trace v2 事件")); - assert!(page.contains("mq-run-chip"), "inline run chips expected"); - assert!( - page.contains("0\n0\n2"), - "Core stdout must be shown escaped" - ); - // Public JSON final value is allowed; per-statement values are not claimed. - assert!(page.contains("Core 本次返回值")); - assert!(page.contains("3")); - assert!( - !page.contains("变量值"), - "must not claim per-assignment values" - ); - - let args = server._core.argv_lines(); - let run_calls = args + .filter_map(|frame| frame.id) + .collect::>(); + assert!(ids.windows(2).all(|pair| pair[0] < pair[1]), "ids: {ids:?}"); + ids.dedup(); + let terminal = frames.last().expect("terminal frame"); + let data = terminal.data.as_ref().expect("terminal data"); + assert_eq!(data["schema"], "marqdo.view-run-events"); + assert_eq!(data["schema_version"], 1); + assert_eq!(data["run_id"], run_id.as_str()); + assert_eq!(data["state"], "succeeded"); + assert_eq!(data["result"]["success"], true); + assert_eq!(data["trace"]["status"], "verified"); + assert!(!data["trace"]["events"].as_array().unwrap().is_empty()); + let states: Vec<_> = frames .iter() - .filter(|line| line.as_str() == "arg=run") - .count(); - assert_eq!(run_calls, 1, "exactly one explicit run expected"); - assert!(args.iter().any(|line| line == "arg=pure")); - assert!(args.iter().any(|line| line == "arg=--trace-file")); + .filter_map(|frame| frame.data.as_ref().and_then(|data| data["state"].as_str())) + .collect(); + assert!(frame_state(&frames, "accepted"), "states: {states:?}"); + assert!(frame_state(&frames, "running"), "states: {states:?}"); + assert!(server.core.dir.join("run-was-called").exists()); } -#[test] -fn run_api_rejects_missing_token_wrong_origin_and_bad_requests() { - let server = start_server_with( - "examples/control-flow", - "tests/golden/analysis-v2/control-flow.json", - Some("tests/golden/trace-v2/control-flow.run.json"), - Some("tests/golden/trace-v2/control-flow.trace.json"), - ); - let body = r#"{"path":"index.mq.md","mode":"pure","confirm":true}"#; - - let no_token = http_post( - server.port, - "/api/run", - &[("Content-Type", "application/json".to_string())], - body, - ); - assert_eq!(no_token.status, 403); - assert!(no_token.body.contains("view.run_denied")); - - let page = http_get(server.port, None, "/"); - let token = csrf_token(&page.body); - let wrong_origin = http_post( - server.port, - "/api/run", - &[ - ("Content-Type", "application/json".to_string()), - ("X-MQ-CSRF", token.clone()), - ("Origin", "https://attacker.example".to_string()), - ], - body, - ); - assert_eq!(wrong_origin.status, 403); - - let no_confirm = http_post( - server.port, - "/api/run", - &[ - ("Content-Type", "application/json".to_string()), - ("X-MQ-CSRF", token.clone()), - ], - r#"{"path":"index.mq.md","mode":"pure","confirm":false}"#, - ); - assert_eq!(no_confirm.status, 400); - - let project_mode = http_post( - server.port, - "/api/run", - &[ - ("Content-Type", "application/json".to_string()), - ("X-MQ-CSRF", token.clone()), - ], - r#"{"path":"index.mq.md","mode":"project","confirm":true}"#, - ); - assert_eq!(project_mode.status, 403); - assert!(project_mode.body.contains("view.run_denied")); - // Public errors never leak absolute paths or raw subprocess text. - assert!( - !project_mode.body.contains("/root/"), - "{}", - project_mode.body - ); - - let args = server._core.argv_lines(); - let run_calls = args +fn frame_state(frames: &[SseFrame], wanted: &str) -> bool { + frames .iter() - .filter(|line| line.as_str() == "arg=run") + .any(|frame| frame.data.as_ref().and_then(|data| data["state"].as_str()) == Some(wanted)) +} + +#[test] +fn last_event_id_replays_only_newer_events_and_old_cursor_gets_snapshot() { + let server = control_flow(); + let (session, _) = open_session(&server, "/"); + let body = run_body( + "index.mq.md", + &session.digest, + serde_json::json!({"kind": "entry"}), + "req-replay", + ); + let accepted = submit(&server, &session, &body).json(); + let run_id = accepted["run_id"].as_str().unwrap().to_string(); + let mut reader = http::SseReader::open( + server.port, + &format!("/api/runs/{run_id}/events"), + &[("Cookie", session.cookie.clone())], + ); + let frames = collect_until_terminal(&mut reader); + let first_seq = frames.first().and_then(|frame| frame.id).unwrap_or(0); + assert!(first_seq >= 1); + + // Reconnect with a valid cursor inside the buffer: only newer events. + let mut reader = http::SseReader::open( + server.port, + &format!("/api/runs/{run_id}/events"), + &[ + ("Cookie", session.cookie.clone()), + ("Last-Event-ID", first_seq.to_string()), + ], + ); + let replay = collect_until_terminal(&mut reader); + assert!(replay.iter().all(|frame| frame.id.unwrap_or(0) > first_seq)); + assert_eq!( + replay.last().unwrap().data.as_ref().unwrap()["state"], + "succeeded" + ); + + // A forged/too-new cursor gets an authoritative snapshot, never fake history. + let mut reader = http::SseReader::open( + server.port, + &format!("/api/runs/{run_id}/events"), + &[ + ("Cookie", session.cookie.clone()), + ("Last-Event-ID", "999999".to_string()), + ], + ); + let snapshot = reader.next_frame().expect("snapshot frame"); + assert_eq!(snapshot.event, "run.snapshot"); + let data = snapshot.data.as_ref().unwrap(); + assert_eq!(data["run_id"], run_id.as_str()); + assert!(data["seq"].as_u64().unwrap() > 0); +} + +#[test] +fn duplicate_request_id_is_idempotent_and_busy_or_conflict_never_starts_a_second_process() { + let server = control_flow(); + server.core.set_sleep_seconds(2); + let (session, _) = open_session(&server, "/"); + let body = run_body( + "index.mq.md", + &session.digest, + serde_json::json!({"kind": "entry"}), + "req-dedupe-http", + ); + let first = submit(&server, &session, &body).json(); + let second = submit(&server, &session, &body).json(); + assert_eq!(first["run_id"], second["run_id"]); + assert_eq!(second["reused"], true); + + let other = run_body( + "index.mq.md", + &session.digest, + serde_json::json!({"kind": "entry"}), + "req-busy-http", + ); + let busy = submit(&server, &session, &other); + assert_eq!(busy.status, 409); + assert_eq!(busy.json()["code"], "view.run_busy"); + + let mut changed: serde_json::Value = serde_json::from_str(&body).unwrap(); + changed["mode"] = serde_json::json!("project"); + let conflict = submit(&server, &session, changed.to_string().as_str()); + assert_eq!(conflict.status, 409); + assert_eq!(conflict.json()["code"], "view.run_conflict"); + + // Cancel the active job so the test process does not leave a child behind. + let cancel = http::post( + server.port, + first["cancel_url"].as_str().unwrap(), + &post_headers(&server, &session, false), + None, + ); + assert_eq!(cancel.status, 200); +} + +#[test] +fn cancel_is_idempotent_and_yields_one_terminal_state() { + let server = http::start_with_env( + "examples/control-flow", + ANALYSIS_GOLDEN, + Some(RUN_GOLDEN), + Some(TRACE_GOLDEN), + &[("MARQDO_VIEW_SSE_HEARTBEAT_SECS", "1")], + ); + server.core.set_sleep_seconds(10); + let (session, _) = open_session(&server, "/"); + let body = run_body( + "index.mq.md", + &session.digest, + serde_json::json!({"kind": "entry"}), + "req-cancel-http", + ); + let accepted = submit(&server, &session, &body).json(); + let run_id = accepted["run_id"].as_str().unwrap().to_string(); + let mut reader = http::SseReader::open( + server.port, + &format!("/api/runs/{run_id}/events"), + &[("Cookie", session.cookie.clone())], + ); + // Read at least one state so the job is observed as running or accepted. + let first = reader.next_frame().expect("first frame"); + assert!(first.data.is_some()); + + let started = Instant::now(); + let cancel = http::post( + server.port, + &format!("/api/runs/{run_id}/cancel"), + &post_headers(&server, &session, false), + None, + ); + eprintln!( + "CANCEL_DEBUG first={:?} cancel={:?} elapsed={:?}", + first, + cancel.json(), + started.elapsed() + ); + assert_eq!(cancel.status, 200); + let repeat = http::post( + server.port, + &format!("/api/runs/{run_id}/cancel"), + &post_headers(&server, &session, false), + None, + ); + assert_eq!(repeat.status, 200); + + let frames = collect_until_terminal(&mut reader); + let terminal_count = frames + .iter() + .filter(|frame| { + frame + .data + .as_ref() + .and_then(|data| data["state"].as_str()) + .map(|state| { + matches!( + state, + "succeeded" | "failed" | "cancelled" | "timed_out" | "unavailable" + ) + }) + .unwrap_or(false) + }) .count(); - assert_eq!(run_calls, 0, "rejected requests must never spawn a run"); + assert_eq!(terminal_count, 1); + assert_eq!( + frames.last().unwrap().data.as_ref().unwrap()["state"], + "cancelled" + ); + assert!(started.elapsed() < Duration::from_secs(8)); } #[test] -fn run_cache_can_be_cleared_and_stales_after_source_change() { - // Use a temporary copy so the test never mutates committed examples while - // other test binaries read them. - let repo_root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let project = common::TempProject::new("stale-run-project"); - project.write( - "marqdo.yaml", - "project:\n name: control-flow\n version: 0.1.0\n", +fn sse_heartbeats_keep_a_slow_job_connected() { + let server = http::start_with_env( + "examples/control-flow", + ANALYSIS_GOLDEN, + Some(RUN_GOLDEN), + Some(TRACE_GOLDEN), + &[("MARQDO_VIEW_SSE_HEARTBEAT_SECS", "1")], ); - let source = - std::fs::read_to_string(repo_root.join("examples/control-flow/index.mq.md")).unwrap(); - let source_path = project.write("index.mq.md", &source); - let project_path = project.dir.to_str().unwrap().to_string(); - let server = start_server_with( - &project_path, - "tests/golden/analysis-v2/control-flow.json", - Some("tests/golden/trace-v2/control-flow.run.json"), - Some("tests/golden/trace-v2/control-flow.trace.json"), + server.core.set_sleep_seconds(3); + let (session, _) = open_session(&server, "/"); + let body = run_body( + "index.mq.md", + &session.digest, + serde_json::json!({"kind": "entry"}), + "req-heartbeat", ); - - let page = http_get(server.port, None, "/"); - let token = csrf_token(&page.body); - let response = http_post( + let accepted = submit(&server, &session, &body).json(); + let run_id = accepted["run_id"].as_str().unwrap().to_string(); + let mut reader = http::SseReader::open( server.port, - "/api/run", - &[ - ("Content-Type", "application/json".to_string()), - ("X-MQ-CSRF", token.clone()), - ], - r#"{"path":"index.mq.md","mode":"pure","confirm":true}"#, + &format!("/api/runs/{run_id}/events"), + &[("Cookie", session.cookie.clone())], ); - let json = json_body(&response.body); - let run_id = json["run_id"].as_str().unwrap().to_string(); - let redirect = json["redirect"].as_str().unwrap().to_string(); - let run_page = http_get(server.port, None, &redirect); - assert!(run_page.body.contains("mq-run-panel")); - - let clear = http_post( - server.port, - "/api/clear-run", - &[ - ("Content-Type", "application/json".to_string()), - ("X-MQ-CSRF", token.clone()), - ], - &format!(r#"{{"run_id":"{run_id}"}}"#), - ); - assert_eq!(clear.status, 200); - let after_clear = http_get(server.port, None, &redirect); - assert!(!after_clear.body.contains("mq-run-panel")); - - // Run again, then change the source bytes. - let rerun = http_post( - server.port, - "/api/run", - &[ - ("Content-Type", "application/json".to_string()), - ("X-MQ-CSRF", token), - ], - r#"{"path":"index.mq.md","mode":"pure","confirm":true}"#, - ); - let rerun_json = json_body(&rerun.body); - let stale_redirect = rerun_json["redirect"].as_str().unwrap().to_string(); - std::fs::write( - &source_path, - format!("{source}\n\n"), - ) - .unwrap(); - let stale_page = http_get(server.port, None, &stale_redirect); - assert_eq!(stale_page.status, 200); + let frames = collect_until_terminal(&mut reader); assert!( - stale_page.body.contains("data-run-state=\"stale\"") - || stale_page - .body - .contains("data-source-status=\"source-mismatch\""), - "expected stale/source-mismatch marker" - ); - assert!(!stale_page.body.contains("mq-run-chip")); -} - -#[test] -fn truncated_trace_is_marked_not_claimed_complete() { - let server = start_server_with( - "examples/control-flow", - "tests/golden/analysis-v2/control-flow.json", - Some("tests/golden/trace-v2/control-flow.truncated.run.json"), - Some("tests/golden/trace-v2/control-flow.truncated.trace.json"), - ); - let (_, page) = run_and_get_page(&server); - assert!(page.contains("data-run-state=\"truncated\"")); - assert!(page.contains("Trace 被截断")); - assert!(!page.contains("data-run-state=\"succeeded\"")); -} - -#[test] -fn failed_run_reports_core_error_code_without_fake_success() { - let server = start_server_with( - "examples/mixed-modes", - "tests/golden/analysis-v2/mixed-modes.json", - Some("tests/golden/trace-v2/mixed-modes.arity.run.json"), - Some("tests/golden/trace-v2/mixed-modes.arity.trace.json"), - ); - // The fake core exits 0 for run, but the run JSON reports failure with the - // Core error code; View must surface that instead of a success state. - let (_, page) = run_and_get_page(&server); - assert!(page.contains("data-run-state=\"failed\"")); - assert!(page.contains("call.arity")); - assert!(!page.contains("data-run-state=\"succeeded\"")); -} - -#[test] -fn program_stdout_is_escaped_not_injected_as_markup() { - let tmp = std::path::PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!( - "hostile-stdout-{}-{}.json", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0) - )); - std::fs::write( - &tmp, - r#"{"command":"run","success":true,"stdout":"","stderr":"","trace":[],"value":{"type":"int","decimal":"3"}}"#, - ) - .unwrap(); - let server = start_server_with( - "examples/control-flow", - "tests/golden/analysis-v2/control-flow.json", - Some(tmp.to_str().unwrap()), - Some("tests/golden/trace-v2/control-flow.trace.json"), - ); - let (_, page) = run_and_get_page(&server); - assert!(page.contains("<script>alert(1)</script>")); - assert!(!page.contains("