Compare commits

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

No files matched your search

+7
View File
@@ -9,6 +9,13 @@ loop, 7-route Live API, controlled project grants and Trace-bound annotations).
The earlier `0.1.0` development line was never published; its verified reader / The earlier `0.1.0` development line was never published; its verified reader /
Analysis / export work is folded into this entry. Analysis / export work is folded into this entry.
## [Unreleased]
- Read safe project-local images, standard Markdown fragments and equations rendered as offline MathML.
- Consume Analysis v2/v3 and stream source-bound Execution Events v1 from the published RC.2 Core.
- Call functions beside their headings and inspect the current result inline.
- Download one selected, session-owned result as a script-free static ZIP after reviewing the included fields. Ordinary export retains its document-only behavior.
## [0.2.0] - 2026-11-22 ## [0.2.0] - 2026-11-22
### Fixed during issue #2 acceptance ### Fixed during issue #2 acceptance
+8 -6
View File
@@ -7,7 +7,8 @@
| View 产品版本 | `0.2.0` | 独立 SemVer,与 CLI 不共用 | | View 产品版本 | `0.2.0` | 独立 SemVer,与 CLI 不共用 |
| `marqdo` 产品范围 | `>=3.0.0-beta.1,<4.0.0` | 安装与分发时由 CLI 强制校验 | | `marqdo` 产品范围 | `>=3.0.0-beta.1,<4.0.0` | 安装与分发时由 CLI 强制校验 |
| CLI Tool Protocol | `1` | `tool.json` 清单/整包摘要/分发 | | CLI Tool Protocol | `1` | `tool.json` 清单/整包摘要/分发 |
| Analysis | `2` | 未知 major 直接拒绝,不回退 | | Analysis | `2`、`3` | 按实际信封版本验证,未知 major 拒绝 |
| Execution Events | `1` | RC.2 起提供实时输出与可验证的导出终态 |
| Trace | `2` | 与 Analysis 精确字节摘要绑定 | | Trace | `2` | 与 Analysis 精确字节摘要绑定 |
| Markdown profile | `marqdo.md.v1` | 与冻结 CLI 相同选项集 | | Markdown profile | `marqdo.md.v1` | 与冻结 CLI 相同选项集 |
@@ -17,7 +18,7 @@ Beta 版 CLI 必须使用 prerelease 范围(`>=3.0.0-beta.1,<4.0.0`);`>=3.
| 平台 | 状态 | 说明 | | 平台 | 状态 | 说明 |
|---|---|---| |---|---|---|
| Linux x86_64 (glibc 2.39+) | **Supported** | 完整验收使用官方 CLI Beta | | Linux x86_64 (glibc 2.39+) | **Supported** | 完整阅读和结果 ZIP 使用官方 RC.2 验收;媒体需要 Linux 5.6+ |
| Linux aarch64 | 未构建 | 未验证 | | Linux aarch64 | 未构建 | 未验证 |
| macOS / Windows | 未验证 | 不声明支持;路径/进程组逻辑留有平台分支,但未做实测 | | macOS / Windows | 未验证 | 不声明支持;路径/进程组逻辑留有平台分支,但未做实测 |
@@ -25,13 +26,13 @@ Beta 版 CLI 必须使用 prerelease 范围(`>=3.0.0-beta.1,<4.0.0`);`>=3.
| 能力 | 状态 | | 能力 | 状态 |
|---|---| |---|---|
| 原始 Markdown 只读浏览(GFM 表/列表/引用/代码围栏/数学文本) | **已实现**(PR-02) | | 原始 Markdown 只读浏览(GFM 表/列表/引用/代码围栏/MathML/本地图片) | **已实现**(PR-02) |
| Analysis v2 静态语义(函数/Unit/诊断/引用/资源) | **已实现**(PR-02) | | Analysis v2/v3 静态语义(函数/Unit/诊断/引用/资源) | **已实现**(PR-02) |
| 文档态 / 源码态切换 | **已实现**(PR-02) | | 文档态 / 源码态切换 | **已实现**(PR-02) |
| 暖纸 Reader 视觉(单一 CSS/JS) | 已实现并经 Chromium 验收 | | 暖纸 Reader 视觉(单一 CSS/JS) | 已实现并经 Chromium 验收 |
| 用户显式触发运行 + SSE + Trace v2 事件可视化 | **已实现**(0002 PR-04;`pure`/受控 `project`,显式确认 + 会话 CSRF) | | 用户显式触发运行 + SSE + Trace v2 事件可视化 | **已实现**(0002 PR-04;`pure`/受控 `project`,显式确认 + 会话 CSRF) |
| Live 本机安全 API(7 路由) | **已实现**(0002 PR-04;Cookie/CSRF/Origin/CSP/单任务/SSE) | | Live 本机安全 API(含媒体和 ZIP) | **已实现**(0002 PR-04;Cookie/CSRF/Origin/CSP/单任务/SSE) |
| 静态离线导出(纯只读) | **已实现**(PR-05,同一渲染器) | | 静态离线导出 | 普通导出与显式单次结果 ZIP 共用渲染器 |
| 逐语句变量值 / 参数实际值 / 内存快照 | **UNSUPPORTED**(Trace v2 不提供,绝不伪造) | | 逐语句变量值 / 参数实际值 / 内存快照 | **UNSUPPORTED**(Trace v2 不提供,绝不伪造) |
| 知识“已证明”状态 | **UNSUPPORTED**(需要独立 Prove 协议与证书) | | 知识“已证明”状态 | **UNSUPPORTED**(需要独立 Prove 协议与证书) |
| `project` 运行与 fs grants | **已实现(受控)**:仅相对项目根 read/write glob,显式二次确认;其它权限拒绝 | | `project` 运行与 fs grants | **已实现(受控)**:仅相对项目根 read/write glob,显式二次确认;其它权限拒绝 |
@@ -44,6 +45,7 @@ Beta 版 CLI 必须使用 prerelease 范围(`>=3.0.0-beta.1,<4.0.0`);`>=3.
## 消费者契约 ## 消费者契约
- 新 Core 使用 `--event-stream jsonl` 与 Trace v2。兼容的旧 Core 继续使用 `--json` 与 Trace v2。
- 未知 `schema_version` → `view.protocol_incompatible`,不回退猜测。 - 未知 `schema_version` → `view.protocol_incompatible`,不回退猜测。
- `sha256(exact analysis.json bytes) == trace.source.analysis_digest`;不匹配 → `view.trace_stale`。 - `sha256(exact analysis.json bytes) == trace.source.analysis_digest`;不匹配 → `view.trace_stale`。
- `trace.source.root_id == analysis.project.root_id`;事件 `module_id` 必须存在于 Analysis。 - `trace.source.root_id == analysis.project.root_id`;事件 `module_id` 必须存在于 Analysis。
Generated
+289
View File
@@ -2,6 +2,12 @@
# It is not intended for manual editing. # It is not intended for manual editing.
version = 4 version = 4
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]] [[package]]
name = "anstream" name = "anstream"
version = "1.0.0" version = "1.0.0"
@@ -52,12 +58,39 @@ dependencies = [
"windows-sys", "windows-sys",
] ]
[[package]]
name = "arbitrary"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed"
dependencies = [
"derive_arbitrary",
]
[[package]] [[package]]
name = "ascii" name = "ascii"
version = "1.1.0" version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16" checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16"
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]] [[package]]
name = "block-buffer" name = "block-buffer"
version = "0.10.4" version = "0.10.4"
@@ -67,6 +100,24 @@ dependencies = [
"generic-array", "generic-array",
] ]
[[package]]
name = "bumpalo"
version = "3.20.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db"
[[package]]
name = "bytemuck"
version = "1.25.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
[[package]]
name = "byteorder-lite"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
[[package]] [[package]]
name = "caseless" name = "caseless"
version = "0.2.2" version = "0.2.2"
@@ -128,6 +179,12 @@ version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79"
[[package]]
name = "color_quant"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
[[package]] [[package]]
name = "colorchoice" name = "colorchoice"
version = "1.0.5" version = "1.0.5"
@@ -160,6 +217,15 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "crc32fast"
version = "1.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64"
dependencies = [
"cfg-if",
]
[[package]] [[package]]
name = "crypto-common" name = "crypto-common"
version = "0.1.7" version = "0.1.7"
@@ -170,6 +236,17 @@ dependencies = [
"typenum", "typenum",
] ]
[[package]]
name = "derive_arbitrary"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]] [[package]]
name = "digest" name = "digest"
version = "0.10.7" version = "0.10.7"
@@ -186,12 +263,27 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5320ae4c3782150d900b79807611a59a99fc9a1d61d686faafc24b93fc8d7ca" checksum = "b5320ae4c3782150d900b79807611a59a99fc9a1d61d686faafc24b93fc8d7ca"
[[package]]
name = "equivalent"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
[[package]] [[package]]
name = "fastrand" name = "fastrand"
version = "2.5.0" version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "fdeflate"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
dependencies = [
"simd-adler32",
]
[[package]] [[package]]
name = "fearless_simd" name = "fearless_simd"
version = "1.2.0" version = "1.2.0"
@@ -215,6 +307,17 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ded33109e99472f809cb7495544506eea45e366725dacf2a383e184f660456" checksum = "09ded33109e99472f809cb7495544506eea45e366725dacf2a383e184f660456"
[[package]]
name = "flate2"
version = "1.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
dependencies = [
"crc32fast",
"miniz_oxide 0.9.1",
"zlib-rs",
]
[[package]] [[package]]
name = "generic-array" name = "generic-array"
version = "0.14.7" version = "0.14.7"
@@ -225,6 +328,22 @@ dependencies = [
"version_check", "version_check",
] ]
[[package]]
name = "gif"
version = "0.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae047235e33e2829703574b54fdec96bfbad892062d97fed2f76022287de61b"
dependencies = [
"color_quant",
"weezl",
]
[[package]]
name = "hashbrown"
version = "0.17.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc"
[[package]] [[package]]
name = "heck" name = "heck"
version = "0.5.0" version = "0.5.0"
@@ -237,6 +356,44 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "image"
version = "0.25.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "529feb3e6769d234375c4cf1ee2ce713682b8e76538cb13f9fc23e1400a591e7"
dependencies = [
"bytemuck",
"byteorder-lite",
"color_quant",
"gif",
"image-webp",
"moxcms",
"num-traits",
"png",
"zune-core",
"zune-jpeg",
]
[[package]]
name = "image-webp"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"
dependencies = [
"byteorder-lite",
"quick-error",
]
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]] [[package]]
name = "is_terminal_polyfill" name = "is_terminal_polyfill"
version = "1.70.2" version = "1.70.2"
@@ -265,14 +422,19 @@ checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
name = "marqdo-view" name = "marqdo-view"
version = "0.2.0" version = "0.2.0"
dependencies = [ dependencies = [
"base64",
"clap", "clap",
"comrak", "comrak",
"image",
"libc", "libc",
"pulldown-latex",
"roxmltree",
"semver", "semver",
"serde", "serde",
"serde_json", "serde_json",
"sha2", "sha2",
"tiny_http", "tiny_http",
"zip",
] ]
[[package]] [[package]]
@@ -291,6 +453,45 @@ dependencies = [
"fearless_simd_macros", "fearless_simd_macros",
] ]
[[package]]
name = "miniz_oxide"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "miniz_oxide"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "moxcms"
version = "0.7.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac9557c559cd6fc9867e122e20d2cbefc9ca29d80d027a8e39310920ed2f0a97"
dependencies = [
"num-traits",
"pxfm",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]] [[package]]
name = "once_cell_polyfill" name = "once_cell_polyfill"
version = "1.70.2" version = "1.70.2"
@@ -336,6 +537,19 @@ dependencies = [
"siphasher", "siphasher",
] ]
[[package]]
name = "png"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
dependencies = [
"bitflags",
"crc32fast",
"fdeflate",
"flate2",
"miniz_oxide 0.8.9",
]
[[package]] [[package]]
name = "proc-macro2" name = "proc-macro2"
version = "1.0.107" version = "1.0.107"
@@ -345,6 +559,27 @@ dependencies = [
"unicode-ident", "unicode-ident",
] ]
[[package]]
name = "pulldown-latex"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1cf850381ae0dbb131f36e31d6090f55363d079ab3e518ad0323b9cb6a96d115"
dependencies = [
"bumpalo",
]
[[package]]
name = "pxfm"
version = "0.1.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
[[package]]
name = "quick-error"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
[[package]] [[package]]
name = "quote" name = "quote"
version = "1.0.47" version = "1.0.47"
@@ -354,6 +589,15 @@ dependencies = [
"proc-macro2", "proc-macro2",
] ]
[[package]]
name = "roxmltree"
version = "0.21.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907"
dependencies = [
"memchr",
]
[[package]] [[package]]
name = "rustc-hash" name = "rustc-hash"
version = "2.1.3" version = "2.1.3"
@@ -420,6 +664,12 @@ dependencies = [
"digest", "digest",
] ]
[[package]]
name = "simd-adler32"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
[[package]] [[package]]
name = "siphasher" name = "siphasher"
version = "1.0.4" version = "1.0.4"
@@ -506,6 +756,12 @@ version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "weezl"
version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
[[package]] [[package]]
name = "windows-link" name = "windows-link"
version = "0.2.1" version = "0.2.1"
@@ -521,8 +777,41 @@ dependencies = [
"windows-link", "windows-link",
] ]
[[package]]
name = "zip"
version = "4.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1"
dependencies = [
"arbitrary",
"crc32fast",
"indexmap",
"memchr",
]
[[package]]
name = "zlib-rs"
version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
[[package]] [[package]]
name = "zmij" name = "zmij"
version = "1.0.23" version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zune-core"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a"
[[package]]
name = "zune-jpeg"
version = "0.4.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29ce2c8a9384ad323cf564b67da86e21d3cfdff87908bc1223ed5c99bc792713"
dependencies = [
"zune-core",
]
+5
View File
@@ -27,6 +27,10 @@ name = "integration"
path = "tests/integration/main.rs" path = "tests/integration/main.rs"
[dependencies] [dependencies]
base64 = "0.22"
image = { version = "=0.25.8", default-features = false, features = ["png", "jpeg", "webp", "gif"] }
pulldown-latex = "=0.8.0"
roxmltree = "0.21"
clap = { version = "4.5", features = ["derive"] } clap = { version = "4.5", features = ["derive"] }
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
@@ -34,6 +38,7 @@ sha2 = "0.10"
comrak = { version = "=1.0.0", default-features = false } comrak = { version = "=1.0.0", default-features = false }
semver = "1" semver = "1"
tiny_http = "0.12" tiny_http = "0.12"
zip = { version = "=4.6.1", default-features = false }
[target.'cfg(unix)'.dependencies] [target.'cfg(unix)'.dependencies]
libc = "0.2" libc = "0.2"
+25 -18
View File
@@ -1,11 +1,12 @@
# marqdo-view # marqdo-view
Marqdo View(`0.2.0`)是一个独立的可执行文档阅读器:以**原始 Markdown 为阅读主体**,把冻结 Marqdo View(`0.2.0`)是一个独立的可执行文档阅读器:以**原始 Markdown 为阅读主体**,把冻结
`marqdo` CLI 的静态语义(Analysis v2)与用户显式触发的真实运行轨迹(Trace v2) `marqdo` CLI 的静态语义(Analysis v2/v3)与用户显式触发的真实运行事件(Execution Events v1、Trace v2)
附着回原文,而不是把文档翻译成另一套语言。 附着回原文,而不是把文档翻译成另一套语言。
- 状态(唯一现状来源):[`docs/STATUS.md`](docs/STATUS.md) - 状态(唯一现状来源):[`docs/STATUS.md`](docs/STATUS.md)
- **实施规范(当前)**:[`docs/architecture/RFC-VIEW-0002.md`](docs/architecture/RFC-VIEW-0002.md) - **完整阅读与结果导出**:[实施 RFC](docs/architecture/RFC-VIEW-0001-complete-reader.md) · [设计图](docs/design/complete-reader.png) · [验收](docs/evidence/issue-3/README.md)
- **执行基础规范**:[`docs/architecture/RFC-VIEW-0002.md`](docs/architecture/RFC-VIEW-0002.md)
- 0002 合规矩阵:[`docs/CONFORMANCE.md`](docs/CONFORMANCE.md) - 0002 合规矩阵:[`docs/CONFORMANCE.md`](docs/CONFORMANCE.md)
- 历史基础设计:[`docs/architecture/RFC-VIEW-0001.md`](docs/architecture/RFC-VIEW-0001.md) - 历史基础设计:[`docs/architecture/RFC-VIEW-0001.md`](docs/architecture/RFC-VIEW-0001.md)
- 旧 View 静态审计:[`docs/audits/legacy-view.md`](docs/audits/legacy-view.md) - 旧 View 静态审计:[`docs/audits/legacy-view.md`](docs/audits/legacy-view.md)
@@ -13,21 +14,18 @@ Marqdo View(`0.2.0`)是一个独立的可执行文档阅读器:以**原始
- 兼容性:[`COMPATIBILITY.md`](COMPATIBILITY.md) / 变更:[`CHANGELOG.md`](CHANGELOG.md) - 兼容性:[`COMPATIBILITY.md`](COMPATIBILITY.md) / 变更:[`CHANGELOG.md`](CHANGELOG.md)
- 决策记录:[`docs/decisions/`](docs/decisions/) - 决策记录:[`docs/decisions/`](docs/decisions/)
> **当前状态**:RFC-VIEW-0002 PR-00~PR-06 已完成,按 §10 发布门禁验收 > 阅读、函数调用和单次结果 ZIP 可用。实时执行事件和结果 ZIP 需要官方
> **PASS**(真实冻结 CLI + 真实 Chromium;见 > `marqdo 3.0.0-rc.2` 或更新的兼容版本。Beta 仍可使用旧版运行与 Trace 流程。
> [`docs/ACCEPTANCE.md`](docs/ACCEPTANCE.md) 与
> `docs/evidence/<CLI-SHA>/manifest.json`)。像素级人工比对与完整
> screen-reader 走查仍为 `UNVERIFIED`,见 `docs/STATUS.md`。
## 能力 ## 能力
| 能力 | 状态 | | 能力 | 状态 |
|---|---| |---|---|
| 原始 Markdown + GFM 阅读、源码态、文档态 | ✅ | | Markdown + GFM、源码态、项目图片、跨页锚点、离线数学 | ✅ |
| Analysis v2 静态语义(函数/Unit/签名/诊断/导入/引用/资源) | ✅ 严格校验,span 无效则降级 | | Analysis v2/v3 静态语义(函数/Unit/签名/诊断/导入/引用/资源) | ✅ 严格校验,span 无效则降级 |
| 本机 Live 阅读(默认 `127.0.0.1`,只读 API + 显式执行端点) | ✅ | | 本机 Live 阅读(默认 `127.0.0.1`,只读 API + 显式执行端点) | ✅ |
| 显式确认后运行 + SSE 状态/取消 + 真实 Trace v2 | ✅ 单任务、无轮询、断线重放 | | 显式确认后运行、SSE 实时输出与取消、真实 Trace v2 | ✅ RC.2;单任务、断线重放 |
| 纯只读静态导出(离线 `file://`、manifest/哈希、原子发布) | ✅ | | 只读静态导出(离线 `file://`、媒体/字体/哈希) | ✅ 普通站点与显式结果 ZIP |
| 单函数参数表单 + 受控 `project` fs grants | ✅ 参数来自 Analysis 签名;project 需显式 glob 二次确认 | | 单函数参数表单 + 受控 `project` fs grants | ✅ 参数来自 Analysis 签名;project 需显式 glob 二次确认 |
| SSE 状态推送 / 取消 / 断线重放(禁止轮询) | ✅ `POST /api/runs` + `GET …/events` + `POST …/cancel` | | SSE 状态推送 / 取消 / 断线重放(禁止轮询) | ✅ `POST /api/runs` + `GET …/events` + `POST …/cancel` |
| 逐语句变量值 / 参数值 / 内存快照 | ❌ UNSUPPORTED(协议不提供,绝不伪造) | | 逐语句变量值 / 参数值 / 内存快照 | ❌ UNSUPPORTED(协议不提供,绝不伪造) |
@@ -70,11 +68,18 @@ marqdo view export examples/mixed-modes --out ./site --no-annotations
``` ```
开发期可直接运行 `marqdo-view`(用 `--marqdo-bin` 指定冻结核心)。运行只有一个入口: 开发期可直接运行 `marqdo-view`(用 `--marqdo-bin` 指定冻结核心)。运行只有一个入口:
Live 页面点击 Dock “运行”(执行 `main`)或函数面板的“调用”(执行 `call`), Live 页面点击 Dock “运行”(执行 `main`)或函数标题旁的“调用”(执行 `call`),
阅读命令预览与权限说明后点击“确认执行”,服务端才 `POST /api/runs` 启动一个 阅读命令预览与权限说明后点击“确认执行”,服务端才 `POST /api/runs` 启动一个
CLI 子进程;状态与结果通过 SSE 推送,可取消,断线可重放。页面刷新/打开/搜索/ CLI 子进程;状态与结果通过 SSE 推送,可取消,断线可重放。页面刷新/打开/搜索/
切换/导出都不会运行,也没有状态轮询。 切换/导出都不会运行,也没有状态轮询。
在函数旁的“本次执行”中选择“导出文档(含本次结果)”,检查预览和选项,
确认后下载 ZIP。默认勾选标量返回值和可用的 Trace 摘要。stdout、stderr、
已提交的参数和非标量返回值由用户选择。ZIP 解压后直接打开 `index.html`,
可离线阅读、打印和通过清单校验文件。可导出结果在当前会话的任务内保留
15 分钟。普通 `view export` 始终只导出文档。
## 架构(强制约束) ## 架构(强制约束)
```text ```text
@@ -86,7 +91,7 @@ ReaderRenderer(唯一模板,Live/Export 共用)
│ │
PresentationModel(reader::assemble / reader::model) PresentationModel(reader::assemble / reader::model)
│ │
CoreClient ─ MARQDO_BIN 子进程 + 公开 JSON(check --emit / run/call --trace-file) CoreClient ─ MARQDO_BIN 公开协议(check --emit / Events v1 / Trace v2)
│ │
ExecutionController ─ 单任务、取消、SSE 事件(仅 POST /api/runs 可达) ExecutionController ─ 单任务、取消、SSE 事件(仅 POST /api/runs 可达)
│ │
@@ -94,9 +99,9 @@ ExecutionController ─ 单任务、取消、SSE 事件(仅 POST /api/runs 可
``` ```
- 单一 Rust package、单一渲染入口、单一主题文件;没有第二个 Markdown→语义管线。 - 单一 Rust package、单一渲染入口、单一主题文件;没有第二个 Markdown→语义管线。
- 服务端只有 7 条固定路由;SSE 只推送 View 自有 `run.*` 生命周期事件。 - View SSE 推送任务状态与已校验的实时输出。受保护的 `POST /api/exports` 从当前会话的终态生成只读 ZIP。
- Analysis v2 是唯一语义权威:函数/语句/分支/循环/诊断均来自 `check --emit`, - Analysis v2/v3 是唯一语义权威:函数/语句/分支/循环/诊断均来自 `check --emit`,
源码字节 span 只用于绑定视觉位置。 源码字节 span 用于绑定视觉位置。文档跳转采用确定性的标题锚点。
- Trace v2 与 Analysis 字节摘要严格绑定;`STALE/TRUNCATED/FAILED/UNSUPPORTED` - Trace v2 与 Analysis 字节摘要严格绑定;`STALE/TRUNCATED/FAILED/UNSUPPORTED`
状态显式呈现,不猜测未公开值。 状态显式呈现,不猜测未公开值。
- Live/Export 内容同源;导出绝不执行、绝不覆盖项目源文件或无关目录。 - Live/Export 内容同源;导出绝不执行、绝不覆盖项目源文件或无关目录。
@@ -106,6 +111,8 @@ ExecutionController ─ 单任务、取消、SSE 事件(仅 POST /api/runs 可
## 开发与验收 ## 开发与验收
完整阅读和结果导出的复验命令见 [工单 #3 验收](docs/evidence/issue-3/README.md)。
```bash ```bash
export PATH="$HOME/.cargo/bin:$PATH" export PATH="$HOME/.cargo/bin:$PATH"
cargo fmt --all -- --check cargo fmt --all -- --check
@@ -147,8 +154,8 @@ MARQDO_BIN=... ./scripts/test-browser.sh # 真实 Chromium 视觉/交互/响
- 运行仅 `pure`(默认)与受控 `project` fs read/write;`strict`、网络/进程/环境/ - 运行仅 `pure`(默认)与受控 `project` fs read/write;`strict`、网络/进程/环境/
plugin/provider/kernel 授权不在首版 UI,必须使用终端 CLI。 plugin/provider/kernel 授权不在首版 UI,必须使用终端 CLI。
- `project` 不是 OS 沙箱;View 不继承 `marqdo.yaml` 的 capability 请求。 - `project` 不是 OS 沙箱;View 不继承 `marqdo.yaml` 的 capability 请求。
- SSE 只推送 View 生命周期与终态数据,不承诺逐字 stdout/Token 流;Trace v2 不含 - RC.2 之前的兼容 Core 使用终态 JSON 与 Trace v2。尚未收到真实 Core 终态的取消或超时可在 Live 阅读,结果 ZIP 只向来源匹配的成功或失败终态开放。
参数实际值/逐语句变量/内存快照。 - Linux 项目媒体使用 `openat2`(Linux 5.6+)。每个图片最多 4 MiB、约 1600 万像素。SVG 只接受静态图形元素。
- 平台:仅 Linux x86_64 正式验证;Windows/macOS 不支持声明。 - 平台:仅 Linux x86_64 正式验证;Windows/macOS 不支持声明。
- 远端 CI 配置已提供(`.github/workflows/ci.yml`),本环境未实际运行远端 CI; - 远端 CI 配置已提供(`.github/workflows/ci.yml`),本环境未实际运行远端 CI;
验收证据来自本地真实命令。 验收证据来自本地真实命令。
Binary file not shown.
+155
View File
@@ -0,0 +1,155 @@
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: Noto
Upstream-Contact: https://github.com/googlei18n/noto-fonts/issues
http://groups.google.com/group/noto-font
Source: https://github.com/googlei18n/noto-fonts
Files: *
Copyright:
2010,2012-2020, Google Inc.
2015-2020, Google LLC.
License-Grant:
This Font Software is licensed under the SIL Open Font License,
Version 1.1.
License: OFL-1.1
Files:
debian/*
Copyright:
2013-2020, Jonas Smedegaard <dr@jones.dk>
2020, Purism, SPC
2013, Vasudev Kamath <kamathvasudev@gmail.com>
License-Grant:
This program is free software;
you can redistribute it and/or modify it
under the terms of the GNU General Public License
as published by the Free Software Foundation;
either version 3, or (at your option) any later version.
License: GPL-3+
Files:
debian/NotoMono/NotoMono-Regular.ttf
Copyright:
2007, Google Inc.
License-Grant:
This Font Software is licensed under the SIL Open Font License,
Version 1.1.
License: OFL-1.1
License: OFL-1.1
PREAMBLE
.
The goals of the Open Font License (OFL) are to stimulate
worldwide development of collaborative font projects,
to support the font creation efforts
of academic and linguistic communities,
and to provide a free and open framework
in which fonts may be shared and improved
in partnership with others.
.
The OFL allows the licensed fonts to be used, studied,
modified and redistributed freely
as long as they are not sold by themselves.
The fonts, including any derivative works,
can be bundled, embedded,
redistributed and/or sold with any software
provided that any reserved names are not used
by derivative works.
The fonts and derivatives, however,
cannot be released under any other type of license.
The requirement for fonts to remain under this license
does not apply to any document
created using the fonts or their derivatives.
.
DEFINITIONS
.
"Font Software" refers to the set of files
released by the Copyright Holder(s) under this license
and clearly marked as such.
This may include source files, build scripts and documentation.
.
"Reserved Font Name" refers to any names specified as such
after the copyright statement(s).
.
"Original Version" refers to the collection
of Font Software components
as distributed by the Copyright Holder(s).
.
"Modified Version" refers to any derivative
made by adding to, deleting, or substituting --
in part or in whole --
any of the components of the Original Version,
by changing formats
or by porting the Font Software to a new environment.
.
"Author" refers to any designer, engineer, programmer,
technical writer or other person
who contributed to the Font Software.
.
PERMISSION & CONDITIONS
.
Permission is hereby granted, free of charge,
to any person obtaining a copy of the Font Software,
to use, study, copy, merge, embed, modify, redistribute,
and sell modified and unmodified copies of the Font Software,
subject to the following conditions:
.
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions,
may be sold by itself.
.
2) Original or Modified Versions of the Font Software
may be bundled, redistributed and/or sold with any software,
provided that each copy contains the above copyright notice
and this license.
These can be included either as stand-alone text files,
human-readable headers or in the appropriate
machine-readable metadata fields within text or binary files
as long as those fields can be easily viewed by the user.
.
3) No Modified Version of the Font Software may use
the Reserved Font Name(s)
unless explicit written permission is granted
by the corresponding Copyright Holder.
This restriction only applies to the primary font name
as presented to the users.
.
4) The name(s) of the Copyright Holder(s)
or the Author(s) of the Font Software
shall not be used to promote,
endorse or advertise any Modified Version,
except to acknowledge the contribution(s)
of the Copyright Holder(s) and the Author(s)
or with their explicit written permission.
.
5) The Font Software,
modified or unmodified, in part or in whole,
must be distributed entirely under this license,
and must not be distributed under any other license.
The requirement for fonts to remain under this license
does not apply to any document
created using the Font Software.
.
TERMINATION
.
This license becomes null and void
if any of the above conditions are not met.
.
DISCLAIMER
.
THE FONT SOFTWARE IS PROVIDED "AS IS",
WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO
ANY WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT.
IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT,
INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF THE USE OR INABILITY TO USE
THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
License: GPL-3+
License-Reference: /usr/share/common-licenses/GPL-3
+139
View File
@@ -1370,3 +1370,142 @@
overflow-wrap: anywhere; overflow-wrap: anywhere;
} }
} }
@font-face {
font-family: "Noto Sans Math";
src: url("__MATH_FONT__") format("truetype");
font-display: swap;
}
@layer typography {
.mq-document-image { max-inline-size: 100%; block-size: auto; }
.mq-heading-anchor { display: block; }
.mq-document math { font-family: "Noto Sans Math", math; }
}
@layer semantics {
.mq-document h2 .mq-fn-call {
margin-inline-start: .8rem;
vertical-align: middle;
border-color: var(--mq-gold);
color: var(--mq-focus);
}
.mq-result-slot:empty { display: none; }
.mq-result-slot .mq-run-panel {
border-color: var(--mq-olive);
background: var(--mq-surface);
margin-block: 1.25rem 1.75rem;
}
.mq-run-panel > summary {
cursor: pointer;
font-weight: 650;
color: var(--mq-olive);
margin-block-end: .6rem;
}
.mq-run-panel[hidden] { display: none; }
}
@layer semantics {
.mq-snapshot, .mq-snapshot-notice, .mq-static-source {
background: var(--mq-surface);
border: 1px solid var(--mq-line);
border-radius: .65rem;
padding: .9rem 1rem;
margin-block: 1.25rem;
}
.mq-snapshot {
border-color: var(--mq-olive);
overflow-wrap: anywhere;
}
.mq-snapshot > summary, .mq-static-source > summary {
font-weight: 650;
cursor: pointer;
}
.mq-snapshot pre, .mq-static-source pre {
white-space: pre-wrap;
overflow-wrap: anywhere;
font: .9rem/1.55 var(--mq-mono);
}
.mq-snapshot-counts {
display: grid;
grid-template-columns: minmax(0, 2fr) 1fr;
}
.mq-snapshot-counts dd { margin: 0; }
}
@layer overlays {
.mq-export-dialog {
max-inline-size: min(36rem, calc(100vw - 2rem));
max-block-size: calc(100dvh - 2rem);
overflow: auto;
}
.mq-export-target {
background: var(--mq-surface-2);
border: 1px solid var(--mq-line);
border-radius: .45rem;
padding: .65rem .85rem;
}
.mq-export-fields {
padding: 0;
border: 0;
margin: 0 0 1rem;
min-inline-size: 0;
}
.mq-export-fields legend { font-weight: 650; }
.mq-export-fields label {
display: grid;
grid-template-columns: 1.25rem minmax(0, 1fr) auto;
align-items: center;
gap: .55rem;
border-block-start: 1px solid var(--mq-line);
padding: .65rem 0 .4rem;
}
.mq-export-fields small { color: var(--mq-muted); }
.mq-export-fields details {
margin-inline-start: 1.8rem;
margin-block-end: .6rem;
font-size: .86rem;
}
.mq-export-fields pre {
white-space: pre-wrap;
overflow-wrap: anywhere;
overflow: auto;
max-block-size: 12rem;
background: var(--mq-surface-2);
padding: .65rem;
}
.mq-export-confirm { display: block; margin-block: .75rem; }
.mq-export-confirm[hidden], .mq-export-result[hidden] { display: none; }
.mq-export-result { margin-block-start: .75rem; }
#mq-export-error { color: var(--mq-error); }
}
@layer layout {
.mq-snapshot-topbar .mq-brand { grid-column: 2; }
}
@layer overlays {
.mq-export-dialog input[type="checkbox"] { accent-color: var(--mq-gold); }
.mq-export-dialog button[disabled] { opacity: .55; cursor: default; }
}
@layer semantics {
.mq-snapshot-notice a { color: var(--mq-focus); }
}
+198 -10
View File
@@ -310,6 +310,12 @@
case "cancel-run": case "cancel-run":
cancelRun(); cancelRun();
break; break;
case "export-result":
openExportPreview();
break;
case "download-result":
downloadSnapshot();
break;
case "call-function": case "call-function":
if (trigger) { if (trigger) {
var params = []; var params = [];
@@ -372,12 +378,13 @@
case "cancelled": return "已取消"; case "cancelled": return "已取消";
case "timed_out": return "超时"; case "timed_out": return "超时";
case "unavailable": return "不可用"; case "unavailable": return "不可用";
case "incomplete": return "事件流不完整";
default: return String(state || "未知"); default: return String(state || "未知");
} }
} }
function isTerminalState(state) { function isTerminalState(state) {
return ["succeeded", "failed", "cancelled", "timed_out", "unavailable"].indexOf(state) >= 0; return ["succeeded", "failed", "cancelled", "timed_out", "unavailable", "incomplete"].indexOf(state) >= 0;
} }
function runPanel() { function runPanel() {
@@ -408,6 +415,7 @@
button.disabled = false; button.disabled = false;
} }
} }
$$(".mq-fn-call[data-action=call-function]").forEach(function (call) { call.disabled = busy; });
var cancel = $("#mq-run-actions"); var cancel = $("#mq-run-actions");
if (cancel) cancel.hidden = !busy; if (cancel) cancel.hidden = !busy;
} }
@@ -429,6 +437,10 @@
if (stdout) stdout.hidden = true; if (stdout) stdout.hidden = true;
var stderr = $("#mq-run-stderr"); var stderr = $("#mq-run-stderr");
if (stderr) stderr.hidden = true; if (stderr) stderr.hidden = true;
var exportButton = $("#mq-export-result");
if (exportButton) exportButton.hidden = true;
var traceTitle = $("#mq-run-trace-title");
if (traceTitle) traceTitle.textContent = "实时结构事件";
var traceWrap = $("#mq-run-trace-wrap"); var traceWrap = $("#mq-run-trace-wrap");
if (traceWrap) traceWrap.hidden = true; if (traceWrap) traceWrap.hidden = true;
$$(".mq-run-chip[data-view-chip]").forEach(function (chip) { $$(".mq-run-chip[data-view-chip]").forEach(function (chip) {
@@ -473,12 +485,15 @@
var preview = $("#mq-run-command"); var preview = $("#mq-run-command");
if (!preview || !pendingRun) return; if (!preview || !pendingRun) return;
var mode = selectedMode(); var mode = selectedMode();
var protocol = reader.dataset.executionEvents === "true" ? ["--event-stream", "jsonl"] : ["--json"];
var args = ["--mode", mode].concat(protocol, ["--trace-file", "<临时文件>"]);
var parts = []; var parts = [];
if (pendingRun.kind === "entry") { if (pendingRun.kind === "entry") {
parts = ["marqdo", "run", reader.dataset.document, "--mode", mode, "--json", "--trace-file", "<临时文件>"]; parts = ["marqdo", "run", reader.dataset.document].concat(args);
} else { } else {
parts = ["marqdo", "call", reader.dataset.document, "<函数 " + pendingRun.label + ">", "--mode", mode, "--json", "--trace-file", "<临时文件>"]; parts = ["marqdo", "call", reader.dataset.document, "<函数 " + pendingRun.label + ">"].concat(args);
rawParams().forEach(function (param) { rawParams().forEach(function (param) {
if (!param.required && param.expression.trim() === "") return;
parts.push("--arg"); parts.push("--arg");
parts.push(param.name + "=" + (param.expression || "<常量表达式>")); parts.push(param.name + "=" + (param.expression || "<常量表达式>"));
}); });
@@ -587,7 +602,9 @@
target: pendingRun.kind === "entry" target: pendingRun.kind === "entry"
? { kind: "entry" } ? { kind: "entry" }
: { kind: "function", function_id: pendingRun.functionId }, : { kind: "function", function_id: pendingRun.functionId },
parameters: params.map(function (param) { parameters: params.filter(function (param) {
return param.required || param.expression.trim() !== "";
}).map(function (param) {
return { name: param.name, expression: param.expression }; return { name: param.name, expression: param.expression };
}), }),
analysis_digest: reader.dataset.analysisDigest, analysis_digest: reader.dataset.analysisDigest,
@@ -597,6 +614,14 @@
}; };
closeAllDialogs(); closeAllDialogs();
clearRunOutput(); clearRunOutput();
var panel = runPanel();
var slot = $$(".mq-result-slot").find(function (element) {
return element.dataset.resultFor === payload.target.function_id ||
(payload.target.kind === "entry" && element.dataset.resultFor.split(".").pop().split("::").pop() === "main");
});
if (slot && panel) slot.appendChild(panel);
else if (panel) $("#mq-document").after(panel);
if (panel) panel.open = true;
showRunPanel(); showRunPanel();
setRunBusy(true); setRunBusy(true);
setRunStatus("正在提交运行请求…"); setRunStatus("正在提交运行请求…");
@@ -622,7 +647,7 @@
toast("运行未启动:" + reason); toast("运行未启动:" + reason);
return; return;
} }
subscribeRun(result.data, pendingRun ? pendingRun.label : "运行"); subscribeRun(result.data, pendingRun ? pendingRun.label : "运行", payload.parameters);
}) })
.catch(function (error) { .catch(function (error) {
setRunBusy(false); setRunBusy(false);
@@ -631,7 +656,7 @@
}); });
} }
function subscribeRun(job, targetLabel) { function subscribeRun(job, targetLabel, parameters) {
closeActiveObserver(); closeActiveObserver();
activeRun = { activeRun = {
runId: job.run_id, runId: job.run_id,
@@ -640,6 +665,7 @@
source: null, source: null,
lastSeq: -1, lastSeq: -1,
targetLabel: targetLabel || "运行", targetLabel: targetLabel || "运行",
parameters: parameters,
terminal: false terminal: false
}; };
clearRunOutput(); clearRunOutput();
@@ -650,6 +676,7 @@
setRunStatus("浏览器不支持 EventSource,无法接收运行状态;请使用现代浏览器。"); setRunStatus("浏览器不支持 EventSource,无法接收运行状态;请使用现代浏览器。");
return; return;
} }
var decoders = { stdout: new TextDecoder(), stderr: new TextDecoder() };
var source = new EventSource(job.events_url, { withCredentials: true }); var source = new EventSource(job.events_url, { withCredentials: true });
activeRun.source = source; activeRun.source = source;
function apply(event) { function apply(event) {
@@ -659,7 +686,7 @@
} catch (error) { } catch (error) {
return; return;
} }
if (!data || if (!data || !activeRun || activeRun.runId !== job.run_id ||
data.schema !== "marqdo.view-run-events" || data.schema !== "marqdo.view-run-events" ||
data.schema_version !== 1 || data.schema_version !== 1 ||
data.run_id !== job.run_id || data.run_id !== job.run_id ||
@@ -668,9 +695,13 @@
return; return;
} }
activeRun.lastSeq = data.seq; activeRun.lastSeq = data.seq;
if (data.observation) {
renderObservation(data.observation, decoders);
return;
}
updateRunView(data); updateRunView(data);
} }
["run.state", "run.complete", "run.error", "run.snapshot"].forEach(function (kind) { ["run.state", "run.complete", "run.error", "run.snapshot", "run.observation"].forEach(function (kind) {
source.addEventListener(kind, apply); source.addEventListener(kind, apply);
}); });
source.onerror = function () { source.onerror = function () {
@@ -680,6 +711,28 @@
}; };
} }
function renderObservation(observation, decoders) {
var stream = observation.kind === "stdout.chunk" ? "stdout"
: observation.kind === "stderr.chunk" ? "stderr" : null;
if (stream) {
var output = $("#mq-run-" + stream);
if (!output) return;
var bytes = Uint8Array.from(atob(observation.data_base64), function (value) {
return value.charCodeAt(0);
});
output.append(document.createTextNode(decoders[stream].decode(bytes, { stream: true })));
output.hidden = false;
} else if (/^(branch|loop|control|call)\./.test(observation.kind)) {
var wrap = $("#mq-run-trace-wrap");
if (wrap) wrap.hidden = false;
var events = $("#mq-run-events");
if (events && events.childElementCount < 100) {
appendLine(events, "li", "", observation.kind +
(observation.decision === undefined ? "" : " · " + observation.decision));
}
}
}
function updateRunView(data) { function updateRunView(data) {
var panel = runPanel(); var panel = runPanel();
if (panel) { if (panel) {
@@ -692,17 +745,148 @@
setRunBusy(true); setRunBusy(true);
return; return;
} }
if (activeRun) activeRun.terminal = true; if (activeRun) {
activeRun.terminal = true;
activeRun.exportData = data.result && data.result.export_preview ? data : null;
var exportButton = $("#mq-export-result");
if (exportButton) exportButton.hidden = !activeRun.exportData;
}
closeActiveObserver(); closeActiveObserver();
setRunBusy(false); setRunBusy(false);
if (data.result) renderRunResult(data.result, data.state, data.error); if (data.result) renderRunResult(data.result, data.state, data.error);
else if (data.error) renderRunResult(null, data.state, data.error); else if (data.error) renderRunResult(null, data.state, data.error);
if (data.trace) renderTrace(data.trace); if (data.trace) {
var traceTitle = $("#mq-run-trace-title");
if (traceTitle && data.trace.status === "verified") traceTitle.textContent = "已验证的 Trace v2 事件";
renderTrace(data.trace);
}
else if (data.result && data.result.trace_status) renderTraceStatus(data.result.trace_status); else if (data.result && data.result.trace_status) renderTraceStatus(data.result.trace_status);
if (data.state === "succeeded") toast("运行完成"); if (data.state === "succeeded") toast("运行完成");
else toast("运行" + stateLabel(data.state)); else toast("运行" + stateLabel(data.state));
} }
function previewBytes(text, count) {
if (!text || !count) return "";
return new TextDecoder().decode(new TextEncoder().encode(text).slice(0, count));
}
function exportNeedsPartial(data) {
var preview = data.result.export_preview;
return data.state !== "succeeded" || !preview.output_complete ||
!preview.result_complete || preview.observation_truncated ||
preview.trace_status === "truncated";
}
function updateExportConfirm() {
var button = $("#mq-export-download");
var data = activeRun && activeRun.exportData;
if (!button || !data) return;
button.disabled = button.dataset.busy === "true" || !$("#mq-export-confirm").checked ||
(exportNeedsPartial(data) && !$("#mq-export-partial").checked);
}
function openExportPreview() {
var data = activeRun && activeRun.exportData;
if (!data) return;
var result = data.result;
var preview = result.export_preview;
var fields = $("#mq-export-fields");
var counts = preview.trace_summary && data.trace && data.trace.counts;
var argumentsText = (activeRun.parameters || []).map(function (parameter) {
return parameter.name + " = " + parameter.expression;
}).join("\n");
$("#mq-export-target").textContent = preview.label + " · " + stateLabel(data.state) +
(exportNeedsPartial(data) ? " · 部分观察" : "");
fields.textContent = "";
[
["result_value", "返回值", preview.value_bytes, preview.value_is_public_scalar, preview.value],
["stdout", "stdout", preview.stdout_bytes, false, previewBytes(result.stdout, preview.stdout_bytes)],
["stderr", "stderr", preview.stderr_bytes, false, previewBytes(result.stderr, preview.stderr_bytes)],
["trace_summary", "轨迹摘要", counts ? new TextEncoder().encode(JSON.stringify(counts)).length : null, true, counts && JSON.stringify(counts, null, 2)],
["arguments", "已提交的参数", preview.arguments_count ? new TextEncoder().encode(argumentsText).length : null, false, argumentsText]
].forEach(function (field) {
var label = document.createElement("label");
var input = document.createElement("input");
input.type = "checkbox";
input.name = field[0];
input.disabled = !field[2];
input.checked = field[3] && !input.disabled;
label.appendChild(input);
appendLine(label, "span", "", field[1]);
appendLine(label, "small", "", field[2] ? field[2] + " B" : "无内容");
fields.appendChild(label);
if (field[4]) {
var disclosure = document.createElement("details");
appendLine(disclosure, "summary", "", "查看" + field[1]);
appendLine(disclosure, "pre", "", field[4]);
fields.appendChild(disclosure);
}
});
$("#mq-export-confirm").checked = false;
$("#mq-export-partial").checked = false;
$("#mq-export-partial-row").hidden = !exportNeedsPartial(data);
$("#mq-export-error").hidden = true;
updateExportConfirm();
openDialog("mq-dialog-export");
}
async function downloadSnapshot() {
var button = $("#mq-export-download");
var data = activeRun && activeRun.exportData;
if (!data || button.disabled) return;
var include = {};
$$("#mq-export-fields input").forEach(function (input) {
include[input.name] = input.checked;
});
var error = $("#mq-export-error");
error.hidden = true;
button.dataset.busy = "true";
updateExportConfirm();
try {
var response = await fetch("/api/exports", {
method: "POST",
credentials: "same-origin",
cache: "no-store",
headers: { "Content-Type": "application/json", "Accept": "application/zip", "X-View-CSRF": csrfToken() },
body: JSON.stringify({
schema: "marqdo.view-static-export-request",
schema_version: 1,
run_id: data.run_id,
document: data.result.document,
analysis_digest: data.result.analysis_digest,
scope: "document",
include: include,
confirm_sensitive_output: $("#mq-export-confirm").checked,
confirm_partial: $("#mq-export-partial").checked,
client_export_request_id: randomId()
})
});
if (!response.ok) {
var failure = await response.json();
throw new Error(failure.message || "导出请求未完成");
}
if (!(response.headers.get("Content-Type") || "").startsWith("application/zip")) {
throw new Error("服务返回的文件格式无效");
}
var url = URL.createObjectURL(await response.blob());
var link = document.createElement("a");
link.href = url;
link.download = "marqdo-execution-snapshot.zip";
document.body.appendChild(link);
link.click();
link.remove();
window.setTimeout(function () { URL.revokeObjectURL(url); }, 1000);
closeAllDialogs();
toast("执行快照已下载");
} catch (failure) {
error.textContent = failure.message;
error.hidden = false;
} finally {
delete button.dataset.busy;
updateExportConfirm();
}
}
function renderRunResult(result, state, error) { function renderRunResult(result, state, error) {
var summary = $("#mq-run-summary"); var summary = $("#mq-run-summary");
if (!summary) return; if (!summary) return;
@@ -856,6 +1040,7 @@
function clearRun() { function clearRun() {
closeAllDialogs(); closeAllDialogs();
closeActiveObserver(); closeActiveObserver();
activeRun = null;
var panel = runPanel(); var panel = runPanel();
if (panel) { if (panel) {
panel.hidden = true; panel.hidden = true;
@@ -898,6 +1083,9 @@
} }
}); });
document.addEventListener("change", function (event) { document.addEventListener("change", function (event) {
if (event.target && (event.target.id === "mq-export-confirm" || event.target.id === "mq-export-partial")) {
updateExportConfirm();
}
if (event.target && event.target.name === "mq-mode") { if (event.target && event.target.name === "mq-mode") {
var grants = $("#mq-run-grants"); var grants = $("#mq-run-grants");
if (grants) grants.hidden = event.target.value !== "project"; if (grants) grants.hidden = event.target.value !== "project";
+17 -3
View File
@@ -1,7 +1,21 @@
# marqdo-view 现状(STATUS) # marqdo-view 现状(STATUS)
> 唯一现状来源。规范见 `docs/architecture/RFC-VIEW-0002.md`;本文只记录 > 最后更新:2026-11-24。工单 #3 实施规范见 [完整阅读与静态结果导出](architecture/RFC-VIEW-0001-complete-reader.md)。
> **实际完成、证据与限制**。最后更新:2026-11-22(Issue #2 复验)
## 完整阅读与结果 ZIP(工单 #3)
| 能力 | 当前状态 |
|---|---|
| Markdown / GFM / 链接和锚点 | 同页与跨文档支持百分号编码、Unicode 与稳定重复标题编号 |
| 本地媒体与离线数学 | PNG/JPEG/GIF/WebP、静态 SVG、MathML 与内嵌 Noto Sans Math 字体 |
| 分析和运行 | Analysis v2/v3;RC.2 Events v1 → View SSE;Trace v2 独立校验 |
| 函数旁交互 | 默认参数、显式确认、实时 stdout、可折叠终态与来源信息 |
| 普通导出 | 正文、媒体、字体、文件哈希;零运行、零执行结果 |
| 结果导出 | 当前会话内选定一次可信终态,展示隐私预览后下载只读 ZIP |
| 可导出终态 | 成功;来源一致的失败或截断观察需另行确认。无真实 Core 终态的任务可以在 Live 显示状态 |
| 证据 | [官方 RC.2 和 Chromium 验收](evidence/issue-3/README.md) |
以下里程碑记录 RFC-VIEW-0002 交付基线。
## 版本与基线 ## 版本与基线
@@ -29,7 +43,7 @@
| PR-05 Trace 绑定/原文标注/浏览器回归 | **完成** | Controller Trace 摘要/`source_id`/stale、ADR-0010、`docs/evidence/PR-05/` | | PR-05 Trace 绑定/原文标注/浏览器回归 | **完成** | Controller Trace 摘要/`source_id`/stale、ADR-0010、`docs/evidence/PR-05/` |
| PR-06 静态导出/发布包/示例/文档闭环 | **完成** | `examples/*.mq.md`、`scripts/check-examples.sh`、`scripts/test-no-exec.sh`、`docs/ACCEPTANCE.md`、最终 evidence manifest | | PR-06 静态导出/发布包/示例/文档闭环 | **完成** | `examples/*.mq.md`、`scripts/check-examples.sh`、`scripts/test-no-exec.sh`、`docs/ACCEPTANCE.md`、最终 evidence manifest |
## 能力现状 ## RFC-VIEW-0002 能力基线
| 能力 | 状态 | | 能力 | 状态 |
|---|---| |---|---|
@@ -0,0 +1,722 @@
# RFC-VIEW-0001(定稿建议):完整 Markdown 阅读、统一函数调用与显式结果静态导出
> **状态:Proposed / 开发规范,不表示已经实现或通过验收。**
>
> **目标仓库:** [`cflmy/marqdo-view`](https://github.com/cflmy/marqdo-view),本次审阅基线 `master@dcb9daeaf4e5eefd8c35aa0c843dd8a0eaf7fef5`(`0.2.0`)。
>
> **核心仓库:** [`cflmy/marqdo-cli`](https://github.com/cflmy/marqdo-cli),审阅基线 `master@652ea763603517ba4d13325a405e3124844ded31`(已包含 3.0.0-rc.2 候选控制流、Analysis v3 与 Execution Events v1)。这些是**源代码审阅事实**,不是新特性已在发行二进制上验证的声明。
>
> **适用对象:** 不熟悉本项目历史的 View/CLI/前端开发者、审查者与测试维护者。
>
> **文档优先级:** 这是一份自足的完整实施 RFC,**整体替代**此前同名 RFC-VIEW-0003 的“历史结果持久化版”和“绝不在导出中包含结果版”;已实现的 RFC-VIEW-0002 能力仍是可复用基线。无须阅读任何聊天或前置 RFC 才能实施。
>
> **一句话产品定义:** **View 是一篇可调用的 Markdown 阅读器;执行结果只在当前交互中暂存,用户主动导出时,才被固化为一份独立、只读、可离线阅读的文档快照。**
---
## 0. 决议摘要:不建结果数据库,只允许显式静态导出
本规范区分三类对象。它们不可互换。
| 对象 | 权威来源 | 生命周期 | 允许操作 |
|---|---|---|---|
| `.mq.md` 源文档、依赖、知识 | 用户项目和版本控制 | 与 View 无关 | 阅读、静态分析、明确调用;**永不被导出结果改写** |
| 当前执行观察:参数、stdout/stderr、返回值、事件 | 真实 CLI `run/call` | View 进程内的有限任务生命周期 | 当前页面显示、取消、短时断线重连、在过期前选择导出 |
| **静态结果快照**:文档、已选定的一次结果、媒体、来源信息 | 用户明确点击“导出(含本次结果)”生成的文件 | 由用户下载/分发后独立于 View | 离线阅读、分享、审查;**不会恢复为可执行会话** |
### 0.1 必须满足的不变量
1. **打开、刷新、跳转、搜索、切换文档、普通静态导出都绝不执行程序。** 显式 `POST /api/runs` 是唯一启动 CLI `run/call` 的入口。
2. **导出结果只复制已完成的一次真实执行观察**,不能因导出而重跑、补跑、自动重试、自动申请权限或执行文档中的代码。
3. **默认普通导出**:`marqdo view export PROJECT --out SITE` 保持只读,内容为完整 Markdown 与安全本地媒体;没有结果数据。
4. **含结果导出**:从已运行的 Live 页面,由用户选定**一条仍在临时内存中**且终态明确的运行记录,确认内容与敏感性,然后导出只读快照。
5. **不建立 RunStore、SQLite、结果目录、浏览器 IndexedDB/localStorage 运行历史、持久 Kernel、跨重启恢复、自动导出。** 导出的文件由用户拥有;View 不维护文件索引与生命周期。
6. **静态 HTML 不得具有运行能力。** 无任何可生效的调用 API;无 `POST /api/runs`、无服务端依赖、无自动联网、无执行按钮假象。即使 HTML 中保存了结果,它也不是可恢复的会话。
7. **不得将运行输出伪装为原始 Markdown。** 可见标签须注明“本次执行快照”、运行目标、终态及来源摘要;只有通过验证的事件才能附着到源码位置。
8. **不为 View 修改语言内核或新增 `save_result` HostOp。** 所有真实计算仍使用公开 CLI、Analysis、Trace、Execution Events 和 Tool 协议。
9. **View 的“无保存”应精确定义为无自动、隐式、持久的运行存储;允许用户显式创建静态文档制品。** 这两者不矛盾。
### 0.2 用户路径(产品级完成标准)
1. 用户打开 `marqdo view examples/report/index.mq.md`,看到排版完整的文档、图片、公式、链接;不会自动运行。
2. 用户在 `## @exec ...` 函数标题旁点击“调用”,输入参数、查看权限和预算,确认一次 `marqdo call`。
3. View 显示实时 stdout、分支/循环事件、最终返回值,结果位于相关函数附近,但与源码视觉区分。
4. 用户点击结果旁的 **“导出文档(含本次结果)”**;预览会包含的结果、参数/隐私选项、失败或截断标记。
5. 用户确认后下载一份静态网站包(ZIP;内部 `index.html` + 媒体/字体/样式 + manifest)。解压后可用 `file://` 离线浏览;查看结果无需 CLI、View Server 或网络。
6. 页面再次刷新或 View 服务重启,不保证还存在这次运行;**已经导出的 ZIP 不受影响**。用户没有选择导出,就不会留下 View 管理的持久记录。
---
## 1. 完整职责边界:什么是 Markdown、执行观察和导出制品
### 1.1 Markdown 仍是页面主体
Marqdo 使用固定的 `marqdo.md.v1` Markdown AST;`@exec` 中的普通无标记叙述不执行,显式 `Strong` / `Emph` / inline Code 载体进入语句映射。`@knowledge` 是惰性知识区域。视图不能从视觉标记、Markdown 列表符号推断控制流;语义只依赖公开 Analysis。
UI 不采用 Jupyter 的 Cell/Kernel 模型。用户阅读的是一篇连续的、可执行知识文档。函数周围只有克制的调用入口和**可收起的实际结果**;列表、表格、图片、公式优先于状态卡片。
### 1.2 执行与结果的所有权
- **CLI**:检查、解析、调用、运行、权限、安全预算、计算真值。
- **View ExecutionController**:检查调用请求、显式确认、单活动任务、有界 stdout/事件与终态、取消、短时 SSE 重连;不是持久存储系统。
- **View Reader**:渲染 Markdown 与来源已校验的本次计算观察;不解释 Marqdo 表达式。
- **StaticExporter**:从读取模型及用户明确选中的**已验证终态观察**构建不可执行的离线制品;只做转换/打包,不调用 CLI。
- **用户项目**:如果需要 CSV、JSON、PNG 或其他正式业务数据,仍应由受授权的 Marqdo 程序或其他通用工具明确写出。View 的网页快照不等于领域数据存储。
### 1.3 不做的功能
不做历史列表、保存每次运行、最近实验恢复、Notebook Run All、自动重跑、后台刷新计算、不可见状态会话、结果数据库、实验对比平台、运行数据云同步、自动把运行输出写回 `.mq.md`、对 Math/Agent/Quantum 添加特殊处理。
用户在同一 View 页面上可再次调用函数;当前结果更新即可。为了控制复杂度,**第一阶段一份快照只包含用户明确选定的一次运行**;多次调用并排比较和合并多份结果属于后续独立需求。
---
## 2. 审阅基线与当前真实缺口(固定 SHA)
### 2.1 View 侧
| 分类 | 文件/实现 | 已确认事实 | 实施要求 |
|---|---|---|---|
| EXISTS | `src/reader/markdown.rs` | `comrak` 构造文档树,含图片、链接、表格、列表、数学、UTF-8 source span | 复用既有解析器,不复制第二套 Markdown→语义管线 |
| DEFECT | `src/reader/render.rs::Inline::Image` | 任何图片都显示“阻止自动加载”占位;合法本地图也不可见 | 增加同源安全本地图片解析、呈现与静态打包 |
| DEFECT | `src/reader/render.rs::resolve_link` | `.mq.md#fragment` 重写时可能丢 fragment;标题 ID 按字节位置生成,与常见 Markdown `#slug` 不一致 | 标准标题锚点、重复标题、跨文件锚点均需可导航 |
| DEFECT | `src/reader/render.rs::MathBlock / Inline::Math` | 公式主要显示 LaTeX 原文,不是真正数学排版 | 实现离线、安全数学渲染 |
| EXISTS | `src/reader/render.rs::render_functions` | 已有函数列表、调用按钮和签名信息 | 改善函数标题附近的调用与结果关联,不重写调用机制 |
| EXISTS | `src/execution/request.rs` | `RunRequest`、entry/function、参数校验、Analysis digest 与权限 | 继续保留唯一运行入口和确认流程 |
| EXISTS | `src/execution/controller.rs` | 单活动任务、去重、取消、内存任务、默认终态 TTL=15 分钟、上限 32 任务 | 在**现有 Job 终态内**保留导出需要的有界可信投影,不创建第二套历史库 |
| EXISTS | `src/execution/events.rs` | View 自有 SSE 生命周期事件协议 | 新 CLI 实时事件通过一个 EventBridge 映射;不创建第二个 Controller |
| DEFECT | `src/protocol/analysis_v2.rs` / `tool.json` | View 仅接受 Analysis 2;新 Core 对部分控制流发 Analysis 3 | 支持 Analysis v2/v3,基于 schema_version 协商 |
| DEFECT | `src/core_client.rs` | 现有执行主要为 `--json` + Trace,运行末尾读取结果 | 消费新 `--event-stream jsonl`,不能与 `--json` 同时使用 |
| EXISTS | `src/export.rs` | 静态导出包含 HTML 和 View 内置资源、manifest;还未集成用户 Markdown 图片 | 扩展已有 StaticExporter;允许**可选** `ExportResultOverlay`,不得重写导出器 |
| EXISTS | `src/server/routes.rs` | 有 7 条固定路由,执行入口是 `POST /api/runs` | 增加一个受保护的结果**导出** POST,而非运行/保存/历史路由 |
固定来源:[`View 源码`](https://github.com/cflmy/marqdo-view/tree/dcb9daeaf4e5eefd8c35aa0c843dd8a0eaf7fef5)。
### 2.2 Core 侧公开协议(不可通过猜测添加字段)
- [`spec/markdown-profile.md`](https://github.com/cflmy/marqdo-cli/blob/652ea763603517ba4d13325a405e3124844ded31/spec/markdown-profile.md):`marqdo.md.v1`,CommonMark/GFM/数学/front matter 扩展的闭合选项。
- [`spec/analysis-v2.md`](https://github.com/cflmy/marqdo-cli/blob/652ea763603517ba4d13325a405e3124844ded31/spec/analysis-v2.md)、[`v3`](https://github.com/cflmy/marqdo-cli/blob/652ea763603517ba4d13325a405e3124844ded31/spec/analysis-v3.md):多臂 `else if` 两版支持;含 `break/continue` 的内容可能选择 v3。View 不能假设永远是 v2。
- [`spec/trace-v2.md`](https://github.com/cflmy/marqdo-cli/blob/652ea763603517ba4d13325a405e3124844ded31/spec/trace-v2.md):Trace 绑定精确 Analysis JSON 字节 SHA-256,带 source span 的真实事件,可截断、不可伪造。
- [`spec/execution-events-v1.md`](https://github.com/cflmy/marqdo-cli/blob/652ea763603517ba4d13325a405e3124844ded31/spec/execution-events-v1.md):`run/call --event-stream jsonl`,实时 stdout/stderr chunk、结构事件、可选选择性值观察与终态;`--event-stream` **与 `--json` 互斥**;Trace v2 可并用。
- [`spec/tool-v1.md`](https://github.com/cflmy/marqdo-cli/blob/652ea763603517ba4d13325a405e3124844ded31/spec/tool-v1.md):独立 Tool 的调用/安装/协商,不为 View 添加 CLI 领域分支。
**实现事实不等于发行承诺。** 所有用到 Analysis 3、Events v1 的发布门禁都必须用同一个真实已发布 Core 二进制验证。
---
## 3. 最小模块架构:不是持久化系统
```text
原始项目 (.mq.md + 本地图片/媒体)
│
▼
DocumentService ──► MarkdownDocument + SourceIndex
│ │
├── CoreAdapter ─────┤ Core `check --emit` → Analysis v2/v3
│ │
▼ ▼
PresentationModel ◄── SemanticProjection
│
├── ReaderRenderer ──► Live HTML ← 当前调用结果(可选瞬态附着)
│ ▲
│ └── LinkResolver / MediaResolver / MathRenderer
│
浏览器(显式调用)
│ POST /api/runs(唯一执行入口)
▼
ExecutionController ─► CoreAdapter ─► 真实 MARQDO_BIN run/call
│ │
│ ├── Execution Events v1 → EventBridge → SSE
│ └── Trace v2 → 精确摘要绑定
▼
当前 Job 的有界终态投影(仅内存;TTL 到期删除)
│
│ 用户点击“导出文档(含本次结果)”
▼
POST /api/exports ─► ExportSelectionValidator
│ │
│ ├─确认 session / run_id / 终态 / 摘要 / 隐私
│ └─构造只读 ExportResultOverlay
▼
StaticExporter(与普通导出同一套 Renderer)
│
▼
ZIP: index.html + pages/ + media/ + assets/ + manifest.json
│
└── user download → 文件独立存在;View 不保存索引/历史
```
### 3.1 模块不可违背的依赖方向
- `protocol/` 只验证公开协议,不依赖 `reader/`、DOM、HTTP。
- `execution/` 只持有 CLI 执行与有界任务状态,不存 HTML;Job 可暴露经鉴权的**只读** `TerminalExportCandidate`。
- `reader/` 可以接受不可变的 `ExportResultOverlay` 并安全渲染,但不得反向调用 `ExecutionController`。
- `export.rs` 只接受静态文档模型、媒体清单和可选的不可变导出叠加层;**不得有 `run()`、`call()`、命令执行或未验证事件解析逻辑**。
- `server/` 鉴权并从当前 Job 获取候选结果,然后传入导出器;这是唯一把瞬态执行观察连接到静态发行物的边界。
- Live、纯文档导出、含结果导出共用 **同一个** `DocumentModel`、`ReaderRenderer`、Link/Media Resolver 和主题。禁止第二套“结果版 HTML 模板”。
### 3.2 推荐目录变更(文件名仅为建议,不强求完全一致)
```text
src/
core_client.rs # MARQDO_BIN 唯一公开调用适配层
protocol/
analysis.rs # Analysis v2/v3 版本分发 + 验证
execution_events_v1.rs # Core NDJSON 事件验证
trace_v2.rs # Trace 绑定与可选观察
reader/
markdown.rs # 原有 comrak 文字/结构模型
model.rs # 原有 PresentationModel
render.rs # 单一 HTML 渲染器
links.rs # 文档路径、标题锚点
media.rs # 项目内媒体只读解析/安全检查
execution/
request.rs # 统一参数与权限请求
process.rs # 唯一进程执行实现
controller.rs # 单活动任务;瞬态 Job;无结果数据库
events.rs # View SSE
export_candidate.rs # 从已完成 Job 只读投影可导出字段
export.rs # 共用静态导出核心
export_result.rs # 选择、审查、脱敏、生成 Overlay
server/
routes.rs # 一个新 POST /api/exports
security.rs # session/Origin/CSRF
assets/
reader.js # 含结果导出确认、文件下载
reader.css # 只读结果排版
```
**若仅需几十行代码,不必为了名字建立一层空模块。** 核心约束是责任单一、依赖单向、统一协议和单渲染管线。
---
## 4. Markdown 全面可视呈现:优先于结果导出
### 4.1 正常可显示的内容
| 类型 | 最小通过要求 |
|---|---|
| H1–H6/Setext | 连续文档流;保持层级;`@exec/@knowledge` 标注不吞标题内容 |
| 段落/行内强调/代码 | CommonMark 源样式;载体高亮不得改变内核语义 |
| 有序/无序/嵌套列表 | 真正 HTML 列表层级;`1.` 分支风格与 `-` 循环风格正确显示;**列表本身不执行** |
| GFM 表格、任务列表、删除线 | 表格对齐、checkbox、删除线真实可见 |
| 代码围栏/引用/分隔线 | 正确显示并保持惰性资源属性 |
| 本地 PNG/JPEG/WebP/GIF/SVG | 有权限控制的真实图片渲染;替代文本、尺寸限制;本地恶意 SVG 不得获得脚本能力 |
| 同页、跨 `.mq.md`、外部链接 | fragment 不丢失;重复标题确定性锚点;外部链接只导航不自动下载 |
| 行内与块级数学 | 离线 KaTeX 或等效安全渲染;无 CDN;不可执行 LaTeX 宏 |
| 源码态 | 无损精确 UTF-8 原文;中文/BOM/CRLF span 可对应 |
| Raw HTML | 默认**不直接执行** HTML/JS;安全降级为明确提示或受限 allowlist,而非声称支持运行任意网页代码 |
注意:Marqdo 的 Markdown profile **不是所有非标准 Markdown 扩展的全集**。例如脚注、自动 URL 链接、wiki-link 等若未启用,不得假称内核支持。View 可展示原文,但不得偷偷让解析选项改变程序语义。
### 4.2 图片与媒体安全
- 从当前文档目录解析相对 URL,允许 `../assets/x.png` **仅在规范化并解析真实路径后仍位于项目根之内**;阻止绝对路径、NUL、控制字符、 symlink 逃逸与 TOCTOU。
- Live 增加受保护的只读媒体读取路由;验证扩展名不足,必须校验 MIME/魔数及尺寸/字节预算。
- Export 将引用的安全媒体复制到 `media/`,计算 SHA-256 和 manifest,脱离原工作目录仍可 `file://` 阅读。
- 默认不自动拉取远程图片、CDN 脚本、字体或执行输出引用;远程资源降级时保留 alt/地址与原因。
- 原始 HTML、SVG 中的脚本、`javascript:` URL、`data:text/html` 等受限;普通外链可单击导航,但不自动发送页面内容。
### 4.3 链接与锚点
`resolve_link()` 必须统一处理:`#slug`、`doc.mq.md#slug`、`../docs/doc.mq.md#slug`、百分号编码与 Unicode、重复同名标题、文档重命名及不存在的目标。Live 和 Export 应产生同义结果,实际点击必须到达目标标题;不能只看生成了 `<a>` 标签。
源字节 span ID 可以继续用于 Analysis 精确绑定,**但需要另外提供符合 Markdown 阅读习惯的稳定标题 slug**;两者分别服务语义锚定与读者跳转,不可混用。
### 4.4 数学公式
数学排版是 View 责任,不是 Math HostOp。资源应离线、固定版本、禁止不可信 HTML/宏,Live 和 Export 共用同一公式处理与字体资产;导出的计算快照即使不能执行,也必须保留公式排版。
---
## 5. 统一单函数执行:View 只有一条运行数据通道
### 5.1 静态能力与目标
- `check --emit` 输出 Analysis v2 或 v3(按 JSON 实际 `schema_version` 验证,绝不猜)。
- H2 `@exec` 函数从 Analysis 确定可调用目标、签名、参数名、默认值;`@knowledge` 不调用。
- `main` 显式 `run` 与所选函数 `call` 使用**同一** `ExecutionController`、权限确认、预算、终态和结果组件;不得扩展为分函数单独后台线程池。
- 对 `else if` 使用已有 `branch.arms`;对 `break/continue` 投影 Analysis v3 对应节点。不存在这些语句时 v2 继续正常支持。
- 跨文档函数调用遵循 CLI `call` 已公开可调用目标限制;不能把依赖模块的任何可见标题都当成可直接调用的独立入口。
### 5.2 实时事件
运行必须在真实已发布二进制上验证:
```bash
marqdo check index.mq.md --emit ./analysis.json
marqdo call index.mq.md 计算均值 --arg 'a=3' --arg 'b=5' --event-stream jsonl --trace-file ./trace.json
```
> 示例仅说明调用与协议形状;参数名称、函数及作用域须与项目真实声明匹配。`--event-stream jsonl` 与 `--json` 互斥,必须做模式选择,不能将两者拼在一起。
`EventBridge` 负责完整解析 `stream.opened`、`run.started`、`stdout.chunk`、`stderr.chunk`、`call.*`、`branch.eval`、`loop.iteration`、`control.break/continue`、`effect`、`run.completed/failed/rejected`。严格校验 seq、schema/version、run_id、终态唯一性、base64 长度和源摘要;EOF 无终态就是 `incomplete`,不是成功。
SSE 仍为 View 与浏览器之间的现有通道。**Core NDJSON 和 View SSE 是不同协议**;允许 Versioned EventBridge 映射,不得把未经验证的 JSON 直接抛给前端执行或视为可信 HTML。
### 5.3 权限和预算
沿用现有 session Cookie、Origin、CSRF、单活动任务、显式授权与 `pure/project` 限制;不暗中开放 net/process/foreign/plugin。Live 页面调用与静态导出都是独立行为;**静态导出 API 不具备运行 Core 的权限或调用路径**。
当前的有界内存 Job 已足够提供“最近一次结果导出”,无需结果历史服务。若执行输出过大,终态保留安全截断标记;**不要为了导出提高 Core 的执行权限或无限内存预算**。
---
## 6. 核心新功能:显式导出包含一次运行结果的静态文档
### 6.1 两种导出,单一实现
**A. 纯文档导出(默认、既有模式)**
```bash
marqdo view export ./project --out ./site
```
含原始 Markdown 的静态阅读视图、引用本地安全媒体、公式资产、manifest。**无需执行、不读取 Controller、不含运行结果**。该命令在全新进程中运行,不存在“刚才浏览器里跑过一次所以能找到结果”的假设。
**B. 含本次执行结果的导出(新增、仅 Live 当前会话)**
浏览器内先显式运行一次,再在终态区域选择“导出文档(含本次结果)”,勾选敏感字段和输出范围,确认后调用 `POST /api/exports`。后台从**同一进程、同一 session 的现有 Job 内存态**读取这次终态,验证后传给同一个 `StaticExporter`;最后直接返回 ZIP 文件供用户下载。**绝不重新运行 CLI**。
本阶段不提供 `marqdo view export --include-last-run` 等会误导人的选项:一个新启动的命令行进程无权也无法访问浏览器会话中的内存任务。未来如需纯 CLI 的“明确运行 → 导出”一体化工作流,必须另立接口规范,要求可验证的同一次执行和显式输出,不能偷偷变成持久 RunStore。
### 6.2 唯一新增 HTTP 路由
`POST /api/exports`,**不是** `/api/runs/save`、`/api/history`、`/api/records`;其职责仅为把一次当前终态转为即刻下载的静态制品。
提议请求格式(本协议为**View 自有新增 v1**,需要在 View 仓库落地 schema 与负例):
```json
{
"schema": "marqdo.view-static-export-request",
"schema_version": 1,
"run_id": "<current-session-terminal-job-id>",
"document": "index.mq.md",
"analysis_digest": "sha256:<exact-current-analysis-bytes>",
"scope": "document",
"include": {
"result_value": true,
"stdout": true,
"stderr": false,
"trace_summary": true,
"arguments": false
},
"confirm_sensitive_output": false,
"client_export_request_id": "<opaque-id>"
}
```
- body 大小、字段集合、枚举、长度均有严格上限;拒绝未知字段、未知 major。
- 必须是当前 Cookie session 的 Job;`run_id` **不是**授权令牌,不得仅凭 ID 访问其他会话结果。
- 服务器重新验证 Origin + CSRF 及当前文档、真实当前 Analysis 字节摘要、项目身份、Job 终态与来源。
- `run_id` 处于 `running/accepted`、已过 TTL、不存在或不属于当前 session:明确拒绝;**绝不启动新运行**。
- `scope=document` 第一阶段只导出承载该次函数的文档和必要媒体;如果继续保留现有项目级导出布局,则其他页面为**纯文档**,不得把一次结果贴到所有页面。
- `include.arguments=false` 默认。不要默认导出输入参数的实际表达式、授权 glob、环境变量、文本观察值或原始扩展细节。任何含敏感数据选择必须展示最终预览并二次确认;`confirm_sensitive_output` 不替代用户真实 UI 操作。
- 可以导出失败、取消、超时的**终态观察**,但必须醒目标记 `failed/cancelled/timed_out` 和是否有部分数据,不得当成成功结果;第一阶段可为它们提供明确的单独复选确认。
- HTTP 输出为直接下载的 `application/zip`,设置 `Content-Disposition: attachment`、`Cache-Control: no-store`、`X-Content-Type-Options: nosniff` 与严格 CSP。ZIP 构建在有界、私有、短生命周期临时目录内,发送完立刻清理;不增加后台缓存下载接口。
- 浏览器使用经过认证的 `fetch POST` 获取 ZIP `Blob` 后触发用户下载,及时释放 Blob URL;**不能用 localStorage/IndexedDB 缓存 ZIP 或计算结果**。
### 6.3 一个额外的只读导出投影,而不是新数据系统
不新增 `RunStore`。在原有 `Job` 终态中保留足够导出的、**已经完成验证且有字节上限**的 `TerminalExportCandidate`;只在现有 TTL 内存在。Controller 暴露:
```text
get_export_candidate(session_id, run_id)
-> Result<ImmutableTerminalExportCandidate, ViewError>
```
这个 API **只读、不能执行、不分配长期 ID、不创建记录文件**。内部包含:
- View `run_id` 与 CLI 真实 `core_run_id`(如果协议提供,来源明确)、函数 `function_id`、源文档 `module_id`/相对路径、终态和时间。
- **精确** `analysis_digest`、`root_id`、相关源码 SHA-256、可用的 lock digest、已选择的媒体哈希。为避免泄漏,绝对路径、用户名、环境变量、秘钥不放入导出。
- Core 版本与协议版本、运行模式和预算的**安全摘要**(不包含授权秘密和具体敏感路径)。
- 通过解析器验证后的 Wire Result、stdout/stderr 文本/字节及其完整性状态、可选经核验的 Trace 结构摘要。
- `truncated`、`trace_invalid`、`source_changed`、`output_incomplete` 等独立事实状态;不能为了拥有一个“成功”徽章而合并这些区别。
**注意隐私:** 不记录省略参数值的未经加盐普通哈希作为“隐私替代”,低熵参数可能被猜测;默认只标记 `parameters: omitted`。需要复现实验的用户可以明确选择导出必要的可见参数并接受隐私提醒。
### 6.4 快照来源与失效规则
- 导出开始前获取并核对**当前** `check --emit` 的真实 Analysis 字节摘要;必须与候选结果的 `analysis_digest` 相同,来源 `root_id` 与选定函数 ID 相符。`run.started.source` 的摘要也需要一致。
- 用户运行之后源码、导入内容、锁文件或相关模块变更:第一阶段**拒绝“将旧结果贴到新正文”**,UI 提示先重新运行;不得仅凭函数名相同就附着。
- 运行时源验证通过,但 Trace 文件无效或缺失:导出可保留真实终态、返回值和 stdout,但必须清楚标记 `trace_status=invalid/unavailable`,**不附着任何未经核验的源码侧注**。
- Trace 截断、输出截断、SSE 未收到终态:区分处理。无真实终态的运行不可作为成功快照;可以提供“错误报告”但必须单独实现与审查,不在 P0 混入。
- 静态快照在导出时被冻结;以后源代码变化**不会改变已下载的 HTML**。manifest 提供当时内容的来源摘要,但**不声称当前代码仍与历史结果匹配**。
- 来源身份不是数学正确性证明或第三方签名。除非独立 Prove 工具验证过证书,不展示 `proved`。
### 6.5 导出的内容结构
最低交付为一套 HTML+资产的 ZIP,不要求单文件 HTML;优先延续当前 `StaticExporter`:
```text
marqdo-report-2026-11-24.zip
index.html
pages/
index.mq.md.html
media/
diagram-<digest>.png
assets/
reader-<digest>.css
math-<digest>.css
...
manifest.json
```
`index.html` 中的结果应插入**所选函数阅读区域下方**,并在页面顶部有简洁的“本文件包含一次执行快照”提示。静态导出页面的调用按钮应被完全移除;结果使用 `<details>` 或可打印的常规 HTML,禁用 JS 也能阅读。源码段落和结果块的 DOM 类名/aria 标签不同。
**建议 manifest v2 示例**(是 View 自有导出契约,不是 Core 改动):
```json
{
"schema": "marqdo.view-export",
"schema_version": 2,
"view": {"name": "marqdo-view", "version": "<view-version>"},
"source": {
"project_root_id": "root:demo@0.1.0",
"document": "index.mq.md",
"source_sha256": "<64hex>",
"analysis_digest": "sha256:<64hex>",
"lock_digest": "<lock-digest-or-null>"
},
"execution": {
"included": true,
"target": "root:demo@0.1.0::index.mq.md::计算均值",
"status": "succeeded",
"source_verified": true,
"trace_status": "verified",
"result_complete": true,
"parameters": "omitted",
"core_protocol": {"analysis": 2, "trace": 2, "events": 1}
},
"assets": [
{"path": "assets/reader-<digest>.css", "sha256": "<64hex>", "size": 1234}
],
"files": [
{"path": "index.html", "sha256": "<64hex>", "size": 5678}
],
"executed_during_export": false
}
```
这些 `<...>` 字段是**规范示例占位符**,不是可运行的发行文件。真实 manifest 必须通过自有 JSON Schema 校验。`execution.included` 与 `executed_during_export` 是两个不同概念:**包含过去一次明确执行的观察,不代表导出动作执行了任何代码**。不要沿用只有一个易混淆 `executed` 布尔值的旧表示。
是否在 HTML 中另存一份完整机器可读 EventStream,需单独考虑隐私、文件膨胀和浏览器安全;**P0 只保存选择的结果与经过验证的有界摘要**,并在 manifest 中声明完整性,不把所有 token、每个变量、原始秘密偷偷打包。
### 6.6 导出样例的实际 HTML 阅读效果
源 Markdown(继续保持普通、可直接渲染):
````markdown
# @knowledge 一个小型统计实验
这份文档说明两数平均值的计算依据,并允许读者调用函数。
![算法说明图](./media/overview.png)
## @exec 计算均值
对两个整数求平均值;结果可能有小数部分。
`params(a: Int, b: Int)`
**结果 = (a + b) / 2**
`return 结果`
````
用户手动调用 `计算均值(a=3, b=5)`,假设真实返回 `4`。View 中显示:
> **本次执行** · 函数:计算均值 · 成功
>
> 参数:a=3, b=5(仅在本地 UI 中显示;是否导出由用户决定)
>
> 返回值:`4` · 来源:已验证的 CLI 终态
>
> [导出文档(含本次结果)]
用户确认导出时,静态页面中对应函数下方出现:
> **执行快照(用户于导出时明确附加;不是源文档)**
>
> 执行目标:计算均值;状态:成功;返回值:`4`
>
> 来源:项目/源码/Analysis 摘要见 manifest;未在导出期间重新运行
>
> 参数:未包含(默认隐私设置)
这里的 Markdown 行为只是产品说明,并不意味着执行结果会注入项目 `.mq.md` 文件。样例需要在真实 CLI 与 browser E2E 中验证;如数值类型的 Wire 表达与示意不同,应以真实协议编码为准。
---
## 7. 导出安全与隐私:这是文件发行,不是本地历史
### 7.1 显式披露与选择
输出可能包含令牌、路径、个人信息、数据库记录或远端服务响应。点击导出后至少展示:目标函数、执行终态、所选 stdout/stderr 大小、结果字节数、是否包含参数值、是否含观察值、是否有失败/截断/敏感性风险。用户必须明确确认;不得把浏览器执行结果默认为可发布数据。
推荐默认:包含返回值和有界 stdout、经过验证的结构事件**摘要**;不包含 stderr、原始参数表达式、环境变量、绝对路径、观察到的原始 Text 值、资源句柄或完整二进制内存。用户如需增加内容必须手动勾选,并通过大小及隐私门禁。
### 7.2 严格隔离和输出转义
- 同源鉴权 Cookie + Origin + CSRF + session-job 所有权。禁止跨浏览器会话导出同一个 `run_id`。
- 编码与 HTML 转义统一在 `ReaderRenderer`;stdout、stderr、result/Trace 字符串必须以**文本**渲染,不允许 `innerHTML`、远端模板、运行输出中的 `<img onerror>` 生效。
- ZIP 安全:固定内容路径与规范化目录名、绝不写 `../` 归档条目、不包含系统绝对路径、不将软链接解引用到项目外;控制总文件数、总字节数、单媒体上限、压缩比/解压后大小。
- CSP:静态快照默认 `default-src 'none'`,只开放打包的 CSS、同源相对媒体和必要的离线公式字体;不要包含自动远程字体、远程 JavaScript、iframe 等。
- HTTP `no-store`、下载后立即删除服务端临时文件;浏览器下载动作结束撤销 Blob URL。
- manifest 内容摘要不等于签名;可选独立签名属于未来工具,不得虚构真实性认证。
### 7.3 无保存架构门禁
仓库测试/静态检查应拒绝以下新增行为:
- `.marqdo-view/runs/`、`run_history.db`、`RunStore`、`RunRecord`、浏览器 IndexedDB 持久输出与 `POST /api/runs/save`。
- View 进程启动后主动扫描历史输出或恢复终态。
- `marqdo view export` 在新进程中猜测/查找“最近一次执行结果”。
- 含结果导出未提供有效 `run_id` 却直接执行 Core 以填充结果。
- 为导出特意保留永久临时目录,或导出后在服务器暴露永久下载 URL。
**允许:** 终态 Job 的原有 TTL 内存、只在响应期间存在的临时 ZIP、用户已下载的 ZIP、静态 HTML 所引用的必要本地媒体与样式。
---
## 8. 浏览器与 HTTP 交互设计
现有 API 不破坏,新增路由只做快照导出。
| 路由 | 作用 | 会执行 Core? | 结果生命周期 |
|---|---|---:|---|
| `GET /`、`GET /file?...` | 阅读当前文档 | 否 | 无 |
| `GET /assets/...` | View 内置 CSS/JS | 否 | 发行资源 |
| `GET /api/documents` | 文档列表 | 否 | 无 |
| `GET /media/...`(提议) | 验证后的项目媒体 | 否 | 只读 |
| `POST /api/runs` | **唯一显式运行入口** | **是** | 现有单任务、临时 Job |
| `GET /api/runs/{id}/events` | SSE 重连/观察 | 否 | TTL |
| `POST /api/runs/{id}/cancel` | 取消已有运行 | 不启动新运行 | TTL |
| **`POST /api/exports`(提议)** | 当前终态 → 静态 ZIP 直接下载 | **绝不** | 响应完成后删除服务端临时文件 |
浏览器 UI 流程:
```text
未运行文档
│ 点击“调用”→ 填参 → 确认
▼
执行中:EventBridge → SSE(取消可用;“含结果导出”不可用)
│ 唯一终态
▼
结果面板:返回 / stdout / 事件 / 状态 / 来源
├── 清除当前结果(仅内存 UI)
└── “导出文档(含本次结果)”
│
▼
结果范围 + 隐私预览 + 明确确认
│ POST /api/exports(无 Core 调用)
▼
浏览器下载 .zip,独立离线可阅读
```
若用户选择“导出纯文档”,仍走现有 StaticExporter,只传 `ExportResultOverlay=None`。不应把“已经在 UI 中看到了结果”理解成自动将它放入任何普通导出包。
---
## 9. 数据边界:实现者需要的最小类型与失效状态
提议数据模型(代码为设计伪类型,不表示当前仓库已有这些定义):
```text
ImmutableTerminalExportCandidate {
view_run_id, session_owner, terminal_status,
function_id, module_id, document_relative_path,
core_version, analysis_version, analysis_digest,
project_root_id, source_sha256, lock_digest?,
result_value?, stdout?, stderr?,
trace_status, verified_trace_summary?,
output_complete, observation_truncated,
created_at, terminal_at
}
ExportSelection {
run_id, document, analysis_digest,
include_result_value, include_stdout, include_stderr,
include_trace_summary, include_arguments,
confirmed_sensitive_output
}
ExportResultOverlay {
source: VerifiedSourceBinding,
target: VerifiedFunctionIdentity,
state: TerminalState,
value: SafeDisplayValue?,
stdout: EscapedText?, stderr: EscapedText?,
trace: VerifiedTraceSummary?,
completeness: ExplicitFlags
}
```
**禁止 `ExportResultOverlay` 保存 `Arc<Job>`/锁/进程句柄**;它是从执行端复制出的受上限约束、不可变的数据。将其传给 `StaticExporter` 时,不允许导出器自行重查 Controller,也不允许重新解释 Value Wire。
状态显示必须区分:`not_run / running / succeeded / failed / cancelled / timed_out / incomplete / source_changed / trace_unavailable / trace_invalid / trace_truncated / output_truncated`。其中失败/取消/截断是不同维度;不能把 `trace_invalid` 当成运行失败,也不能把运行成功当成完整 Trace 或证明成功。
---
## 10. 真实测试:先构造无法蒙混的 fixture
### 10.1 必需的示例项目
```text
examples/complete-reader/
marqdo.yaml
index.mq.md # @knowledge、@exec、文本、列表、表格、公式、函数
docs/explanation.mq.md # 带跨文档与 fragment 链接、重复标题
media/flow.png # 真实 PNG,非占位字符串
media/result.webp # 真实 WebP,需解码校验
media/diagram.svg # 经过安全审核的 SVG
media/README.md # 资源来源及使用许可
```
必须有显式函数:`main`、有参数纯函数、含 `else if` 的函数、含 `break/continue` 的循环、失败函数和有界 stdout 函数。真实 Core 使用固定 SHA 的 Linux 发行包测试;View UI 使用真实 Chromium,不仅是 HTML contains 断言。
### 10.2 主要验收矩阵
| ID | 测试情景 | 必须观察到的事实 |
|---|---|---|
| MD-01 | 本地 PNG/WebP/GIF | 实际 `naturalWidth>0`,alt 有效,响应 MIME 与哈希正确 |
| MD-02 | 图像引用 `../media/x.png` | 根内允许;逃逸根、symlink 到外面拒绝 |
| MD-03 | 图片静态导出后离线打开 | 没有任何网络请求,图片仍显示 |
| MD-04 | 外链/相对链接/同页 anchor/跨文件 anchor | 实际点击到达目标;重复标题确定性编号 |
| MD-05 | 行内/块数学和 GFM 表格、列表 | Live、Export 同样渲染,无远端字体 |
| MD-06 | Raw HTML/恶意 SVG/JS URL | 不产生脚本执行或远端加载 |
| CORE-01 | 纯函数 Analysis v2 | 函数表单可用、结果正确 |
| CORE-02 | 带 `break/continue` 的项目 Analysis v3 | View 成功协商、显示正确语义,不误拒绝 |
| CORE-03 | `else if` 多臂 | View 不重新推断分支;结构与来源正确 |
| CORE-04 | `--event-stream jsonl` | `stream.opened` 到唯一终态按 seq 显示;不与 `--json` 混用 |
| CORE-05 | stdout 中间输出 | 执行完成前可见;最终字节与真实输出一致 |
| CORE-06 | EOF 无终态 / 非法 NDJSON / 源摘要错 | 标 `incomplete`/`invalid`,不伪造成功 |
| CORE-07 | 未确认权限/无 main/错误参数 | 不能执行或提示正确,不自动降级权限 |
| EXPORT-01 | 未执行时普通导出 | 没有结果,Core `run/call` 计数 0 |
| EXPORT-02 | 已完成一次函数调用后普通导出 | **仍不包含结果**,执行次数不增加 |
| EXPORT-03 | 已完成一次函数调用后含结果导出 | ZIP 解压可见选中的真实结果,Core 调用数**完全不增加** |
| EXPORT-04 | 同一函数另一次调用 | 只能选定明确的 run_id,不能混合结果 |
| EXPORT-05 | 导出前源码或锁变更 | 拒绝绑定旧结果与新文档;没有隐式重跑 |
| EXPORT-06 | `run_id` 属于其他 session、过期、仍运行 | 403/404/409 中明确稳定错误;没有内容泄漏 |
| EXPORT-07 | 参数/文本观察值涉及秘密 | 默认不含参数、stderr、敏感原始观察;显示导出预览与确认 |
| EXPORT-08 | stdout 包含 `<script>`、`<img onerror>` | 导出页面显示为纯文本,Chromium 无脚本事件 |
| EXPORT-09 | 失败/取消/超时、Trace 缺失/截断 | 显示真实状态;仅合规字段被导出;不标“已验证成功” |
| EXPORT-10 | 导出下载 ZIP 后关闭 View/删除临时目录 | `file://` 完全离线可读、无外部请求;没有依赖 localhost |
| EXPORT-11 | View 重启、超过终态 TTL | 不能恢复任何运行;先前已下载的 ZIP 正常 |
| EXPORT-12 | POST 导出未带 CSRF 或跨 Origin | 拒绝;不进入生成器、不访问其他 session 的 Job |
| EXPORT-13 | 多个恶意路径、ZIP 条目、超大结果 | 不发生目录穿越、内存失控、Zip Slip |
| EXPORT-14 | snapshot manifest / CSS / 媒体篡改 | 哈希验证失败;结果来源与资产身份可核对 |
| EXPORT-15 | 打包中途失败、客户端断开 | 无半成品持久文件;临时文件被清理 |
| ARCH-01 | 查找 View 源码的历史库、持久缓存 | 无 RunStore/历史 DB/跨重启恢复/浏览器结果存储 |
| ARCH-02 | 解析导出函数调用关系 | `StaticExporter` 无 `run/call` 依赖;只有 POST `/api/runs` 执行 |
| ARCH-03 | 单一渲染器 | Live、纯文档导出、含结果导出复用同一个 HTML 构造与安全转义 |
### 10.3 三条最高优先级黑盒门禁
1. 打开 View → 不执行;运行一次 → `run/call` 次数恰为 1;点击“导出含结果” → 次数**仍为 1**。
2. 将 `.mq.md`、图片、依赖摘要在运行之后改变 → 含结果导出**拒绝把旧结果贴到新正文**;不尝试重跑。
3. 下载 ZIP,关闭 View Server,断网,清空浏览器缓存后,从 `file://` 阅读文档、图片、公式及结果;没有脚本执行、远程资源请求或运行功能。
### 10.4 证据要求
须记录用于验收的 CLI 发行二进制哈希和版本、View 源码 SHA、Linux 平台、`cargo fmt/clippy/test --locked`、受保护的 HTTP 与 ZIP 负例、Chromium 截图/浏览器日志、运行计数哨兵和 manifest 摘要。未执行的验证必须写 `UNVERIFIED`,不能用旧版 RFC 的 PASS 代替。
---
## 11. 开发实施顺序:少量 PR,单一职责
| PR | 内容 | 完成标准 |
|---|---|---|
| PR-00 | 固定 CLI/View 二进制与源码基线;更新 ADR,撤销旧 RunRecord/不允许结果导出的相反决策;新增失败 fixture | 开发者只读本 RFC 与仓库即可复现真实缺口 |
| PR-01 | Analysis v2/v3 消费者;新控制流;Execution Events v1 EventBridge | 真实 Core 的 check/call/run 通过,SSE 不重造语义 |
| PR-02 | Markdown 完整性、图片只读媒体、链接/slug、公式排版 | 真正图片与跨页链接在 Chromium 可用,恶意资源拒绝 |
| PR-03 | 将媒体与字体纳入既有 StaticExporter;保持纯文档导出零结果/零运行 | 离线 `file://` 阅读 PASS,manifest 完整 |
| PR-04 | 函数旁就地调用、终态投影稳定、结果源验证;不建历史数据库 | 同函数调用一次、取消、失败、截断均正确显示 |
| **PR-05** | `POST /api/exports`、ExportSelectionValidator、不可变 Overlay、共用 Renderer 的“含结果” ZIP | 显式单次结果快照;**导出绝不执行**;源变更/跨会话拒绝 |
| PR-06 | 浏览器隐私预览、下载流程、a11y/打印/离线、全链路安全/性能/验收证据 | 真实 CLI + Chromium + ZIP/哈希验证通过 |
实施时 PR 不宜一边修协议一边创造新产品数据模型。P0 从**一条已完成且来源匹配的当前会话结果**生成静态 ZIP 即可,不做多结果合并、分享服务器与结果搜索。
---
## 12. 独立开发的 DoD(验收标准)
- [ ] View 仍是独立 Tool v1;不修改 `marqdo-cli`、不链接私有 Rust crate、不添加 `save_*` HostOp。
- [ ] 纯 Markdown 阅读、图片、跨文档链接、锚点、公式、代码围栏、GFM 表格都符合 Profile,真实浏览器完成验证。
- [ ] Analysis v2/v3 与 Events v1/Trace v2 通过公开 Schema 和固定来源摘要验证,旧 CLI 能力不足时**明确拒绝**而不是伪造。
- [ ] `run(main)` 与 `call(function)` 统一任务流程,只有 `POST /api/runs` 触发执行、且必须用户显式确认。
- [ ] 普通 `view export` 零运行、零结果;含结果导出要求当前 session 中明确选中的**终态**,绝不启动第二次执行。
- [ ] 所有导出使用唯一 `DocumentModel` / `ReaderRenderer` / `StaticExporter`,仅通过不可变 `ExportResultOverlay` 添加已验证结果。
- [ ] 用户下载 ZIP 中的 HTML/资源离线可读,结果与原文可视觉区分,源码和源项目不被改动。
- [ ] 运行后源、Analysis、项目身份变更时阻止错误附着;Trace 缺失与运行终态分离,不捏造证据。
- [ ] 默认输出不含未确认的参数值、stderr、秘密、绝对路径或原始高风险观察;HTML/ZIP/XSS/CSRF/媒体路径门禁 PASS。
- [ ] 进程重启后无运行历史可恢复;用户已下载文件可以永久独立存在;没有 RunStore、数据库、`localStorage` 结果缓存、后台自动保存。
- [ ] 全套测试在同一 SHA 的真实发行 Core、真实 Chromium 和离线环境通过;未测试项标 UNVERIFIED。
---
## 13. FAQ:开发者不能自行改写这些设计决定
**Q1:为什么允许用户下载一份包含结果的 ZIP,却不允许保存结果?**
因为两者有本质区别:View 不会在每次运行后主动创建可查询的持久记录;只有用户明确选择“发行一份静态报告”时,才产生一个由用户持有的不可执行文件。**这是文档导出,不是 View 的运行历史系统。**
**Q2:为什么不直接把结果追加到 `.mq.md`?**
`.mq.md` 是源文档与可执行知识,修改它会改变 Git diff、摘要和语义引用,还可能把本来是输出的内容误作为 `@exec` 载体。导出把输出放在独立 HTML 附着层;原文完全不变。
**Q3:为什么不采用 `.ipynb` 的 Cell Outputs / Kernel?**
我们只借鉴“结果与文档共同可阅读、可以离线带走”的优点。Marqdo 以完整 Markdown 文档为中心、函数显式调用并独立执行;Persistent Kernel 会引入隐藏共享变量、历史顺序依赖与新的执行语义,超出 View 职责。
**Q4:用户刷新浏览器,能不能还看到当前结果?**
UI 可以在相同 session、Job 未过 TTL 且安全验证的条件下恢复该次当前任务的 SSE 状态,但**不承诺跨刷新、跨浏览器或跨进程恢复**。想永久保留,须在结果仍可选时主动下载静态快照。
**Q5:为什么不能直接在新启动的 `marqdo view export` 命令中附带“上次结果”?**
因为前一次运行在另一个 View Server 进程的有限内存中;为得到“上次结果”而扫描目录或查询数据库就会重新引入历史存储。另起 CLI 无权猜测这次运行内容。第一阶段只允许 Live 页面引用**同一进程当前 Job**。
**Q6:用户需要真正的科研数据、图像或 Agent 制品怎么办?**
使用 Marqdo 的一般文件/资源能力,由程序在用户授权下明确输出普通文件或外部资源。View 的 ZIP 是一次阅读与执行说明的静态报告;它不代替业务数据文件。必要的项目本地图片可按安全规则一并打包。
**Q7:失败或者 Trace 不完整的运行可以导出吗?**
可以考虑导出**事实清楚标记的失败/部分结果报告**,但绝不能作为成功计算、完整轨迹或证明证书。第一阶段必须至少支持成功终态;其他终态需要显式 UI 确认和对应负例测试。
**Q8:导出文件还能再次执行函数吗?**
不可以。导出是不可执行静态报告。若要重新计算,回到原 `.mq.md` 和真实 Marqdo CLI,再经用户授权调用。
---
## 14. 审计来源与维护要求
### View 仓库源码
- [`src/reader/markdown.rs`](https://github.com/cflmy/marqdo-view/blob/dcb9daeaf4e5eefd8c35aa0c843dd8a0eaf7fef5/src/reader/markdown.rs)
- [`src/reader/render.rs`](https://github.com/cflmy/marqdo-view/blob/dcb9daeaf4e5eefd8c35aa0c843dd8a0eaf7fef5/src/reader/render.rs)
- [`src/reader/source.rs`](https://github.com/cflmy/marqdo-view/blob/dcb9daeaf4e5eefd8c35aa0c843dd8a0eaf7fef5/src/reader/source.rs)
- [`src/core_client.rs`](https://github.com/cflmy/marqdo-view/blob/dcb9daeaf4e5eefd8c35aa0c843dd8a0eaf7fef5/src/core_client.rs)
- [`src/execution/{request,controller,events}.rs`](https://github.com/cflmy/marqdo-view/tree/dcb9daeaf4e5eefd8c35aa0c843dd8a0eaf7fef5/src/execution)
- [`src/export.rs`](https://github.com/cflmy/marqdo-view/blob/dcb9daeaf4e5eefd8c35aa0c843dd8a0eaf7fef5/src/export.rs)
- [`src/server/routes.rs`](https://github.com/cflmy/marqdo-view/blob/dcb9daeaf4e5eefd8c35aa0c843dd8a0eaf7fef5/src/server/routes.rs)
- [`tool.json`](https://github.com/cflmy/marqdo-view/blob/dcb9daeaf4e5eefd8c35aa0c843dd8a0eaf7fef5/tool.json)
### CLI 公开协议
- [`spec/markdown-profile.md`](https://github.com/cflmy/marqdo-cli/blob/652ea763603517ba4d13325a405e3124844ded31/spec/markdown-profile.md)
- [`spec/analysis-v2.md`](https://github.com/cflmy/marqdo-cli/blob/652ea763603517ba4d13325a405e3124844ded31/spec/analysis-v2.md) / [`analysis-v3.md`](https://github.com/cflmy/marqdo-cli/blob/652ea763603517ba4d13325a405e3124844ded31/spec/analysis-v3.md)
- [`spec/trace-v2.md`](https://github.com/cflmy/marqdo-cli/blob/652ea763603517ba4d13325a405e3124844ded31/spec/trace-v2.md)
- [`spec/execution-events-v1.md`](https://github.com/cflmy/marqdo-cli/blob/652ea763603517ba4d13325a405e3124844ded31/spec/execution-events-v1.md)
- [`spec/tool-v1.md`](https://github.com/cflmy/marqdo-cli/blob/652ea763603517ba4d13325a405e3124844ded31/spec/tool-v1.md)
### 交付前必须做的事情
1. 重新取得最新 View HEAD 与已发布 Core tag/binary SHA,核对所有“当前事实”是否仍成立。
2. 对本 RFC 的**新增**请求、manifest 和 Overlay 写入 View 自有版本化 Schema、负例、ADR 与兼容文档,禁止直接把提议示例冒充既有公开协议。
3. 每个 PR 记录测试证据;源码阅读、示例设计与假 Core 测试不能替代真实冻结 CLI/浏览器/离线验收。
4. 更新 `docs/STATUS.md` 与 README,写清“目前支持”和“设计待实现”,禁止把下载 ZIP、Events v1、数学排版等拟议能力提前标为已完成。
**最终设计判据:** 用户只需阅读一篇 Markdown → 明确调用一个函数 → 看懂真实结果 → 在需要时主动把**当前这一次真实结果**连同原文导出为静态报告;这一过程无需 View 保存历史,也不迫使精简 `marqdo-cli` 增加任何 View 专用接口。
@@ -0,0 +1,7 @@
# ADR-0011 显式发行一次终态结果
- 状态:Accepted,实施与验证状态见 [STATUS](../STATUS.md)。
- 规范:[RFC-VIEW-0001 完整阅读与导出](../architecture/RFC-VIEW-0001-complete-reader.md)
- 本决策更新 ADR-0005 的可导出内容。普通导出及 Live 结果导出共用文档模型、渲染器和打包核心。
唯一执行入口仍为 `POST /api/runs`。用户可在当前会话的终态 Job 有效期内选择一次结果,明确确认后由 `POST /api/exports` 返回静态 ZIP。该路由验证当前来源、会话和字段选择,将有界不可变的数据交给渲染器。结果随 Job 过期,下载完成的文件由用户保管。
+7
View File
@@ -0,0 +1,7 @@
# 完整阅读与结果导出设计
[高保真设计图](complete-reader.png)由内置 ImageGen 生成,参考旧版 View 截图。实现沿用旧版居中品牌、暖纸色、衬线正文、金色函数标记和橄榄色结果边框。示意图右侧是独立的导出确认状态,窄屏使用单列。
提示词见下方。
> Use case: ui-mockup. Asset type: high fidelity desktop Marqdo View implementation design reference. Create a wide storyboard of two product states using the provided old Marqdo View screenshot as a visual reference (retain its centered logo, warm paper, understated pale blossom upper left, amber accent, olive success and serif document typography). Left 64%: real desktop reader, with centered header Marqdo, navigation 文档, 源码, subdued filename index.mq.md, readable title 小型统计实验, a paragraph, rendered mathematical mean formula and small document figure. Continue in the same article with a gold-slash function heading 计算均值 and a small outline button 调用 on the same row. Under the function body put one thin olive-bordered collapsible 本次执行 panel, status 成功, read-only 返回值 4, stdout preview and action 导出文档(含本次结果). Right 36%: show the opened export confirmation dialog as a full flat inset panel headed 导出文档(含本次结果), target 计算均值 and status 成功, checklist with 返回值, stdout and 轨迹摘要 selected, 参数 and stderr unselected, byte counts, privacy confirmation, and an amber 下载 ZIP button beside 取消. Quiet editorial composition, no coding dashboard, no charts unrelated to document, no extra product copy. Flat straight-on browser UI, readable typography, generous whitespace, clean borders. The reference is for an existing paper-themed reader, preserve its design language.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

+2 -1
View File
@@ -61,7 +61,8 @@
- **导入/引用标签**:椭圆 chip,`◇`/`⟶` 前缀,mono 12px。 - **导入/引用标签**:椭圆 chip,`◇`/`⟶` 前缀,mono 12px。
- **GFM 表**:横向可滚动容器;表头 `--mq-surface-2`;1px `--mq-line` 分隔。 - **GFM 表**:横向可滚动容器;表头 `--mq-surface-2`;1px `--mq-line` 分隔。
- **代码围栏**:`--mq-surface` 底、1px 边、圆角 10px;横向滚动;无行号(源码态除外)。 - **代码围栏**:`--mq-surface` 底、1px 边、圆角 10px;横向滚动;无行号(源码态除外)。
- **公式**:首版以等宽/衬线文本呈现原文(`$...$` 与 `$$...$$`),标注“未渲染数学”;不引入 vendor。 - **公式**:正文使用离线 MathML 与本地 Noto Sans Math。无法安全排版的式子保留原文。
- **结果与导出**:函数旁使用金色描边按钮,终态以橄榄边框折叠区呈现。导出预览沿用暖纸色对话框,显示所选字段与字节数。
- **侧注**:正文右侧 170px;金色/橄榄 1px 贝塞尔曲线,起点为真实语义锚点;无来源不画线;拥挤时退化为内联 keyed 注释。 - **侧注**:正文右侧 170px;金色/橄榄 1px 贝塞尔曲线,起点为真实语义锚点;无来源不画线;拥挤时退化为内联 keyed 注释。
- **装饰**:樱花 `blossom.webp` 左上、羽毛 `feather.webp` 仅 Welcome Hero;`aria-hidden="true"`;打印隐藏。 - **装饰**:樱花 `blossom.webp` 左上、羽毛 `feather.webp` 仅 Welcome Hero;`aria-hidden="true"`;打印隐藏。
+9
View File
@@ -0,0 +1,9 @@
# 工单 #3 基线
- View 基线:`dcb9daeaf4e5eefd8c35aa0c843dd8a0eaf7fef5`。
- [Linux x86_64 RC.2 发行包](https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-rc.2)与发行方 SHA-256 清单核对通过。
- 发行 tag:`9149ee40a48fcda692c5c112f66c465487d13dfb`。
- 包 SHA-256:`e32e6426caf023fc813ebdbf5a171ec164ee2ffb843ae5594b8e7b9780f496ea`。
- 二进制 SHA-256:`5caa90b8f6a282aef5bb301443ede6cd3bdcf5f64c88969e6d71cb324b03dc5b`。
发行 CLI 完成示例的 `check --emit`(Analysis v3)和 `call`(Events v1、Trace v2),返回 Float 4.0。View 基线只接收 Analysis v2,无法显示这个项目的执行语义。本文件记录 CLI 可观察的基线,View 的端到端门禁另行验证。
+47
View File
@@ -0,0 +1,47 @@
# 工单 #3 验收
Linux x86_64 使用官方 `marqdo 3.0.0-rc.2` 发行归档及 Chromium
`131.0.6778.33`。View 代码和测试提交、发行包、可执行文件、结果 ZIP、
清单与证据文件的 SHA-256 见 [验收清单](manifest.json)。Core 源码标签
及安装归档校验见 [发行基线](../issue-3-baseline.md)。
| 检查 | 结果 |
|---|---|
| Rust 格式、严格 Clippy、160 项单元与集成回归 | PASS |
| 发行包构建、官方 RC.2 安装独立 Tool、Analysis v3 核对 | PASS |
| 原有 Chromium 四套回归 | PASS |
| 本地图片、跨文档重复标题锚点、离线公式和 390px 布局 | PASS |
| 函数旁显式调用及默认参数、终态前可见 stdout、预览确认与下载 | PASS |
| 打开和导出零运行;两种导出后执行计数仍为 1 | PASS |
| 缺少 CSRF、跨 Origin/会话、过期或活动 Job、篡改、源码/锁/导入/图片变化 | PASS |
| 成功、失败确认、取消、超时、Trace 缺失与纯文本输出 | PASS |
| ZIP 条目与清单哈希、打包失败与客户端断开清理、进程重启 | PASS |
| 关闭服务器后,禁用 JavaScript 和网络,以 `file://` 阅读并打印结果 | PASS |
| 完整外部屏幕阅读器手工走查 | UNVERIFIED |
测试日志见 [Rust 与打包](checks.log)、[HTTP 与 ZIP](http.log)及
[浏览器](browser.log)。浏览器验证用真实发行 CLI。计数包装器审查传给 CLI
的 argv,并在流式验证场景延迟转发终态,以观察真实 stdout 在终态之前出现。
- [函数旁结果](live-result.png)
- [导出预览](export-preview.png)
- [离线正文及媒体](offline-snapshot.png)
- [离线结果](offline-result.png)
- [窄屏阅读](mobile-reader.png)
## 复跑
```bash
export MARQDO_BIN=/absolute/path/to/released/marqdo
cargo fmt --all -- --check
cargo clippy --locked --all-targets -- -D warnings
cargo test --locked
cargo build --locked
./scripts/test-complete-reader.py
(cd tests/browser && npm ci && npx playwright install chromium)
node tests/browser/complete-reader.browser.cjs
```
如已有 Chromium,可通过 `CHROMIUM_BIN` 指定可执行文件。
`MQ_SCREENSHOT_DIR` 可收集浏览器截图,`SNAPSHOT_ZIP` 可保存 HTTP 验收下载文件。
部署前可运行 `scripts/package.sh`,用同一官方 CLI 复验 Tool 安装。
+11
View File
@@ -0,0 +1,11 @@
Chromium 131.0.6778.33
Live media, cross-document anchors, confirmed call, pre-terminal stdout, private download and offline ZIP: PASS
==> browser suite: examples/welcome
browser: PASS
==> browser suite: examples/control-flow
browser: PASS
==> browser suite: examples/function-params.mq.md
browser: PASS
==> browser suite: tests/fixtures/security-project
browser: PASS
browser: PASS (core sha256 5caa90b8f6a282aef5bb301443ede6cd3bdcf5f64c88969e6d71cb324b03dc5b unchanged; screenshots: /tmp/marqdo-view-regression)
+11
View File
@@ -0,0 +1,11 @@
cargo fmt --all -- --check: PASS
cargo clippy --locked --all-targets -- -D warnings: PASS
test result: ok. 65 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.02s
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
test result: ok. 41 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.34s
test result: ok. 43 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 3.23s
test result: ok. 11 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.13s
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
install-smoke: PASS (core sha256 5caa90b8f6a282aef5bb301443ede6cd3bdcf5f64c88969e6d71cb324b03dc5b unchanged)
Installed Tool: verify examples/complete-reader --json emitted Analysis v3, result PASS and executed=false
Draft 2020-12 schema definitions and generated v2 manifest: PASS
Binary file not shown.

After

Width:  |  Height:  |  Size: 147 KiB

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

After

Width:  |  Height:  |  Size: 74 KiB

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

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

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

After

Width:  |  Height:  |  Size: 364 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 488 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 482 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 367 B

+2 -1
View File
@@ -66,6 +66,7 @@ import sys
bundle = pathlib.Path(sys.argv[1]) bundle = pathlib.Path(sys.argv[1])
version, target, source_sha = sys.argv[2], sys.argv[3], sys.argv[4] version, target, source_sha = sys.argv[2], sys.argv[3], sys.argv[4]
tool = json.loads((bundle / 'tool.json').read_text())
files = [] files = []
for path in sorted(bundle.rglob('*')): for path in sorted(bundle.rglob('*')):
if not path.is_file(): if not path.is_file():
@@ -89,7 +90,7 @@ info = {
'source_sha': source_sha, 'source_sha': source_sha,
'compatibility': { 'compatibility': {
'marqdo': '>=3.0.0-beta.1,<4.0.0', 'marqdo': '>=3.0.0-beta.1,<4.0.0',
'analysis': [2], 'analysis': tool['compatibility']['analysis'],
'trace': [2], 'trace': [2],
'tool_protocol': 1, 'tool_protocol': 1,
'markdown_profile': 'marqdo.md.v1', 'markdown_profile': 'marqdo.md.v1',
+303
View File
@@ -0,0 +1,303 @@
#!/usr/bin/env python3
"""HTTP and ZIP acceptance against an unmodified RC.2 release binary."""
import hashlib
import http.cookiejar
import io
import json
import os
from pathlib import Path, PurePosixPath
import re
import shutil
import socket
import struct
import subprocess
import tempfile
import time
import urllib.error
import urllib.request
import zipfile
ROOT = Path(__file__).resolve().parents[1]
CORE = Path(os.environ["MARQDO_BIN"]).resolve(strict=True)
VIEW = Path(os.environ.get("VIEW_BIN", ROOT / "target/debug/marqdo-view")).resolve(strict=True)
def sha(data):
return hashlib.sha256(data).hexdigest()
def session(base):
browser = urllib.request.build_opener(
urllib.request.ProxyHandler({}),
urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()),
)
html = browser.open(base, timeout=10).read().decode()
token = re.search(r'name="mq-csrf-token" content="([a-f0-9]+)"', html)[1]
digest = re.search(r'data-analysis-digest="([^"]+)"', html)[1]
return browser, token, digest, html
def post(browser, base, route, token, body, status=200, origin=None):
headers = {"Content-Type": "application/json", "Origin": origin or base}
if token is not None:
headers["X-View-CSRF"] = token
request = urllib.request.Request(base + route, json.dumps(body).encode(), headers)
try:
with browser.open(request, timeout=20) as response:
assert response.status == status, (route, response.status, status)
return response.read(), response.headers
except urllib.error.HTTPError as error:
assert error.code == status, (route, error.code, status, error.read())
return error.read(), error.headers
def verify_zip(payload, destination, expected_digest):
with zipfile.ZipFile(io.BytesIO(payload)) as archive:
names = archive.namelist()
assert len(names) == len(set(names))
for item in archive.infolist():
path = PurePosixPath(item.filename)
assert not path.is_absolute() and ".." not in path.parts
assert item.compress_type == zipfile.ZIP_STORED and item.file_size <= 16 * 1024 ** 2
raw_manifest = archive.read("manifest.json")
assert sha(raw_manifest) == expected_digest
manifest = json.loads(raw_manifest)
assert manifest["schema_version"] == 2 and not manifest["executed_during_export"]
assert manifest["execution"]["source_verified"] and manifest["execution"]["status"] == "succeeded"
assert manifest["execution"]["parameters"] == "omitted"
assert manifest["source"]["document"] == "index.mq.md"
assert manifest["execution"]["core_protocol"] == {"analysis": 3, "trace": 2, "events": 1}
for entry in manifest["files"] + manifest["assets"]:
data = archive.read(entry["path"])
assert sha(data) == entry["sha256"] and len(data) == entry["size"]
assert not any(name.endswith(".js") for name in names)
html = archive.read("index.html").decode()
assert "<math" in html and "<script" not in html and 'data-action="call-function"' not in html
assert "本次执行快照" in html and "Int(4)" in html and "参数未包含" in html
assert html.count('class="mq-snapshot"') == 1
other = archive.read("pages/docs/explanation.mq.md.html").decode()
assert 'class="mq-snapshot"' not in other and '<script' not in other
if destination:
Path(destination).write_bytes(payload)
print("snapshot manifest sha256", sha(archive.read("manifest.json")))
def check(root):
project = root / "project"
shutil.copytree(ROOT / "examples/complete-reader", project)
attack_text = b"<script>bad()</script><img onerror=bad()>"
lines = ["", "## @exec write_markup", "", f"`buffer = memory.new(1, {len(attack_text)})`", ""]
for index, byte in enumerate(attack_text):
lines.extend([f"`buffer[{index}] = {byte}`", ""])
lines.extend(['`out = resource.open("stdio", "stdout", ["write"])`', "",
f"`resource.write(out, buffer, 0, {len(attack_text)})`", "",
"`resource.close(out)`", "", "`return 1`", ""])
with (project / "index.mq.md").open("a") as source:
source.write("\n".join(lines))
scratch = root / "scratch"
scratch.mkdir()
count = root / "runs"
wrapper = root / "core"
wrapper.write_text(
"#!/usr/bin/env python3\n"
"import os, subprocess, sys, time\n"
f"core, count = {str(CORE)!r}, {str(count)!r}\n"
"if sys.argv[1] in ('run', 'call'):\n"
" assert '--event-stream' in sys.argv and '--json' not in sys.argv\n"
" with open(count, 'a') as f: f.write(sys.argv[1]+'\\n')\n"
" if sys.argv[1] == 'call' and sys.argv[3] == 'write_markup':\n"
" result = subprocess.run([core, *sys.argv[1:]], check=False)\n"
" os.unlink(sys.argv[sys.argv.index('--trace-file') + 1])\n"
" sys.exit(result.returncode)\n"
" if sys.argv[1] == 'call' and sys.argv[3] == 'scan': time.sleep(2)\n"
"os.execv(core, [core, *sys.argv[1:]])\n"
)
wrapper.chmod(0o700)
env = {**os.environ, "TMPDIR": str(scratch)}
args = [str(VIEW), "--marqdo-bin", str(wrapper)]
with subprocess.Popen(
[*args, str(project), "--port", "0", "--no-open"],
stderr=subprocess.PIPE,
text=True,
env=env,
) as server:
try:
base = server.stderr.readline().split()[-1].rstrip("/")
browser, token, digest, html = session(base)
assert not count.exists()
assert "<math" in html and 'alt="样本数据图"' in html
media = re.search(r'src="(/media/[^"]+)" alt="样本数据图"', html)[1]
with browser.open(base + media, timeout=10) as response:
data = response.read()
assert response.headers.get_content_type() == "image/png"
assert sha(data) in media
try:
urllib.request.build_opener(urllib.request.ProxyHandler({})).open(base + media, timeout=10)
except urllib.error.HTTPError as error:
assert error.code == 401
else:
raise AssertionError("unauthenticated project media was accessible")
original = {path: sha(path.read_bytes()) for path in project.rglob("*") if path.is_file()}
def submit(function, request_id, parameters=None):
body = {
"document": "index.mq.md",
"target": {"kind": "function", "function_id": f"root:complete-reader@0.1.0::index.mq.md::计算.{function}"},
"parameters": parameters or [],
"analysis_digest": digest,
"client_request_id": request_id,
}
payload, _ = post(browser, base, "/api/runs", token, body, 202)
return json.loads(payload)
def observe(accepted):
with browser.open(base + accepted["events_url"], timeout=20) as response:
events = [json.loads(line[6:]) for line in response.read().decode().splitlines() if line.startswith("data: ")]
return accepted["run_id"], events[-1]
run_id, terminal = observe(submit("write_output", "one"))
assert terminal["state"] == "succeeded" and terminal["result"]["stdout"] == "4\n", terminal
assert terminal["result"]["trace_status"] == "verified"
assert count.read_text().splitlines() == ["call"]
selection = {
"schema": "marqdo.view-static-export-request",
"schema_version": 1,
"run_id": run_id,
"document": "index.mq.md",
"analysis_digest": digest,
"scope": "document",
"include": {"result_value": True, "stdout": True, "stderr": False, "arguments": False, "trace_summary": True},
"confirm_sensitive_output": True,
"client_export_request_id": "zip-one",
}
post(browser, base, "/api/exports", None, selection, 403)
post(browser, base, "/api/exports", token, selection, 403, "https://example.invalid")
other, other_token, _, _ = session(base)
post(other, base, "/api/exports", other_token, selection, 404)
post(browser, base, "/api/exports", token, {**selection, "schema_version": 2}, 400)
post(browser, base, "/api/exports", token, {**selection, "confirm_sensitive_output": False}, 400)
post(browser, base, "/api/exports", token, {**selection, "run_id": "unknown"}, 404)
payload, headers = post(browser, base, "/api/exports", token, selection)
assert headers.get_content_type() == "application/zip" and "attachment" in headers["Content-Disposition"]
assert headers["Cache-Control"] == "no-store" and headers["X-Content-Type-Options"] == "nosniff"
verify_zip(payload, os.environ.get("SNAPSHOT_ZIP"), headers["X-Marqdo-Manifest-SHA256"])
manifest_digest = headers["X-Marqdo-Manifest-SHA256"]
with zipfile.ZipFile(io.BytesIO(payload)) as archive:
manifest = json.loads(archive.read("manifest.json"))
assert sha(archive.read("manifest.json") + b" ") != manifest_digest
for entry in manifest["files"] + manifest["assets"]:
assert sha(archive.read(entry["path"]) + b" ") != entry["sha256"]
post(browser, base, "/api/exports", token, {**selection, "unknown": "x" * 8192}, 429)
auth = next(handler.cookiejar for handler in browser.handlers if hasattr(handler, "cookiejar"))
cookies = "; ".join(f"{cookie.name}={cookie.value}" for cookie in auth)
body = json.dumps(selection).encode()
host, port = base.removeprefix("http://").rsplit(":", 1)
request = (f"POST /api/exports HTTP/1.1\r\nHost: {host}:{port}\r\n"
f"Origin: {base}\r\nX-View-CSRF: {token}\r\nCookie: {cookies}\r\n"
f"Content-Type: application/json\r\nContent-Length: {len(body)}\r\n\r\n").encode()
with socket.create_connection((host, int(port)), timeout=10) as abandoned:
abandoned.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 4096)
abandoned.sendall(request + body)
assert abandoned.recv(16).startswith(b"HTTP/1.1 200")
abandoned.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
deadline = time.monotonic() + 5
while list(scratch.iterdir()) and time.monotonic() < deadline:
time.sleep(.01)
assert not list(scratch.iterdir()), list(scratch.iterdir())
forbidden_entry = project / "bad:archive-name.mq.md"
forbidden_entry.write_text("# @knowledge Archive path fixture\n")
post(browser, base, "/api/exports", token, selection, 500)
forbidden_entry.unlink()
assert not list(scratch.iterdir()), list(scratch.iterdir())
subprocess.run([*args, "export", str(project), "--out", str(root / "pure")], check=True, env=env)
assert "本次执行快照" not in (root / "pure/index.html").read_text()
assert count.read_text().splitlines() == ["call"]
assert original == {path: sha(path.read_bytes()) for path in project.rglob("*") if path.is_file()}
source = project / "index.mq.md"
original_source = source.read_bytes()
source.write_bytes(original_source + b"\nsource changed\n")
post(browser, base, "/api/exports", token, selection, 409)
source.write_bytes(original_source)
image = project / "media/flow.png"
original_image = image.read_bytes()
image.unlink()
image.symlink_to(root / "external.png")
(root / "external.png").write_bytes(original_image)
post(browser, base, "/api/exports", token, selection, 409)
image.unlink()
image.write_bytes(original_image)
dependency = project / "docs/explanation.mq.md"
dependency_bytes = dependency.read_bytes()
dependency.write_bytes(dependency_bytes + b"\nDependency changed.\n")
post(browser, base, "/api/exports", token, selection, 409)
dependency.write_bytes(dependency_bytes)
lock = project / "marqdo.lock"
assert not lock.exists()
lock.write_text("changed lock bytes")
post(browser, base, "/api/exports", token, selection, 409)
lock.unlink()
assert count.read_text().splitlines() == ["call"]
print("pure and selected export leave execution count at 1; source, lock, dependency and media staleness denied")
pending = submit("scan", "cancelled")
pending_selection = {**selection, "run_id": pending["run_id"]}
post(browser, base, "/api/exports", token, pending_selection, 409)
bare_cancel = urllib.request.Request(base + pending["cancel_url"], b"", {
"Origin": base, "X-View-CSRF": token
}, method="POST")
with browser.open(bare_cancel, timeout=10) as response:
assert response.status in (200, 202)
_, cancelled = observe(pending)
assert cancelled["state"] == "cancelled", cancelled
post(browser, base, "/api/exports", token, pending_selection, 409)
failed_id, failed = observe(submit("fail", "failed", [{"name": "divisor", "expression": "0"}]))
assert failed["state"] == "failed", failed
failed_selection = {**selection, "run_id": failed_id}
post(browser, base, "/api/exports", token, failed_selection, 400)
failed_zip, _ = post(browser, base, "/api/exports", token, {**failed_selection, "confirm_partial": True})
with zipfile.ZipFile(io.BytesIO(failed_zip)) as archive:
assert json.loads(archive.read("manifest.json"))["execution"]["status"] == "failed"
text_id, text = observe(submit("write_markup", "markup"))
assert text["state"] == "succeeded" and text["result"]["trace_status"] == "unavailable", text
assert text["result"]["stdout"] == attack_text.decode()
text_zip, _ = post(browser, base, "/api/exports", token, {**selection, "run_id": text_id})
with zipfile.ZipFile(io.BytesIO(text_zip)) as archive:
html = archive.read("index.html").decode()
assert "<script>" not in html and "&lt;script&gt;bad()" in html
assert json.loads(archive.read("manifest.json"))["execution"]["trace_status"] == "unavailable"
first, headers = post(browser, base, "/api/exports", token, selection)
verify_zip(first, None, headers["X-Marqdo-Manifest-SHA256"])
print("active/cancelled export denied, verified failure gated, stdout escaped, missing Trace separate")
print("selected IDs remain isolated, tampering detected, oversized request denied, failed and aborted packages cleaned")
calls = count.read_text().splitlines()
assert calls == ["call"] * 4, calls
print("run/call count matches four explicit submissions:", calls)
finally:
server.terminate()
server.wait(timeout=5)
with subprocess.Popen(
[*args, str(project), "--port", "0", "--no-open", "--run-timeout", "1"],
stderr=subprocess.PIPE, text=True, env=env,
) as restarted:
try:
base = restarted.stderr.readline().split()[-1].rstrip("/")
browser, token, digest, _ = session(base)
post(browser, base, "/api/exports", token, selection, 404)
timed_id, timed = observe(submit("scan", "timeout"))
assert timed["state"] == "timed_out", timed
post(browser, base, "/api/exports", token, {**selection, "run_id": timed_id}, 409)
finally:
restarted.terminate()
restarted.wait(timeout=5)
assert not list(scratch.iterdir()), list(scratch.iterdir())
print("restarted View cannot recover the previous job; timed-out execution is not exportable; private scratch directories are empty")
if __name__ == "__main__":
with tempfile.TemporaryDirectory(prefix="marqdo-view-acceptance-") as directory:
check(Path(directory))
+14 -62
View File
@@ -66,6 +66,7 @@ pub struct CheckOptions {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct RunOptions { pub struct RunOptions {
pub event_stream: bool,
pub mode: SandboxMode, pub mode: SandboxMode,
pub grants: Grants, pub grants: Grants,
pub fuel: Option<u64>, pub fuel: Option<u64>,
@@ -80,6 +81,7 @@ pub struct RunOptions {
impl Default for RunOptions { impl Default for RunOptions {
fn default() -> Self { fn default() -> Self {
Self { Self {
event_stream: false,
mode: SandboxMode::Pure, mode: SandboxMode::Pure,
grants: Grants::default(), grants: Grants::default(),
fuel: None, fuel: None,
@@ -148,65 +150,7 @@ pub struct RunOutput {
pub trace_sha256: Option<String>, pub trace_sha256: Option<String>,
} }
/// A private temporary directory for Core artifacts. pub use crate::scratch::ScratchDir;
pub struct ScratchDir {
path: PathBuf,
}
impl ScratchDir {
pub fn create(label: &str) -> ViewResult<Self> {
let base = std::env::temp_dir();
let unique = format!(
"marqdo-view-{}-{}-{}",
std::process::id(),
unique_counter(),
sanitize_label(label)
);
let path = base.join(unique);
std::fs::create_dir_all(&path)
.map_err(|err| ViewError::io(&format!("create scratch {}", path.display()), err))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700))
.map_err(|err| ViewError::io(&format!("chmod scratch {}", path.display()), err))?;
}
Ok(Self { path })
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn file(&self, name: &str) -> PathBuf {
self.path.join(name)
}
}
impl Drop for ScratchDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
fn unique_counter() -> u64 {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos() as u64)
.unwrap_or(0);
seq ^ nanos.rotate_left(17)
}
fn sanitize_label(label: &str) -> String {
label
.chars()
.map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '-' })
.take(32)
.collect()
}
/// Negotiated public-client for one frozen core binary. /// Negotiated public-client for one frozen core binary.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@@ -481,7 +425,13 @@ fn append_common_args(args: &mut Vec<OsString>, trace_path: &Path, options: &Run
} }
args.push(OsString::from("--mode")); args.push(OsString::from("--mode"));
args.push(OsString::from(options.mode.as_str())); args.push(OsString::from(options.mode.as_str()));
args.push(OsString::from("--json")); if options.event_stream {
push_pair(args, "--event-stream", "jsonl");
push_pair(args, "--observe-max-events", "10000");
push_pair(args, "--observe-max-bytes", "4194304");
} else {
args.push(OsString::from("--json"));
}
args.push(OsString::from("--trace-file")); args.push(OsString::from("--trace-file"));
args.push(trace_path.as_os_str().to_os_string()); args.push(trace_path.as_os_str().to_os_string());
for glob in &options.grants.allow_read { for glob in &options.grants.allow_read {
@@ -696,7 +646,7 @@ pub fn verify_command(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32>
}, },
"analysis": { "analysis": {
"schema": "marqdo.analysis", "schema": "marqdo.analysis",
"schema_version": tool_v1::ANALYSIS_PROTOCOL, "schema_version": projection.schema_version,
"digest": projection.analysis_digest, "digest": projection.analysis_digest,
"producer_version": projection.producer_version, "producer_version": projection.producer_version,
"markdown_profile": projection.markdown_profile, "markdown_profile": projection.markdown_profile,
@@ -736,7 +686,8 @@ pub fn verify_command(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32>
); );
println!("document: {entry}"); println!("document: {entry}");
println!( println!(
"analysis: schema=marqdo.analysis v2 modules={} functions={} digest={}", "analysis: schema=marqdo.analysis v{} modules={} functions={} digest={}",
projection.schema_version,
projection.modules.len(), projection.modules.len(),
projection.functions.len(), projection.functions.len(),
projection.analysis_digest projection.analysis_digest
@@ -757,6 +708,7 @@ mod tests {
Path::new("/p/index.mq.md"), Path::new("/p/index.mq.md"),
Path::new("/t/trace.json"), Path::new("/t/trace.json"),
&RunOptions { &RunOptions {
event_stream: false,
mode: SandboxMode::Pure, mode: SandboxMode::Pure,
grants: Grants { grants: Grants {
allow_read: vec!["data/**".into()], allow_read: vec!["data/**".into()],
+94 -25
View File
@@ -17,55 +17,115 @@ pub enum ExitClass {
#[derive(Debug)] #[derive(Debug)]
pub enum ViewError { pub enum ViewError {
/// `MARQDO_BIN` unset, missing, or not executable. /// `MARQDO_BIN` unset, missing, or not executable.
CoreMissing { detail: String }, CoreMissing {
detail: String,
},
/// Tool/Analysis/Trace protocol or product range mismatch. /// Tool/Analysis/Trace protocol or product range mismatch.
ProtocolIncompatible { detail: String }, ProtocolIncompatible {
detail: String,
},
/// Core `check` failed; prose stays readable but semantics are unusable. /// Core `check` failed; prose stays readable but semantics are unusable.
AnalysisFailed { detail: String }, AnalysisFailed {
detail: String,
},
/// Analysis `source_digest` does not match the current source bytes. /// Analysis `source_digest` does not match the current source bytes.
SourceMismatch { expected: String, actual: String }, SourceMismatch {
expected: String,
actual: String,
},
/// A Core byte span is out of range or not on a UTF-8 boundary. /// A Core byte span is out of range or not on a UTF-8 boundary.
SourceSpanInvalid { detail: String }, SourceSpanInvalid {
detail: String,
},
/// Trace does not bind to the current Analysis bytes. /// Trace does not bind to the current Analysis bytes.
TraceStale { detail: String }, TraceStale {
detail: String,
},
/// The user did not confirm, or the requested mode/grants are not allowed. /// The user did not confirm, or the requested mode/grants are not allowed.
RunDenied { detail: String }, RunDenied {
detail: String,
},
/// Path escapes the allowed project root or is otherwise forbidden. /// Path escapes the allowed project root or is otherwise forbidden.
PathForbidden { detail: String }, PathForbidden {
detail: String,
},
/// Refused a bind address that is not explicitly allowed. /// Refused a bind address that is not explicitly allowed.
BindDenied { detail: String }, BindDenied {
detail: String,
},
/// Embedded asset digest mismatch (build/package integrity). /// Embedded asset digest mismatch (build/package integrity).
AssetIntegrity { detail: String }, AssetIntegrity {
detail: String,
},
/// Export target is unsafe or the write failed. /// Export target is unsafe or the write failed.
ExportFailed { detail: String }, ExportFailed {
detail: String,
},
ExportInvalid {
detail: String,
},
ExportUnavailable {
detail: String,
},
ExportSourceChanged {
detail: String,
},
/// A configured resource limit was exceeded. /// A configured resource limit was exceeded.
ResourceLimit { detail: String }, ResourceLimit {
detail: String,
},
/// Core subprocess could not be spawned. /// Core subprocess could not be spawned.
CoreSpawn { detail: String }, CoreSpawn {
detail: String,
},
/// The submitted run request failed schema/target/parameter validation. /// The submitted run request failed schema/target/parameter validation.
RunInvalid { detail: String }, RunInvalid {
detail: String,
},
/// The entry document has no resolvable `main`; View never substitutes one. /// The entry document has no resolvable `main`; View never substitutes one.
NoEntryFunction { detail: String }, NoEntryFunction {
detail: String,
},
/// A page/SSE/POST requires a valid local session cookie. /// A page/SSE/POST requires a valid local session cookie.
SessionRequired { detail: String }, SessionRequired {
detail: String,
},
/// Another explicit run is already active; View allows one at a time. /// Another explicit run is already active; View allows one at a time.
RunBusy { detail: String }, RunBusy {
detail: String,
},
/// The same client request id was reused with a different payload. /// The same client request id was reused with a different payload.
RunConflict { detail: String }, RunConflict {
detail: String,
},
/// The requested run id is unknown, expired or belongs to another session. /// The requested run id is unknown, expired or belongs to another session.
RunNotFound { detail: String }, RunNotFound {
detail: String,
},
/// Bounded capture of CLI stdout/stderr/JSON/trace exceeded the budget. /// Bounded capture of CLI stdout/stderr/JSON/trace exceeded the budget.
OutputLimit { detail: String }, OutputLimit {
detail: String,
},
/// The CLI exited but its `--json` document was missing or invalid. /// The CLI exited but its `--json` document was missing or invalid.
CoreProtocol { detail: String }, CoreProtocol {
detail: String,
},
/// More than two concurrent SSE observers for one job. /// More than two concurrent SSE observers for one job.
SseBusy { detail: String }, SseBusy {
detail: String,
},
/// Core subprocess exceeded the View-level timeout and was killed. /// Core subprocess exceeded the View-level timeout and was killed.
CoreTimeout { detail: String }, CoreTimeout {
detail: String,
},
/// Local file system / HTTP I/O failure. /// Local file system / HTTP I/O failure.
Io { detail: String }, Io {
detail: String,
},
/// Feature intentionally not implemented in this build (honest status). /// Feature intentionally not implemented in this build (honest status).
Unsupported { detail: String }, Unsupported {
detail: String,
},
} }
impl ViewError { impl ViewError {
@@ -82,6 +142,9 @@ impl ViewError {
ViewError::BindDenied { .. } => "view.bind_denied", ViewError::BindDenied { .. } => "view.bind_denied",
ViewError::AssetIntegrity { .. } => "view.asset_integrity", ViewError::AssetIntegrity { .. } => "view.asset_integrity",
ViewError::ExportFailed { .. } => "view.export_failed", ViewError::ExportFailed { .. } => "view.export_failed",
ViewError::ExportInvalid { .. } => "view.export_invalid",
ViewError::ExportUnavailable { .. } => "view.export_unavailable",
ViewError::ExportSourceChanged { .. } => "view.export_source_changed",
ViewError::ResourceLimit { .. } => "view.resource_limit", ViewError::ResourceLimit { .. } => "view.resource_limit",
ViewError::CoreSpawn { .. } => "view.core_spawn", ViewError::CoreSpawn { .. } => "view.core_spawn",
ViewError::CoreTimeout { .. } => "view.core_timeout", ViewError::CoreTimeout { .. } => "view.core_timeout",
@@ -151,6 +214,9 @@ impl ViewError {
"view.bind_denied" => "拒绝绑定该网络地址。", "view.bind_denied" => "拒绝绑定该网络地址。",
"view.asset_integrity" => "内嵌资源摘要不一致。", "view.asset_integrity" => "内嵌资源摘要不一致。",
"view.export_failed" => "静态导出失败(输出目录不安全或写入失败)。", "view.export_failed" => "静态导出失败(输出目录不安全或写入失败)。",
"view.export_invalid" => "导出范围或隐私确认无效。",
"view.export_unavailable" => "本次执行尚无可导出的已验证终态。",
"view.export_source_changed" => "文档、依赖或图片已变更。请刷新并重新运行后再导出。",
"view.resource_limit" => "超过配置的资源上限。", "view.resource_limit" => "超过配置的资源上限。",
"view.core_spawn" => "无法启动冻结核心。", "view.core_spawn" => "无法启动冻结核心。",
"view.core_timeout" => "冻结核心执行超时,已终止。", "view.core_timeout" => "冻结核心执行超时,已终止。",
@@ -204,6 +270,9 @@ impl ViewError {
| ViewError::BindDenied { detail } | ViewError::BindDenied { detail }
| ViewError::AssetIntegrity { detail } | ViewError::AssetIntegrity { detail }
| ViewError::ExportFailed { detail } | ViewError::ExportFailed { detail }
| ViewError::ExportInvalid { detail }
| ViewError::ExportUnavailable { detail }
| ViewError::ExportSourceChanged { detail }
| ViewError::ResourceLimit { detail } | ViewError::ResourceLimit { detail }
| ViewError::CoreSpawn { detail } | ViewError::CoreSpawn { detail }
| ViewError::CoreTimeout { detail } | ViewError::CoreTimeout { detail }
+242 -35
View File
@@ -8,8 +8,12 @@
use crate::core_client::{build_call_args, build_run_args, RunOptions, SandboxMode, ScratchDir}; use crate::core_client::{build_call_args, build_run_args, RunOptions, SandboxMode, ScratchDir};
use crate::error::{ViewError, ViewResult}; use crate::error::{ViewError, ViewResult};
use crate::execution::events::{EventLog, RunEvent, RunState, Subscription}; use crate::execution::events::{EventLog, RunEvent, RunState, Subscription};
use crate::execution::process::{run_bounded_with_hook, ProcessBudget, ProcessOutcome}; use crate::execution::export_candidate::TerminalExportCandidate;
use crate::execution::process::{
run_bounded_with_hook, Captured, ProcessBudget, ProcessHooks, ProcessOutcome,
};
use crate::execution::request::{self, payload_digest, ExecutionPlan, ExecutionTarget, RunMode}; use crate::execution::request::{self, payload_digest, ExecutionPlan, ExecutionTarget, RunMode};
use crate::protocol::execution_events_v1 as core_events;
use crate::protocol::trace_v2::{verify_trace, TraceVerificationInput}; use crate::protocol::trace_v2::{verify_trace, TraceVerificationInput};
use crate::reader::assemble::{DocumentService, StaticDocument}; use crate::reader::assemble::{DocumentService, StaticDocument};
use crate::reader::source::{sha256_hex, sha256_prefixed}; use crate::reader::source::{sha256_hex, sha256_prefixed};
@@ -123,6 +127,7 @@ pub struct Job {
struct JobInner { struct JobInner {
log: EventLog, log: EventLog,
terminal_at: Option<Instant>, terminal_at: Option<Instant>,
export_candidate: Option<Arc<TerminalExportCandidate>>,
connections: usize, connections: usize,
} }
@@ -137,6 +142,7 @@ impl Job {
inner: Mutex::new(JobInner { inner: Mutex::new(JobInner {
log: EventLog::new(), log: EventLog::new(),
terminal_at: None, terminal_at: None,
export_candidate: None,
connections: 0, connections: 0,
}), }),
} }
@@ -168,7 +174,13 @@ struct ControllerState {
jobs: HashMap<String, Arc<Job>>, jobs: HashMap<String, Arc<Job>>,
order: VecDeque<String>, order: VecDeque<String>,
active: Option<String>, active: Option<String>,
dedupe: HashMap<String, DedupeEntry>, dedupe: HashMap<(String, String), DedupeEntry>,
}
struct CoreRun {
process: ProcessOutcome,
trace: ViewResult<Option<Vec<u8>>>,
stream: Option<core_events::Stream>,
} }
pub struct ExecutionController { pub struct ExecutionController {
@@ -186,6 +198,25 @@ impl ExecutionController {
} }
} }
/// Sweep inactive jobs even if the browser never makes another request.
pub fn start_expiry_sweep(self: &Arc<Self>) {
let weak = Arc::downgrade(self);
let period = self
.config
.terminal_ttl
.min(Duration::from_secs(30))
.max(Duration::from_millis(100));
std::thread::spawn(move || loop {
std::thread::sleep(period);
let Some(controller) = weak.upgrade() else {
break;
};
if let Ok(mut state) = controller.state.lock() {
controller.purge_locked(&mut state);
};
});
}
pub fn config(&self) -> &ExecutionConfig { pub fn config(&self) -> &ExecutionConfig {
&self.config &self.config
} }
@@ -196,13 +227,13 @@ impl ExecutionController {
pub fn submit(self: &Arc<Self>, session_id: &str, body: &[u8]) -> ViewResult<AcceptedRun> { pub fn submit(self: &Arc<Self>, session_id: &str, body: &[u8]) -> ViewResult<AcceptedRun> {
let validated = request::validate_request(body)?; let validated = request::validate_request(body)?;
let digest = payload_digest(body); let digest = payload_digest(body);
let client_request_id = validated.client_request_id.clone(); let request_identity = (session_id.to_string(), validated.client_request_id.clone());
let mut state = self.state.lock().map_err(|_| ViewError::Io { let mut state = self.state.lock().map_err(|_| ViewError::Io {
detail: "execution controller lock poisoned".to_string(), detail: "execution controller lock poisoned".to_string(),
})?; })?;
self.purge_locked(&mut state); self.purge_locked(&mut state);
if let Some(entry) = state.dedupe.get(&client_request_id) { if let Some(entry) = state.dedupe.get(&request_identity) {
if entry.digest != digest { if entry.digest != digest {
return Err(ViewError::RunConflict { return Err(ViewError::RunConflict {
detail: "同一 client_request_id 携带了不同请求内容;拒绝执行以避免偷换任务" detail: "同一 client_request_id 携带了不同请求内容;拒绝执行以避免偷换任务"
@@ -250,7 +281,7 @@ impl ExecutionController {
state.jobs.insert(run_id.clone(), Arc::clone(&job)); state.jobs.insert(run_id.clone(), Arc::clone(&job));
state.active = Some(run_id.clone()); state.active = Some(run_id.clone());
state.dedupe.insert( state.dedupe.insert(
client_request_id, request_identity,
DedupeEntry { DedupeEntry {
digest, digest,
run_id: run_id.clone(), run_id: run_id.clone(),
@@ -282,7 +313,7 @@ impl ExecutionController {
plan: ExecutionPlan, plan: ExecutionPlan,
) { ) {
let started = Instant::now(); let started = Instant::now();
let outcome = self.run_core(&job, &plan); let outcome = self.run_core(&job, &plan, &static_doc);
let cancel_requested = job.cancel.load(Ordering::SeqCst); let cancel_requested = job.cancel.load(Ordering::SeqCst);
eprintln!( eprintln!(
"JOB_DEBUG id={} run_core elapsed={:?} cancel={cancel_requested}", "JOB_DEBUG id={} run_core elapsed={:?} cancel={cancel_requested}",
@@ -299,6 +330,16 @@ impl ExecutionController {
let (state, result, trace, trace_status, error_code, error_message) = terminal; let (state, result, trace, trace_status, error_code, error_message) = terminal;
let mut result = result; let mut result = result;
result["trace_status"] = serde_json::json!(trace_status.clone()); result["trace_status"] = serde_json::json!(trace_status.clone());
if let Some(candidate) = TerminalExportCandidate::from_terminal(
state,
&plan,
&static_doc,
&result,
trace.as_ref(),
) {
result["export_preview"] = candidate.preview();
inner.export_candidate = Some(Arc::new(candidate));
}
match state { match state {
RunState::Succeeded => { RunState::Succeeded => {
inner.log.publish_complete(result, trace); inner.log.publish_complete(result, trace);
@@ -336,7 +377,8 @@ impl ExecutionController {
&self, &self,
job: &Arc<Job>, job: &Arc<Job>,
plan: &ExecutionPlan, plan: &ExecutionPlan,
) -> Result<(ProcessOutcome, Option<Vec<u8>>), ViewError> { static_doc: &StaticDocument,
) -> ViewResult<CoreRun> {
let client = self let client = self
.service .service
.core_client() .core_client()
@@ -346,7 +388,10 @@ impl ExecutionController {
let entry = self.service.project().absolute_for(&plan.document)?; let entry = self.service.project().absolute_for(&plan.document)?;
let scratch = ScratchDir::create("run")?; let scratch = ScratchDir::create("run")?;
let trace_path = scratch.file("trace.json"); let trace_path = scratch.file("trace.json");
let options = self.run_options(plan); let mut options = self.run_options(plan);
let projection = &static_doc.verified.projection;
options.event_stream =
crate::protocol::tool_v1::supports_execution_events(&projection.producer_version);
let args = match &plan.target { let args = match &plan.target {
ExecutionTarget::Entry => build_run_args(&entry, &trace_path, &options), ExecutionTarget::Entry => build_run_args(&entry, &trace_path, &options),
ExecutionTarget::Function { cli_name, .. } => { ExecutionTarget::Function { cli_name, .. } => {
@@ -365,20 +410,60 @@ impl ExecutionController {
wall_clock: self.config.run_timeout, wall_clock: self.config.run_timeout,
..self.config.budget.clone() ..self.config.budget.clone()
}; };
let (send_stream, receive_stream) = std::sync::mpsc::channel();
let mut hooks = ProcessHooks {
on_spawn: Some(Box::new(hook)),
..Default::default()
};
if options.event_stream {
let entry = match &plan.target {
ExecutionTarget::Entry => "main",
ExecutionTarget::Function { cli_name, .. } => cli_name,
};
let binding = core_events::Binding {
digest: static_doc.analysis_digest.clone(),
root: projection.project_root_id.clone(),
entry: format!("{}::{entry}", projection.module_id),
function: plan.function_id.clone(),
mode: plan.mode.as_str().to_string(),
producer: projection.producer_version.clone(),
modules: projection
.modules
.iter()
.map(|module| module.id.clone())
.collect(),
max_output: DEFAULT_MAX_OUTPUT as usize,
};
let observed_job = Arc::clone(job);
hooks.stdout = Some(Box::new(move |stdout| {
let stream = core_events::read(stdout, &binding, |observation| {
if let Ok(mut inner) = observed_job.inner.lock() {
inner.log.publish_observation(observation);
}
});
let _ = send_stream.send(stream);
Captured::default()
}));
}
let outcome = run_bounded_with_hook( let outcome = run_bounded_with_hook(
client.bin(), client.bin(),
&args, &args,
self.service.project().root(), self.service.project().root(),
&budget, &budget,
Some(Arc::clone(&job.cancel)), Some(Arc::clone(&job.cancel)),
Box::new(hook), hooks,
)?; )?;
let trace = read_trace_limited(&trace_path)?; let trace = read_trace_limited(&trace_path);
Ok((outcome, trace)) Ok(CoreRun {
process: outcome,
trace,
stream: receive_stream.try_recv().ok(),
})
} }
fn run_options(&self, plan: &ExecutionPlan) -> RunOptions { fn run_options(&self, plan: &ExecutionPlan) -> RunOptions {
RunOptions { RunOptions {
event_stream: false,
mode: match plan.mode { mode: match plan.mode {
RunMode::Pure => SandboxMode::Pure, RunMode::Pure => SandboxMode::Pure,
RunMode::Project => SandboxMode::Project, RunMode::Project => SandboxMode::Project,
@@ -399,7 +484,7 @@ impl ExecutionController {
plan: &ExecutionPlan, plan: &ExecutionPlan,
static_doc: &StaticDocument, static_doc: &StaticDocument,
started: Instant, started: Instant,
outcome: Result<(ProcessOutcome, Option<Vec<u8>>), ViewError>, outcome: ViewResult<CoreRun>,
cancel_requested: bool, cancel_requested: bool,
) -> ( ) -> (
RunState, RunState,
@@ -410,7 +495,11 @@ impl ExecutionController {
Option<String>, Option<String>,
) { ) {
let duration_ms = started.elapsed().as_millis() as u64; let duration_ms = started.elapsed().as_millis() as u64;
let (outcome, trace_bytes) = match outcome { let CoreRun {
process: outcome,
trace: trace_bytes,
stream,
} = match outcome {
Ok(value) => value, Ok(value) => value,
Err(err) => { Err(err) => {
let state = match err.code() { let state = match err.code() {
@@ -486,7 +575,40 @@ impl ExecutionController {
)), )),
); );
} }
let json: serde_json::Value = let json: serde_json::Value = if let Some(stream) = &stream {
let Some(mut terminal) = stream
.terminal
.clone()
.filter(|terminal| terminal["success"].as_bool() == Some(outcome.status_ok()))
else {
let mut result = base_result(plan, static_doc, duration_ms);
result["stdout"] = serde_json::json!(String::from_utf8_lossy(&stream.stdout));
result["stderr"] = serde_json::json!(String::from_utf8_lossy(&stream.stderr));
result["output_complete"] = serde_json::json!(false);
return (
RunState::Incomplete,
result,
None,
"unavailable".into(),
Some("view.core_protocol".into()),
Some(
if stream.invalid {
"CLI 事件流无效"
} else {
"CLI 事件流缺少可信终态"
}
.into(),
),
);
};
terminal["command"] = serde_json::json!(match plan.target {
ExecutionTarget::Entry => "run",
ExecutionTarget::Function { .. } => "call",
});
terminal["stdout"] = serde_json::json!(String::from_utf8_lossy(&stream.stdout));
terminal["stderr"] = serde_json::json!(String::from_utf8_lossy(&stream.stderr));
terminal
} else {
match serde_json::from_slice::<serde_json::Value>(&outcome.stdout.bytes) { match serde_json::from_slice::<serde_json::Value>(&outcome.stdout.bytes) {
Ok(value) if value.is_object() => value, Ok(value) if value.is_object() => value,
Ok(_) => { Ok(_) => {
@@ -512,7 +634,8 @@ impl ExecutionController {
)), )),
) )
} }
}; }
};
// Re-read the source after the run: a changed source makes the result // Re-read the source after the run: a changed source makes the result
// stale and forbids anchoring events to the current text. // stale and forbids anchoring events to the current text.
@@ -523,15 +646,42 @@ impl ExecutionController {
.unwrap_or_default(); .unwrap_or_default();
let stale = sha256_hex(&current_source) != static_doc.source_sha256; let stale = sha256_hex(&current_source) != static_doc.source_sha256;
let (trace, trace_status) = build_trace_summary( let (mut trace, mut trace_status) = match trace_bytes {
trace_bytes.as_deref(), Ok(trace_bytes) => build_trace_summary(
static_doc, trace_bytes.as_deref(),
&json, static_doc,
outcome.exit_code.unwrap_or(-1), &json,
stale, outcome.exit_code.unwrap_or(-1),
); stale,
),
Err(_) => (None, "invalid".into()),
};
let mut result = build_cli_result(plan, static_doc, duration_ms, &json, &outcome); let mut result = build_cli_result(plan, static_doc, duration_ms, &json, &outcome);
result["stale"] = serde_json::json!(stale); result["stale"] = serde_json::json!(stale);
if let Some(stream) = stream {
result["event_protocol"] = serde_json::json!(1);
result["core_run_id"] = serde_json::json!(stream.id);
result["source_verified"] = serde_json::json!(stream.verified && !stale);
result["observation_truncated"] = serde_json::json!(stream.truncated);
result["stdout_bytes"] = serde_json::json!(stream.stdout.len());
result["stderr_bytes"] = serde_json::json!(stream.stderr.len());
result["output_complete"] = serde_json::json!(
std::str::from_utf8(&stream.stdout).is_ok()
&& std::str::from_utf8(&stream.stderr).is_ok()
&& !json["error"]["code"]
.as_str()
.is_some_and(|code| code.contains("output_limit"))
);
if trace_status == "verified"
&& trace
.as_ref()
.and_then(|trace| trace["core_run_id"].as_str())
!= Some(&stream.id)
{
trace = None;
trace_status = "invalid".into();
}
}
let success = json let success = json
.get("success") .get("success")
.and_then(serde_json::Value::as_bool) .and_then(serde_json::Value::as_bool)
@@ -617,10 +767,28 @@ impl ExecutionController {
Ok(self.lookup(session_id, run_id)?.state()) Ok(self.lookup(session_id, run_id)?.state())
} }
pub fn get_export_candidate(
&self,
session_id: &str,
run_id: &str,
) -> ViewResult<Arc<TerminalExportCandidate>> {
let job = self.lookup(session_id, run_id)?;
let inner = job.inner.lock().map_err(|_| ViewError::Io {
detail: "job lock poisoned".into(),
})?;
inner
.export_candidate
.clone()
.ok_or_else(|| ViewError::ExportUnavailable {
detail: "job has no verified exportable terminal observation".into(),
})
}
fn lookup(&self, session_id: &str, run_id: &str) -> ViewResult<Arc<Job>> { fn lookup(&self, session_id: &str, run_id: &str) -> ViewResult<Arc<Job>> {
let state = self.state.lock().map_err(|_| ViewError::Io { let mut state = self.state.lock().map_err(|_| ViewError::Io {
detail: "execution controller lock poisoned".to_string(), detail: "execution controller lock poisoned".to_string(),
})?; })?;
self.purge_locked(&mut state);
let job = state let job = state
.jobs .jobs
.get(run_id) .get(run_id)
@@ -630,7 +798,7 @@ impl ExecutionController {
})?; })?;
if job.session_id != session_id { if job.session_id != session_id {
return Err(ViewError::RunNotFound { return Err(ViewError::RunNotFound {
detail: "运行任务不属于当前会话".to_string(), detail: "运行任务不存在或已过期".to_string(),
}); });
} }
Ok(job) Ok(job)
@@ -671,18 +839,22 @@ impl ExecutionController {
} }
fn read_trace_limited(path: &std::path::Path) -> ViewResult<Option<Vec<u8>>> { fn read_trace_limited(path: &std::path::Path) -> ViewResult<Option<Vec<u8>>> {
match std::fs::read(path) { use std::io::Read;
Ok(bytes) if bytes.is_empty() => Ok(None), let file = match std::fs::File::open(path) {
Ok(bytes) if bytes.len() > MAX_TRACE_FILE_BYTES => Err(ViewError::OutputLimit { Ok(file) => file,
detail: format!("Trace 文件超过 {} 字节上限", MAX_TRACE_FILE_BYTES), Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
}), Err(err) => return Err(ViewError::io("open Core Trace", err)),
Ok(bytes) => Ok(Some(bytes)), };
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None), let mut bytes = Vec::new();
Err(err) => Err(ViewError::io( file.take(MAX_TRACE_FILE_BYTES as u64 + 1)
&format!("read trace {}", path.display()), .read_to_end(&mut bytes)
err, .map_err(|err| ViewError::io("read Core Trace", err))?;
)), if bytes.len() > MAX_TRACE_FILE_BYTES {
return Err(ViewError::OutputLimit {
detail: "Trace v2 byte limit exceeded".into(),
});
} }
Ok((!bytes.is_empty()).then_some(bytes))
} }
fn base_result( fn base_result(
@@ -692,6 +864,7 @@ fn base_result(
) -> serde_json::Value { ) -> serde_json::Value {
serde_json::json!({ serde_json::json!({
"document": plan.document.as_str(), "document": plan.document.as_str(),
"function_id": plan.function_id,
"target": match &plan.target { "target": match &plan.target {
ExecutionTarget::Entry => serde_json::json!({"kind": "entry"}), ExecutionTarget::Entry => serde_json::json!({"kind": "entry"}),
ExecutionTarget::Function { cli_name, label } => serde_json::json!({ ExecutionTarget::Function { cli_name, label } => serde_json::json!({
@@ -1025,6 +1198,40 @@ fn unique_counter() -> u64 {
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn expired_terminal_job_is_never_returned_for_export() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("examples/welcome");
let service = Arc::new(DocumentService::open(&root, None).unwrap());
let config = ExecutionConfig {
terminal_ttl: Duration::ZERO,
..Default::default()
};
let controller = ExecutionController::new(service, config);
let job = Arc::new(Job::new(
"expired".into(),
"owner".into(),
"index.mq.md".into(),
));
{
let mut inner = job.inner.lock().unwrap();
inner.log.publish_state(RunState::Succeeded);
inner.terminal_at = Some(Instant::now());
}
{
let mut state = controller.state.lock().unwrap();
state.jobs.insert(job.run_id.clone(), Arc::clone(&job));
state.order.push_back(job.run_id.clone());
}
assert_eq!(
controller
.get_export_candidate("owner", &job.run_id)
.unwrap_err()
.code(),
"view.run_not_found"
);
assert!(controller.state.lock().unwrap().jobs.is_empty());
}
#[test] #[test]
fn wire_value_summary_is_safe_and_never_html() { fn wire_value_summary_is_safe_and_never_html() {
assert_eq!( assert_eq!(
+18
View File
@@ -26,6 +26,7 @@ pub enum RunState {
Cancelled, Cancelled,
TimedOut, TimedOut,
Unavailable, Unavailable,
Incomplete,
} }
impl RunState { impl RunState {
@@ -39,6 +40,7 @@ impl RunState {
RunState::Cancelled => "cancelled", RunState::Cancelled => "cancelled",
RunState::TimedOut => "timed_out", RunState::TimedOut => "timed_out",
RunState::Unavailable => "unavailable", RunState::Unavailable => "unavailable",
RunState::Incomplete => "incomplete",
} }
} }
@@ -52,6 +54,7 @@ impl RunState {
RunState::Cancelled => "已取消", RunState::Cancelled => "已取消",
RunState::TimedOut => "超时", RunState::TimedOut => "超时",
RunState::Unavailable => "不可用", RunState::Unavailable => "不可用",
RunState::Incomplete => "事件流不完整",
} }
} }
@@ -63,6 +66,7 @@ impl RunState {
| RunState::Cancelled | RunState::Cancelled
| RunState::TimedOut | RunState::TimedOut
| RunState::Unavailable | RunState::Unavailable
| RunState::Incomplete
) )
} }
} }
@@ -73,6 +77,7 @@ pub enum EventKind {
Complete, Complete,
Error, Error,
Snapshot, Snapshot,
Observation,
} }
impl EventKind { impl EventKind {
@@ -82,6 +87,7 @@ impl EventKind {
EventKind::Complete => "run.complete", EventKind::Complete => "run.complete",
EventKind::Error => "run.error", EventKind::Error => "run.error",
EventKind::Snapshot => "run.snapshot", EventKind::Snapshot => "run.snapshot",
EventKind::Observation => "run.observation",
} }
} }
} }
@@ -98,6 +104,7 @@ pub struct RunEvent {
pub trace: Option<serde_json::Value>, pub trace: Option<serde_json::Value>,
/// `{code, message}` for terminal failures. /// `{code, message}` for terminal failures.
pub error: Option<serde_json::Value>, pub error: Option<serde_json::Value>,
pub observation: Option<serde_json::Value>,
} }
impl RunEvent { impl RunEvent {
@@ -119,6 +126,9 @@ impl RunEvent {
if let Some(error) = &self.error { if let Some(error) = &self.error {
data["error"] = error.clone(); data["error"] = error.clone();
} }
if let Some(observation) = &self.observation {
data["observation"] = observation.clone();
}
data data
} }
@@ -180,6 +190,7 @@ impl EventLog {
result: None, result: None,
trace: None, trace: None,
error: None, error: None,
observation: None,
}; };
self.next_seq += 1; self.next_seq += 1;
self.last_state = state; self.last_state = state;
@@ -213,6 +224,12 @@ impl EventLog {
self.record(event) self.record(event)
} }
pub fn publish_observation(&mut self, observation: serde_json::Value) {
let mut event = self.next_event(EventKind::Observation, self.last_state);
event.observation = Some(observation);
self.record(event);
}
pub fn publish_complete( pub fn publish_complete(
&mut self, &mut self,
result: serde_json::Value, result: serde_json::Value,
@@ -276,6 +293,7 @@ impl EventLog {
result: None, result: None,
trace: None, trace: None,
error: None, error: None,
observation: None,
} }
} }
+161
View File
@@ -0,0 +1,161 @@
//! A bounded projection retained only inside an existing terminal Job.
use crate::execution::events::RunState;
use crate::execution::request::ExecutionPlan;
use crate::reader::assemble::StaticDocument;
use serde_json::{json, Value};
use std::collections::BTreeMap;
const MAX_TEXT: usize = 128 * 1024;
#[derive(Debug)]
pub struct TerminalExportCandidate {
pub document: String,
pub function_id: String,
pub label: String,
pub project_root_id: String,
pub module_id: String,
pub analysis_digest: String,
pub analysis_version: u32,
pub source_sha256: String,
pub lock_digest: String,
pub media: BTreeMap<String, String>,
pub core_run_id: String,
pub core_version: String,
pub mode: String,
pub terminal_at: String,
pub state: RunState,
pub value: Option<String>,
pub value_is_public_scalar: bool,
pub stdout: String,
pub stderr: String,
pub arguments: Vec<(String, String)>,
pub trace_status: String,
pub trace_counts: Option<BTreeMap<String, u64>>,
pub output_complete: bool,
pub result_complete: bool,
pub observation_truncated: bool,
}
impl TerminalExportCandidate {
pub(super) fn from_terminal(
state: RunState,
plan: &ExecutionPlan,
document: &StaticDocument,
result: &Value,
trace: Option<&Value>,
) -> Option<Self> {
if !matches!(state, RunState::Succeeded | RunState::Failed)
|| result.get("source_verified").and_then(Value::as_bool) != Some(true)
|| result.get("event_protocol").and_then(Value::as_u64) != Some(1)
{
return None;
}
let projection = &document.verified.projection;
let function = projection
.functions
.iter()
.find(|function| function.id == plan.function_id)?;
let (stdout, stdout_complete) = bounded_text(result["stdout"].as_str());
let (stderr, stderr_complete) = bounded_text(result["stderr"].as_str());
let wire = &result["value"];
let value_is_scalar = matches!(
wire["type"].as_str(),
Some("int" | "float" | "bool" | "unit" | "none" | "text")
);
let value_text = match state {
RunState::Succeeded if value_is_scalar => {
result["value_text"].as_str().map(str::to_string)
}
RunState::Succeeded if crate::protocol::value_wire_v1::transferable(wire) => {
Some(wire.to_string())
}
_ => None,
};
let (value, value_complete) = match value_text {
Some(text) => {
let (text, complete) = bounded_text(Some(&text));
(Some(text), complete)
}
None => (None, false),
};
let trace_status = match &result["trace_status"] {
Value::String(status) if status == "verified" => {
if trace.is_some_and(|trace| !trace["truncated"].is_null()) {
"truncated"
} else {
"verified"
}
}
Value::String(status) if status == "invalid" => "invalid",
_ => "unavailable",
};
let trace_counts = trace
.filter(|trace| trace["status"] == "verified")
.and_then(|trace| trace["counts"].as_object())
.map(|counts| {
counts
.iter()
.filter_map(|(kind, count)| Some((kind.clone(), count.as_u64()?)))
.collect()
});
let value_is_public_scalar = value_is_scalar && wire["type"] != "text";
Some(Self {
document: plan.document.to_string(),
function_id: function.id.clone(),
label: function.local_name.clone(),
project_root_id: projection.project_root_id.clone(),
module_id: projection.module_id.clone(),
analysis_digest: document.analysis_digest.clone(),
analysis_version: projection.schema_version,
source_sha256: document.source_sha256.clone(),
lock_digest: projection.lock_digest.clone(),
media: document.media_digests.clone(),
core_run_id: result["core_run_id"].as_str()?.to_string(),
core_version: projection.producer_version.clone(),
mode: plan.mode.as_str().to_string(),
terminal_at: crate::execution::events::utc_now(),
state,
value,
value_is_public_scalar,
stdout,
stderr,
arguments: plan.arguments.clone(),
trace_status: trace_status.to_string(),
trace_counts,
output_complete: result["output_complete"].as_bool() == Some(true)
&& stdout_complete
&& stderr_complete,
result_complete: state == RunState::Succeeded && value_complete,
observation_truncated: result["observation_truncated"].as_bool().unwrap_or(false),
})
}
pub(super) fn preview(&self) -> Value {
json!({
"label": self.label,
"value_bytes": self.value.as_ref().map(String::len),
"value": self.value,
"value_is_public_scalar": self.value_is_public_scalar,
"stdout_bytes": self.stdout.len(),
"stderr_bytes": self.stderr.len(),
"arguments_count": self.arguments.len(),
"trace_summary": self.trace_counts.is_some(),
"trace_status": self.trace_status,
"observation_truncated": self.observation_truncated,
"output_complete": self.output_complete,
"result_complete": self.result_complete,
})
}
}
fn bounded_text(value: Option<&str>) -> (String, bool) {
let Some(text) = value else {
return (String::new(), true);
};
let mut end = text.len().min(MAX_TEXT);
while !text.is_char_boundary(end) {
end -= 1;
}
(text[..end].to_string(), end == text.len())
}
+1
View File
@@ -11,5 +11,6 @@
pub mod controller; pub mod controller;
pub mod events; pub mod events;
pub mod export_candidate;
pub mod process; pub mod process;
pub mod request; pub mod request;
+17 -4
View File
@@ -85,7 +85,15 @@ pub fn run_bounded(
budget: &ProcessBudget, budget: &ProcessBudget,
cancel: Option<Arc<AtomicBool>>, cancel: Option<Arc<AtomicBool>>,
) -> ViewResult<ProcessOutcome> { ) -> ViewResult<ProcessOutcome> {
run_bounded_with_hook(bin, args, cwd, budget, cancel, Box::new(|| {})) run_bounded_with_hook(bin, args, cwd, budget, cancel, ProcessHooks::default())
}
type StdoutReader = Box<dyn FnOnce(std::process::ChildStdout) -> Captured + Send>;
#[derive(Default)]
pub struct ProcessHooks {
pub on_spawn: Option<Box<dyn FnOnce() + Send>>,
pub stdout: Option<StdoutReader>,
} }
/// Same as [`run_bounded`], with a hook invoked exactly once **after** the /// Same as [`run_bounded`], with a hook invoked exactly once **after** the
@@ -96,7 +104,7 @@ pub fn run_bounded_with_hook(
cwd: &Path, cwd: &Path,
budget: &ProcessBudget, budget: &ProcessBudget,
cancel: Option<Arc<AtomicBool>>, cancel: Option<Arc<AtomicBool>>,
on_spawn: Box<dyn FnOnce() + Send>, hooks: ProcessHooks,
) -> ViewResult<ProcessOutcome> { ) -> ViewResult<ProcessOutcome> {
let started = Instant::now(); let started = Instant::now();
let mut command = Command::new(bin); let mut command = Command::new(bin);
@@ -122,12 +130,17 @@ pub fn run_bounded_with_hook(
let mut child = command.spawn().map_err(|err| ViewError::CoreSpawn { let mut child = command.spawn().map_err(|err| ViewError::CoreSpawn {
detail: format!("spawn {}: {err}", bin.display()), detail: format!("spawn {}: {err}", bin.display()),
})?; })?;
on_spawn(); if let Some(on_spawn) = hooks.on_spawn {
on_spawn();
}
let stdout = child.stdout.take().expect("piped stdout"); let stdout = child.stdout.take().expect("piped stdout");
let stderr = child.stderr.take().expect("piped stderr"); let stderr = child.stderr.take().expect("piped stderr");
let stdout_cap = budget.max_stdout; let stdout_cap = budget.max_stdout;
let stderr_cap = budget.max_stderr; let stderr_cap = budget.max_stderr;
let stdout_thread = std::thread::spawn(move || read_bounded(stdout, stdout_cap)); let stdout_thread = std::thread::spawn(move || match hooks.stdout {
Some(read_stdout) => read_stdout(stdout),
None => read_bounded(stdout, stdout_cap),
});
let stderr_thread = std::thread::spawn(move || read_bounded(stderr, stderr_cap)); let stderr_thread = std::thread::spawn(move || read_bounded(stderr, stderr_cap));
let deadline = started + budget.wall_clock; let deadline = started + budget.wall_clock;
+26 -17
View File
@@ -111,6 +111,7 @@ pub enum ExecutionTarget {
pub struct ExecutionPlan { pub struct ExecutionPlan {
pub document: SafeRelativePath, pub document: SafeRelativePath,
pub target: ExecutionTarget, pub target: ExecutionTarget,
pub function_id: String,
pub arguments: Vec<(String, String)>, pub arguments: Vec<(String, String)>,
pub mode: RunMode, pub mode: RunMode,
pub grants: Grants, pub grants: Grants,
@@ -122,17 +123,17 @@ impl ValidatedRequest {
/// Resolve the target and parameter names against the verified entry-module /// Resolve the target and parameter names against the verified entry-module
/// Analysis. Never accepts a dependency-module function id (RFC §6.3). /// Analysis. Never accepts a dependency-module function id (RFC §6.3).
pub fn plan_against(self, projection: &SemanticProjection) -> ViewResult<ExecutionPlan> { pub fn plan_against(self, projection: &SemanticProjection) -> ViewResult<ExecutionPlan> {
let target = match &self.target { let (target, function_id) = match &self.target {
RunTarget::Entry => { RunTarget::Entry => {
if resolve_main(projection).is_none() { let Some(function) = resolve_main(projection) else {
return Err(ViewError::NoEntryFunction { return Err(ViewError::NoEntryFunction {
detail: format!( detail: format!(
"{} 没有可调用的 main;请从函数面板选择一个 H2 Exec 函数", "{} 没有可调用的 main;请从函数面板选择一个 H2 Exec 函数",
self.document self.document
), ),
}); });
} };
ExecutionTarget::Entry (ExecutionTarget::Entry, function.id.clone())
} }
RunTarget::Function { function_id } => { RunTarget::Function { function_id } => {
let function = projection let function = projection
@@ -153,12 +154,16 @@ impl ValidatedRequest {
}; };
let label = canonical; let label = canonical;
validate_parameters(&self.parameters, projection, &function.id)?; validate_parameters(&self.parameters, projection, &function.id)?;
ExecutionTarget::Function { cli_name, label } (
ExecutionTarget::Function { cli_name, label },
function.id.clone(),
)
} }
}; };
Ok(ExecutionPlan { Ok(ExecutionPlan {
document: self.document, document: self.document,
target, target,
function_id,
arguments: self arguments: self
.parameters .parameters
.into_iter() .into_iter()
@@ -201,7 +206,7 @@ pub fn validate_request(body: &[u8]) -> ViewResult<ValidatedRequest> {
|| function_id.chars().any(|ch| ch.is_control() || ch == '\0') || function_id.chars().any(|ch| ch.is_control() || ch == '\0')
{ {
return Err(ViewError::RunInvalid { return Err(ViewError::RunInvalid {
detail: "function_id 必须来自 Analysis v2 且长度为 1..=512".to_string(), detail: "function_id 必须来自 Analysis 且长度为 1..=512".to_string(),
}); });
} }
} }
@@ -364,17 +369,21 @@ fn validate_glob(glob: &str) -> ViewResult<()> {
/// Resolve `main` exactly like the frozen CLI does for `run`: canonical name /// Resolve `main` exactly like the frozen CLI does for `run`: canonical name
/// first, then a unique local name. No fallback to any other function. /// first, then a unique local name. No fallback to any other function.
fn resolve_main(projection: &SemanticProjection) -> Option<(String, String)> { fn resolve_main(
if let Some(function) = projection.functions.iter().find(|function| { projection: &SemanticProjection,
canonical_name(&function.id, &projection.module_id) == "main" ) -> Option<&crate::protocol::analysis_v2::SemanticFunction> {
|| function.local_name == "main" projection
}) { .functions
return Some(( .iter()
canonical_name(&function.id, &projection.module_id), .find(|function| canonical_name(&function.id, &projection.module_id) == "main")
function.local_name.clone(), .or_else(|| {
)); let mut candidates = projection
} .functions
None .iter()
.filter(|function| function.local_name == "main");
let first = candidates.next()?;
candidates.next().is_none().then_some(first)
})
} }
fn unique_local_name(projection: &SemanticProjection, local_name: &str, id: &str) -> bool { fn unique_local_name(projection: &SemanticProjection, local_name: &str, id: &str) -> bool {
+242 -133
View File
@@ -8,9 +8,12 @@ use crate::error::{ViewError, ViewResult};
use crate::reader::assemble::DocumentService; use crate::reader::assemble::DocumentService;
use crate::reader::assets::AssetBundle; use crate::reader::assets::AssetBundle;
use crate::reader::render::ReaderRenderer; use crate::reader::render::ReaderRenderer;
use crate::reader::snapshot::ExportResultOverlay;
use crate::reader::source::sha256_hex; use crate::reader::source::sha256_hex;
use crate::reader::source::SafeRelativePath; use crate::reader::source::SafeRelativePath;
use crate::scratch::ScratchDir;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::Arc;
const MANIFEST_SCHEMA: &str = "marqdo.view-export"; const MANIFEST_SCHEMA: &str = "marqdo.view-export";
@@ -29,8 +32,6 @@ pub struct ExportSummary {
} }
pub fn export(context: &DocumentService, options: &ExportOptions) -> ViewResult<ExportSummary> { pub fn export(context: &DocumentService, options: &ExportOptions) -> ViewResult<ExportSummary> {
let bundle = AssetBundle::get();
let renderer = ReaderRenderer::new();
let root = context.project().root().to_path_buf(); let root = context.project().root().to_path_buf();
let out = absolute_export_target(&options.out)?; let out = absolute_export_target(&options.out)?;
if out.starts_with(&root) { if out.starts_with(&root) {
@@ -44,149 +45,257 @@ pub fn export(context: &DocumentService, options: &ExportOptions) -> ViewResult<
} }
validate_existing_target(&out)?; validate_existing_target(&out)?;
let documents = context.project().list_documents()?;
if documents.is_empty() {
return Err(ViewError::ExportFailed {
detail: "项目内没有 .mq.md 文档可导出".to_string(),
});
}
let entry = context.project().entry().relative.clone();
let staging = staging_dir(&out)?; let staging = staging_dir(&out)?;
let result = (|| {
let result = (|| -> ViewResult<ExportSummary> { let entry = context.load(&context.project().entry().relative)?;
let assets_dir = staging.join("assets"); let site = build_site(context, &entry, &staging, !options.no_annotations, None)?;
let pages_dir = staging.join("pages");
std::fs::create_dir_all(&assets_dir)
.map_err(|err| ViewError::io(&format!("create {}", assets_dir.display()), err))?;
std::fs::create_dir_all(&pages_dir)
.map_err(|err| ViewError::io(&format!("create {}", pages_dir.display()), err))?;
// Assets: the exact same bytes Live serves.
let mut asset_manifest = Vec::new();
for asset in bundle.all() {
let name = if asset.extension == "css" && asset.name == "reader" {
bundle.hashed_css_name()
} else {
asset.hashed_name()
};
let bytes = if asset.extension == "css" && asset.name == "reader" {
bundle.css_bytes().to_vec()
} else {
asset.bytes.to_vec()
};
std::fs::write(assets_dir.join(&name), &bytes)
.map_err(|err| ViewError::io(&format!("write asset {name}"), err))?;
asset_manifest.push(serde_json::json!({
"path": format!("assets/{name}"),
"sha256": sha256_hex(&bytes),
"size": bytes.len(),
}));
}
let mut pages = Vec::new();
let mut file_manifest: Vec<serde_json::Value> = Vec::new();
for relative in &documents {
let model = context.load(relative)?;
let depth = relative.as_str().split('/').count();
let context =
crate::reader::render::RenderContext::static_export(depth, !options.no_annotations);
let page = renderer.render(&model, &context);
let page_path = pages_dir.join(format!("{}.html", relative.as_str()));
if let Some(parent) = page_path.parent() {
std::fs::create_dir_all(parent)
.map_err(|err| ViewError::io(&format!("create {}", parent.display()), err))?;
}
std::fs::write(&page_path, page.html.as_bytes())
.map_err(|err| ViewError::io(&format!("write {}", page_path.display()), err))?;
let page_sha = sha256_hex(page.html.as_bytes());
let page_rel = format!("pages/{}.html", relative.as_str());
file_manifest.push(serde_json::json!({
"path": page_rel,
"sha256": page_sha,
"size": page.html.len(),
}));
pages.push(serde_json::json!({
"relative_path": relative.as_str(),
"module_id": model.document.identity.module_id,
"source_sha256": sha256_hex(model.document.source.as_bytes()),
"source_status": model.source_status.data_value(),
"analysis_digest": model.semantic.as_ref().map(|semantic| semantic.analysis_digest.clone()),
"file": page_rel,
"sha256": page_sha,
"annotations": !options.no_annotations,
}));
}
// index.html is the same renderer output with site-root depth.
let entry_model = context.load(&entry)?;
let entry_context =
crate::reader::render::RenderContext::static_export(0, !options.no_annotations);
let index_page = renderer.render(&entry_model, &entry_context);
let index_path = staging.join("index.html");
std::fs::write(&index_path, index_page.html.as_bytes())
.map_err(|err| ViewError::io(&format!("write {}", index_path.display()), err))?;
let index_sha = sha256_hex(index_page.html.as_bytes());
file_manifest.push(serde_json::json!({
"path": "index.html",
"sha256": index_sha,
"size": index_page.html.len(),
}));
file_manifest.sort_by(|a, b| {
a["path"]
.as_str()
.unwrap_or("")
.cmp(b["path"].as_str().unwrap_or(""))
});
let manifest = serde_json::json!({
"schema": MANIFEST_SCHEMA,
"schema_version": 1,
"view": {
"name": "marqdo-view",
"version": env!("CARGO_PKG_VERSION"),
},
"compatibility": {
"marqdo": crate::protocol::tool_v1::PRODUCT_RANGE,
"tool_protocol": crate::protocol::tool_v1::TOOL_PROTOCOL,
"analysis": crate::protocol::tool_v1::ANALYSIS_PROTOCOL,
"trace": crate::protocol::tool_v1::TRACE_PROTOCOL,
"markdown_profile": "marqdo.md.v1",
},
"core_version": entry_model.core_version,
"entry": {
"relative_path": entry.as_str(),
"file": "index.html",
"sha256": index_sha,
},
"pages": pages,
"assets": asset_manifest,
"files": file_manifest,
"executed": false,
"note": "Static export only; reading or exporting never executes the document.",
});
let manifest_bytes =
serde_json::to_vec_pretty(&manifest).map_err(|err| ViewError::ExportFailed {
detail: format!("serialize export manifest: {err}"),
})?;
let manifest_path = staging.join("manifest.json");
std::fs::write(&manifest_path, &manifest_bytes)
.map_err(|err| ViewError::io(&format!("write {}", manifest_path.display()), err))?;
publish(&staging, &out)?; publish(&staging, &out)?;
Ok(ExportSummary { Ok(ExportSummary {
out, out,
pages: documents.len(), pages: site.pages,
files: file_manifest.len() + asset_manifest.len() + 1, files: site.entries.len(),
manifest_sha256: sha256_hex(&manifest_bytes), manifest_sha256: site.manifest_sha256,
}) })
})(); })();
if result.is_err() { if result.is_err() {
let _ = std::fs::remove_dir_all(&staging); let _ = std::fs::remove_dir_all(&staging);
} }
result result
} }
struct Site {
pages: usize,
entries: Vec<String>,
manifest_sha256: String,
}
struct SiteWriter<'a> {
root: &'a Path,
entries: std::collections::BTreeSet<String>,
remaining_bytes: usize,
}
impl SiteWriter<'_> {
fn write(&mut self, relative: &str, bytes: &[u8]) -> ViewResult<serde_json::Value> {
if relative.contains([':', '\\'])
|| SafeRelativePath::parse(relative).is_err()
|| relative
.split('/')
.any(|part| part.is_empty() || part == ".")
{
return Err(ViewError::ExportFailed {
detail: "unsafe static asset path".into(),
});
}
if self.entries.insert(relative.to_string()) {
self.remaining_bytes =
self.remaining_bytes
.checked_sub(bytes.len())
.ok_or_else(|| ViewError::ResourceLimit {
detail: "static package size limit exceeded".into(),
})?;
if self.entries.len() > 6_000 {
return Err(ViewError::ResourceLimit {
detail: "static package file limit exceeded".into(),
});
}
let path = self.root.join(relative);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)
.map_err(|err| ViewError::io("create static package directory", err))?;
}
std::fs::write(path, bytes)
.map_err(|err| ViewError::io("write static package file", err))?;
}
Ok(serde_json::json!({"path": relative, "sha256": sha256_hex(bytes), "size": bytes.len()}))
}
}
fn build_site(
context: &DocumentService,
entry_model: &crate::reader::model::PresentationModel,
staging: &Path,
annotations: bool,
overlay: Option<Arc<ExportResultOverlay>>,
) -> ViewResult<Site> {
let documents = context.project().list_documents()?;
let entry = SafeRelativePath::parse(&entry_model.document.identity.relative_path)?;
if !documents.contains(&entry) {
return Err(ViewError::ExportFailed {
detail: "entry document is missing".into(),
});
}
let mut writer = SiteWriter {
root: staging,
entries: Default::default(),
remaining_bytes: 96 * 1024 * 1024,
};
let bundle = AssetBundle::get();
let renderer = ReaderRenderer::new();
let mut assets = Vec::new();
for asset in bundle.all() {
if overlay.is_some() && asset.extension == "js" {
continue;
}
let (name, bytes) = if asset.name == "reader" && asset.extension == "css" {
(bundle.hashed_css_name(), bundle.css_bytes())
} else {
(asset.hashed_name(), asset.bytes)
};
assets.push(writer.write(&format!("assets/{name}"), bytes)?);
}
let mut pages = Vec::new();
let mut files = Vec::new();
let mut media_files = std::collections::BTreeMap::new();
for relative in &documents {
let loaded;
let model = if *relative == entry {
entry_model
} else {
loaded = context.load(relative)?;
&loaded
};
for media in model.media.values() {
let path = format!("media/{}", media.filename());
if let std::collections::btree_map::Entry::Vacant(entry) = media_files.entry(path) {
let mut record = writer.write(entry.key(), &media.bytes)?;
record["mime"] = serde_json::json!(media.mime);
entry.insert(record);
}
}
let depth = relative.as_str().split('/').count();
let mut settings = crate::reader::render::RenderContext::static_export(depth, annotations);
settings.snapshot_package = overlay.is_some();
settings.overlay = if *relative == entry {
overlay.clone()
} else {
None
};
let page = renderer.render(model, &settings);
let path = format!("pages/{}.html", relative.as_str());
let file = writer.write(&path, page.html.as_bytes())?;
pages.push(serde_json::json!({
"relative_path": relative.as_str(),
"module_id": model.document.identity.module_id,
"source_sha256": sha256_hex(model.document.source.as_bytes()),
"source_status": model.source_status.data_value(),
"analysis_digest": model.semantic.as_ref().map(|semantic| &semantic.analysis_digest),
"file": path,
"sha256": file["sha256"],
"annotations": annotations,
}));
files.push(file);
}
files.extend(media_files.values().cloned());
let mut index_context = crate::reader::render::RenderContext::static_export(0, annotations);
index_context.snapshot_package = overlay.is_some();
index_context.overlay = overlay.clone();
let index_page = renderer.render(entry_model, &index_context);
let index_file = writer.write("index.html", index_page.html.as_bytes())?;
let index_sha = index_file["sha256"].clone();
files.push(index_file);
files.sort_by(|a, b| a["path"].as_str().cmp(&b["path"].as_str()));
let mut manifest = serde_json::json!({
"schema": MANIFEST_SCHEMA,
"schema_version": 1,
"view": {"name": "marqdo-view", "version": env!("CARGO_PKG_VERSION")},
"compatibility": {
"marqdo": crate::protocol::tool_v1::PRODUCT_RANGE,
"tool_protocol": crate::protocol::tool_v1::TOOL_PROTOCOL,
"analysis": crate::protocol::tool_v1::ANALYSIS_PROTOCOL,
"analysis_supported": crate::protocol::tool_v1::ANALYSIS_PROTOCOLS,
"trace": crate::protocol::tool_v1::TRACE_PROTOCOL,
"markdown_profile": "marqdo.md.v1",
},
"core_version": entry_model.core_version,
"entry": {"relative_path": entry.as_str(), "file": "index.html", "sha256": index_sha},
"pages": pages,
"assets": assets,
"files": files,
"executed": false,
"note": "Static export only; reading or exporting never executes the document.",
});
if let Some(overlay) = overlay {
manifest["schema_version"] = serde_json::json!(2);
manifest["source"] = serde_json::json!(overlay.source);
manifest["execution"] = serde_json::json!(overlay.execution);
manifest["scope"] = serde_json::json!("document");
manifest["executed_during_export"] = serde_json::json!(false);
if let Some(fields) = manifest.as_object_mut() {
fields.remove("executed");
fields.remove("note");
}
}
let manifest_bytes =
serde_json::to_vec_pretty(&manifest).map_err(|err| ViewError::ExportFailed {
detail: format!("serialize export manifest: {err}"),
})?;
writer.write("manifest.json", &manifest_bytes)?;
Ok(Site {
pages: documents.len(),
entries: writer.entries.into_iter().collect(),
manifest_sha256: sha256_hex(&manifest_bytes),
})
}
pub struct SnapshotArchive {
pub file: std::fs::File,
pub len: usize,
pub manifest_sha256: String,
_scratch: ScratchDir,
}
pub fn snapshot(
context: &DocumentService,
model: &crate::reader::model::PresentationModel,
overlay: ExportResultOverlay,
) -> ViewResult<SnapshotArchive> {
let temp = std::env::temp_dir()
.canonicalize()
.map_err(|err| ViewError::io("resolve temporary location", err))?;
if temp.starts_with(context.project().root()) {
return Err(ViewError::ExportFailed {
detail: "temporary location is inside the project".into(),
});
}
let scratch = ScratchDir::create("snapshot")?;
let staging = scratch.file("site");
std::fs::create_dir(&staging)
.map_err(|err| ViewError::io("create private snapshot site", err))?;
let site = build_site(context, model, &staging, true, Some(Arc::new(overlay)))?;
let path = scratch.file("snapshot.zip");
let archive =
std::fs::File::create(&path).map_err(|err| ViewError::io("create snapshot ZIP", err))?;
let mut archive = zip::ZipWriter::new(archive);
let zip_error = |err: zip::result::ZipError| ViewError::ExportFailed {
detail: format!("package snapshot ZIP: {err}"),
};
let options = zip::write::SimpleFileOptions::default()
.compression_method(zip::CompressionMethod::Stored)
.unix_permissions(0o644);
for name in site.entries {
archive.start_file(&name, options).map_err(zip_error)?;
let mut file = std::fs::File::open(staging.join(name))
.map_err(|err| ViewError::io("open static snapshot file", err))?;
std::io::copy(&mut file, &mut archive)
.map_err(|err| ViewError::io("write snapshot file into ZIP", err))?;
}
archive.finish().map_err(zip_error)?;
let file = std::fs::File::open(path).map_err(|err| ViewError::io("open snapshot ZIP", err))?;
let len = file
.metadata()
.map_err(|err| ViewError::io("stat snapshot ZIP", err))?
.len() as usize;
Ok(SnapshotArchive {
file,
len,
manifest_sha256: site.manifest_sha256,
_scratch: scratch,
})
}
fn absolute_export_target(raw: &Path) -> ViewResult<PathBuf> { fn absolute_export_target(raw: &Path) -> ViewResult<PathBuf> {
let absolute = if raw.is_absolute() { let absolute = if raw.is_absolute() {
raw.to_path_buf() raw.to_path_buf()
+189
View File
@@ -0,0 +1,189 @@
//! Validate the selected session result against a freshly loaded document.
//! The output is an owned reader projection, independent of the job.
use crate::{
execution::{events::RunState, export_candidate::TerminalExportCandidate},
reader::{
assemble::DocumentService,
media,
model::PresentationModel,
snapshot::{ExportResultOverlay, SnapshotExecution, SnapshotProtocols, SnapshotSource},
source::{sha256_hex, SafeRelativePath},
},
ViewError, ViewResult,
};
use serde::Deserialize;
pub const MAX_EXPORT_REQUEST: usize = 8 * 1024;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ExportSelection {
schema: String,
schema_version: u32,
pub run_id: String,
document: String,
analysis_digest: String,
scope: Scope,
include: Include,
confirm_sensitive_output: bool,
#[serde(default)]
confirm_partial: bool,
client_export_request_id: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
enum Scope {
Document,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Include {
result_value: bool,
stdout: bool,
stderr: bool,
trace_summary: bool,
arguments: bool,
}
impl ExportSelection {
pub fn parse(body: &[u8]) -> ViewResult<Self> {
let invalid = || ViewError::ExportInvalid {
detail: "invalid v1 static export request".into(),
};
let selection: Self = serde_json::from_slice(body).map_err(|_| invalid())?;
let valid_token = |value: &str| {
!value.is_empty()
&& value.len() <= 128
&& value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
};
let path = SafeRelativePath::parse(&selection.document).map_err(|_| invalid())?;
let digest = selection
.analysis_digest
.strip_prefix("sha256:")
.ok_or_else(invalid)?;
if selection.schema != "marqdo.view-static-export-request"
|| selection.schema_version != 1
|| !matches!(selection.scope, Scope::Document)
|| selection.document.len() > 1024
|| path.as_str() != selection.document
|| !selection.document.ends_with(".mq.md")
|| digest.len() != 64
|| !digest
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
|| !valid_token(&selection.run_id)
|| !valid_token(&selection.client_export_request_id)
{
return Err(invalid());
}
Ok(selection)
}
pub fn prepare(
&self,
service: &DocumentService,
candidate: &TerminalExportCandidate,
) -> ViewResult<(PresentationModel, ExportResultOverlay)> {
let changed = || ViewError::ExportSourceChanged {
detail: "selected execution no longer matches the document".into(),
};
let invalid = || ViewError::ExportInvalid {
detail: "missing confirmation for selected fields or partial result".into(),
};
if self.document != candidate.document || self.analysis_digest != candidate.analysis_digest
{
return Err(changed());
}
if (self.include.stdout
|| self.include.stderr
|| self.include.arguments
|| self.include.result_value
&& candidate.value.is_some()
&& !candidate.value_is_public_scalar)
&& !self.confirm_sensitive_output
{
return Err(invalid());
}
if (candidate.state != RunState::Succeeded
|| !candidate.output_complete
|| !candidate.result_complete
|| candidate.observation_truncated
|| candidate.trace_status == "truncated")
&& !self.confirm_partial
{
return Err(invalid());
}
let document = SafeRelativePath::parse(&self.document)?;
let model = service.load(&document).map_err(|_| changed())?;
let analysis = model.semantic.as_ref().ok_or_else(changed)?;
if analysis.analysis_digest != candidate.analysis_digest
|| analysis.schema_version != candidate.analysis_version
|| analysis.project_root_id != candidate.project_root_id
|| analysis.module_id != candidate.module_id
|| analysis.lock_digest != candidate.lock_digest
|| sha256_hex(model.document.source.as_bytes()) != candidate.source_sha256
|| media::digests(&model.media) != candidate.media
|| !analysis
.functions
.iter()
.any(|function| function.id == candidate.function_id)
{
return Err(changed());
}
let overlay = ExportResultOverlay {
source: SnapshotSource {
project_root_id: candidate.project_root_id.clone(),
document: candidate.document.clone(),
module_id: candidate.module_id.clone(),
source_sha256: candidate.source_sha256.clone(),
analysis_digest: candidate.analysis_digest.clone(),
lock_digest: (!candidate.lock_digest.is_empty())
.then(|| candidate.lock_digest.clone()),
},
execution: SnapshotExecution {
included: true,
core_run_id: candidate.core_run_id.clone(),
target: candidate.function_id.clone(),
core_version: candidate.core_version.clone(),
status: candidate.state.data_value(),
terminal_at: candidate.terminal_at.clone(),
source_verified: true,
trace_status: candidate.trace_status.clone(),
result_complete: candidate.result_complete,
output_complete: candidate.output_complete,
observation_truncated: candidate.observation_truncated,
parameters: if self.include.arguments {
"included"
} else {
"omitted"
},
mode: candidate.mode.clone(),
core_protocol: SnapshotProtocols {
analysis: candidate.analysis_version,
trace: 2,
events: 1,
},
},
label: candidate.label.clone(),
value: self
.include
.result_value
.then(|| candidate.value.clone())
.flatten(),
stdout: self.include.stdout.then(|| candidate.stdout.clone()),
stderr: self.include.stderr.then(|| candidate.stderr.clone()),
trace_counts: self
.include
.trace_summary
.then(|| candidate.trace_counts.clone())
.flatten(),
arguments: self.include.arguments.then(|| candidate.arguments.clone()),
};
Ok((model, overlay))
}
}
+2
View File
@@ -12,8 +12,10 @@ pub mod core_client;
pub mod error; pub mod error;
pub mod execution; pub mod execution;
pub mod export; pub mod export;
pub mod export_result;
pub mod protocol; pub mod protocol;
pub mod reader; pub mod reader;
mod scratch;
pub mod server; pub mod server;
pub use cli::Cli; pub use cli::Cli;
+21 -9
View File
@@ -73,6 +73,8 @@ pub enum StatementKind {
Branch, Branch,
Loop, Loop,
Return, Return,
Break,
Continue,
Other, Other,
} }
@@ -84,6 +86,8 @@ impl StatementKind {
StatementKind::Branch => "条件分支", StatementKind::Branch => "条件分支",
StatementKind::Loop => "循环", StatementKind::Loop => "循环",
StatementKind::Return => "返回", StatementKind::Return => "返回",
StatementKind::Break => "跳出循环",
StatementKind::Continue => "继续循环",
StatementKind::Other => "语句", StatementKind::Other => "语句",
} }
} }
@@ -95,6 +99,8 @@ impl StatementKind {
StatementKind::Branch => "branch", StatementKind::Branch => "branch",
StatementKind::Loop => "loop", StatementKind::Loop => "loop",
StatementKind::Return => "return", StatementKind::Return => "return",
StatementKind::Break => "break",
StatementKind::Continue => "continue",
StatementKind::Other => "other", StatementKind::Other => "other",
} }
} }
@@ -210,6 +216,7 @@ pub struct ModuleSummary {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct SemanticProjection { pub struct SemanticProjection {
pub schema_version: u32,
pub analysis_sha256: String, pub analysis_sha256: String,
pub analysis_digest: String, pub analysis_digest: String,
pub producer_version: String, pub producer_version: String,
@@ -541,19 +548,18 @@ pub fn verify_analysis(
) -> ViewResult<VerifiedAnalysis> { ) -> ViewResult<VerifiedAnalysis> {
let raw: RawAnalysis = let raw: RawAnalysis =
serde_json::from_slice(analysis_bytes).map_err(|err| ViewError::AnalysisFailed { serde_json::from_slice(analysis_bytes).map_err(|err| ViewError::AnalysisFailed {
detail: format!("Analysis v2 is not valid JSON: {err}"), detail: format!("Analysis is not valid JSON: {err}"),
})?; })?;
if raw.schema != "marqdo.analysis" { if raw.schema != "marqdo.analysis" {
return Err(ViewError::ProtocolIncompatible { return Err(ViewError::ProtocolIncompatible {
detail: format!("unexpected Analysis schema {:?}", raw.schema), detail: format!("unexpected Analysis schema {:?}", raw.schema),
}); });
} }
if raw.schema_version != crate::protocol::tool_v1::ANALYSIS_PROTOCOL { if !crate::protocol::tool_v1::ANALYSIS_PROTOCOLS.contains(&raw.schema_version) {
return Err(ViewError::ProtocolIncompatible { return Err(ViewError::ProtocolIncompatible {
detail: format!( detail: format!(
"Analysis schema_version {} is not supported (View implements v{})", "Analysis schema_version {} is not supported (View implements v2/v3)",
raw.schema_version, raw.schema_version
crate::protocol::tool_v1::ANALYSIS_PROTOCOL
), ),
}); });
} }
@@ -641,7 +647,9 @@ pub fn verify_analysis(
let statements = function let statements = function
.body .body
.iter() .iter()
.filter_map(|statement| convert_statement(statement, &mut valid_span)) .filter_map(|statement| {
convert_statement(statement, raw.schema_version, &mut valid_span)
})
.collect(); .collect();
Some(SemanticFunction { Some(SemanticFunction {
id: function.id.clone(), id: function.id.clone(),
@@ -777,6 +785,7 @@ pub fn verify_analysis(
Ok(VerifiedAnalysis { Ok(VerifiedAnalysis {
projection: SemanticProjection { projection: SemanticProjection {
schema_version: raw.schema_version,
analysis_sha256: sha256_hex(analysis_bytes), analysis_sha256: sha256_hex(analysis_bytes),
analysis_digest: sha256_prefixed(analysis_bytes), analysis_digest: sha256_prefixed(analysis_bytes),
producer_version: raw.producer.version.clone(), producer_version: raw.producer.version.clone(),
@@ -804,6 +813,7 @@ pub fn verify_analysis(
fn convert_statement( fn convert_statement(
raw: &RawStatement, raw: &RawStatement,
schema_version: u32,
valid_span: &mut impl FnMut(Option<SourceSpan>, &str) -> Option<SourceSpan>, valid_span: &mut impl FnMut(Option<SourceSpan>, &str) -> Option<SourceSpan>,
) -> Option<SemanticStatement> { ) -> Option<SemanticStatement> {
let span = valid_span(raw.span, "语句")?; let span = valid_span(raw.span, "语句")?;
@@ -813,12 +823,14 @@ fn convert_statement(
"branch" => StatementKind::Branch, "branch" => StatementKind::Branch,
"loop" => StatementKind::Loop, "loop" => StatementKind::Loop,
"return" => StatementKind::Return, "return" => StatementKind::Return,
"break" if schema_version == 3 => StatementKind::Break,
"continue" if schema_version == 3 => StatementKind::Continue,
_ => StatementKind::Other, _ => StatementKind::Other,
}; };
let body = raw let body = raw
.body .body
.iter() .iter()
.filter_map(|child| convert_statement(child, valid_span)) .filter_map(|child| convert_statement(child, schema_version, valid_span))
.collect(); .collect();
let arms = raw let arms = raw
.arms .arms
@@ -829,7 +841,7 @@ fn convert_statement(
body: arm body: arm
.body .body
.iter() .iter()
.filter_map(|child| convert_statement(child, valid_span)) .filter_map(|child| convert_statement(child, schema_version, valid_span))
.collect(), .collect(),
}) })
.collect(); .collect();
@@ -905,7 +917,7 @@ mod tests {
let index = SourceIndex::new(source); let index = SourceIndex::new(source);
let digest = sha256_hex(source.as_bytes()); let digest = sha256_hex(source.as_bytes());
let err = let err =
verify_analysis(&analysis(3, &digest), source, &index, "index.mq.md").unwrap_err(); verify_analysis(&analysis(4, &digest), source, &index, "index.mq.md").unwrap_err();
assert_eq!(err.code(), "view.protocol_incompatible"); assert_eq!(err.code(), "view.protocol_incompatible");
} }
+355
View File
@@ -0,0 +1,355 @@
//! Decode the CLI's bounded, source-bound NDJSON stream. The browser only
//! receives projections selected by this decoder.
use base64::{engine::general_purpose::STANDARD, Engine};
use serde::Deserialize;
use serde_json::{json, Value};
use std::io::{BufRead, BufReader, Read};
const SCHEMA: &str = "marqdo.execution-events";
const MAX_LINE: usize = 4 * 1024 * 1024;
const MAX_CHUNK: usize = 64 * 1024;
const MAX_TRANSPORT: usize = 16 * 1024 * 1024;
pub struct Binding {
pub digest: String,
pub root: String,
pub entry: String,
pub function: String,
pub mode: String,
pub producer: String,
pub modules: Vec<String>,
pub max_output: usize,
}
#[derive(Default)]
pub struct Stream {
pub id: String,
pub verified: bool,
pub truncated: bool,
pub stdout: Vec<u8>,
pub stderr: Vec<u8>,
pub terminal: Option<Value>,
pub invalid: bool,
}
#[derive(Deserialize)]
struct Event {
schema: String,
schema_version: u32,
run_id: String,
seq: u64,
kind: String,
payload: serde_json::Map<String, Value>,
}
pub fn read(input: impl Read, binding: &Binding, mut publish: impl FnMut(Value)) -> Stream {
let mut input = BufReader::new(input);
let mut stream = Stream::default();
let mut line = Vec::new();
let mut total = 0;
let mut seq = 0;
let mut entry_frame_seen = false;
loop {
line.clear();
let size = match input
.by_ref()
.take(MAX_LINE as u64 + 1)
.read_until(b'\n', &mut line)
{
Ok(0) => break,
Ok(size) => size,
Err(_) => {
stream.invalid = true;
break;
}
};
total += size;
if total > MAX_TRANSPORT || size > MAX_LINE {
stream.invalid = true;
break;
}
if line.last() != Some(&b'\n') {
stream.invalid = true;
break;
}
let Ok(event) = serde_json::from_slice::<Event>(&line) else {
stream.invalid = true;
break;
};
match consume(&mut stream, binding, event, seq, &mut entry_frame_seen) {
Ok(Some(projection)) => publish(projection),
Ok(None) => {}
Err(()) => {
stream.invalid = true;
break;
}
}
seq += 1;
}
if stream.invalid {
// Drain without keeping bytes so a malformed child cannot block on its pipe.
let _ = std::io::copy(&mut input, &mut std::io::sink());
stream.terminal = None;
}
stream
}
fn consume(
stream: &mut Stream,
binding: &Binding,
event: Event,
seq: u64,
entry_frame_seen: &mut bool,
) -> Result<Option<Value>, ()> {
if event.schema != SCHEMA
|| event.schema_version != 1
|| event.seq != seq
|| event.run_id.is_empty()
|| event.run_id.len() > 128
|| stream.terminal.is_some()
{
return Err(());
}
let payload = &event.payload;
let kind = event.kind.as_str();
if seq == 0 {
if kind != "stream.opened"
|| payload.get("protocol") != Some(&json!({"name": SCHEMA, "schema_version": 1}))
|| payload
.get("producer")
.and_then(|value| value["name"].as_str())
!= Some("marqdo")
|| payload
.get("producer")
.and_then(|value| value["version"].as_str())
!= Some(&binding.producer)
|| !payload.get("limits").is_some_and(Value::is_object)
|| !payload.get("observation").is_some_and(Value::is_object)
{
return Err(());
}
stream.id = event.run_id;
return Ok(Some(json!({"seq": seq, "kind": kind})));
}
if stream.id != event.run_id {
return Err(());
}
let mut projection = json!({"seq": seq, "kind": kind});
if seq == 1 {
match kind {
"run.rejected" => {
if text(payload, "status") != Some("rejected") || text(payload, "phase").is_none() {
return Err(());
}
stream.terminal = Some(failure(payload)?);
return Ok(None);
}
"run.started" => {
let source = payload.get("source").ok_or(())?;
if source["analysis_digest"].as_str() != Some(&binding.digest)
|| source["root_id"].as_str() != Some(&binding.root)
|| text(payload, "entry") != Some(&binding.entry)
|| text(payload, "mode") != Some(&binding.mode)
{
return Err(());
}
stream.verified = true;
return Ok(Some(projection));
}
_ => return Err(()),
}
}
match kind {
"stream.opened" | "run.started" | "run.rejected" => return Err(()),
"stdout.chunk" | "stderr.chunk" => {
let data = text(payload, "data_base64").ok_or(())?;
if text(payload, "encoding") != Some("base64") || data.len() > MAX_CHUNK.div_ceil(3) * 4
{
return Err(());
}
let bytes = STANDARD.decode(data).map_err(|_| ())?;
if bytes.len() > MAX_CHUNK
|| payload.get("byte_count").and_then(Value::as_u64) != Some(bytes.len() as u64)
{
return Err(());
}
if stream.stdout.len() + stream.stderr.len() + bytes.len() > binding.max_output {
return Err(());
}
if kind == "stdout.chunk" {
stream.stdout.extend_from_slice(&bytes);
} else {
stream.stderr.extend_from_slice(&bytes);
}
projection["data_base64"] = json!(data);
}
"run.completed" => {
let value = payload
.get("value")
.filter(|value| super::value_wire_v1::valid(value))
.ok_or(())?;
if text(payload, "status") != Some("ok") || (!*entry_frame_seen && !stream.truncated) {
return Err(());
}
stream.terminal = Some(json!({"success": true, "value": value}));
return Ok(None);
}
"run.failed" => {
if text(payload, "status") != Some("error") {
return Err(());
}
stream.terminal = Some(failure(payload)?);
return Ok(None);
}
"observation.truncated" => {
if stream.truncated
|| !matches!(
text(payload, "reason"),
Some("event_budget" | "byte_budget")
)
|| payload.get("limit").and_then(Value::as_u64).is_none()
|| payload.get("written").and_then(Value::as_u64).is_none()
|| !payload
.get("dropped")
.is_some_and(|value| value.is_null() || value.is_u64())
{
return Err(());
}
stream.truncated = true;
}
"call.enter" | "call.exit" | "return" | "branch.eval" | "loop.iteration"
| "control.break" | "control.continue" | "effect" => {
let module = text(payload, "module_id").ok_or(())?;
let span = payload.get("span").ok_or(())?;
let span_ok = span["start"]
.as_u64()
.zip(span["end"].as_u64())
.is_some_and(|(start, end)| start < end);
if !binding.modules.iter().any(|known| known == module)
|| !(span_ok
|| span.is_null() && !matches!(kind, "control.break" | "control.continue"))
|| kind != "effect" && text(payload, "frame_id").is_none()
{
return Err(());
}
match kind {
"call.enter" => {
let function = text(payload, "function_id").ok_or(())?;
match payload.get("parent_frame_id") {
Some(Value::Null) if !*entry_frame_seen && function == binding.function => {
*entry_frame_seen = true
}
Some(Value::String(_)) if *entry_frame_seen => {}
_ => return Err(()),
}
}
"call.exit" if text(payload, "status").is_none() => return Err(()),
"return" if text(payload, "value_type").is_none() => return Err(()),
"branch.eval" => {
projection["decision"] =
json!(payload.get("result").and_then(Value::as_bool).ok_or(())?)
}
"loop.iteration" => {
let decision = text(payload, "decision")
.filter(|decision| matches!(*decision, "continue" | "exit"))
.ok_or(())?;
projection["decision"] = json!(decision);
}
"effect"
if text(payload, "operation").is_none()
|| text(payload, "result_code").is_none() =>
{
return Err(())
}
_ => {}
}
}
// Values and additive kinds are never emitted as browser observations.
_ => return Ok(None),
}
Ok(Some(projection))
}
fn text<'a>(payload: &'a serde_json::Map<String, Value>, key: &str) -> Option<&'a str> {
payload
.get(key)?
.as_str()
.filter(|text| !text.is_empty() && text.len() <= MAX_LINE)
}
fn failure(payload: &serde_json::Map<String, Value>) -> Result<Value, ()> {
let error = payload.get("error").ok_or(())?;
let code = error["code"].as_str().ok_or(())?;
let message = error["message"].as_str().ok_or(())?;
Ok(json!({"success": false, "error": {"code": code, "message": message}}))
}
#[cfg(test)]
mod tests {
use super::*;
fn sample() -> (Binding, Vec<Value>) {
let binding = Binding {
digest: "sha256:expected".into(),
root: "root:p".into(),
entry: "root:p::index.mq.md::main".into(),
function: "root:p::index.mq.md::main".into(),
mode: "pure".into(),
producer: "3.0.0-rc.2".into(),
modules: vec!["root:p::index.mq.md".into()],
max_output: 100,
};
let event = |seq, kind, payload| {
json!({"schema": SCHEMA, "schema_version": 1, "run_id": "r", "seq": seq,
"kind": kind, "payload": payload})
};
let events = vec![
event(
0,
"stream.opened",
json!({"protocol": {"name": SCHEMA, "schema_version": 1},
"producer": {"name": "marqdo", "version": binding.producer}, "limits": {}, "observation": {}}),
),
event(
1,
"run.started",
json!({"entry": binding.entry, "mode": binding.mode,
"source": {"analysis_digest": binding.digest, "root_id": binding.root}}),
),
event(
2,
"stdout.chunk",
json!({"data_base64": "NAo=", "encoding": "base64", "byte_count": 2}),
),
event(
3,
"run.failed",
json!({"status": "error", "error": {"code": "runtime.test", "message": "test"}}),
),
];
(binding, events)
}
fn decode(binding: &Binding, events: &[Value]) -> Stream {
let ndjson = events
.iter()
.map(|value| format!("{value}\n"))
.collect::<String>();
read(ndjson.as_bytes(), binding, |_| {})
}
#[test]
fn validates_stream_identity_bytes_and_terminal_boundary() {
let (binding, mut events) = sample();
let stream = decode(&binding, &events);
assert!(stream.verified && !stream.invalid);
assert_eq!(stream.stdout, b"4\n");
assert!(stream.terminal.is_some());
assert!(decode(&binding, &events[..3]).terminal.is_none());
events[2]["payload"]["byte_count"] = json!(1);
assert!(decode(&binding, &events).invalid);
events[1]["payload"]["source"]["analysis_digest"] = json!("wrong");
assert!(!decode(&binding, &events).verified);
}
}
+2
View File
@@ -4,5 +4,7 @@
//! second publisher or implementation of them (RFC-VIEW-0002 §5.3). //! second publisher or implementation of them (RFC-VIEW-0002 §5.3).
pub mod analysis_v2; pub mod analysis_v2;
pub mod execution_events_v1;
pub mod tool_v1; pub mod tool_v1;
pub mod trace_v2; pub mod trace_v2;
pub mod value_wire_v1;
+10 -2
View File
@@ -15,6 +15,7 @@ pub const MIN_PRODUCT: &str = "3.0.0-beta.1";
pub const TOOL_PROTOCOL: u32 = 1; pub const TOOL_PROTOCOL: u32 = 1;
pub const ANALYSIS_PROTOCOL: u32 = 2; pub const ANALYSIS_PROTOCOL: u32 = 2;
pub const ANALYSIS_PROTOCOLS: [u32; 2] = [2, 3];
pub const TRACE_PROTOCOL: u32 = 2; pub const TRACE_PROTOCOL: u32 = 2;
/// Environment variables injected by CLI Tool Protocol v1. /// Environment variables injected by CLI Tool Protocol v1.
@@ -62,6 +63,12 @@ pub fn product_is_compatible(version: &Version) -> bool {
version.major == 3 && version >= &min version.major == 3 && version >= &min
} }
/// RC.2 is the first public Core release with Execution Events v1.
pub fn supports_execution_events(version: &str) -> bool {
let first = Version::parse("3.0.0-rc.2").expect("valid Core version");
Version::parse(version).is_ok_and(|version| version >= first)
}
/// Validate the negotiated environment for Tool Protocol v1. /// Validate the negotiated environment for Tool Protocol v1.
/// ///
/// Absence of `MARQDO_PROTOCOL_*` is allowed for a directly-run development /// Absence of `MARQDO_PROTOCOL_*` is allowed for a directly-run development
@@ -83,10 +90,10 @@ pub fn negotiate_protocol_env(
} }
if let Some(raw) = analysis_protocol { if let Some(raw) = analysis_protocol {
let value = parse_env_u32(ENV_PROTOCOL_ANALYSIS, raw)?; let value = parse_env_u32(ENV_PROTOCOL_ANALYSIS, raw)?;
if value != ANALYSIS_PROTOCOL { if !ANALYSIS_PROTOCOLS.contains(&value) {
return Err(ViewError::ProtocolIncompatible { return Err(ViewError::ProtocolIncompatible {
detail: format!( detail: format!(
"{ENV_PROTOCOL_ANALYSIS}={value} is not supported (this View requires Analysis v{ANALYSIS_PROTOCOL})" "{ENV_PROTOCOL_ANALYSIS}={value} is not supported (this View implements Analysis v2/v3)"
), ),
}); });
} }
@@ -141,6 +148,7 @@ mod tests {
fn negotiates_known_protocols_only() { fn negotiates_known_protocols_only() {
assert!(negotiate_protocol_env(Some("1"), Some("2"), Some("2")).is_ok()); assert!(negotiate_protocol_env(Some("1"), Some("2"), Some("2")).is_ok());
assert!(negotiate_protocol_env(None, None, None).is_ok()); assert!(negotiate_protocol_env(None, None, None).is_ok());
assert!(negotiate_protocol_env(Some("1"), Some("3"), Some("2")).is_ok());
assert!(negotiate_protocol_env(Some("2"), None, None).is_err()); assert!(negotiate_protocol_env(Some("2"), None, None).is_err());
assert!(negotiate_protocol_env(None, Some("1"), None).is_err()); assert!(negotiate_protocol_env(None, Some("1"), None).is_err());
assert!(negotiate_protocol_env(None, None, Some("3")).is_err()); assert!(negotiate_protocol_env(None, None, Some("3")).is_err());
+83
View File
@@ -0,0 +1,83 @@
//! Validation for the public CLI result encoding. Values stay as inert JSON.
use serde_json::Value;
pub fn valid(value: &Value) -> bool {
valid_at(value, 0)
}
fn valid_at(value: &Value, depth: usize) -> bool {
if depth > 64 {
return false;
}
let child = |item: &Value| valid_at(item, depth + 1);
match value["type"].as_str() {
Some("unit" | "none" | "resource" | "memory") => true,
Some("bool") => value["value"].is_boolean(),
Some("int") => value["decimal"].as_str().is_some_and(|value| {
let digits = value.strip_prefix('-').unwrap_or(value);
!digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit())
}),
Some("float") => match (value.get("value"), value.get("special")) {
(Some(value), None) => value.as_f64().is_some_and(f64::is_finite),
(None, Some(special)) => {
matches!(special.as_str(), Some("nan" | "infinity" | "-infinity"))
}
_ => false,
},
Some("text") => value["value"].is_string(),
Some("list") => value["items"]
.as_array()
.is_some_and(|items| items.iter().all(child)),
Some("map") => value["entries"]
.as_object()
.is_some_and(|entries| entries.values().all(child)),
Some("table") => value["header"].as_array().is_some_and(|header| {
header.iter().all(Value::is_string)
&& value["rows"].as_array().is_some_and(|rows| {
rows.iter().all(|row| {
row.as_array().is_some_and(|cells| {
cells.len() == header.len() && cells.iter().all(child)
})
})
})
}),
Some("formula") => {
value["latex"].is_string() && optional(value, "display", Value::is_boolean)
}
Some("code") => {
value["source"].is_string()
&& optional(value, "language", Value::is_string)
&& optional(value, "content_hash", Value::is_string)
}
Some("function_ref") => value["module"].is_string() && value["name"].is_string(),
Some("plugin_handle") => {
value["plugin"].is_string() && value["export"].is_string() && value["id"].is_u64()
}
_ => false,
}
}
fn optional(value: &Value, name: &str, check: fn(&Value) -> bool) -> bool {
value.get(name).is_none_or(check)
}
/// Archive terminal values that can be represented as data without handle IDs.
pub fn transferable(value: &Value) -> bool {
match value["type"].as_str() {
Some("memory" | "resource" | "plugin_handle" | "function_ref") => false,
Some("list") => value["items"]
.as_array()
.is_some_and(|items| items.iter().all(transferable)),
Some("map") => value["entries"]
.as_object()
.is_some_and(|items| items.values().all(transferable)),
Some("table") => value["rows"].as_array().is_some_and(|rows| {
rows.iter().all(|row| {
row.as_array()
.is_some_and(|values| values.iter().all(transferable))
})
}),
_ => true,
}
}
+13 -2
View File
@@ -70,6 +70,8 @@ pub fn build(input: BuildInput<'_>) -> PresentationModel {
PresentationModel { PresentationModel {
version: PRESENTATION_VERSION, version: PRESENTATION_VERSION,
title: document.title(), title: document.title(),
heading_slugs: super::links::heading_slugs(&document.blocks),
media: Default::default(),
document, document,
semantic, semantic,
source_status: status, source_status: status,
@@ -313,7 +315,8 @@ impl DocumentService {
(None, _) => None, (None, _) => None,
}; };
Ok(build(BuildInput { let media = super::media::collect(&self.project, relative, &document.blocks);
let mut model = build(BuildInput {
document, document,
analysis: verified.as_ref(), analysis: verified.as_ref(),
status, status,
@@ -322,7 +325,9 @@ impl DocumentService {
navigation, navigation,
core_version: self.core_version.clone(), core_version: self.core_version.clone(),
run: attached_run.as_ref(), run: attached_run.as_ref(),
})) });
model.media = media;
Ok(model)
} }
} }
@@ -377,6 +382,7 @@ pub struct StaticDocument {
pub source_sha256: String, pub source_sha256: String,
/// Exact bytes written by `marqdo check --emit`. /// Exact bytes written by `marqdo check --emit`.
pub analysis_bytes: Vec<u8>, pub analysis_bytes: Vec<u8>,
pub media_digests: std::collections::BTreeMap<String, String>,
pub analysis_digest: String, pub analysis_digest: String,
pub verified: crate::protocol::analysis_v2::VerifiedAnalysis, pub verified: crate::protocol::analysis_v2::VerifiedAnalysis,
} }
@@ -438,6 +444,10 @@ impl DocumentService {
&source_index, &source_index,
relative.as_str(), relative.as_str(),
)?; )?;
let document =
DocumentModel::parse(source.clone(), DocumentIdentity::placeholder(relative));
let media = super::media::collect(&self.project, relative, &document.blocks);
let media_digests = super::media::digests(&media);
Ok(StaticDocument { Ok(StaticDocument {
relative: relative.clone(), relative: relative.clone(),
source, source,
@@ -445,6 +455,7 @@ impl DocumentService {
source_sha256, source_sha256,
analysis_digest: check.analysis_digest, analysis_digest: check.analysis_digest,
analysis_bytes: check.analysis_bytes, analysis_bytes: check.analysis_bytes,
media_digests,
verified, verified,
}) })
} }
+14 -1
View File
@@ -71,6 +71,18 @@ impl AssetBundle {
"image/webp", "image/webp",
include_bytes!("../../assets/feather.webp"), include_bytes!("../../assets/feather.webp"),
), ),
asset(
"noto-math",
"ttf",
"font/ttf",
include_bytes!("../../assets/NotoSansMath-Regular.ttf"),
),
asset(
"noto-math-license",
"txt",
"text/plain; charset=utf-8",
include_bytes!("../../assets/licenses/NOTO-MATH-LICENSE.txt"),
),
]; ];
let mut by_hashed_name = HashMap::new(); let mut by_hashed_name = HashMap::new();
for (index, asset) in assets.iter().enumerate() { for (index, asset) in assets.iter().enumerate() {
@@ -79,7 +91,8 @@ impl AssetBundle {
let css_text = std::str::from_utf8(assets[0].bytes).expect("reader.css is UTF-8"); let css_text = std::str::from_utf8(assets[0].bytes).expect("reader.css is UTF-8");
let css_with_images = css_text let css_with_images = css_text
.replace("__BLOSSOM__", &assets[3].data_uri()) .replace("__BLOSSOM__", &assets[3].data_uri())
.replace("__FEATHER__", &assets[4].data_uri()); .replace("__FEATHER__", &assets[4].data_uri())
.replace("__MATH_FONT__", &assets[5].hashed_name());
let css_served_sha256 = sha256_hex(css_with_images.as_bytes()); let css_served_sha256 = sha256_hex(css_with_images.as_bytes());
Self { Self {
assets, assets,
+100
View File
@@ -0,0 +1,100 @@
//! Markdown navigation and URL normalization shared by Live and export.
use crate::reader::markdown::{DocBlock, Inline};
use crate::reader::source::{SafeRelativePath, SourceSpan};
use std::collections::{HashMap, HashSet};
pub fn decode(raw: &str) -> Option<String> {
let mut result = Vec::with_capacity(raw.len());
let mut bytes = raw.bytes();
while let Some(byte) = bytes.next() {
if byte == b'%' {
let hi = (bytes.next()? as char).to_digit(16)?;
let lo = (bytes.next()? as char).to_digit(16)?;
result.push((hi * 16 + lo) as u8);
} else {
result.push(byte);
}
}
String::from_utf8(result)
.ok()
.filter(|value| !value.chars().any(char::is_control))
}
pub fn relative_url(current: &SafeRelativePath, url: &str) -> Option<SafeRelativePath> {
let relative = decode(url)?;
if relative.is_empty() || relative.starts_with('/') || relative.contains(['\\', ':']) {
return None;
}
let parent = current.parent();
let mut components = parent
.as_ref()
.map_or_else(Vec::new, |parent| parent.as_str().split('/').collect());
for part in relative.split('/') {
match part {
"" | "." => {}
".." => {
components.pop()?;
}
_ => components.push(part),
}
}
SafeRelativePath::parse(&components.join("/")).ok()
}
pub fn heading_slugs(blocks: &[DocBlock]) -> HashMap<SourceSpan, String> {
let mut slugs = HashMap::new();
let mut used = HashSet::new();
visit_headings(blocks, &mut |span, content| {
let label = content.iter().map(Inline::plain_text).collect::<String>();
let label = ["@exec", "@knowledge"]
.into_iter()
.find_map(|prefix| {
label
.strip_prefix(prefix)
.filter(|suffix| suffix.starts_with(char::is_whitespace))
})
.unwrap_or(&label)
.trim();
let base: String = label
.to_lowercase()
.chars()
.filter_map(|ch| {
if ch.is_whitespace() {
Some('-')
} else if ch.is_alphanumeric() || matches!(ch, '-' | '_') {
Some(ch)
} else {
None
}
})
.collect();
let base = if base.is_empty() { "section" } else { &base };
let base = if base.starts_with("mq-") {
format!("section-{base}")
} else {
base.to_string()
};
let mut slug = base.clone();
let mut suffix = 1;
while !used.insert(slug.clone()) {
slug = format!("{base}-{suffix}");
suffix += 1;
}
slugs.insert(span, slug);
});
slugs
}
fn visit_headings(blocks: &[DocBlock], visit: &mut impl FnMut(SourceSpan, &[Inline])) {
for block in blocks {
match block {
DocBlock::Heading { span, content, .. } => visit(*span, content),
DocBlock::List { items, .. } => visit_headings(items, visit),
DocBlock::ListItem { children, .. } | DocBlock::BlockQuote { children, .. } => {
visit_headings(children, visit)
}
_ => {}
}
}
}
+124
View File
@@ -0,0 +1,124 @@
//! Bounded TeX math to inert MathML, shared by all rendering modes.
use pulldown_latex::{config::DisplayMode, push_mathml, Parser, RenderConfig, Storage};
pub fn render(source: &str, block: bool) -> Option<String> {
if source.len() > 4096
|| source.chars().filter(|ch| *ch == '{').count() > 128
|| source.split('\\').skip(1).any(|rest| {
let end = rest
.find(|ch: char| !ch.is_ascii_alphabetic())
.unwrap_or(rest.len());
matches!(
&rest[..end],
"def"
| "gdef"
| "edef"
| "xdef"
| "newcommand"
| "renewcommand"
| "providecommand"
| "let"
| "futurelet"
| "csname"
| "input"
| "include"
| "href"
| "url"
| "includegraphics"
| "htmlClass"
| "htmlStyle"
| "htmlId"
)
})
{
return None;
}
let storage = Storage::new();
let config = RenderConfig {
display_mode: if block {
DisplayMode::Block
} else {
DisplayMode::Inline
},
..Default::default()
};
let mut html = String::new();
let mut parsed = true;
let parser = Parser::new(source, &storage).inspect(|event| parsed &= event.is_ok());
push_mathml(&mut html, parser, config).ok()?;
if !parsed || html.len() > 64 * 1024 {
return None;
}
let xml = roxmltree::Document::parse(&html).ok()?;
if xml.root_element().tag_name().name() != "math" {
return None;
}
let safe = xml
.descendants()
.filter(roxmltree::Node::is_element)
.all(|node| {
matches!(
node.tag_name().name(),
"math"
| "mrow"
| "mi"
| "mo"
| "mn"
| "mtext"
| "mfrac"
| "msqrt"
| "mroot"
| "msub"
| "msup"
| "msubsup"
| "munder"
| "mover"
| "munderover"
| "mtable"
| "mtr"
| "mtd"
| "mspace"
| "mpadded"
| "mstyle"
| "menclose"
| "mphantom"
| "mmultiscripts"
| "mprescripts"
| "none"
) && node.attributes().all(|attr| {
attr.namespace().is_none()
&& matches!(
attr.name(),
"display"
| "mathvariant"
| "mathsize"
| "mathcolor"
| "displaystyle"
| "scriptlevel"
| "stretchy"
| "symmetric"
| "movablelimits"
| "form"
| "fence"
| "separator"
| "lspace"
| "rspace"
| "minsize"
| "maxsize"
| "accent"
| "accentunder"
| "linethickness"
| "width"
| "height"
| "depth"
| "columnalign"
| "rowalign"
| "rowspacing"
| "columnspacing"
| "notation"
)
})
});
safe.then_some(html)
}
+309
View File
@@ -0,0 +1,309 @@
//! Bounded project-local assets used by the reader and static export.
use crate::reader::links::relative_url;
use crate::reader::markdown::{DocBlock, Inline};
use crate::reader::source::{sha256_hex, Project, SafeRelativePath};
use image::{ImageFormat, ImageReader};
use std::collections::{BTreeMap, BTreeSet};
use std::fs::File;
use std::io::{Cursor, Read};
use std::sync::Arc;
const MAX_BYTES: usize = 4 * 1024 * 1024;
const MAX_DOCUMENT_BYTES: usize = 16 * 1024 * 1024;
const MAX_REFERENCES: usize = 128;
const MAX_AXIS: u32 = 8192;
const MAX_PIXELS: u64 = 16_000_000;
#[derive(Debug)]
pub struct Media {
pub path: SafeRelativePath,
pub bytes: Vec<u8>,
pub digest: String,
pub mime: &'static str,
pub extension: &'static str,
pub width: u32,
pub height: u32,
}
impl Media {
pub fn filename(&self) -> String {
format!("{}.{}", self.digest, self.extension)
}
}
pub fn collect(
project: &Project,
current: &SafeRelativePath,
blocks: &[DocBlock],
) -> BTreeMap<String, Arc<Media>> {
let mut urls = BTreeSet::new();
scan_blocks(blocks, &mut urls);
let mut total = 0;
let mut resolved = BTreeMap::<SafeRelativePath, Arc<Media>>::new();
let mut result = BTreeMap::new();
for url in urls {
let Some(path) = relative_url(current, url) else {
continue;
};
if let Some(media) = resolved.get(&path) {
result.insert(url.to_string(), Arc::clone(media));
continue;
}
if let Some(media) = load(project, &path) {
total += media.bytes.len();
if total > MAX_DOCUMENT_BYTES {
break;
}
let media = Arc::new(media);
resolved.insert(path, Arc::clone(&media));
result.insert(url.to_string(), media);
}
}
result
}
pub fn digests(media: &BTreeMap<String, Arc<Media>>) -> BTreeMap<String, String> {
media
.values()
.map(|item| (item.path.to_string(), item.digest.clone()))
.collect()
}
fn scan_blocks<'a>(blocks: &'a [DocBlock], urls: &mut BTreeSet<&'a str>) {
for block in blocks {
match block {
DocBlock::Heading { content, .. } | DocBlock::Paragraph { content, .. } => {
scan_inlines(content, urls)
}
DocBlock::List { items, .. } => scan_blocks(items, urls),
DocBlock::ListItem { children, .. } | DocBlock::BlockQuote { children, .. } => {
scan_blocks(children, urls)
}
DocBlock::Table { header, rows, .. } => {
for cell in header.iter().chain(rows.iter().flatten()) {
scan_inlines(cell, urls);
}
}
_ => {}
}
}
}
fn scan_inlines<'a>(inlines: &'a [Inline], urls: &mut BTreeSet<&'a str>) {
for inline in inlines {
if urls.len() >= MAX_REFERENCES {
return;
}
match inline {
Inline::Image { url, .. } => {
urls.insert(url);
}
Inline::Emph { children, .. }
| Inline::Strong { children, .. }
| Inline::Strikethrough { children, .. }
| Inline::Link { children, .. } => scan_inlines(children, urls),
_ => {}
}
}
}
pub fn load(project: &Project, path: &SafeRelativePath) -> Option<Media> {
let extension = path.file_name().rsplit_once('.')?.1.to_ascii_lowercase();
let (mime, extension, format) = match extension.as_str() {
"png" => ("image/png", "png", Some(ImageFormat::Png)),
"jpeg" | "jpg" => ("image/jpeg", "jpg", Some(ImageFormat::Jpeg)),
"gif" => ("image/gif", "gif", Some(ImageFormat::Gif)),
"webp" => ("image/webp", "webp", Some(ImageFormat::WebP)),
"svg" => ("image/svg+xml", "svg", None),
_ => return None,
};
let file = open_beneath(project, path)?;
let metadata = file.metadata().ok()?;
if !metadata.is_file() || metadata.len() > MAX_BYTES as u64 {
return None;
}
let mut bytes = Vec::with_capacity(metadata.len() as usize);
file.take(MAX_BYTES as u64 + 1)
.read_to_end(&mut bytes)
.ok()?;
if bytes.len() > MAX_BYTES {
return None;
}
let (width, height) = if let Some(format) = format {
if image::guess_format(&bytes).ok()? != format {
return None;
}
let dimensions = ImageReader::with_format(Cursor::new(&bytes), format)
.into_dimensions()
.ok()?;
if !valid_dimensions(dimensions.0, dimensions.1) {
return None;
}
let mut decoder = ImageReader::with_format(Cursor::new(&bytes), format);
let mut limits = image::Limits::default();
limits.max_image_width = Some(MAX_AXIS);
limits.max_image_height = Some(MAX_AXIS);
limits.max_alloc = Some(128 * 1024 * 1024);
decoder.limits(limits);
decoder.decode().ok()?;
dimensions
} else {
svg_dimensions(&bytes)?
};
if !valid_dimensions(width, height) {
return None;
}
Some(Media {
path: path.clone(),
digest: sha256_hex(&bytes),
bytes,
mime,
extension,
width,
height,
})
}
fn valid_dimensions(width: u32, height: u32) -> bool {
width > 0
&& height > 0
&& width <= MAX_AXIS
&& height <= MAX_AXIS
&& u64::from(width) * u64::from(height) <= MAX_PIXELS
}
#[cfg(target_os = "linux")]
fn open_beneath(project: &Project, path: &SafeRelativePath) -> Option<File> {
use std::os::fd::{AsRawFd, FromRawFd};
let root = project.root_handle();
let name = std::ffi::CString::new(path.as_str()).ok()?;
// SAFETY: open_how is a C struct of integer fields.
let mut how: libc::open_how = unsafe { std::mem::zeroed() };
how.flags = (libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NONBLOCK) as u64;
how.resolve = libc::RESOLVE_BENEATH | libc::RESOLVE_NO_MAGICLINKS;
// SAFETY: the descriptor and both pointers stay valid for openat2.
let fd = unsafe {
libc::syscall(
libc::SYS_openat2,
root.as_raw_fd(),
name.as_ptr(),
&how as *const libc::open_how,
std::mem::size_of_val(&how),
)
};
if fd < 0 {
return None;
}
// SAFETY: openat2 returned a new owned descriptor.
Some(unsafe { File::from_raw_fd(fd as std::os::fd::RawFd) })
}
#[cfg(not(target_os = "linux"))]
fn open_beneath(_project: &Project, _path: &SafeRelativePath) -> Option<File> {
None
}
fn svg_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
const SVG: &str = "http://www.w3.org/2000/svg";
let xml = std::str::from_utf8(bytes).ok()?;
let options = roxmltree::ParsingOptions {
nodes_limit: 10_000,
..Default::default()
};
let tree = roxmltree::Document::parse_with_options(xml, options).ok()?;
if tree.descendants().any(|node| node.is_pi()) {
return None;
}
let root = tree.root_element();
if !root.has_tag_name((SVG, "svg")) {
return None;
}
for node in tree.descendants().filter(roxmltree::Node::is_element) {
if node.tag_name().namespace() != Some(SVG)
|| !matches!(
node.tag_name().name(),
"svg"
| "g"
| "path"
| "rect"
| "circle"
| "ellipse"
| "line"
| "polyline"
| "polygon"
| "text"
| "tspan"
| "title"
| "desc"
)
{
return None;
}
for attr in node.attributes() {
if attr.namespace().is_some()
|| !matches!(
attr.name(),
"width"
| "height"
| "viewBox"
| "preserveAspectRatio"
| "x"
| "y"
| "x1"
| "x2"
| "y1"
| "y2"
| "rx"
| "ry"
| "r"
| "cx"
| "cy"
| "d"
| "points"
| "transform"
| "fill"
| "fill-rule"
| "fill-opacity"
| "stroke"
| "stroke-width"
| "stroke-opacity"
| "stroke-linecap"
| "stroke-linejoin"
| "stroke-dasharray"
| "opacity"
| "font-size"
| "text-anchor"
| "dominant-baseline"
)
|| (matches!(attr.name(), "fill" | "stroke")
&& !attr
.value()
.chars()
.all(|ch| ch.is_ascii_alphanumeric() || ch == '#'))
{
return None;
}
}
}
let dimension = |key| {
root.attribute(key)?
.trim_end_matches("px")
.parse::<u32>()
.ok()
};
if let (Some(width), Some(height)) = (dimension("width"), dimension("height")) {
return Some((width, height));
}
let viewbox: Vec<f64> = root
.attribute("viewBox")?
.split(|ch: char| ch.is_whitespace() || ch == ',')
.filter(|part| !part.is_empty())
.map(str::parse)
.collect::<Result<_, _>>()
.ok()?;
if viewbox.len() != 4 || !viewbox.iter().all(|value| value.is_finite()) {
return None;
}
Some((viewbox[2].ceil() as u32, viewbox[3].ceil() as u32))
}
+4
View File
@@ -6,7 +6,11 @@
pub mod assemble; pub mod assemble;
pub mod assets; pub mod assets;
pub mod links;
pub mod markdown; pub mod markdown;
pub mod math;
pub mod media;
pub mod model; pub mod model;
pub mod render; pub mod render;
pub mod snapshot;
pub mod source; pub mod source;
+2
View File
@@ -91,6 +91,8 @@ pub struct PresentationModel {
pub version: u32, pub version: u32,
pub title: String, pub title: String,
pub document: DocumentModel, pub document: DocumentModel,
pub heading_slugs: std::collections::HashMap<crate::reader::source::SourceSpan, String>,
pub media: std::collections::BTreeMap<String, std::sync::Arc<super::media::Media>>,
pub semantic: Option<SemanticProjection>, pub semantic: Option<SemanticProjection>,
pub source_status: SourceStatus, pub source_status: SourceStatus,
/// Human-readable reason for a degraded status (already normalized: no /// Human-readable reason for a degraded status (already normalized: no
+306 -103
View File
@@ -41,7 +41,23 @@ impl LinkPolicy {
for _ in 0..*page_depth { for _ in 0..*page_depth {
prefix.push_str("../"); prefix.push_str("../");
} }
format!("{prefix}pages/{}.html", target.as_str()) format!(
"{prefix}pages/{}.html",
percent_encode_path(target.as_str())
)
}
}
}
fn media_href(&self, media: &super::media::Media) -> String {
match self {
LinkPolicy::LocalServer => format!(
"/media/{}?path={}",
media.filename(),
percent_encode_path(media.path.as_str())
),
LinkPolicy::StaticRelative { page_depth } => {
format!("{}media/{}", "../".repeat(*page_depth), media.filename())
} }
} }
} }
@@ -61,7 +77,7 @@ impl LinkPolicy {
} }
/// Everything the renderer needs beyond the model. /// Everything the renderer needs beyond the model.
#[derive(Debug, Clone)] #[derive(Clone)]
pub struct RenderContext { pub struct RenderContext {
pub links: LinkPolicy, pub links: LinkPolicy,
pub live: bool, pub live: bool,
@@ -75,6 +91,8 @@ pub struct RenderContext {
pub run_timeout_secs: u64, pub run_timeout_secs: u64,
/// Whether a frozen Core was negotiated (an explicit run form can exist). /// Whether a frozen Core was negotiated (an explicit run form can exist).
pub core_available: bool, pub core_available: bool,
pub snapshot_package: bool,
pub overlay: Option<std::sync::Arc<super::snapshot::ExportResultOverlay>>,
} }
impl RenderContext { impl RenderContext {
@@ -87,6 +105,8 @@ impl RenderContext {
annotations: true, annotations: true,
run_timeout_secs: 30, run_timeout_secs: 30,
core_available: false, core_available: false,
snapshot_package: false,
overlay: None,
} }
} }
@@ -99,6 +119,8 @@ impl RenderContext {
annotations: true, annotations: true,
run_timeout_secs: 0, run_timeout_secs: 0,
core_available: false, core_available: false,
snapshot_package: false,
overlay: None,
} }
} }
@@ -137,12 +159,14 @@ impl ReaderRenderer {
let logo_uri = self.assets.logo().data_uri(); let logo_uri = self.assets.logo().data_uri();
let navigation = &model.navigation; let navigation = &model.navigation;
let document_href = format!( let script = if ctx.snapshot_package {
"{prefix}reader.{hash}.css", String::new()
prefix = asset_prefix, } else {
hash = &self.assets.css_served_sha256()[..16] format!(
); "<script defer src=\"{}\"></script>",
let _ = document_href; escape_attr(&format!("{asset_prefix}{js_name}"))
)
};
let mut html = String::with_capacity(16 * 1024 + model.document.source.len()); let mut html = String::with_capacity(16 * 1024 + model.document.source.len());
let relative_path = model.document.identity.relative_path.clone(); let relative_path = model.document.identity.relative_path.clone();
let analysis_digest = model let analysis_digest = model
@@ -169,24 +193,27 @@ impl ReaderRenderer {
<title>{title}</title> <title>{title}</title>
<link rel="icon" type="image/svg+xml" href="{logo}"/> <link rel="icon" type="image/svg+xml" href="{logo}"/>
<link rel="stylesheet" href="{css}"/> <link rel="stylesheet" href="{css}"/>
<script defer src="{js}"></script> {script}
</head> </head>
<body class="mq-reader" data-mode="document" data-theme="light" data-annotations="{annotations}" data-size="normal" data-source-status="{status}" data-run-state="{run_state}" data-run-available="{run_available}" data-has-main="{has_main}" data-core-available="{core_available}" data-document="{document}" data-analysis-digest="{analysis_digest}" data-run-timeout="{run_timeout}" data-live="{live}"> <body class="mq-reader" data-mode="document" data-theme="light" data-annotations="{annotations}" data-size="normal" data-source-status="{status}" data-run-state="{run_state}" data-run-available="{run_available}" data-has-main="{has_main}" data-core-available="{core_available}" data-execution-events="{execution_events}" data-document="{document}" data-analysis-digest="{analysis_digest}" data-run-timeout="{run_timeout}" data-live="{live}">
<a class="mq-skip" href="#mq-main">跳到正文</a> <a class="mq-skip" href="#mq-main">跳到正文</a>
"##, "##,
presentation_version = model.version, presentation_version = model.version,
view_version = env!("CARGO_PKG_VERSION"), view_version = env!("CARGO_PKG_VERSION"),
csp = csp_policy(), csp = csp_policy(ctx.snapshot_package),
title = escape_text(&page_title), title = escape_text(&page_title),
logo = escape_attr(&logo_uri), logo = escape_attr(&logo_uri),
css = escape_attr(&format!("{asset_prefix}{css_name}")), css = escape_attr(&format!("{asset_prefix}{css_name}")),
js = escape_attr(&format!("{asset_prefix}{js_name}")),
status = model.source_status.data_value(), status = model.source_status.data_value(),
annotations = if ctx.annotations { "on" } else { "off" }, annotations = if ctx.annotations { "on" } else { "off" },
run_state = model.run_state().data_value(), run_state = model.run_state().data_value(),
run_available = if ctx.run_available { "true" } else { "false" }, run_available = if ctx.run_available { "true" } else { "false" },
has_main = if has_main { "true" } else { "false" }, has_main = if has_main { "true" } else { "false" },
core_available = if ctx.core_available { "true" } else { "false" }, core_available = if ctx.core_available { "true" } else { "false" },
execution_events = model
.core_version
.as_deref()
.is_some_and(crate::protocol::tool_v1::supports_execution_events),
document = escape_attr(&relative_path), document = escape_attr(&relative_path),
analysis_digest = escape_attr(&analysis_digest), analysis_digest = escape_attr(&analysis_digest),
run_timeout = ctx.run_timeout_secs, run_timeout = ctx.run_timeout_secs,
@@ -200,7 +227,14 @@ impl ReaderRenderer {
if navigation.welcome { if navigation.welcome {
self.render_welcome(&mut html, navigation); self.render_welcome(&mut html, navigation);
} }
self.render_document_meta(&mut html, model); self.render_document_meta(&mut html, model, ctx.overlay.is_some());
if ctx.overlay.is_some() {
let prefix = match ctx.links {
LinkPolicy::StaticRelative { page_depth } => "../".repeat(page_depth),
LinkPolicy::LocalServer => String::new(),
};
let _ = write!(html, "<p class=\"mq-snapshot-notice\">此文档包含一次执行快照。来源摘要见 <a href=\"{prefix}manifest.json\">manifest.json</a>。</p>");
}
self.render_diagnostics(&mut html, model); self.render_diagnostics(&mut html, model);
self.render_functions(&mut html, model, ctx); self.render_functions(&mut html, model, ctx);
self.render_document(&mut html, model, ctx); self.render_document(&mut html, model, ctx);
@@ -209,18 +243,30 @@ impl ReaderRenderer {
} else { } else {
self.render_run_panel(&mut html, model, ctx); self.render_run_panel(&mut html, model, ctx);
} }
self.render_source_pane(&mut html, model, ctx); if ctx.snapshot_package {
let _ = write!(html, "<details class=\"mq-static-source\"><summary>原始源码</summary><pre>{}</pre></details>",
escape_text(&model.document.source));
html.push_str(&self.render_file_list(model, ctx));
} else {
self.render_source_pane(&mut html, model, ctx);
}
self.render_footer(&mut html, model); self.render_footer(&mut html, model);
let _ = write!(html, "</main>\n"); let _ = write!(html, "</main>\n");
self.render_dock(&mut html, ctx); if !ctx.snapshot_package {
self.render_toast(&mut html); self.render_dock(&mut html, ctx);
self.render_dialogs(&mut html, model, ctx); self.render_toast(&mut html);
self.render_dialogs(&mut html, model, ctx);
}
html.push_str("</body>\n</html>\n"); html.push_str("</body>\n</html>\n");
RenderedPage { RenderedPage {
html, html,
assets_used: vec![css_name, js_name], assets_used: if ctx.snapshot_package {
vec![css_name]
} else {
vec![css_name, js_name]
},
} }
} }
@@ -231,6 +277,11 @@ impl ReaderRenderer {
ctx: &RenderContext, ctx: &RenderContext,
navigation: &crate::reader::model::Navigation, navigation: &crate::reader::model::Navigation,
) { ) {
if ctx.snapshot_package {
let _ = write!(html, "<header class=\"mq-topbar mq-snapshot-topbar\"><a class=\"mq-brand\" href=\"#mq-main\"><img class=\"mq-brand-logo\" src=\"{}\" width=\"44\" height=\"44\" alt=\"\"><span class=\"mq-brand-word\">{}</span></a></header>",
escape_attr(&self.assets.logo().data_uri()), escape_text(&navigation.site_title));
return;
}
let active = model let active = model
.navigation .navigation
.active .active
@@ -259,6 +310,7 @@ impl ReaderRenderer {
</header> </header>
<nav class="mq-tabs" aria-label="阅读导航"> <nav class="mq-tabs" aria-label="阅读导航">
<button type="button" class="mq-tab" data-action="mode-document" aria-current="page">文档</button> <button type="button" class="mq-tab" data-action="mode-document" aria-current="page">文档</button>
<button type="button" class="mq-tab" data-action="mode-source">源码</button>
<button type="button" class="mq-tab" data-action="functions">函数</button> <button type="button" class="mq-tab" data-action="functions">函数</button>
{run_tab} {run_tab}
</nav> </nav>
@@ -291,7 +343,12 @@ impl ReaderRenderer {
); );
} }
fn render_document_meta(&self, html: &mut String, model: &PresentationModel) { fn render_document_meta(
&self,
html: &mut String,
model: &PresentationModel,
has_snapshot: bool,
) {
let status = model.source_status; let status = model.source_status;
let _ = write!( let _ = write!(
html, html,
@@ -301,7 +358,11 @@ impl ReaderRenderer {
"##, "##,
file = escape_text(&model.document.identity.relative_path), file = escape_text(&model.document.identity.relative_path),
status_value = status.data_value(), status_value = status.data_value(),
label = escape_text(status.label()), label = if has_snapshot {
"静态文档 · 含执行快照".into()
} else {
escape_text(status.label())
},
); );
if let Some(run) = &model.run { if let Some(run) = &model.run {
let _ = write!( let _ = write!(
@@ -404,17 +465,10 @@ impl ReaderRenderer {
== entry.anchor == entry.anchor
}) })
}); });
let (function_id, params, callable) = match function { let call_button = if ctx.live && ctx.core_available {
Some(function) => (function.id.clone(), function_params_json(function), true), function
None => (String::new(), "[]".to_string(), false), .map(|function| function_call_button(function, &entry.label))
}; .unwrap_or_default()
let call_button = if callable && ctx.core_available {
format!(
"<button type=\"button\" class=\"mq-fn-call\" data-action=\"call-function\" data-function-id=\"{id}\" data-function-label=\"{label}\" data-params=\"{params}\">调用</button>",
id = escape_attr(&function_id),
label = escape_attr(&entry.label),
params = escape_attr(&params)
)
} else { } else {
String::new() String::new()
}; };
@@ -435,14 +489,30 @@ impl ReaderRenderer {
let current = SafeRelativePath::parse(&model.document.identity.relative_path).ok(); let current = SafeRelativePath::parse(&model.document.identity.relative_path).ok();
match &current { match &current {
Some(current) => { Some(current) => {
render_blocks( let mut section = None;
html, let place_result = |html: &mut String, function: &crate::protocol::analysis_v2::SemanticFunction| {
&model.document.blocks, if ctx.live {
model, let _ = write!(html, "<div class=\"mq-result-slot\" data-result-for=\"{}\"></div>", escape_attr(&function.id));
ctx, }
current, if let Some(overlay) = ctx.overlay.as_deref().filter(|overlay| overlay.execution.target == function.id) {
self.assets, render_snapshot(html, overlay);
); }
};
for block in &model.document.blocks {
if let DocBlock::Heading {
level: 1 | 2, span, ..
} = block
{
if let Some(function) = section.take() {
place_result(html, function);
}
section = function_at(model, *span);
}
render_block(html, block, model, ctx, current, self.assets);
}
if let Some(function) = section {
place_result(html, function);
}
} }
None => { None => {
let _ = write!( let _ = write!(
@@ -506,8 +576,8 @@ impl ReaderRenderer {
/// exists until the user explicitly submits one (RFC-VIEW-0002 §7.1). /// exists until the user explicitly submits one (RFC-VIEW-0002 §7.1).
fn render_live_run_shell(&self, html: &mut String, _ctx: &RenderContext) { fn render_live_run_shell(&self, html: &mut String, _ctx: &RenderContext) {
html.push_str( html.push_str(
r##"<section class="mq-run-panel" id="mq-run-panel" data-run-state="idle" aria-labelledby="mq-run-title" hidden> r##"<details class="mq-run-panel" id="mq-run-panel" data-run-state="idle" aria-labelledby="mq-run-title" open hidden>
<h2 id="mq-run-title">本次运行</h2> <summary id="mq-run-title">本次执行</summary>
<p id="mq-run-status" class="mq-run-status" role="status" aria-live="polite">尚未运行。点击 Dock 的“运行”执行 main,或在函数面板选择函数。</p> <p id="mq-run-status" class="mq-run-status" role="status" aria-live="polite">尚未运行。点击 Dock 的“运行”执行 main,或在函数面板选择函数。</p>
<div id="mq-run-actions" class="mq-run-actions" hidden> <div id="mq-run-actions" class="mq-run-actions" hidden>
<button type="button" class="mq-secondary" data-action="cancel-run">取消运行</button> <button type="button" class="mq-secondary" data-action="cancel-run">取消运行</button>
@@ -516,11 +586,11 @@ impl ReaderRenderer {
<pre id="mq-run-stdout" class="mq-stdout" aria-label="程序标准输出" hidden></pre> <pre id="mq-run-stdout" class="mq-stdout" aria-label="程序标准输出" hidden></pre>
<pre id="mq-run-stderr" class="mq-stdout mq-stderr" aria-label="程序标准错误" hidden></pre> <pre id="mq-run-stderr" class="mq-stdout mq-stderr" aria-label="程序标准错误" hidden></pre>
<details id="mq-run-trace-wrap" class="mq-run-events-wrap" hidden> <details id="mq-run-trace-wrap" class="mq-run-events-wrap" hidden>
<summary>真实 Trace v2 事件</summary> <summary id="mq-run-trace-title">实时结构事件</summary>
<ol id="mq-run-events" class="mq-run-events"></ol> <ol id="mq-run-events" class="mq-run-events"></ol>
</details> </details>
<p id="mq-run-note" class="mq-colophon">结果只来自本次显式运行的 CLI --json 与经摘要校验的 Trace v2;不提供参数实际值、逐语句变量或内存快照。</p> <button type="button" class="mq-fn-call mq-export-result" data-action="export-result" id="mq-export-result" hidden>导出文档(含本次结果)</button>
</section> </details>
"##, "##,
); );
} }
@@ -603,7 +673,7 @@ impl ReaderRenderer {
<ul class="mq-menu-list"> <ul class="mq-menu-list">
<li><button type="button" data-action="mode-document">文档态 <span class="mq-menu-hint">原始 Markdown 阅读</span></button></li> <li><button type="button" data-action="mode-document">文档态 <span class="mq-menu-hint">原始 Markdown 阅读</span></button></li>
<li><button type="button" data-action="mode-source">源码态 <span class="mq-menu-hint">逐行原文,含标记</span></button></li> <li><button type="button" data-action="mode-source">源码态 <span class="mq-menu-hint">逐行原文,含标记</span></button></li>
<li><button type="button" data-action="functions">函数大纲 <span class="mq-menu-hint">来自 Analysis v2</span></button></li> <li><button type="button" data-action="functions">函数大纲 <span class="mq-menu-hint">来自 Analysis v2/v3</span></button></li>
<li><button type="button" data-action="unsupported">未提供的能力 <span class="mq-menu-hint">变量 / 内存 / 调试 / 证明</span></button></li> <li><button type="button" data-action="unsupported">未提供的能力 <span class="mq-menu-hint">变量 / 内存 / 调试 / 证明</span></button></li>
<li><button type="button" data-action="print">打印 <span class="mq-menu-hint">隐藏交互与装饰</span></button></li> <li><button type="button" data-action="print">打印 <span class="mq-menu-hint">隐藏交互与装饰</span></button></li>
<li><button type="button" data-action="about">关于 Marqdo View <span class="mq-menu-hint">版本与协议</span></button></li> <li><button type="button" data-action="about">关于 Marqdo View <span class="mq-menu-hint">版本与协议</span></button></li>
@@ -619,14 +689,20 @@ impl ReaderRenderer {
<div id="mq-unsupported-body"></div> <div id="mq-unsupported-body"></div>
</dialog> </dialog>
{run_dialog} {run_dialog}
{export_dialog}
<dialog class="mq-dialog" id="mq-dialog-about" aria-labelledby="mq-about-title"> <dialog class="mq-dialog" id="mq-dialog-about" aria-labelledby="mq-about-title">
<div class="mq-dialog-head"><h2 id="mq-about-title">关于 Marqdo View</h2><button type="button" class="mq-icon-btn mq-close" data-action="close-dialog" aria-label="关闭关于">×</button></div> <div class="mq-dialog-head"><h2 id="mq-about-title">关于 Marqdo View</h2><button type="button" class="mq-icon-btn mq-close" data-action="close-dialog" aria-label="关闭关于">×</button></div>
<p>版本 {view_version} · Tool Protocol v1 · Analysis v2 · Trace v2。</p> <p>版本 {view_version} · Tool Protocol v1 · Analysis v2/v3 · Trace v2。</p>
<p>冻结核心:{core}。</p> <p>冻结核心:{core}。</p>
<p class="mq-colophon">本页面只渲染原始 Markdown 与已校验的静态语义;打开、刷新、搜索、导出都不会执行文档。运行需要用户显式确认。</p> <p class="mq-colophon">本页面只渲染原始 Markdown 与已校验的静态语义;打开、刷新、搜索、导出都不会执行文档。运行需要用户显式确认。</p>
</dialog> </dialog>
"##, "##,
csrf = csrf, csrf = csrf,
export_dialog = if ctx.live && ctx.core_available {
EXPORT_DIALOG
} else {
""
},
files = self.render_file_list(model, ctx), files = self.render_file_list(model, ctx),
run_dialog = if ctx.core_available { run_dialog = if ctx.core_available {
render_run_form_dialog(model, ctx) render_run_form_dialog(model, ctx)
@@ -814,6 +890,18 @@ fn render_block(
} => { } => {
let unit = resolve_heading_unit(model, *span, *level); let unit = resolve_heading_unit(model, *span, *level);
let anchor = anchor_for_span(span.start, span.end); let anchor = anchor_for_span(span.start, span.end);
let slug = model
.heading_slugs
.get(span)
.map(String::as_str)
.unwrap_or(&anchor);
if slug != anchor {
let _ = write!(
html,
"<span class=\"mq-heading-anchor\" id=\"{}\" aria-hidden=\"true\"></span>",
escape_attr(&anchor)
);
}
let (badge, cleaned) = display_heading_content(content, unit); let (badge, cleaned) = display_heading_content(content, unit);
let data_semantic = if let Some((_, data)) = badge { let data_semantic = if let Some((_, data)) = badge {
data data
@@ -830,7 +918,7 @@ fn render_block(
html, html,
"<h{} id=\"{}\" data-source-id=\"{}\" data-semantic=\"{}\">", "<h{} id=\"{}\" data-source-id=\"{}\" data-semantic=\"{}\">",
level, level,
escape_attr(&anchor), escape_attr(slug),
source_id_id(model, *span), source_id_id(model, *span),
data_semantic, data_semantic,
); );
@@ -842,6 +930,11 @@ fn render_block(
); );
} }
render_inlines(html, &cleaned, model, ctx, current, assets); render_inlines(html, &cleaned, model, ctx, current, assets);
if ctx.live && ctx.core_available {
if let Some(function) = function_at(model, *span) {
html.push_str(&function_call_button(function, &function.local_name));
}
}
let _ = write!(html, "</h{level}>\n"); let _ = write!(html, "</h{level}>\n");
} }
DocBlock::Paragraph { content, .. } => { DocBlock::Paragraph { content, .. } => {
@@ -979,13 +1072,13 @@ fn render_block(
DocBlock::MathBlock { span, literal } => { DocBlock::MathBlock { span, literal } => {
let _ = write!( let _ = write!(
html, html,
"<div class=\"mq-math-block\" data-resource-kind=\"formula\" data-source-id=\"{}\"><code>{}</code><span class=\"mq-math-note\">公式原文 · 未渲染数学</span></div>\n", "<div class=\"mq-math-block\" data-resource-kind=\"formula\" data-source-id=\"{}\">{}</div>\n",
escape_attr(&source_id( escape_attr(&source_id(
&model.document.identity.module_id, &model.document.identity.module_id,
*span, *span,
"resource-formula" "resource-formula"
)), )),
escape_text(literal) render_math(literal, true)
); );
} }
DocBlock::ThematicBreak { .. } => html.push_str("<hr/>\n"), DocBlock::ThematicBreak { .. } => html.push_str("<hr/>\n"),
@@ -1220,7 +1313,7 @@ fn render_inline(
} => { } => {
let reference = projection.and_then(|projection| projection.reference_for_span(*span)); let reference = projection.and_then(|projection| projection.reference_for_span(*span));
let state = reference.map(|reference| reference.state.as_str()); let state = reference.map(|reference| reference.state.as_str());
let target = resolve_link(url, current, &ctx.links); let target = resolve_link(url, current, model, &ctx.links);
match target { match target {
Some(href) => { Some(href) => {
let _ = write!(html, "<a href=\"{href}\"", href = escape_attr(&href)); let _ = write!(html, "<a href=\"{href}\"", href = escape_attr(&href));
@@ -1246,17 +1339,14 @@ fn render_inline(
Inline::Image { Inline::Image {
url, alt, title, .. url, alt, title, ..
} => { } => {
// Remote or unverified images are never loaded implicitly. if let Some(media) = model.media.get(url) {
let _ = (url, title); let _ = write!(html, "<img class=\"mq-document-image\" src=\"{}\" alt=\"{}\" width=\"{}\" height=\"{}\" title=\"{}\">",
let _ = write!( escape_attr(&ctx.links.media_href(media)), escape_attr(alt),
html, media.width, media.height, escape_attr(title));
"<span class=\"mq-raw-omitted\" role=\"note\">[图片已阻止自动加载:{}]</span>", } else {
escape_text(if alt.is_empty() { let _ = write!(html, "<span class=\"mq-raw-omitted\" role=\"note\" title=\"{}\">[图片已阻止自动加载:{}]</span>",
"无替代文本" escape_attr(url), escape_text(if alt.is_empty() { "无替代文本" } else { alt }));
} else { }
alt
})
);
} }
Inline::Math { Inline::Math {
span, span,
@@ -1277,9 +1367,8 @@ fn render_inline(
)) ))
)) ))
.unwrap_or_default(), .unwrap_or_default(),
escape_text(literal) render_math(literal, *display)
); );
let _ = display;
} }
Inline::HtmlInline { .. } => { Inline::HtmlInline { .. } => {
html.push_str("<span class=\"mq-raw-omitted\">已忽略原始行内 HTML</span>"); html.push_str("<span class=\"mq-raw-omitted\">已忽略原始行内 HTML</span>");
@@ -1338,10 +1427,71 @@ fn escape_attr(raw: &str) -> String {
escape_text(raw) escape_text(raw)
} }
fn csp_policy() -> &'static str { fn csp_policy(snapshot_package: bool) -> &'static str {
// `frame-ancestors` is ignored in <meta>; the HTTP header (server.rs) adds if snapshot_package {
// the framing restrictions. Keep the meta policy identical otherwise. "default-src 'none'; style-src 'self' file:; img-src 'self' file: data:; font-src 'self' file:; base-uri 'none'; form-action 'none'; object-src 'none'"
"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'; object-src 'none'" } else {
"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'; object-src 'none'"
}
}
fn render_snapshot(html: &mut String, overlay: &super::snapshot::ExportResultOverlay) {
let execution = &overlay.execution;
let status = if execution.status == "succeeded" {
"成功"
} else {
"失败 · 部分观察"
};
let _ = write!(html, "<details class=\"mq-snapshot\" data-run-state=\"{}\" open><summary>本次执行快照 · {} · {status}</summary><p class=\"mq-colophon\">Core {} · {} · <time datetime=\"{}\">{}</time></p>",
escape_attr(execution.status), escape_text(&overlay.label), escape_text(&execution.core_version),
escape_text(&execution.mode), escape_attr(&execution.terminal_at), escape_text(&execution.terminal_at));
for (label, value) in [
("返回值", &overlay.value),
("stdout", &overlay.stdout),
("stderr", &overlay.stderr),
] {
if let Some(value) = value {
let _ = write!(
html,
"<p>{label}</p><pre aria-label=\"{label}\">{}</pre>",
escape_text(value)
);
}
}
if let Some(arguments) = &overlay.arguments {
html.push_str("<p>提交的参数表达式</p><dl>");
for (name, expression) in arguments {
let _ = write!(
html,
"<dt>{}</dt><dd><code>{}</code></dd>",
escape_text(name),
escape_text(expression)
);
}
html.push_str("</dl>");
} else {
html.push_str("<p class=\"mq-colophon\">参数未包含</p>");
}
let trace_status = match execution.trace_status.as_str() {
"verified" => "已验证",
"truncated" => "已验证,轨迹截断",
"invalid" => "无效",
_ => "不可用",
};
let _ = write!(html, "<p class=\"mq-colophon\">Trace v2 {trace_status}</p>");
if let Some(counts) = &overlay.trace_counts {
html.push_str("<dl class=\"mq-snapshot-counts\">");
for (kind, count) in counts {
let _ = write!(html, "<dt>{}</dt><dd>{count}</dd>", escape_text(kind));
}
html.push_str("</dl>");
}
if !execution.output_complete || !execution.result_complete || execution.observation_truncated {
html.push_str(
"<p class=\"mq-run-warning\">部分结果、输出或事件超过显示上限,或未完成。</p>",
);
}
html.push_str("</details>");
} }
fn percent_encode_path(raw: &str) -> String { fn percent_encode_path(raw: &str) -> String {
@@ -1362,51 +1512,64 @@ fn percent_encode_path(raw: &str) -> String {
/// Sanitize one Markdown link destination. Returns `None` for schemes the /// Sanitize one Markdown link destination. Returns `None` for schemes the
/// reader must never expose (`javascript:`, `data:`, `file:`, ...) and for /// reader must never expose (`javascript:`, `data:`, `file:`, ...) and for
/// console-control-looking payloads. /// console-control-looking payloads.
fn resolve_link(raw: &str, current: &SafeRelativePath, policy: &LinkPolicy) -> Option<String> { fn resolve_link(
raw: &str,
current: &SafeRelativePath,
model: &PresentationModel,
policy: &LinkPolicy,
) -> Option<String> {
let url = raw.trim(); let url = raw.trim();
if url.is_empty() { if url.is_empty()
|| url.chars().any(char::is_control)
|| url.contains('\\')
|| url.starts_with('/')
{
return None; return None;
} }
if url.chars().any(|ch| ch.is_control() || ch == '\u{7f}') { let (path_with_query, fragment) = url
return None; .split_once('#')
.map_or((url, None), |(path, fragment)| (path, Some(fragment)));
let path = path_with_query.split('?').next()?;
if let Some((scheme, _)) = path.split_once(':') {
return matches!(
scheme.to_ascii_lowercase().as_str(),
"http" | "https" | "mailto"
)
.then(|| url.to_string());
} }
// Explicit scheme: only http/https/mailto are navigable. A single-letter let fragment = fragment
// prefix is a Windows drive, not a scheme. .map(super::links::decode)
if let Some(colon) = url.find(':') { .unwrap_or_else(|| Some(String::new()))?;
let scheme = &url[..colon]; let suffix = if fragment.is_empty() {
if scheme.len() > 1 && scheme.chars().all(|ch| ch.is_ascii_alphabetic()) { String::new()
return match scheme.to_ascii_lowercase().as_str() { } else {
"http" | "https" | "mailto" => Some(url.to_string()), format!("#{}", percent_encode_path(&fragment))
_ => None, };
}; if path.is_empty() {
return Some(suffix);
}
let target = super::links::relative_url(current, path)?;
if target.as_str().ends_with(".mq.md") {
if !model.navigation.documents.contains(&target) {
return None;
} }
} return Some(format!(
if url.starts_with("//") { "{}{suffix}",
return None; policy.document_href(current, &target)
} ));
if url.starts_with('#') {
return Some(url.to_string());
}
if url.starts_with('/') {
return match policy {
LinkPolicy::LocalServer => Some(url.to_string()),
LinkPolicy::StaticRelative { .. } => None,
};
}
let path_part = url.split(['?', '#']).next().unwrap_or(url);
if path_part.ends_with(".mq.md") {
let joined = match current.parent() {
Some(dir) => format!("{dir}/{path_part}"),
None => path_part.to_string(),
};
if let Ok(target) = SafeRelativePath::parse(&joined) {
return Some(policy.document_href(current, &target));
}
return None;
} }
Some(url.to_string()) Some(url.to_string())
} }
fn render_math(literal: &str, display: bool) -> String {
super::math::render(literal, display).unwrap_or_else(|| {
format!(
"<code title=\"公式无法排版\">{}</code>",
escape_text(literal)
)
})
}
fn render_run_chips(html: &mut String, model: &PresentationModel, statement_span: SourceSpan) { fn render_run_chips(html: &mut String, model: &PresentationModel, statement_span: SourceSpan) {
let Some(run) = &model.run else { let Some(run) = &model.run else {
return; return;
@@ -1430,6 +1593,29 @@ fn render_run_chips(html: &mut String, model: &PresentationModel, statement_span
); );
} }
fn function_at(
model: &PresentationModel,
span: SourceSpan,
) -> Option<&crate::protocol::analysis_v2::SemanticFunction> {
model
.semantic
.as_ref()?
.functions
.iter()
.find(|function| function.heading_span == span)
}
fn function_call_button(
function: &crate::protocol::analysis_v2::SemanticFunction,
label: &str,
) -> String {
format!(
"<button type=\"button\" class=\"mq-fn-call\" data-action=\"call-function\" data-function-id=\"{id}\" data-function-label=\"{label}\" data-params=\"{params}\">调用</button>",
id = escape_attr(&function.id), label = escape_attr(label),
params = escape_attr(&function_params_json(function)),
)
}
fn function_params_json(function: &crate::protocol::analysis_v2::SemanticFunction) -> String { fn function_params_json(function: &crate::protocol::analysis_v2::SemanticFunction) -> String {
serde_json::json!(function serde_json::json!(function
.signature .signature
@@ -1445,6 +1631,23 @@ fn function_params_json(function: &crate::protocol::analysis_v2::SemanticFunctio
.to_string() .to_string()
} }
const EXPORT_DIALOG: &str = r##"<dialog class="mq-dialog mq-export-dialog" id="mq-dialog-export" aria-labelledby="mq-export-title">
<div class="mq-dialog-head"><h2 id="mq-export-title">导出文档(含本次结果)</h2><button type="button" class="mq-icon-btn mq-close" data-action="close-dialog" aria-label="关闭导出">×</button></div>
<p id="mq-export-target" class="mq-export-target"></p>
<fieldset class="mq-export-fields">
<legend>导出内容</legend>
<div id="mq-export-fields"></div>
</fieldset>
<p class="mq-colophon">输出和参数可能包含令牌、路径或个人信息。请检查所选内容。</p>
<label class="mq-export-confirm"><input type="checkbox" id="mq-export-confirm"> 我已检查选中的内容,可以将其写入 ZIP。</label>
<label class="mq-export-confirm" id="mq-export-partial-row" hidden><input type="checkbox" id="mq-export-partial"> 我确认导出带有失败或截断标记的部分观察。</label>
<p id="mq-export-error" role="alert" hidden></p>
<div class="mq-dialog-actions">
<button type="button" class="mq-secondary" data-action="close-dialog">取消</button>
<button type="button" class="mq-primary" id="mq-export-download" data-action="download-result" disabled>下载 ZIP</button>
</div>
</dialog>"##;
fn render_run_form_dialog(model: &PresentationModel, ctx: &RenderContext) -> String { fn render_run_form_dialog(model: &PresentationModel, ctx: &RenderContext) -> String {
let path = &model.document.identity.relative_path; let path = &model.document.identity.relative_path;
format!( format!(
+50
View File
@@ -0,0 +1,50 @@
//! Renderer input for one explicitly selected, already verified terminal result.
use serde::Serialize;
use std::collections::BTreeMap;
#[derive(Serialize)]
pub struct SnapshotSource {
pub project_root_id: String,
pub document: String,
pub module_id: String,
pub source_sha256: String,
pub analysis_digest: String,
pub lock_digest: Option<String>,
}
#[derive(Serialize)]
pub struct SnapshotProtocols {
pub analysis: u32,
pub trace: u32,
pub events: u32,
}
#[derive(Serialize)]
pub struct SnapshotExecution {
pub included: bool,
pub core_run_id: String,
pub core_version: String,
pub target: String,
pub status: &'static str,
pub terminal_at: String,
pub source_verified: bool,
pub trace_status: String,
pub result_complete: bool,
pub output_complete: bool,
pub observation_truncated: bool,
pub parameters: &'static str,
pub mode: String,
pub core_protocol: SnapshotProtocols,
}
pub struct ExportResultOverlay {
pub source: SnapshotSource,
pub execution: SnapshotExecution,
pub label: String,
pub value: Option<String>,
pub stdout: Option<String>,
pub stderr: Option<String>,
pub trace_counts: Option<BTreeMap<String, u64>>,
pub arguments: Option<Vec<(String, String)>>,
}
+26 -2
View File
@@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
/// Half-open byte span `[start, end)` into one module's exact source bytes. /// Half-open byte span `[start, end)` into one module's exact source bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub struct SourceSpan { pub struct SourceSpan {
pub start: u64, pub start: u64,
pub end: u64, pub end: u64,
@@ -402,6 +402,8 @@ pub struct DocumentRef {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Project { pub struct Project {
root: PathBuf, root: PathBuf,
#[cfg(target_os = "linux")]
root_handle: std::sync::Arc<std::fs::File>,
entry: DocumentRef, entry: DocumentRef,
} }
@@ -419,6 +421,8 @@ impl Project {
if metadata.is_file() { if metadata.is_file() {
let root = discover_project_root(&canonical); let root = discover_project_root(&canonical);
let project = Self { let project = Self {
#[cfg(target_os = "linux")]
root_handle: Self::open_root(&root)?,
entry: DocumentRef { entry: DocumentRef {
relative: SafeRelativePath("placeholder".to_string()), relative: SafeRelativePath("placeholder".to_string()),
absolute: canonical.clone(), absolute: canonical.clone(),
@@ -428,6 +432,8 @@ impl Project {
let relative = project.relative_for(&canonical)?; let relative = project.relative_for(&canonical)?;
Ok(Self { Ok(Self {
root: project.root, root: project.root,
#[cfg(target_os = "linux")]
root_handle: project.root_handle,
entry: DocumentRef { entry: DocumentRef {
relative, relative,
absolute: canonical, absolute: canonical,
@@ -436,6 +442,8 @@ impl Project {
} else if metadata.is_dir() { } else if metadata.is_dir() {
let project = Self { let project = Self {
root: canonical.clone(), root: canonical.clone(),
#[cfg(target_os = "linux")]
root_handle: Self::open_root(&canonical)?,
entry: DocumentRef { entry: DocumentRef {
relative: SafeRelativePath("placeholder".to_string()), relative: SafeRelativePath("placeholder".to_string()),
absolute: canonical.clone(), absolute: canonical.clone(),
@@ -444,8 +452,8 @@ impl Project {
let documents = project.list_documents()?; let documents = project.list_documents()?;
let chosen = choose_entry(&project.root, &documents)?; let chosen = choose_entry(&project.root, &documents)?;
Ok(Self { Ok(Self {
root: project.root,
entry: chosen, entry: chosen,
..project
}) })
} else { } else {
Err(ViewError::PathForbidden { Err(ViewError::PathForbidden {
@@ -454,6 +462,22 @@ impl Project {
} }
} }
#[cfg(target_os = "linux")]
fn open_root(path: &Path) -> ViewResult<std::sync::Arc<std::fs::File>> {
use std::os::unix::fs::OpenOptionsExt;
std::fs::OpenOptions::new()
.read(true)
.custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW)
.open(path)
.map(std::sync::Arc::new)
.map_err(|err| ViewError::io("open project root", err))
}
#[cfg(target_os = "linux")]
pub(super) fn root_handle(&self) -> &std::fs::File {
&self.root_handle
}
pub fn root(&self) -> &Path { pub fn root(&self) -> &Path {
&self.root &self.root
} }
+63
View File
@@ -0,0 +1,63 @@
use crate::{ViewError, ViewResult};
use std::path::{Path, PathBuf};
/// A private temporary directory for transient artifacts.
pub struct ScratchDir {
path: PathBuf,
}
impl ScratchDir {
pub fn create(label: &str) -> ViewResult<Self> {
let base = std::env::temp_dir();
let unique = format!(
"marqdo-view-{}-{}-{}",
std::process::id(),
unique_counter(),
sanitize_label(label)
);
let path = base.join(unique);
let mut builder = std::fs::DirBuilder::new();
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt;
builder.mode(0o700);
}
builder
.create(&path)
.map_err(|err| ViewError::io("create private scratch directory", err))?;
Ok(Self { path })
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn file(&self, name: &str) -> PathBuf {
self.path.join(name)
}
}
impl Drop for ScratchDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
fn unique_counter() -> u64 {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos() as u64)
.unwrap_or(0);
seq ^ nanos.rotate_left(17)
}
fn sanitize_label(label: &str) -> String {
label
.chars()
.map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '-' })
.take(32)
.collect()
}
+3 -1
View File
@@ -41,6 +41,7 @@ pub fn serve(service: DocumentService, opts: &RuntimeOpts) -> ViewResult<i32> {
Arc::clone(&service), Arc::clone(&service),
ExecutionConfig::default().with_timeout(opts.run_timeout_secs), ExecutionConfig::default().with_timeout(opts.run_timeout_secs),
)); ));
controller.start_expiry_sweep();
let state = Arc::new(ServerState { let state = Arc::new(ServerState {
service, service,
controller, controller,
@@ -48,6 +49,7 @@ pub fn serve(service: DocumentService, opts: &RuntimeOpts) -> ViewResult<i32> {
cache: Mutex::new(HashMap::new()), cache: Mutex::new(HashMap::new()),
security: crate::server::security::SecurityState::new(port), security: crate::server::security::SecurityState::new(port),
active_requests: AtomicUsize::new(0), active_requests: AtomicUsize::new(0),
snapshot_export: Mutex::new(()),
}); });
eprintln!("marqdo view: {url}"); eprintln!("marqdo view: {url}");
@@ -62,7 +64,7 @@ pub fn serve(service: DocumentService, opts: &RuntimeOpts) -> ViewResult<i32> {
.unwrap_or(0) .unwrap_or(0)
); );
if let Some(version) = state.service.core_version() { if let Some(version) = state.service.core_version() {
eprintln!("core: marqdo {version} (Analysis v2, Trace v2)"); eprintln!("core: marqdo {version} (Analysis v2/v3, Trace v2)");
} else if let Some(note) = state.service.core_note() { } else if let Some(note) = state.service.core_note() {
eprintln!("core: unavailable ({note})"); eprintln!("core: unavailable ({note})");
} }
+123 -10
View File
@@ -6,6 +6,8 @@
//! | `GET /file?path=...` | no | //! | `GET /file?path=...` | no |
//! | `GET /assets/...` | no | //! | `GET /assets/...` | no |
//! | `GET /api/documents` | no | //! | `GET /api/documents` | no |
//! | `GET /media/...` | no |
//! | `POST /api/exports` | no (static snapshot) |
//! | `POST /api/runs` | **yes — the only execution entry** | //! | `POST /api/runs` | **yes — the only execution entry** |
//! | `GET /api/runs/{id}/events` | no (observe only) | //! | `GET /api/runs/{id}/events` | no (observe only) |
//! | `POST /api/runs/{id}/cancel` | no (control of an existing job) | //! | `POST /api/runs/{id}/cancel` | no (control of an existing job) |
@@ -37,6 +39,7 @@ pub struct ServerState {
pub cache: Mutex<HashMap<String, CacheEntry>>, pub cache: Mutex<HashMap<String, CacheEntry>>,
pub security: SecurityState, pub security: SecurityState,
pub active_requests: AtomicUsize, pub active_requests: AtomicUsize,
pub snapshot_export: Mutex<()>,
} }
#[derive(Clone)] #[derive(Clone)]
@@ -50,21 +53,29 @@ impl ServerState {
/// bytes are unchanged. This path performs the read-only `check` only. /// bytes are unchanged. This path performs the read-only `check` only.
pub fn load(&self, relative: &SafeRelativePath) -> ViewResult<PresentationModel> { pub fn load(&self, relative: &SafeRelativePath) -> ViewResult<PresentationModel> {
let digest = self.service.project().source_digest(relative)?; let digest = self.service.project().source_digest(relative)?;
if let Ok(cache) = self.cache.lock() { let cached = self.cache.lock().ok().and_then(|cache| {
if let Some(entry) = cache.get(relative.as_str()) { let entry = cache.get(relative.as_str())?;
if entry.source_digest == digest { (entry.source_digest == digest).then(|| entry.model.clone())
return Ok(entry.model.clone()); });
} if let Some(mut model) = cached {
} model.media = crate::reader::media::collect(
self.service.project(),
relative,
&model.document.blocks,
);
model.navigation.documents = self.service.project().list_documents()?;
return Ok(model);
} }
let model = self.service.load(relative)?; let model = self.service.load(relative)?;
if let Ok(mut cache) = self.cache.lock() { if let Ok(mut cache) = self.cache.lock() {
if cache.len() < 64 { if cache.len() < 64 {
let mut cached = model.clone();
cached.media.clear();
cache.insert( cache.insert(
relative.as_str().to_string(), relative.as_str().to_string(),
CacheEntry { CacheEntry {
source_digest: digest, source_digest: digest,
model: model.clone(), model: cached,
}, },
); );
} }
@@ -102,6 +113,9 @@ pub fn handle(state: &ServerState, request: Request) -> ViewResult<()> {
if let Some(hashed_name) = path.strip_prefix("/assets/") { if let Some(hashed_name) = path.strip_prefix("/assets/") {
return serve_asset(request, hashed_name); return serve_asset(request, hashed_name);
} }
if let Some(name) = path.strip_prefix("/media/") {
return serve_media(state, request, name, query);
}
if path == "/" || path == "/index.html" { if path == "/" || path == "/index.html" {
return serve_page(state, request, None); return serve_page(state, request, None);
} }
@@ -118,6 +132,9 @@ pub fn handle(state: &ServerState, request: Request) -> ViewResult<()> {
} }
if method == Method::Post { if method == Method::Post {
if path == "/api/exports" {
return submit_export(state, request);
}
if path == "/api/runs" { if path == "/api/runs" {
return submit_run(state, request); return submit_run(state, request);
} }
@@ -177,6 +194,8 @@ fn serve_page(
annotations: true, annotations: true,
run_timeout_secs: state.controller.config().run_timeout_secs(), run_timeout_secs: state.controller.config().run_timeout_secs(),
core_available: state.service.core().is_some(), core_available: state.service.core().is_some(),
snapshot_package: false,
overlay: None,
}; };
let page = state.renderer.render(&model, &ctx); let page = state.renderer.render(&model, &ctx);
let mut headers = Vec::new(); let mut headers = Vec::new();
@@ -288,7 +307,7 @@ fn serve_documents(state: &ServerState, request: Request, query: &str) -> ViewRe
"source_status": model.source_status.data_value(), "source_status": model.source_status.data_value(),
"semantics_usable": model.source_status.semantics_usable(), "semantics_usable": model.source_status.semantics_usable(),
"analysis": semantic.map(|projection| serde_json::json!({ "analysis": semantic.map(|projection| serde_json::json!({
"schema_version": crate::protocol::tool_v1::ANALYSIS_PROTOCOL, "schema_version": projection.schema_version,
"digest": projection.analysis_digest, "digest": projection.analysis_digest,
"producer_version": projection.producer_version, "producer_version": projection.producer_version,
"project_root_id": projection.project_root_id, "project_root_id": projection.project_root_id,
@@ -315,6 +334,60 @@ fn serve_documents(state: &ServerState, request: Request, query: &str) -> ViewRe
} }
/// The only execution entry in the whole product. /// The only execution entry in the whole product.
fn submit_export(state: &ServerState, mut request: Request) -> ViewResult<()> {
use crate::export_result::{ExportSelection, MAX_EXPORT_REQUEST};
let result = (|| {
let session = state.security.authenticate_post(&request)?;
let selection = ExportSelection::parse(&read_body(&mut request, MAX_EXPORT_REQUEST)?)?;
let candidate = state
.controller
.get_export_candidate(&session.id, &selection.run_id)?;
let guard = state
.snapshot_export
.try_lock()
.map_err(|_| ViewError::ResourceLimit {
detail: "a snapshot download is already being prepared or sent".into(),
})?;
let (model, overlay) = selection.prepare(&state.service, &candidate)?;
let archive = crate::export::snapshot(&state.service, &model, overlay)?;
Ok((guard, archive))
})();
let (_guard, archive) = match result {
Ok(result) => result,
Err(err) => return respond_error(request, status_for(&err), &err),
};
let mut headers = crate::server::security::security_headers();
headers.retain(|(name, _)| *name != "Content-Security-Policy");
headers.extend([
("Content-Type", "application/zip"),
(
"Content-Disposition",
"attachment; filename=marqdo-execution-snapshot.zip",
),
("Content-Security-Policy", "default-src 'none'; sandbox"),
]);
let mut headers: Vec<Header> = headers
.into_iter()
.map(|(name, value)| {
Header::from_bytes(name, value).expect("valid snapshot download header")
})
.collect();
headers.push(
Header::from_bytes("X-Marqdo-Manifest-SHA256", archive.manifest_sha256.as_str())
.expect("valid manifest digest header"),
);
let response = Response::new(
StatusCode(200),
headers,
archive.file,
Some(archive.len),
None,
);
request
.respond(response)
.map_err(|err| ViewError::io("send snapshot ZIP", err))
}
fn submit_run(state: &ServerState, mut request: Request) -> ViewResult<()> { fn submit_run(state: &ServerState, mut request: Request) -> ViewResult<()> {
let session = match state.security.authenticate_post(&request) { let session = match state.security.authenticate_post(&request) {
Ok(session) => session, Ok(session) => session,
@@ -387,6 +460,43 @@ fn cancel_run(state: &ServerState, request: Request, run_id: &str) -> ViewResult
} }
} }
fn serve_media(state: &ServerState, request: Request, name: &str, query: &str) -> ViewResult<()> {
if let Err(err) = state.security.require_session(&request) {
return respond_error(request, status_for(&err), &err);
}
let Some(path) =
query_param(query, "path").and_then(|path| SafeRelativePath::parse(&path).ok())
else {
return respond_text(
request,
StatusCode(404),
"media not found\n",
CacheKind::NoStore,
);
};
let Some(media) = crate::reader::media::load(state.service.project(), &path)
.filter(|media| media.filename() == name)
else {
return respond_text(
request,
StatusCode(404),
"media not found\n",
CacheKind::NoStore,
);
};
respond_bytes(
request,
StatusCode(200),
media.mime,
media.bytes,
CacheKind::NoStore,
vec![
Header::from_bytes("Content-Security-Policy", "default-src 'none'; sandbox")
.expect("valid media CSP"),
],
)
}
fn serve_asset(request: Request, hashed_name: &str) -> ViewResult<()> { fn serve_asset(request: Request, hashed_name: &str) -> ViewResult<()> {
let bundle = AssetBundle::get(); let bundle = AssetBundle::get();
if hashed_name == bundle.hashed_css_name() { if hashed_name == bundle.hashed_css_name() {
@@ -430,8 +540,11 @@ fn status_for(err: &ViewError) -> StatusCode {
match err.code() { match err.code() {
"view.session_required" => StatusCode(401), "view.session_required" => StatusCode(401),
"view.run_denied" => StatusCode(403), "view.run_denied" => StatusCode(403),
"view.run_invalid" | "view.no_entry_function" => StatusCode(400), "view.run_invalid" | "view.no_entry_function" | "view.export_invalid" => StatusCode(400),
"view.run_busy" | "view.run_conflict" => StatusCode(409), "view.run_busy"
| "view.run_conflict"
| "view.export_unavailable"
| "view.export_source_changed" => StatusCode(409),
"view.run_not_found" => StatusCode(404), "view.run_not_found" => StatusCode(404),
"view.sse_busy" | "view.resource_limit" => StatusCode(429), "view.sse_busy" | "view.resource_limit" => StatusCode(429),
"view.output_limit" => StatusCode(413), "view.output_limit" => StatusCode(413),
+184
View File
@@ -0,0 +1,184 @@
"use strict";
const assert = require("node:assert/strict");
const { execFileSync, spawn } = require("node:child_process");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { createInterface } = require("node:readline");
const { pathToFileURL } = require("node:url");
const { chromium } = require("playwright");
const root = path.resolve(__dirname, "../..");
const core = fs.realpathSync(process.env.MARQDO_BIN);
const view = process.env.VIEW_BIN || path.join(root, "target/debug/marqdo-view");
const artifactDir = process.env.MQ_SCREENSHOT_DIR;
const temp = fs.mkdtempSync(path.join(os.tmpdir(), "mq-complete-browser-"));
const project = path.join(temp, "project");
const runCount = path.join(temp, "calls");
const wrapper = path.join(temp, "counted-core");
fs.cpSync(path.join(root, "examples/complete-reader"), project, { recursive: true });
fs.writeFileSync(wrapper, `#!/usr/bin/env python3
import json, os, subprocess, sys, time
core, calls = ${JSON.stringify(core)}, ${JSON.stringify(runCount)}
args = sys.argv[1:]
if args[0] not in ('run','call'):
os.execv(core, [core, *args])
assert '--event-stream' in args and '--json' not in args
with open(calls, 'a') as f: f.write(args[0]+'\\n')
if 'write_output' not in args:
os.execv(core, [core, *args])
with subprocess.Popen([core, *args], stdout=subprocess.PIPE) as child:
for line in child.stdout:
sys.stdout.buffer.write(line)
sys.stdout.buffer.flush()
if json.loads(line)['kind'] == 'stdout.chunk': time.sleep(1.2)
sys.exit(child.wait())
`, { mode: 0o700 });
async function awaitUrl(server) {
const logger = createInterface({ input: server.stderr });
return new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error("View startup timeout")), 8000);
logger.on("line", line => {
const url = line.match(/http:\/\/127\.0\.0\.1:\d+\//);
if (url) {
clearTimeout(timer);
resolve(url[0]);
}
});
server.once("exit", (code) => {
clearTimeout(timer);
reject(new Error("View exited " + code));
});
server.once("error", reject);
});
}
async function screenshot(page, file) {
if (!artifactDir) return;
fs.mkdirSync(artifactDir, { recursive: true });
await page.screenshot({ path: path.join(artifactDir, file), animations: "disabled" });
}
async function imagesLoaded(page, count) {
const loaded = await page.evaluate(async () => {
const images = Array.from(document.querySelectorAll("img.mq-document-image"));
await Promise.all(images.map(image => image.decode()));
return images.filter(image => image.complete && image.naturalWidth > 0).length;
});
assert.equal(loaded, count);
}
async function verifyOffline(browser, url) {
const offline = await browser.newContext({ javaScriptEnabled: false, offline: true });
const page = await offline.newPage();
const requests = [];
page.on("request", request => requests.push(request.url()));
await page.goto(url);
await imagesLoaded(page, 1);
assert.equal(await page.locator("math mfrac").count(), 1);
assert.equal(await page.locator("script, [data-action=run], [data-action=call-function]").count(), 0);
assert.match(await page.locator(".mq-snapshot pre[aria-label=返回值]").innerText(), /4\.0|Float\(4\)/);
assert.equal(await page.locator(".mq-snapshot [aria-label=stdout]").count(), 0);
await screenshot(page, "offline-snapshot.png");
await page.locator(".mq-snapshot").scrollIntoViewIfNeeded();
await screenshot(page, "offline-result.png");
await page.emulateMedia({ media: "print" });
assert.equal(await page.locator(".mq-snapshot").isVisible(), true);
await page.emulateMedia({ media: "screen" });
await page.getByRole("link", { name: "误差说明", exact: true }).click();
await imagesLoaded(page, 3);
assert.equal(decodeURIComponent(new URL(page.url()).hash), "#误差-1");
assert.equal(await page.locator(":target").textContent(), "误差");
assert.equal(await page.locator(".mq-snapshot").count(), 0);
assert.ok(requests.every(request => request.startsWith("file:") || request.startsWith("data:")), requests);
await offline.close();
}
(async () => {
const server = spawn(view, ["--marqdo-bin", wrapper, project, "--port", "0", "--no-open"], {
stdio: ["ignore", "ignore", "pipe"],
});
let browser;
try {
const url = await awaitUrl(server);
browser = await chromium.launch({ executablePath: process.env.CHROMIUM_BIN || undefined });
console.log("Chromium " + browser.version());
const context = await browser.newContext({ viewport: { width: 1480, height: 960 }, acceptDownloads: true });
const page = await context.newPage();
const external = [];
const errors = [];
page.on("request", request => {
if (!request.url().startsWith(url) && !request.url().startsWith("data:") &&
!request.url().startsWith("blob:")) external.push(request.url());
});
page.on("pageerror", error => errors.push(String(error)));
await page.goto(url);
await imagesLoaded(page, 1);
assert.equal(await page.locator("math mfrac").count(), 1);
await page.getByRole("link", { name: "误差说明", exact: true }).click();
await imagesLoaded(page, 3);
assert.equal(await page.locator(":target").textContent(), "误差");
assert.equal(decodeURIComponent(new URL(page.url()).hash), "#误差-1");
await page.getByRole("link", { name: "返回计算均值", exact: true }).click();
assert.match(await page.locator(":target").innerText(), /计算均值/);
assert.equal(fs.existsSync(runCount), false);
await page.locator("h2[id=计算均值] [data-action=call-function]").click();
await page.locator("[data-param-name=a]").fill("3");
assert.equal(fs.existsSync(runCount), false);
await page.locator("[data-action=run-confirm]").click();
const result = page.locator(".mq-result-slot #mq-run-panel");
await result.locator("[data-action=export-result]").waitFor();
assert.equal(await result.getAttribute("data-run-state"), "succeeded");
assert.match(await result.locator("#mq-run-summary").innerText(), /Float\(4\.0\)/);
assert.equal(fs.readFileSync(runCount, "utf8"), "call\n");
await result.scrollIntoViewIfNeeded();
await screenshot(page, "live-result.png");
await result.locator("[data-action=export-result]").click();
assert.equal(await page.locator("#mq-export-download").isDisabled(), true);
assert.equal(await page.locator("#mq-export-fields [name=arguments]").isChecked(), false);
assert.equal(await page.locator("#mq-export-fields [name=stdout]").isChecked(), false);
await screenshot(page, "export-preview.png");
await page.keyboard.press("Escape");
assert.equal(await page.locator("#mq-dialog-export").isVisible(), false);
await result.locator("[data-action=export-result]").click();
await page.locator("#mq-export-confirm").check();
const downloading = page.waitForEvent("download");
await page.locator("#mq-export-download").click();
const download = await downloading;
assert.equal(fs.readFileSync(runCount, "utf8"), "call\n");
const zip = path.join(temp, "snapshot.zip");
await download.saveAs(zip);
const extracted = path.join(temp, "offline");
execFileSync("python3", ["-m", "zipfile", "-e", zip, extracted]);
await page.locator("h2[id=write_output] [data-action=call-function]").click();
await page.locator("[data-action=run-confirm]").click();
await page.locator("#mq-run-stdout").waitFor();
assert.equal(await result.getAttribute("data-run-state"), "running");
assert.equal((await page.locator("#mq-run-stdout").innerText()).trim(), "4");
await page.locator("[data-action=export-result]").waitFor();
assert.equal(fs.readFileSync(runCount, "utf8"), "call\ncall\n");
assert.deepEqual(external, []);
assert.deepEqual(errors, []);
const mobile = await context.newPage();
await mobile.setViewportSize({ width: 390, height: 844 });
await mobile.goto(url);
await imagesLoaded(mobile, 1);
assert.equal(await mobile.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true);
await screenshot(mobile, "mobile-reader.png");
await context.close();
server.kill();
await verifyOffline(browser, pathToFileURL(path.join(extracted, "index.html")).href);
console.log("Live media, cross-document anchors, confirmed call, pre-terminal stdout, private download and offline ZIP: PASS");
} finally {
if (browser) await browser.close();
server.kill();
fs.rmSync(temp, { recursive: true, force: true });
}
})().catch(error => { console.error(error); process.exitCode = 1; });
+1 -1
View File
@@ -81,7 +81,7 @@ fn theme_has_one_token_layer_and_no_legacy_skin() {
"the theme must not rely on !important overrides" "the theme must not rely on !important overrides"
); );
// No remote font/CDN requests. // No remote font/CDN requests.
for banned in ["@font-face", "fonts.googleapis", "https://"] { for banned in ["fonts.googleapis", "https://"] {
assert!(!css.contains(banned), "remote resource marker {banned}"); assert!(!css.contains(banned), "remote resource marker {banned}");
} }
} }
+2 -2
View File
@@ -249,13 +249,13 @@ fn cli_verify_end_to_end_against_fake_core() {
} }
#[test] #[test]
fn cli_verify_rejects_schema_v3_and_digest_mismatch() { fn cli_verify_rejects_schema_v4_and_digest_mismatch() {
let (project, core) = fixture("verify_negative"); let (project, core) = fixture("verify_negative");
let source = std::fs::read(project.path("index.mq.md")).unwrap(); let source = std::fs::read(project.path("index.mq.md")).unwrap();
let script = core.script.to_str().unwrap().to_string(); let script = core.script.to_str().unwrap().to_string();
let dir = project.dir.to_str().unwrap().to_string(); let dir = project.dir.to_str().unwrap().to_string();
core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 3)); core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 4));
let output = common::run_view( let output = common::run_view(
&["verify", "index.mq.md", "--marqdo-bin", &script], &["verify", "index.mq.md", "--marqdo-bin", &script],
std::path::Path::new(&dir), std::path::Path::new(&dir),
+1 -1
View File
@@ -182,7 +182,7 @@ fn tool_manifest_matches_package_and_protocols() {
"tool.json version must match Cargo package version" "tool.json version must match Cargo package version"
); );
assert_eq!(tool["compatibility"]["marqdo"], ">=3.0.0-beta.1,<4.0.0"); assert_eq!(tool["compatibility"]["marqdo"], ">=3.0.0-beta.1,<4.0.0");
assert_eq!(tool["compatibility"]["analysis"], serde_json::json!([2])); assert_eq!(tool["compatibility"]["analysis"], serde_json::json!([2, 3]));
assert_eq!(tool["compatibility"]["trace"], serde_json::json!([2])); assert_eq!(tool["compatibility"]["trace"], serde_json::json!([2]));
} }
+1 -1
View File
@@ -58,7 +58,7 @@ fn source_digest_mismatch_degrades_instead_of_misbinding() {
fn unknown_analysis_schema_is_a_hard_protocol_error() { fn unknown_analysis_schema_is_a_hard_protocol_error() {
let (project, core) = project("state-protocol"); let (project, core) = project("state-protocol");
let source = std::fs::read(project.path("index.mq.md")).unwrap(); let source = std::fs::read(project.path("index.mq.md")).unwrap();
core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 3)); core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 4));
let context = DocumentService::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 relative = context.project().entry().relative.clone();
let err = context.load(&relative).unwrap_err(); let err = context.load(&relative).unwrap_err();
+1 -1
View File
@@ -7,7 +7,7 @@
"entrypoint": "bin/marqdo-view", "entrypoint": "bin/marqdo-view",
"compatibility": { "compatibility": {
"marqdo": ">=3.0.0-beta.1,<4.0.0", "marqdo": ">=3.0.0-beta.1,<4.0.0",
"analysis": [2], "analysis": [2, 3],
"trace": [2] "trace": [2]
} }
} }