feat(PR-01): single Rust package, Tool Protocol v1 bundle and PublicCoreClient

- src/lib.rs module layout + thin main.rs dispatcher; CLI owns browse/export/verify
- core_client: MARQDO_BIN only, explicit argv (no shell), 0700 scratch dirs,
  wall-clock timeout killing the whole process group, version/protocol negotiation
- project/source_map: canonical path boundary, SafeRelativePath, exact UTF-8
  byte <-> line/column <-> UTF-16 mapping, SHA-256 of exact bytes
- stable view.* error codes with 0/1/2 exit classes; BindDenied for non-loopback
- verify use case: Analysis v2 schema/profile/root_id/source_digest binding, no execution
- tool.json + tools/package.sh + tools/install-smoke.sh; frozen-CLI install smoke PASS
- contract tests with a real fake-core executable + architectural coupling gates
- COMPATIBILITY/CHANGELOG/STATUS updated
This commit is contained in:
marqdo-view dev committed 2026-11-22 10:33:14 +08:00
1 parent ef546f2ca6
commit 8ba20a5c67
23 files changed
+3692 -8

No files matched your search

+1
View File
@@ -5,3 +5,4 @@
/tests/browser/artifacts/
*.swp
.DS_Store
.cargo-home/
+31
View File
@@ -0,0 +1,31 @@
# Changelog
All notable changes to `marqdo-view` are documented here. The format follows
Keep a Changelog and the project uses SemVer for the View product version.
Protocol axes (Tool v1, Analysis v2, Trace v2) are versioned separately.
## [Unreleased]
### Added
- PR-00: legacy View static audit (`docs/audits/legacy-render-paths.md`), visual
tokens, run-state matrix, ADR-0001/0002, MIT/Apache-2.0 licensing, STATUS.
- PR-01: single Rust package with a testable library boundary; `marqdo-view`
CLI (`browse`, `export`, `verify`) owned entirely by View; Tool Protocol v1
manifest (`tool.json`) and packaging/install smoke scripts.
- PR-01: `PublicCoreClient` over `MARQDO_BIN` with explicit argv arrays, private
0700 scratch artifacts, wall-clock timeout that kills the whole process group,
product-range and protocol negotiation, and stable `view.*` error codes.
- PR-01: `verify` command/use case that checks CLI version, Analysis v2 schema,
Markdown profile, project identity and exact source digest without executing.
- PR-01: contract tests with a real fake-core executable (argv, exit codes,
stderr preservation, missing emit, timeout, invalid JSON) and architectural
coupling gates.
### Known limitations
- `browse` and `export` currently return `view.unsupported`; they land in
PR-02/PR-03 (reader) and PR-05 (export).
- The single `assets/reader.css` + `assets/reader.js` theme is not present yet.
- `verify` uses a structural binding check; the typed `SemanticProjection`
replaces it in PR-02 with the same external result.
+48
View File
@@ -0,0 +1,48 @@
# Compatibility
## 版本轴(不得混用)
| 轴 | 本 View 值 | 说明 |
|---|---|---|
| View 产品版本 | `0.1.0` | 独立 SemVer,与 CLI 不共用 |
| `marqdo` 产品范围 | `>=3.0.0-beta.1,<4.0.0` | 安装与分发时由 CLI 强制校验 |
| CLI Tool Protocol | `1` | `tool.json` 清单/整包摘要/分发 |
| Analysis | `2` | 未知 major 直接拒绝,不回退 |
| Trace | `2` | 与 Analysis 精确字节摘要绑定 |
| Markdown profile | `marqdo.md.v1` | 与冻结 CLI 相同选项集 |
Beta 版 CLI 必须使用 prerelease 范围(`>=3.0.0-beta.1,<4.0.0`);`>=3.0.0,<4.0.0` **不匹配** `3.0.0-beta.1`。
## 平台
| 平台 | 状态 | 说明 |
|---|---|---|
| Linux x86_64 (glibc) | **Supported** | 与 CLI Beta 唯一发布目标一致 |
| Linux aarch64 | 未构建 | 未验证 |
| macOS / Windows | 未验证 | 不声明支持;路径/进程组逻辑留有平台分支,但未做实测 |
## 能力边界(诚实状态)
| 能力 | 状态 |
|---|---|
| 原始 Markdown 只读浏览(GFM 表/列表/引用/代码围栏/数学文本) | 计划 PR-02 |
| Analysis v2 静态语义(函数/Unit/诊断/引用/资源) | 计划 PR-02 |
| 文档态 / 源码态切换 | 计划 PR-02 |
| 暖纸 Reader 视觉(单一 CSS/JS) | 计划 PR-03 |
| 用户显式触发运行 + Trace v2 事件可视化 | 计划 PR-04 |
| Live 本机安全 API | 计划 PR-05 |
| 静态离线导出(纯只读) | 计划 PR-05 |
| 逐语句变量值 / 参数实际值 / 内存快照 | **UNSUPPORTED**(Trace v2 不提供,绝不伪造) |
| 知识“已证明”状态 | **UNSUPPORTED**(需要独立 Prove 协议与证书) |
| 调试器/断点/单步 | **不实现**(首版非目标) |
| Knowledge/Prove/Lint 引擎 | **不实现**(独立仓库/未来可选信息层) |
实际完成状态以 [`docs/STATUS.md`](docs/STATUS.md) 与 CI 证据为准,本文不代替现状。
## 消费者契约
- 未知 `schema_version` → `view.protocol_incompatible`,不回退猜测。
- `sha256(exact analysis.json bytes) == trace.source.analysis_digest`;不匹配 → `view.trace_stale`。
- `trace.source.root_id == analysis.project.root_id`;事件 `module_id` 必须存在于 Analysis。
- `trace.truncated != null` → `TRUNCATED`,不声明全部分支/循环已遍历。
- 运行只使用 `MARQDO_BIN` 子进程与公开 JSON;不链接 Core crate、不读 Core 源码、不依赖私有 IR。
Generated
+528
View File
@@ -0,0 +1,528 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "anstream"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"is_terminal_polyfill",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
[[package]]
name = "anstyle-parse"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
"windows-sys",
]
[[package]]
name = "anstyle-wincon"
version = "3.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
"windows-sys",
]
[[package]]
name = "ascii"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16"
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
"generic-array",
]
[[package]]
name = "caseless"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b6fd507454086c8edfd769ca6ada439193cdb209c7681712ef6275cccbfe5d8"
dependencies = [
"unicode-normalization",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "chunked_transfer"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901"
[[package]]
name = "clap"
version = "4.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "844c5c0b65be192cb68d570cca1b21a6444431d24e39c084dc0336177015337c"
dependencies = [
"clap_builder",
"clap_derive",
]
[[package]]
name = "clap_builder"
version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
dependencies = [
"anstream",
"anstyle",
"clap_lex",
"strsim",
]
[[package]]
name = "clap_derive"
version = "4.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "clap_lex"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79"
[[package]]
name = "colorchoice"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]
name = "comrak"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d981d666dca19afb3cc090dc7c381560cb8ba76582dda6e2c14686ff39fd547f"
dependencies = [
"caseless",
"entities",
"finl_unicode",
"memchr-n",
"phf",
"phf_codegen",
"rustc-hash",
"smallvec",
"typed-arena",
]
[[package]]
name = "cpufeatures"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
dependencies = [
"libc",
]
[[package]]
name = "crypto-common"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
]
[[package]]
name = "entities"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5320ae4c3782150d900b79807611a59a99fc9a1d61d686faafc24b93fc8d7ca"
[[package]]
name = "fastrand"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "fearless_simd"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "629c9d6b6f30b5604089e0980f4d924a013aacb1654a6cdf5d3d852224f68651"
[[package]]
name = "fearless_simd_macros"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e91d94c6885390b81782d7ee60fd6583b33907333a8b340de25ccf468353315"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "finl_unicode"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ded33109e99472f809cb7495544506eea45e366725dacf2a383e184f660456"
[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "httpdate"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]]
name = "itoa"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "log"
version = "0.4.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
[[package]]
name = "marqdo-view"
version = "0.1.0"
dependencies = [
"clap",
"comrak",
"libc",
"semver",
"serde",
"serde_json",
"sha2",
"tiny_http",
]
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "memchr-n"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f48c6352cc1185740af256ccc396af598d2366bfd90a34f5afe48744bf06a5b5"
dependencies = [
"fearless_simd",
"fearless_simd_macros",
]
[[package]]
name = "once_cell_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]]
name = "phf"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6"
dependencies = [
"phf_shared",
"serde",
]
[[package]]
name = "phf_codegen"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41b585a510fb76fdebead6897982ef2a03a21d8e6cbcca904999742a4afc6ffe"
dependencies = [
"phf_generator",
"phf_shared",
]
[[package]]
name = "phf_generator"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100"
dependencies = [
"fastrand",
"phf_shared",
]
[[package]]
name = "phf_shared"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89"
dependencies = [
"siphasher",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rustc-hash"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
[[package]]
name = "semver"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "sha2"
version = "0.10.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "siphasher"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"
[[package]]
name = "smallvec"
version = "1.16.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59"
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tiny_http"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "389915df6413a2e74fb181895f933386023c71110878cd0825588928e64cdc82"
dependencies = [
"ascii",
"chunked_transfer",
"httpdate",
"log",
]
[[package]]
name = "tinyvec"
version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
[[package]]
name = "typed-arena"
version = "2.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6af6ae20167a9ece4bcb41af5b80f8a1f1df981f6391189ce00fd257af04126a"
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "unicode-normalization"
version = "0.1.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d"
dependencies = [
"tinyvec",
]
[[package]]
name = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+32
View File
@@ -0,0 +1,32 @@
[package]
name = "marqdo-view"
version = "0.1.0"
edition = "2021"
rust-version = "1.85"
license = "MIT OR Apache-2.0"
description = "Marqdo View: read .mq.md documents as documents, with optional verified Analysis v2 and Trace v2"
repository = "https://github.com/cflmy/marqdo-view"
readme = "README.md"
keywords = ["marqdo", "markdown", "reader", "executable-document"]
categories = ["command-line-utilities", "documentation"]
[[bin]]
name = "marqdo-view"
path = "src/main.rs"
[dependencies]
clap = { version = "4.5", features = ["derive"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.10"
comrak = { version = "=1.0.0", default-features = false }
semver = "1"
tiny_http = "0.12"
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[profile.release]
lto = "thin"
codegen-units = 1
strip = "symbols"
@@ -13,15 +13,16 @@
## 决策
1. **单一 Rust package**(`Cargo.toml` 只有一个 `[package]`,无 workspace、无内部 crate)。
2. **唯一依赖方向**:
2. **库边界**:`src/lib.rs` 暴露模块以便集成测试与未来 server 复用,`src/main.rs` 只是解析参数、调用 `run()`、打印诊断并退出的薄分派器;这不是第二个渲染/解析入口。
3. **唯一依赖方向**:
`CLI/Server → Application → Domain → ProtocolAdapter`,以及
`Application → Presentation → Renderer → Assets`。
`Domain` 不得引用 HTTP 请求;`Renderer` 不得启动子进程;`reader.js` 不得解释 Marqdo 语义。
3. **唯一渲染入口**:`render.rs::ReaderRenderer::render(&PresentationModel, LinkPolicy)`。Live 与 Export 只差 `LinkPolicy` 与控件可用性;`Command` 层不得自己拼 HTML。
4. **唯一呈现模型**:`presentation.rs::PresentationModel { document, semantic, run, overlays, source_status }`,由 `PresentationBuilder` 从**已验证**类型构建;未验证 JSON 不进入渲染端。
5. **唯一前端主题**:`assets/reader.css`(`@layer reset,tokens,layout,typography,semantics,overlays,interactions,responsive`)+ `assets/reader.js`(只操作 `[data-action]`/`[data-source-id]`/`data-*`)。禁止 `legacy.css`/`new.css` 并行、禁止 `!important` 覆盖链。
6. **唯一用户可见命令层**:`cli.rs` 用 clap 解析 `view` 自身的 `browse/export/verify`;`main.rs` 只做分发。
7. **唯一核心交互**:`core_client.rs::PublicCoreClient` 通过 `MARQDO_BIN` 子进程与公开 JSON 交互;`check --emit` 生成 Analysis v2,`run --trace-file` 生成 Trace v2。禁止链接 CLI crate、读取 CLI 源码、`inspect --ir`。
4. **唯一渲染入口**:`render.rs::ReaderRenderer::render(&PresentationModel, LinkPolicy)`。Live 与 Export 只差 `LinkPolicy` 与控件可用性;`Command` 层不得自己拼 HTML。
5. **唯一呈现模型**:`presentation.rs::PresentationModel { document, semantic, run, overlays, source_status }`,由 `PresentationBuilder` 从**已验证**类型构建;未验证 JSON 不进入渲染端。
6. **唯一前端主题**:`assets/reader.css`(`@layer reset,tokens,layout,typography,semantics,overlays,interactions,responsive`)+ `assets/reader.js`(只操作 `[data-action]`/`[data-source-id]`/`data-*`)。禁止 `legacy.css`/`new.css` 并行、禁止 `!important` 覆盖链。
7. **唯一用户可见命令层**:`cli.rs` 用 clap 解析 `view` 自身的 `browse/export/verify`;`main.rs` 只做分发。
8. **唯一核心交互**:`core_client.rs::PublicCoreClient` 通过 `MARQDO_BIN` 子进程与公开 JSON 交互;`check --emit` 生成 Analysis v2,`run --trace-file` 生成 Trace v2。禁止链接 CLI crate、读取 CLI 源码、`inspect --ir`。
## 后果
+3 -2
View File
@@ -21,7 +21,7 @@
| 阶段 | 状态 | 证据 |
|---|---|---|
| PR-00 基线与旧 View 取证 | **完成** | `docs/audits/legacy-render-paths.md`、`docs/design/visual-tokens.md`、`docs/design/state-matrix.md`、ADR-0001/0002 |
| PR-01 Tool v1 安装闭环 | 未开始 | — |
| PR-01 Tool v1 安装闭环 | **完成** | `tool.json`、`tools/package.sh`、`tools/install-smoke.sh`、`tests/core_contract.rs`、`tests/no_coupling.rs` |
| PR-02 DocumentModel + Analysis v2 浏览 | 未开始 | — |
| PR-03 Reader 视觉重建 | 未开始 | — |
| PR-04 Trace v2 运行可视化 | 未开始 | — |
@@ -31,6 +31,7 @@
## 证据与限制
- 旧 View 运行时状态:`LEGACY_RUNTIME_UNVERIFIED`(旧仓库无预编译产物,且任务禁止修改/编译旧仓库;只做只读静态审计)。
- 本仓库尚未包含可运行实现;在 PR-01 之前 `marqdo view` 不存在。
- PR-01 起 `marqdo view --help/--version/verify` 由本程序提供;`browse`/`export` 仍返回 `view.unsupported`(PR-02/PR-05 落地)。
- 冻结 CLI 安装烟测通过前不得声称 Tool v1 闭环可用;证据由 `tools/install-smoke.sh` 生成。
- 已核对旧视觉资产许可(旧仓库 Apache-2.0):logo/blossom/feather 可复用,KaTeX 不引入。
- 已知非目标:变量运行值、内存快照、调试器、Prove/Knowledge/Lint 引擎(均标 `UNSUPPORTED`)。
+221
View File
@@ -0,0 +1,221 @@
//! Application layer: turns parsed commands into use cases.
//!
//! No HTML is built here; no Markdown is parsed here. Browse uses the single
//! renderer (PR-02+), verify only checks bindings, export only writes static
//! files through the same renderer (PR-05).
use crate::cli::{ExportArgs, RuntimeOpts, VerifyArgs};
use crate::core_client::{CheckOptions, CoreClient};
use crate::error::{ViewError, ViewResult};
use crate::project::Project;
use crate::source_map::sha256_hex;
use crate::version;
pub fn verify(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32> {
let path = args
.path
.clone()
.or_else(|| opts.path.clone())
.unwrap_or_else(|| std::path::PathBuf::from("."));
let project = Project::open(&path)?;
let entry = project.entry().relative.clone();
let source_bytes = project.read_source(&entry)?;
let source_text = String::from_utf8(source_bytes.clone()).map_err(|err| ViewError::Io {
detail: format!("{entry} is not valid UTF-8: {err}"),
})?;
let _ = source_text;
let client = CoreClient::from_env(opts.marqdo_bin.as_deref())?;
let core_version = client.negotiate()?;
let check = client.check(
&project,
&entry,
&CheckOptions {
refs: args.refs,
timeout: None,
},
)?;
let analysis: serde_json::Value =
serde_json::from_slice(&check.analysis_bytes).map_err(|err| ViewError::AnalysisFailed {
detail: format!("emitted Analysis is not JSON: {err}"),
})?;
let summary = validate_static_binding(&analysis, entry.as_str(), &source_bytes)?;
if args.json {
let doc = serde_json::json!({
"schema": "marqdo.view-verify",
"schema_version": 1,
"ok": true,
"core": {
"version": core_version.version.to_string(),
"supported_range": version::PRODUCT_RANGE,
},
"analysis": {
"schema": "marqdo.analysis",
"schema_version": 2,
"digest": check.analysis_digest,
"producer_version": summary.producer_version,
},
"project": {
"root_id": summary.root_id,
"identity_kind": summary.identity_kind,
},
"document": {
"relative_path": entry.as_str(),
"source_digest": summary.source_digest,
"source_digest_matches": true,
},
"result": "PASS",
"executed": false,
"note": "Static verification only; the document was not executed.",
});
println!(
"{}",
serde_json::to_string_pretty(&doc).unwrap_or_else(|_| "{}".to_string())
);
} else {
println!(
"core: marqdo {} (supported {})",
core_version.version,
version::PRODUCT_RANGE
);
println!("project: {} ({})", summary.root_id, summary.identity_kind);
println!("document: {}", entry);
println!(
"analysis: schema=marqdo.analysis v2 modules={} digest={}",
summary.module_count, check.analysis_digest
);
println!("source digest: match");
println!("result: PASS (static only; document not executed)");
}
Ok(0)
}
pub fn export(_opts: &RuntimeOpts, _args: &ExportArgs) -> ViewResult<i32> {
Err(ViewError::Unsupported {
detail: "static export lands with PR-05; this build teaches Tool Protocol and statics only"
.to_string(),
})
}
pub fn browse(_opts: &RuntimeOpts) -> ViewResult<i32> {
Err(ViewError::Unsupported {
detail: "the Live reader lands with PR-02/PR-03; this build teaches Tool Protocol and statics only"
.to_string(),
})
}
struct BindingSummary {
root_id: String,
identity_kind: String,
producer_version: String,
module_count: usize,
source_digest: String,
}
/// Structural binding checks that do not need the full typed projection yet
/// (the typed `SemanticProjection` replaces this in PR-02 without changing the
/// externally visible `verify` result).
fn validate_static_binding(
analysis: &serde_json::Value,
relative_path: &str,
source_bytes: &[u8],
) -> ViewResult<BindingSummary> {
let schema = analysis
.get("schema")
.and_then(|v| v.as_str())
.unwrap_or("");
if schema != "marqdo.analysis" {
return Err(ViewError::ProtocolIncompatible {
detail: format!("unexpected Analysis schema {schema:?}"),
});
}
match analysis.get("schema_version").and_then(|v| v.as_u64()) {
Some(2) => {}
other => {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"Analysis schema_version {other:?} is not supported (View implements v{})",
version::ANALYSIS_PROTOCOL
),
})
}
}
let producer = analysis
.get("producer")
.ok_or_else(|| ViewError::AnalysisFailed {
detail: "Analysis is missing producer".to_string(),
})?;
let producer_version = producer
.get("version")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let markdown_profile = producer
.get("markdown_profile")
.and_then(|v| v.as_str())
.unwrap_or("");
if markdown_profile != "marqdo.md.v1" {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"unexpected Markdown profile {markdown_profile:?}; this View targets marqdo.md.v1"
),
});
}
let project = analysis
.get("project")
.ok_or_else(|| ViewError::AnalysisFailed {
detail: "Analysis is missing project".to_string(),
})?;
let root_id = project
.get("root_id")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
if root_id.is_empty() {
return Err(ViewError::AnalysisFailed {
detail: "Analysis project.root_id is empty".to_string(),
});
}
let identity_kind = project
.get("identity_kind")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let modules = analysis
.get("modules")
.and_then(|v| v.as_array())
.ok_or_else(|| ViewError::AnalysisFailed {
detail: "Analysis is missing modules[]".to_string(),
})?;
let expected_digest = sha256_hex(source_bytes);
let mut matches = 0usize;
for module in modules {
if module.get("relative_path").and_then(|v| v.as_str()) == Some(relative_path) {
matches += 1;
let digest = module
.get("source_digest")
.and_then(|v| v.as_str())
.unwrap_or("");
if digest != expected_digest {
return Err(ViewError::SourceMismatch {
expected: digest.to_string(),
actual: expected_digest,
});
}
}
}
if matches == 0 {
return Err(ViewError::AnalysisFailed {
detail: format!("Analysis has no module for {relative_path}"),
});
}
Ok(BindingSummary {
root_id,
identity_kind,
producer_version,
module_count: modules.len(),
source_digest: expected_digest,
})
}
+197
View File
@@ -0,0 +1,197 @@
//! Command-line surface owned entirely by View.
//!
//! The Core registers this program as the `view` tool and passes the arguments
//! after `view` unchanged. View therefore parses its own subcommands, options
//! and help; the Core never knows about `export`, `verify`, `--out` or
//! `--no-open` (RFC-VIEW-0001 §10.1).
use clap::{Args, Parser, Subcommand};
use std::path::PathBuf;
#[derive(Debug, Parser)]
#[command(
name = "marqdo-view",
version,
about = "Read .mq.md documents as documents: static Analysis v2, optional explicit run Trace v2",
long_about = "Marqdo View renders the original Markdown and attaches verified Analysis v2 facts. \
Running is never implicit: it requires an explicit user action. \
Export is always a pure read-only operation.",
disable_help_subcommand = true,
propagate_version = true
)]
pub struct Cli {
/// A `.mq.md` document or a project directory (default: `.`).
#[arg(value_name = "PATH")]
pub path: Option<PathBuf>,
/// Development only: explicit path to the frozen `marqdo` binary.
/// Installed Tool Protocol runs get the path from `MARQDO_BIN`.
#[arg(long, value_name = "PATH", global = true)]
pub marqdo_bin: Option<PathBuf>,
/// Loopback host for the Live reader (default 127.0.0.1).
#[arg(long, default_value = "127.0.0.1", global = true)]
pub host: String,
/// Port for the Live reader; `0` lets the OS choose and prints the real URL.
#[arg(long, default_value_t = 7429, global = true)]
pub port: u16,
/// Do not open a browser (the full local URL is still printed).
#[arg(long, global = true)]
pub no_open: bool,
/// Advanced: allow a non-loopback bind. No execution API is opened by it.
#[arg(long, global = true, hide = true)]
pub unsafe_expose: bool,
#[command(subcommand)]
pub command: Option<Command>,
}
#[derive(Debug, Subcommand)]
pub enum Command {
/// Write a static, read-only HTML site (never executes the document).
Export(ExportArgs),
/// Check CLI/Analysis/source binding only; never executes.
Verify(VerifyArgs),
}
#[derive(Debug, Args)]
pub struct ExportArgs {
/// A `.mq.md` document or a project directory (default: parent PATH option).
#[arg(value_name = "PATH")]
pub path: Option<PathBuf>,
/// Output directory for the generated site.
#[arg(short = 'o', long = "out", value_name = "DIR")]
pub out: PathBuf,
/// Disable semantic annotations but keep the prose readable.
#[arg(long)]
pub no_annotations: bool,
}
#[derive(Debug, Args)]
pub struct VerifyArgs {
/// A `.mq.md` document or a project directory.
#[arg(value_name = "PATH")]
pub path: Option<PathBuf>,
/// Also validate Markdown link targets (`check --refs`); may fail where the
/// plain syntax check passes.
#[arg(long)]
pub refs: bool,
/// Machine readable JSON on stdout.
#[arg(long)]
pub json: bool,
}
/// Options shared by every command after parsing.
#[derive(Debug, Clone)]
pub struct RuntimeOpts {
pub path: Option<PathBuf>,
pub marqdo_bin: Option<PathBuf>,
pub host: String,
pub port: u16,
pub no_open: bool,
pub unsafe_expose: bool,
}
impl Cli {
pub fn runtime(&self) -> RuntimeOpts {
RuntimeOpts {
path: self.path.clone(),
marqdo_bin: self.marqdo_bin.clone(),
host: self.host.clone(),
port: self.port,
no_open: self.no_open,
unsafe_expose: self.unsafe_expose,
}
}
}
/// First-version bind policy: loopback only unless the hidden advanced flag is
/// given. Even then no execution API becomes reachable without a session token.
pub fn validate_bind(host: &str, unsafe_expose: bool) -> Result<(), String> {
let loopback = matches!(host, "127.0.0.1" | "localhost" | "::1" | "[::1]");
if loopback {
return Ok(());
}
if unsafe_expose {
Ok(())
} else {
Err(format!(
"refusing to bind non-loopback host {host:?}: the Live reader defaults to 127.0.0.1. \
Use --unsafe-expose only if you understand that it exposes read-only pages on your network."
))
}
}
#[cfg(test)]
mod tests {
use super::*;
use clap::Parser;
#[test]
fn parses_browse_defaults() {
let cli = Cli::parse_from(["marqdo-view"]);
assert!(cli.path.is_none());
assert!(cli.command.is_none());
assert_eq!(cli.host, "127.0.0.1");
assert_eq!(cli.port, 7429);
}
#[test]
fn parses_export_subcommand() {
let cli = Cli::parse_from(["marqdo-view", "export", "examples", "--out", "site"]);
match cli.command {
Some(Command::Export(args)) => {
assert_eq!(args.path.unwrap(), PathBuf::from("examples"));
assert_eq!(args.out, PathBuf::from("site"));
assert!(!args.no_annotations);
}
other => panic!("expected export, got {other:?}"),
}
}
#[test]
fn export_requires_out() {
let err = Cli::try_parse_from(["marqdo-view", "export", "examples"]).unwrap_err();
assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument);
}
#[test]
fn parses_verify_and_global_options_anywhere() {
let cli = Cli::parse_from([
"marqdo-view",
"verify",
"index.mq.md",
"--refs",
"--json",
"--marqdo-bin",
"/opt/marqdo",
]);
assert_eq!(
cli.marqdo_bin.as_deref(),
Some(std::path::Path::new("/opt/marqdo"))
);
match cli.command {
Some(Command::Verify(args)) => {
assert!(args.refs);
assert!(args.json);
assert_eq!(args.path.unwrap(), PathBuf::from("index.mq.md"));
}
other => panic!("expected verify, got {other:?}"),
}
}
#[test]
fn bind_policy_is_loopback_by_default() {
assert!(validate_bind("127.0.0.1", false).is_ok());
assert!(validate_bind("localhost", false).is_ok());
assert!(validate_bind("0.0.0.0", false).is_err());
assert!(validate_bind("0.0.0.0", true).is_ok());
}
}
+677
View File
@@ -0,0 +1,677 @@
//! The only way View talks to the frozen CLI.
//!
//! Invariants (RFC-VIEW-0001 §4.2, §10.3, §14.1):
//! * absolute `MARQDO_BIN`, argv arrays, never `sh -c`, never shell strings;
//! * `check --emit` is the only static channel; `run --trace-file --json` the
//! only dynamic one; private Core IR dumps are never used;
//! * stdout/stderr/exit status are handled separately; a stderr JSON blob is
//! never promoted to a successful Analysis;
//! * temporary artifacts live in a private 0700 directory and are removed on
//! drop.
use crate::error::{ViewError, ViewResult};
use crate::project::{Project, SafeRelativePath};
use crate::source_map::{sha256_hex, sha256_prefixed};
use crate::version::{self, CoreVersion};
use serde::{Deserialize, Serialize};
use std::ffi::OsString;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
/// Default View-level wall clock cap for one Core `run`.
pub const DEFAULT_RUN_TIMEOUT: Duration = Duration::from_secs(120);
/// Default View-level wall clock cap for one Core `check`.
pub const DEFAULT_CHECK_TIMEOUT: Duration = Duration::from_secs(120);
const ENV_MARQDO_BIN: &str = "MARQDO_BIN";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SandboxMode {
Pure,
Project,
Strict,
}
impl SandboxMode {
pub fn as_str(&self) -> &'static str {
match self {
SandboxMode::Pure => "pure",
SandboxMode::Project => "project",
SandboxMode::Strict => "strict",
}
}
}
/// Explicit grants assembled only from a user-approved run request. View never
/// reads project capability declarations to derive grants.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Grants {
pub allow_read: Vec<String>,
pub allow_write: Vec<String>,
pub allow_net: Vec<String>,
pub allow_env: Vec<String>,
pub allow_process: Vec<String>,
pub allow_random: bool,
}
#[derive(Debug, Clone, Default)]
pub struct CheckOptions {
/// `--refs` also validates Markdown link targets; it is a stricter check
/// and may fail where plain syntax succeeds.
pub refs: bool,
pub timeout: Option<Duration>,
}
#[derive(Debug, Clone)]
pub struct RunOptions {
pub mode: SandboxMode,
pub grants: Grants,
pub fuel: Option<u64>,
pub stack: Option<u64>,
pub max_output: Option<u64>,
pub timeout_seconds: Option<u64>,
pub view_timeout: Option<Duration>,
pub trace_max_events: Option<u64>,
pub trace_max_bytes: Option<u64>,
}
impl Default for RunOptions {
fn default() -> Self {
Self {
mode: SandboxMode::Pure,
grants: Grants::default(),
fuel: None,
stack: None,
max_output: None,
timeout_seconds: None,
view_timeout: Some(DEFAULT_RUN_TIMEOUT),
trace_max_events: None,
trace_max_bytes: None,
}
}
}
#[derive(Debug)]
pub struct CheckOutput {
/// Exact bytes written by `check --emit`, the digest source of truth.
pub analysis_bytes: Vec<u8>,
/// Lowercase hex SHA-256 of `analysis_bytes`.
pub analysis_sha256: String,
/// Prefixed digest (`sha256:...`) for comparison with Trace v2.
pub analysis_digest: String,
pub stdout: String,
pub stderr: String,
}
#[derive(Debug)]
pub struct RunOutput {
/// Exactly one JSON document emitted on stdout by the Core.
pub json: serde_json::Value,
pub stdout: String,
pub stderr: String,
pub exit_code: i32,
/// Raw Trace v2 bytes when the Core wrote them (even for a failed run).
pub trace_bytes: Option<Vec<u8>>,
pub trace_sha256: Option<String>,
}
/// A private temporary directory for Core artifacts.
pub struct ScratchDir {
path: PathBuf,
}
impl ScratchDir {
pub fn create(label: &str) -> ViewResult<Self> {
let base = std::env::temp_dir();
let unique = format!(
"marqdo-view-{}-{}-{}",
std::process::id(),
unique_counter(),
sanitize_label(label)
);
let path = base.join(unique);
std::fs::create_dir_all(&path)
.map_err(|err| ViewError::io(&format!("create scratch {}", path.display()), err))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700))
.map_err(|err| ViewError::io(&format!("chmod scratch {}", path.display()), err))?;
}
Ok(Self { path })
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn file(&self, name: &str) -> PathBuf {
self.path.join(name)
}
}
impl Drop for ScratchDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
fn unique_counter() -> u64 {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos() as u64)
.unwrap_or(0);
seq ^ nanos.rotate_left(17)
}
fn sanitize_label(label: &str) -> String {
label
.chars()
.map(|ch| if ch.is_ascii_alphanumeric() { ch } else { '-' })
.take(32)
.collect()
}
/// Negotiated public-client for one frozen core binary.
#[derive(Debug, Clone)]
pub struct CoreClient {
bin: PathBuf,
protocol_env: ProtocolEnv,
}
#[derive(Debug, Clone, Default)]
struct ProtocolEnv {
tool: Option<String>,
analysis: Option<String>,
trace: Option<String>,
}
impl CoreClient {
/// Build a client from `--marqdo-bin` (development) or `MARQDO_BIN`
/// (installed Tool Protocol). Never guesses a `PATH` binary: a wrong
/// version must fail loudly, not silently.
pub fn from_env(explicit: Option<&Path>) -> ViewResult<Self> {
let bin = locate_bin(explicit)?;
Self::with_bin(bin)
}
/// Construct from an explicit binary path, still reading any negotiated
/// protocol environment. Useful for `--marqdo-bin` and integration tests;
/// production dispatch should prefer [`CoreClient::from_env`].
pub fn with_bin(bin: impl Into<PathBuf>) -> ViewResult<Self> {
let bin = validate_bin(&bin.into(), "core binary")?;
Ok(Self {
bin,
protocol_env: ProtocolEnv {
tool: std::env::var(version::ENV_TOOL_PROTOCOL).ok(),
analysis: std::env::var(version::ENV_PROTOCOL_ANALYSIS).ok(),
trace: std::env::var(version::ENV_PROTOCOL_TRACE).ok(),
},
})
}
/// Test-only constructor with an explicit binary and no environment
/// negotiation input.
#[cfg(test)]
pub fn for_test(bin: impl Into<PathBuf>) -> Self {
Self {
bin: bin.into(),
protocol_env: ProtocolEnv::default(),
}
}
pub fn bin(&self) -> &Path {
&self.bin
}
/// Run `--version`, validate the product range and any negotiated protocol
/// environment variables. A missing Development-mode env is allowed; an
/// unknown major is a hard error.
pub fn negotiate(&self) -> ViewResult<CoreVersion> {
version::negotiate_protocol_env(
self.protocol_env.tool.as_deref(),
self.protocol_env.analysis.as_deref(),
self.protocol_env.trace.as_deref(),
)?;
let output = self.execute(
&[OsString::from("--version")],
&std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
DEFAULT_CHECK_TIMEOUT,
)?;
if output.exit_code != 0 {
return Err(ViewError::CoreMissing {
detail: format!(
"{} --version failed (exit {}): {}",
self.bin.display(),
output.exit_code,
output.stderr.trim()
),
});
}
let version = version::parse_version_output(&output.stdout)?;
if !version::product_is_compatible(&version.version) {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"core {} is outside the supported range {}",
version.version,
version::PRODUCT_RANGE
),
});
}
Ok(version)
}
/// `check --emit`; on success returns the exact Analysis v2 bytes.
pub fn check(
&self,
project: &Project,
relative: &SafeRelativePath,
options: &CheckOptions,
) -> ViewResult<CheckOutput> {
let entry = project.absolute_for(relative)?;
let scratch = ScratchDir::create("check")?;
let emit = scratch.file("analysis.json");
let mut args = build_check_args(&entry);
// Scratch path is ours; the argument vector is explicit, no shell.
args.push(OsString::from("--emit"));
args.push(emit.clone().into_os_string());
if options.refs {
args.push(OsString::from("--refs"));
}
let output = self.execute(
&args,
project.root(),
options.timeout.unwrap_or(DEFAULT_CHECK_TIMEOUT),
)?;
if output.exit_code != 0 {
return Err(ViewError::AnalysisFailed {
detail: format!(
"`marqdo check` failed with exit code {}: {}",
output.exit_code,
summarize_stderr(&output.stderr)
),
});
}
let analysis_bytes = std::fs::read(&emit).map_err(|err| ViewError::AnalysisFailed {
detail: format!(
"`marqdo check` succeeded but emitted no Analysis at {}: {err}",
emit.display()
),
})?;
if analysis_bytes.is_empty() {
return Err(ViewError::AnalysisFailed {
detail: "`marqdo check` emitted an empty Analysis file".to_string(),
});
}
Ok(CheckOutput {
analysis_sha256: sha256_hex(&analysis_bytes),
analysis_digest: sha256_prefixed(&analysis_bytes),
analysis_bytes,
stdout: output.stdout,
stderr: output.stderr,
})
}
/// `run --trace-file --json`, only after an explicit user confirmation in
/// the calling layer. Returns the CLI JSON document and raw Trace bytes.
pub fn run(
&self,
project: &Project,
relative: &SafeRelativePath,
options: &RunOptions,
) -> ViewResult<RunOutput> {
let entry = project.absolute_for(relative)?;
let scratch = ScratchDir::create("run")?;
let trace_path = scratch.file("trace.json");
let args = build_run_args(&entry, &trace_path, options);
let output = self.execute(
&args,
project.root(),
options.view_timeout.unwrap_or(DEFAULT_RUN_TIMEOUT),
)?;
let json: serde_json::Value =
serde_json::from_slice(&output.stdout_bytes).map_err(|err| ViewError::Io {
detail: format!(
"`marqdo run --json` did not emit exactly one JSON document: {err}; stderr: {}",
summarize_stderr(&output.stderr)
),
})?;
if !json.is_object() {
return Err(ViewError::Io {
detail: "`marqdo run --json` emitted a non-object JSON document".to_string(),
});
}
let trace_bytes = match std::fs::read(&trace_path) {
Ok(bytes) => {
if bytes.is_empty() {
None
} else {
Some(bytes)
}
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => None,
Err(err) => {
return Err(ViewError::io(
&format!("read trace {}", trace_path.display()),
err,
))
}
};
Ok(RunOutput {
json,
stdout: output.stdout,
stderr: output.stderr,
exit_code: output.exit_code,
trace_sha256: trace_bytes.as_deref().map(sha256_hex),
trace_bytes,
})
}
/// Spawn the core with an explicit argv, private cwd and a wall-clock cap.
fn execute(&self, args: &[OsString], cwd: &Path, timeout: Duration) -> ViewResult<ExecOutput> {
let mut command = Command::new(&self.bin);
command
.args(args)
.current_dir(cwd)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
// Put the core in its own process group so a View-level timeout kills
// the whole subtree, not just the immediate shell-less child.
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
// SAFETY: `setpgid` is async-signal-safe and only touches the child
// before exec.
unsafe {
command.pre_exec(|| {
if libc::setpgid(0, 0) != 0 {
return Err(std::io::Error::last_os_error());
}
Ok(())
});
}
}
let mut child = command.spawn().map_err(|err| ViewError::CoreSpawn {
detail: format!("spawn {}: {err}", self.bin.display()),
})?;
let stdout = child.stdout.take().expect("piped stdout");
let stderr = child.stderr.take().expect("piped stderr");
let stdout_thread = std::thread::spawn(move || read_all(stdout));
let stderr_thread = std::thread::spawn(move || read_all(stderr));
let deadline = Instant::now() + timeout;
let status = loop {
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) => {
if Instant::now() >= deadline {
kill_process_tree(&mut child);
let _ = child.wait();
let _ = stdout_thread.join();
let _ = stderr_thread.join();
return Err(ViewError::CoreTimeout {
detail: format!(
"core did not finish within {}s and was killed",
timeout.as_secs()
),
});
}
std::thread::sleep(Duration::from_millis(10));
}
Err(err) => {
let _ = child.kill();
return Err(ViewError::CoreSpawn {
detail: format!("wait for {}: {err}", self.bin.display()),
});
}
}
};
let stdout_bytes = stdout_thread.join().unwrap_or_default();
let stderr_bytes = stderr_thread.join().unwrap_or_default();
let stdout = String::from_utf8_lossy(&stdout_bytes).to_string();
let stderr = String::from_utf8_lossy(&stderr_bytes).to_string();
Ok(ExecOutput {
exit_code: status.code().unwrap_or(-1),
stdout_bytes,
stdout,
stderr,
})
}
}
struct ExecOutput {
exit_code: i32,
stdout_bytes: Vec<u8>,
stdout: String,
stderr: String,
}
/// Kill the core and every descendant in its process group (Unix), or just the
/// direct child elsewhere. Never leaves a runaway subprocess behind.
fn kill_process_tree(child: &mut std::process::Child) {
#[cfg(unix)]
{
let pid = child.id() as i32;
if pid > 0 {
// SAFETY: negative pid targets the process group created by
// pre_exec(setpgid); ESRCH is harmless when it already exited.
unsafe {
libc::kill(-pid, libc::SIGKILL);
}
}
}
let _ = child.kill();
}
fn read_all(mut reader: impl Read) -> Vec<u8> {
let mut bytes = Vec::new();
let _ = reader.read_to_end(&mut bytes);
bytes
}
/// Build the base `check` arguments. The caller appends `--emit <path>` and
/// optionally `--refs`; this function exists so the argv shape is unit-testable.
fn build_check_args(entry: &Path) -> Vec<OsString> {
vec![OsString::from("check"), entry.as_os_str().to_os_string()]
}
/// Build `run` arguments from an already user-approved request.
pub fn build_run_args(entry: &Path, trace_path: &Path, options: &RunOptions) -> Vec<OsString> {
let mut args = vec![
OsString::from("run"),
entry.as_os_str().to_os_string(),
OsString::from("--mode"),
OsString::from(options.mode.as_str()),
OsString::from("--json"),
OsString::from("--trace-file"),
trace_path.as_os_str().to_os_string(),
];
fn push_pair(args: &mut Vec<OsString>, flag: &str, value: &str) {
args.push(OsString::from(flag));
args.push(OsString::from(value));
}
for glob in &options.grants.allow_read {
push_pair(&mut args, "--allow-read", glob);
}
for glob in &options.grants.allow_write {
push_pair(&mut args, "--allow-write", glob);
}
for host in &options.grants.allow_net {
push_pair(&mut args, "--allow-net", host);
}
for name in &options.grants.allow_env {
push_pair(&mut args, "--allow-env", name);
}
for program in &options.grants.allow_process {
push_pair(&mut args, "--allow-process", program);
}
if options.grants.allow_random {
args.push(OsString::from("--allow-random"));
}
if let Some(fuel) = options.fuel {
push_pair(&mut args, "--fuel", &fuel.to_string());
}
if let Some(stack) = options.stack {
push_pair(&mut args, "--stack", &stack.to_string());
}
if let Some(max_output) = options.max_output {
push_pair(&mut args, "--max-output", &max_output.to_string());
}
if let Some(timeout) = options.timeout_seconds {
push_pair(&mut args, "--timeout", &timeout.to_string());
}
if let Some(max_events) = options.trace_max_events {
push_pair(&mut args, "--trace-max-events", &max_events.to_string());
}
if let Some(max_bytes) = options.trace_max_bytes {
push_pair(&mut args, "--trace-max-bytes", &max_bytes.to_string());
}
args
}
fn locate_bin(explicit: Option<&Path>) -> ViewResult<PathBuf> {
if let Some(path) = explicit {
return validate_bin(path, "--marqdo-bin");
}
if let Some(raw) = std::env::var_os(ENV_MARQDO_BIN) {
if raw.is_empty() {
return Err(ViewError::CoreMissing {
detail: format!("{ENV_MARQDO_BIN} is set but empty"),
});
}
return validate_bin(Path::new(&raw), ENV_MARQDO_BIN);
}
Err(ViewError::CoreMissing {
detail: format!(
"{ENV_MARQDO_BIN} is not set. Install this tool with `marqdo tool install <bundle>/tool.json`, \
or pass --marqdo-bin <path> when running marqdo-view directly."
),
})
}
fn validate_bin(path: &Path, origin: &str) -> ViewResult<PathBuf> {
let canonical = path.canonicalize().map_err(|err| ViewError::CoreMissing {
detail: format!("{origin} points to {}: {err}", path.display()),
})?;
let metadata = std::fs::metadata(&canonical).map_err(|err| ViewError::CoreMissing {
detail: format!("{origin} points to {}: {err}", canonical.display()),
})?;
if !metadata.is_file() {
return Err(ViewError::CoreMissing {
detail: format!("{origin} {} is not a regular file", canonical.display()),
});
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if metadata.permissions().mode() & 0o111 == 0 {
return Err(ViewError::CoreMissing {
detail: format!("{origin} {} is not executable", canonical.display()),
});
}
}
Ok(canonical)
}
fn summarize_stderr(stderr: &str) -> String {
let trimmed = stderr.trim();
if trimmed.is_empty() {
"(no stderr)".to_string()
} else {
let mut text: String = trimmed.chars().take(1200).collect();
if trimmed.chars().count() > 1200 {
text.push('…');
}
text
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn run_args_are_explicit_argv_never_shell() {
let args = build_run_args(
Path::new("/p/index.mq.md"),
Path::new("/t/trace.json"),
&RunOptions {
mode: SandboxMode::Pure,
grants: Grants {
allow_read: vec!["data/**".into()],
allow_net: vec!["example.com".into()],
..Default::default()
},
fuel: Some(1000),
trace_max_events: Some(20),
..Default::default()
},
);
let text: Vec<String> = args
.iter()
.map(|arg| arg.to_string_lossy().to_string())
.collect();
assert_eq!(text[0], "run");
assert_eq!(text[1], "/p/index.mq.md");
assert!(text.contains(&"pure".to_string()));
assert!(text.contains(&"--json".to_string()));
assert!(text.contains(&"--trace-file".to_string()));
assert!(text.contains(&"data/**".to_string()));
assert!(text.contains(&"example.com".to_string()));
assert!(text.contains(&"1000".to_string()));
assert!(text.contains(&"20".to_string()));
// No token is a shell fragment: every argument is a separate value.
assert!(!text
.iter()
.any(|t| t.contains(';') || t.contains('|') || t.contains('&')));
}
#[test]
fn check_args_are_plain_argv() {
let args = build_check_args(Path::new("/p/index.mq.md"));
assert_eq!(args[0], OsString::from("check"));
assert_eq!(args[1], OsString::from("/p/index.mq.md"));
assert_eq!(args.len(), 2);
}
#[test]
fn missing_bin_has_stable_code() {
let err = locate_bin(Some(Path::new("/definitely/not/here/marqdo"))).unwrap_err();
assert_eq!(err.code(), "view.core_missing");
assert_eq!(err.exit_code(), 2);
}
#[test]
fn scratch_dir_is_private_and_removed() {
let scratch = ScratchDir::create("unit").unwrap();
let path = scratch.path().to_path_buf();
assert!(path.is_dir());
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(&path).unwrap().permissions().mode();
assert_eq!(mode & 0o777, 0o700);
}
drop(scratch);
assert!(!path.exists());
}
#[test]
fn stderr_summary_is_bounded() {
let text = summarize_stderr(&"x".repeat(5000));
assert!(text.chars().count() <= 1201);
assert_eq!(summarize_stderr(" "), "(no stderr)");
}
}
+171
View File
@@ -0,0 +1,171 @@
//! Stable View-owned error kinds.
//!
//! Every failure that reaches the user has exactly one stable machine code
//! (`view.*`), an exit code class and a `source` field so Core diagnostics can
//! never be mistaken for View diagnostics. See RFC-VIEW-0001 §10.2.
use std::fmt;
/// Exit code 0: success. Exit code 1: runtime/I/O failure. Exit code 2:
/// argument, protocol or permission failure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExitClass {
Runtime,
Argument,
}
#[derive(Debug)]
pub enum ViewError {
/// `MARQDO_BIN` unset, missing, or not executable.
CoreMissing { detail: String },
/// Tool/Analysis/Trace protocol or product range mismatch.
ProtocolIncompatible { detail: String },
/// Core `check` failed; prose stays readable but semantics are unusable.
AnalysisFailed { detail: String },
/// Analysis `source_digest` does not match the current source bytes.
SourceMismatch { expected: String, actual: String },
/// A Core byte span is out of range or not on a UTF-8 boundary.
SourceSpanInvalid { detail: String },
/// Trace does not bind to the current Analysis bytes.
TraceStale { detail: String },
/// The user did not confirm, or the requested mode/grants are not allowed.
RunDenied { detail: String },
/// Path escapes the allowed project root or is otherwise forbidden.
PathForbidden { detail: String },
/// Refused a bind address that is not explicitly allowed.
BindDenied { detail: String },
/// Embedded asset digest mismatch (build/package integrity).
AssetIntegrity { detail: String },
/// Export target is unsafe or the write failed.
ExportFailed { detail: String },
/// A configured resource limit was exceeded.
ResourceLimit { detail: String },
/// Core subprocess could not be spawned.
CoreSpawn { detail: String },
/// Core subprocess exceeded the View-level timeout and was killed.
CoreTimeout { detail: String },
/// Local file system / HTTP I/O failure.
Io { detail: String },
/// Feature intentionally not implemented in this build (honest status).
Unsupported { detail: String },
}
impl ViewError {
pub fn code(&self) -> &'static str {
match self {
ViewError::CoreMissing { .. } => "view.core_missing",
ViewError::ProtocolIncompatible { .. } => "view.protocol_incompatible",
ViewError::AnalysisFailed { .. } => "view.analysis_failed",
ViewError::SourceMismatch { .. } => "view.source_mismatch",
ViewError::SourceSpanInvalid { .. } => "view.source_span_invalid",
ViewError::TraceStale { .. } => "view.trace_stale",
ViewError::RunDenied { .. } => "view.run_denied",
ViewError::PathForbidden { .. } => "view.path_forbidden",
ViewError::BindDenied { .. } => "view.bind_denied",
ViewError::AssetIntegrity { .. } => "view.asset_integrity",
ViewError::ExportFailed { .. } => "view.export_failed",
ViewError::ResourceLimit { .. } => "view.resource_limit",
ViewError::CoreSpawn { .. } => "view.core_spawn",
ViewError::CoreTimeout { .. } => "view.core_timeout",
ViewError::Io { .. } => "view.io",
ViewError::Unsupported { .. } => "view.unsupported",
}
}
pub fn exit_class(&self) -> ExitClass {
match self {
ViewError::CoreMissing { .. }
| ViewError::ProtocolIncompatible { .. }
| ViewError::RunDenied { .. }
| ViewError::PathForbidden { .. }
| ViewError::BindDenied { .. }
| ViewError::SourceSpanInvalid { .. }
| ViewError::Unsupported { .. } => ExitClass::Argument,
_ => ExitClass::Runtime,
}
}
pub fn exit_code(&self) -> i32 {
match self.exit_class() {
ExitClass::Runtime => 1,
ExitClass::Argument => 2,
}
}
/// `core` is used only for diagnostics that came from the frozen CLI.
pub fn source(&self) -> &'static str {
"view"
}
/// JSON diagnostic with `source:"view"` so it can never masquerade as a
/// Core diagnostic. Contains no absolute machine paths beyond what the
/// caller already supplied.
pub fn to_json(&self) -> serde_json::Value {
serde_json::json!({
"schema": "marqdo.view-error",
"schema_version": 1,
"code": self.code(),
"source": self.source(),
"message": self.detail(),
"exit_code": self.exit_code(),
})
}
pub fn detail(&self) -> &str {
match self {
ViewError::CoreMissing { detail }
| ViewError::ProtocolIncompatible { detail }
| ViewError::AnalysisFailed { detail }
| ViewError::SourceSpanInvalid { detail }
| ViewError::TraceStale { detail }
| ViewError::RunDenied { detail }
| ViewError::PathForbidden { detail }
| ViewError::BindDenied { detail }
| ViewError::AssetIntegrity { detail }
| ViewError::ExportFailed { detail }
| ViewError::ResourceLimit { detail }
| ViewError::CoreSpawn { detail }
| ViewError::CoreTimeout { detail }
| ViewError::Io { detail }
| ViewError::Unsupported { detail } => detail,
ViewError::SourceMismatch { expected, actual } => {
// Cannot return a formatted &str; handled in Display instead.
let _ = (expected, actual);
"source digest mismatch"
}
}
}
}
impl fmt::Display for ViewError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ViewError::SourceMismatch { expected, actual } => write!(
f,
"{}: source digest mismatch (expected {expected}, actual {actual})",
self.code()
),
other => write!(f, "{}: {}", other.code(), other.detail()),
}
}
}
impl std::error::Error for ViewError {}
impl From<std::io::Error> for ViewError {
fn from(err: std::io::Error) -> Self {
ViewError::Io {
detail: err.to_string(),
}
}
}
pub type ViewResult<T> = Result<T, ViewError>;
impl ViewError {
pub fn io(context: &str, err: std::io::Error) -> Self {
ViewError::Io {
detail: format!("{context}: {err}"),
}
}
}
+30
View File
@@ -0,0 +1,30 @@
//! marqdo-view library: a single package with one presentation pipeline.
//!
//! Layer direction (RFC-VIEW-0001 §6.1):
//! `CLI/Server → Application → Domain → ProtocolAdapter`, and
//! `Application → Presentation → Renderer → Assets`.
//! `main.rs` is only a dispatcher; integration tests and future server code use
//! this library so there is never a second renderer or a second parser.
pub mod app;
pub mod cli;
pub mod core_client;
pub mod error;
pub mod project;
pub mod source_map;
pub mod version;
pub use cli::Cli;
pub use error::{ViewError, ViewResult};
/// Dispatch a parsed CLI invocation. Returns the process exit code.
pub fn run(cli: Cli) -> ViewResult<i32> {
let opts = cli.runtime();
cli::validate_bind(&opts.host, opts.unsafe_expose)
.map_err(|detail| ViewError::BindDenied { detail })?;
match cli.command {
Some(cli::Command::Verify(args)) => app::verify(&opts, &args),
Some(cli::Command::Export(args)) => app::export(&opts, &args),
None => app::browse(&opts),
}
}
+15
View File
@@ -0,0 +1,15 @@
//! Thin binary entry point: parse arguments, dispatch through the library,
//! print one stable diagnostic and exit with the View-owned exit code.
use clap::Parser;
fn main() {
let cli = marqdo_view::Cli::parse();
match marqdo_view::run(cli) {
Ok(code) => std::process::exit(code),
Err(err) => {
eprintln!("{err}");
std::process::exit(err.exit_code());
}
}
}
+398
View File
@@ -0,0 +1,398 @@
//! Project-root and path boundary enforcement.
//!
//! Production, HTTP, Export and tests all use these functions; there is no
//! second path validator (RFC-VIEW-0001 §14.4).
use crate::error::{ViewError, ViewResult};
use crate::source_map::sha256_hex;
use std::path::{Path, PathBuf};
/// Hard cap on one source document, matching the Core read limit family.
pub const MAX_SOURCE_BYTES: u64 = 8 * 1024 * 1024;
/// Hard cap on discovered documents per project to bound scans.
pub const MAX_DOCUMENTS: usize = 5_000;
/// Directories never scanned for documents (VCS, caches, build output).
pub const SKIP_DIRS: &[&str] = &[
".git",
".marqdo",
".hg",
".svn",
"node_modules",
"target",
"dist",
];
/// A project-relative path that is safe to join under a project root.
///
/// Rejects absolute paths, `..`, root/prefix components, NUL and control bytes.
/// Backslashes are normalized to `/` so a Windows-style input can never be
/// reinterpreted as a separator by the OS while looking harmless here.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SafeRelativePath(String);
impl SafeRelativePath {
pub fn parse(raw: &str) -> ViewResult<Self> {
if raw.is_empty() {
return Err(ViewError::PathForbidden {
detail: "empty relative path".to_string(),
});
}
if raw.contains('\0') {
return Err(ViewError::PathForbidden {
detail: "path contains NUL".to_string(),
});
}
if raw.chars().any(|ch| ch.is_control()) {
return Err(ViewError::PathForbidden {
detail: "path contains control characters".to_string(),
});
}
let normalized = raw.replace('\\', "/");
if normalized.starts_with('/') {
return Err(ViewError::PathForbidden {
detail: format!("absolute path is not a project-relative path: {raw:?}"),
});
}
if normalized
.split('/')
.next()
.map(|first| first.len() == 2 && first.ends_with(':'))
.unwrap_or(false)
{
return Err(ViewError::PathForbidden {
detail: format!("drive-absolute path is not allowed: {raw:?}"),
});
}
let mut parts = Vec::new();
for part in normalized.split('/') {
if part.is_empty() || part == "." {
continue;
}
if part == ".." {
return Err(ViewError::PathForbidden {
detail: format!("path escapes the project root: {raw:?}"),
});
}
parts.push(part);
}
if parts.is_empty() {
return Err(ViewError::PathForbidden {
detail: "path does not name a file".to_string(),
});
}
Ok(Self(parts.join("/")))
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn to_path(&self) -> PathBuf {
PathBuf::from(self.0.replace('/', std::path::MAIN_SEPARATOR_STR))
}
pub fn file_name(&self) -> &str {
self.0.rsplit('/').next().unwrap_or(&self.0)
}
pub fn parent(&self) -> Option<SafeRelativePath> {
self.0
.rsplit_once('/')
.map(|(parent, _)| SafeRelativePath(parent.to_string()))
}
}
impl std::fmt::Display for SafeRelativePath {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
/// One resolved document inside a project.
#[derive(Debug, Clone)]
pub struct DocumentRef {
pub relative: SafeRelativePath,
pub absolute: PathBuf,
}
/// An opened project root (directory) and its selected entry document.
#[derive(Debug, Clone)]
pub struct Project {
root: PathBuf,
entry: DocumentRef,
}
impl Project {
/// Open `path` (file or directory) and select the entry document.
///
/// File input: the project root is the nearest ancestor containing
/// `marqdo.yaml`, else the file's own directory.
/// Directory input: the directory is the root; `index.mq.md` wins, else the
/// first document in stable sorted order (RFC-VIEW-0001 §9.4).
pub fn open(path: &Path) -> ViewResult<Self> {
let canonical = canonicalize(path, "project path")?;
let metadata = std::fs::metadata(&canonical)
.map_err(|err| ViewError::io(&format!("stat {}", canonical.display()), err))?;
if metadata.is_file() {
let root = discover_project_root(&canonical);
let project = Self {
entry: DocumentRef {
relative: SafeRelativePath("placeholder".to_string()),
absolute: canonical.clone(),
},
root,
};
let relative = project.relative_for(&canonical)?;
Ok(Self {
root: project.root,
entry: DocumentRef {
relative,
absolute: canonical,
},
})
} else if metadata.is_dir() {
let project = Self {
root: canonical.clone(),
entry: DocumentRef {
relative: SafeRelativePath("placeholder".to_string()),
absolute: canonical.clone(),
},
};
let documents = project.list_documents()?;
let chosen = choose_entry(&project.root, &documents)?;
Ok(Self {
root: project.root,
entry: chosen,
})
} else {
Err(ViewError::PathForbidden {
detail: format!("{} is not a regular file or directory", path.display()),
})
}
}
pub fn root(&self) -> &Path {
&self.root
}
pub fn entry(&self) -> &DocumentRef {
&self.entry
}
/// Resolve an absolute path under the root into a safe relative path.
pub fn relative_for(&self, absolute: &Path) -> ViewResult<SafeRelativePath> {
let canonical = canonicalize(absolute, "document path")?;
if !canonical.starts_with(&self.root) {
return Err(ViewError::PathForbidden {
detail: format!(
"document {} is outside project root {}",
canonical.display(),
self.root.display()
),
});
}
let relative =
canonical
.strip_prefix(&self.root)
.map_err(|_| ViewError::PathForbidden {
detail: "document path is not under the project root".to_string(),
})?;
SafeRelativePath::parse(&relative.to_string_lossy())
}
/// Absolute path for a safe relative path, with a final real-path check.
pub fn absolute_for(&self, relative: &SafeRelativePath) -> ViewResult<PathBuf> {
let joined = self.root.join(relative.to_path());
let canonical = canonicalize(&joined, "document path")?;
if !canonical.starts_with(&self.root) {
return Err(ViewError::PathForbidden {
detail: format!("{} escapes the project root", relative),
});
}
Ok(canonical)
}
/// Read exact source bytes. Never normalizes line endings or Unicode.
pub fn read_source(&self, relative: &SafeRelativePath) -> ViewResult<Vec<u8>> {
let absolute = self.absolute_for(relative)?;
let metadata = std::fs::metadata(&absolute)
.map_err(|err| ViewError::io(&format!("stat {}", absolute.display()), err))?;
if !metadata.is_file() {
return Err(ViewError::PathForbidden {
detail: format!("{} is not a regular file", relative),
});
}
if metadata.len() > MAX_SOURCE_BYTES {
return Err(ViewError::ResourceLimit {
detail: format!(
"{} is {} bytes, above the {} byte View limit",
relative,
metadata.len(),
MAX_SOURCE_BYTES
),
});
}
std::fs::read(&absolute)
.map_err(|err| ViewError::io(&format!("read {}", absolute.display()), err))
}
/// Read one document as UTF-8 text.
pub fn read_source_text(&self, relative: &SafeRelativePath) -> ViewResult<String> {
let bytes = self.read_source(relative)?;
String::from_utf8(bytes).map_err(|err| ViewError::Io {
detail: format!("{} is not valid UTF-8: {err}", relative),
})
}
/// Stable sorted list of `*.mq.md` documents under the root.
pub fn list_documents(&self) -> ViewResult<Vec<SafeRelativePath>> {
let mut out = Vec::new();
let mut stack = vec![self.root.clone()];
while let Some(dir) = stack.pop() {
let mut entries = Vec::new();
for entry in std::fs::read_dir(&dir)
.map_err(|err| ViewError::io(&format!("read dir {}", dir.display()), err))?
{
entries.push(entry.map_err(|err| ViewError::io("read dir entry", err))?);
}
entries.sort_by_key(|entry| entry.file_name());
for entry in entries {
let file_type = entry
.file_type()
.map_err(|err| ViewError::io("file type", err))?;
if file_type.is_symlink() {
// Never follow links while scanning; explicit file input is
// canonicalized and boundary-checked separately.
continue;
}
let path = entry.path();
if file_type.is_dir() {
let name = entry.file_name();
let name = name.to_string_lossy();
if SKIP_DIRS.contains(&name.as_ref()) {
continue;
}
stack.push(path);
continue;
}
if file_type.is_file() && is_marqdo_document(&path) {
let relative = self.relative_for(&path)?;
out.push(relative);
if out.len() > MAX_DOCUMENTS {
return Err(ViewError::ResourceLimit {
detail: format!(
"more than {MAX_DOCUMENTS} documents under project root"
),
});
}
}
}
}
out.sort();
Ok(out)
}
/// Resolve a browser-facing relative path to a document reference.
pub fn document(&self, relative: &SafeRelativePath) -> ViewResult<DocumentRef> {
Ok(DocumentRef {
relative: relative.clone(),
absolute: self.absolute_for(relative)?,
})
}
/// `source_digest` of the exact bytes, matching Analysis `source_digest`.
pub fn source_digest(&self, relative: &SafeRelativePath) -> ViewResult<String> {
Ok(sha256_hex(&self.read_source(relative)?))
}
}
/// Discover the project root for a source file: nearest ancestor with
/// `marqdo.yaml`, else the file's directory. The file itself is canonical.
pub fn discover_project_root(file: &Path) -> PathBuf {
let start = file.parent().unwrap_or_else(|| Path::new("/"));
for ancestor in start.ancestors() {
if ancestor.join("marqdo.yaml").is_file() {
return ancestor.to_path_buf();
}
}
start.to_path_buf()
}
pub fn is_marqdo_document(path: &Path) -> bool {
path.file_name()
.and_then(|name| name.to_str())
.map(|name| name.ends_with(".mq.md"))
.unwrap_or(false)
}
fn choose_entry(root: &Path, documents: &[SafeRelativePath]) -> ViewResult<DocumentRef> {
if documents.is_empty() {
return Err(ViewError::PathForbidden {
detail: format!("no .mq.md documents under {}", root.display()),
});
}
if let Some(index) = documents.iter().find(|doc| doc.as_str() == "index.mq.md") {
return Ok(DocumentRef {
relative: index.clone(),
absolute: root.join(index.to_path()),
});
}
let first = documents[0].clone();
Ok(DocumentRef {
relative: first.clone(),
absolute: root.join(first.to_path()),
})
}
fn canonicalize(path: &Path, what: &str) -> ViewResult<PathBuf> {
// CLI arguments may legitimately contain `..`; the security boundary is
// the canonicalized result staying under the canonicalized project root.
// Browser/Export never reach this layer with raw user input: they must go
// through `SafeRelativePath` first.
path.canonicalize()
.map_err(|err| ViewError::io(&format!("canonicalize {} ({what})", path.display()), err))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rejects_unsafe_relative_paths() {
for raw in [
"",
"/etc/passwd",
"../secret",
"a/../../b",
"a\0b",
"a\nb",
"..",
".",
] {
assert!(
SafeRelativePath::parse(raw).is_err(),
"expected rejection for {raw:?}"
);
}
}
#[test]
fn normalizes_harmless_forms() {
assert_eq!(
SafeRelativePath::parse("./docs/../x").unwrap_err().code(),
"view.path_forbidden"
);
assert_eq!(
SafeRelativePath::parse("./docs/index.mq.md")
.unwrap()
.as_str(),
"docs/index.mq.md"
);
assert_eq!(
SafeRelativePath::parse("docs\\index.mq.md")
.unwrap()
.as_str(),
"docs/index.mq.md"
);
}
}
+253
View File
@@ -0,0 +1,253 @@
//! Exact UTF-8 byte ↔ line/column ↔ JavaScript UTF-16 offset mapping.
//!
//! Core Analysis/Trace spans are half-open UTF-8 **byte** offsets into the
//! original file bytes. Browsers count UTF-16 code units. This module is the
//! only place that converts between them (RFC-VIEW-0001 §8.2).
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
/// Half-open byte span `[start, end)` into one module's exact source bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct SourceSpan {
pub start: u64,
pub end: u64,
}
impl SourceSpan {
pub fn new(start: u64, end: u64) -> Self {
Self { start, end }
}
pub fn is_empty(&self) -> bool {
self.start == self.end
}
pub fn len(&self) -> u64 {
self.end.saturating_sub(self.start)
}
pub fn contains(&self, other: SourceSpan) -> bool {
self.start <= other.start && other.end <= self.end
}
pub fn intersects(&self, other: SourceSpan) -> bool {
self.start < other.end && other.start < self.end
}
pub fn as_usize_range(&self) -> Option<std::ops::Range<usize>> {
let start = usize::try_from(self.start).ok()?;
let end = usize::try_from(self.end).ok()?;
if start > end {
return None;
}
Some(start..end)
}
}
/// Compute lowercase hex SHA-256 of exact bytes (no normalization).
pub fn sha256_hex(bytes: &[u8]) -> String {
let mut hasher = Sha256::new();
hasher.update(bytes);
let digest = hasher.finalize();
let mut out = String::with_capacity(64);
for byte in digest {
use std::fmt::Write as _;
let _ = write!(out, "{byte:02x}");
}
out
}
/// SHA-256 with the `sha256:` prefix used by Analysis/Trace identity fields.
pub fn sha256_prefixed(bytes: &[u8]) -> String {
format!("sha256:{}", sha256_hex(bytes))
}
/// Immutable source index built from the exact original bytes.
#[derive(Debug, Clone)]
pub struct SourceIndex {
/// Byte length of the source.
len: usize,
/// Byte offset of the start of every line (0-based line number).
line_starts: Vec<usize>,
/// Number of leading UTF-8 BOM bytes tolerated before the first content
/// byte. Spans in Analysis are relative to the file bytes, so the BOM
/// stays part of the index.
bom_len: usize,
}
impl SourceIndex {
pub fn new(source: &str) -> Self {
let bytes = source.as_bytes();
let bom_len = if source.starts_with('\u{feff}') { 3 } else { 0 };
let mut line_starts = vec![0usize];
let mut index = bom_len;
while index < bytes.len() {
if bytes[index] == b'\n' {
line_starts.push(index + 1);
}
index += 1;
}
Self {
len: bytes.len(),
line_starts,
bom_len,
}
}
pub fn len(&self) -> usize {
self.len
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
pub fn bom_len(&self) -> usize {
self.bom_len
}
pub fn source_text<'a>(&self, source: &'a str, span: SourceSpan) -> Option<&'a str> {
if !self.validate_span_bytes(source.as_bytes(), span) {
return None;
}
let range = span.as_usize_range()?;
source.get(range)
}
/// True when the span is in range and both ends are UTF-8 code-point
/// boundaries of the supplied original bytes.
pub fn validate_span_bytes(&self, bytes: &[u8], span: SourceSpan) -> bool {
let (Ok(start), Ok(end)) = (usize::try_from(span.start), usize::try_from(span.end)) else {
return false;
};
if start > end || end > bytes.len() {
return false;
}
is_char_boundary(bytes, start) && is_char_boundary(bytes, end)
}
/// 1-based line and 1-based byte column for a byte offset, clamped to the
/// file length. Column counts bytes, matching Core's presentation fields.
pub fn line_col(&self, byte: usize) -> (usize, usize) {
let byte = byte.min(self.len);
let line_index = match self.line_starts.binary_search(&byte) {
Ok(found) => found,
Err(insert) => insert.saturating_sub(1),
};
let line_start = self.line_starts[line_index];
(line_index + 1, byte - line_start + 1)
}
/// Byte offset → number of UTF-16 code units before it (JS string index).
pub fn utf16_offset(&self, source: &str, byte: usize) -> Option<usize> {
if byte > source.len() || !is_char_boundary(source.as_bytes(), byte) {
return None;
}
Some(source[..byte].encode_utf16().count())
}
/// Byte offset for a UTF-16 offset, only when it lands on a boundary.
pub fn byte_for_utf16(&self, source: &str, utf16: usize) -> Option<usize> {
let mut units = 0usize;
for (byte, ch) in source.char_indices() {
if units == utf16 {
return Some(byte);
}
if units > utf16 {
return None;
}
units += ch.len_utf16();
}
if units == utf16 {
Some(source.len())
} else {
None
}
}
/// True when an arbitrary `(line, column)` from a Core diagnostic is inside
/// the source index; line/column are presentation hints, spans are primary.
pub fn line_col_in_range(&self, line: u64, column: u64) -> bool {
let Ok(line) = usize::try_from(line) else {
return false;
};
let Ok(column) = usize::try_from(column) else {
return false;
};
if line == 0 || column == 0 || line > self.line_starts.len() {
return false;
}
let start = self.line_starts[line - 1];
let end = self.line_starts.get(line).copied().unwrap_or(self.len);
start + column - 1 <= end
}
}
fn is_char_boundary(bytes: &[u8], offset: usize) -> bool {
if offset == 0 || offset >= bytes.len() {
return offset <= bytes.len();
}
// UTF-8 continuation bytes start with 0b10.
bytes[offset] & 0b1100_0000 != 0b1000_0000
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn maps_multibyte_and_emoji_offsets() {
let source = "中文\nemoji🙂x\r\nlast";
let index = SourceIndex::new(source);
let emoji_byte = source.find('🙂').unwrap();
assert_eq!(index.line_col(emoji_byte), (2, 6));
let utf16 = index.utf16_offset(source, emoji_byte).unwrap();
assert_eq!(index.byte_for_utf16(source, utf16), Some(emoji_byte));
// Inside the emoji is not a char boundary.
assert!(index.utf16_offset(source, emoji_byte + 1).is_none());
let span = SourceSpan::new(emoji_byte as u64, (emoji_byte + 4) as u64);
assert_eq!(index.source_text(source, span), Some("🙂"));
}
#[test]
fn rejects_out_of_range_and_misaligned_spans() {
let source = "# 数学";
let index = SourceIndex::new(source);
assert!(
index.validate_span_bytes(source.as_bytes(), SourceSpan::new(0, source.len() as u64))
);
assert!(!index.validate_span_bytes(
source.as_bytes(),
SourceSpan::new(0, source.len() as u64 + 1)
));
assert!(!index.validate_span_bytes(source.as_bytes(), SourceSpan::new(2, 1)));
// 2 is the middle of the 3-byte 字/数? Either way it is not a boundary
// for the CJK character starting at 2..5; check the interior byte 3.
assert!(!index.validate_span_bytes(source.as_bytes(), SourceSpan::new(3, 5)));
}
#[test]
fn digest_is_exact_bytes() {
assert_eq!(
sha256_hex(b""),
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
);
assert_eq!(
sha256_prefixed(b"a"),
"sha256:ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb"
);
}
#[test]
fn bom_is_still_indexed() {
let source = "\u{feff}# hi";
let index = SourceIndex::new(source);
assert_eq!(index.bom_len(), 3);
assert_eq!(index.line_col(3), (1, 4));
assert_eq!(
index.source_text(source, SourceSpan::new(0, 3)),
Some("\u{feff}")
);
}
}
+149
View File
@@ -0,0 +1,149 @@
//! Product/protocol version negotiation with the frozen CLI.
//!
//! Version axes are independent (RFC-VIEW-0001 §4): product SemVer,
//! Analysis major, Trace major and Tool protocol. We never infer one from
//! another and never silently fall back to a latest-looking JSON.
use crate::error::{ViewError, ViewResult};
use semver::Version;
/// Product range this View build targets. Must match `tool.json`.
pub const PRODUCT_RANGE: &str = ">=3.0.0-beta.1,<4.0.0";
/// Lowest compatible product version (inclusive).
pub const MIN_PRODUCT: &str = "3.0.0-beta.1";
pub const TOOL_PROTOCOL: u32 = 1;
pub const ANALYSIS_PROTOCOL: u32 = 2;
pub const TRACE_PROTOCOL: u32 = 2;
/// Environment variables injected by CLI Tool Protocol v1.
pub const ENV_MARQDO_BIN: &str = "MARQDO_BIN";
pub const ENV_TOOL_PROTOCOL: &str = "MARQDO_TOOL_PROTOCOL";
pub const ENV_PROTOCOL_ANALYSIS: &str = "MARQDO_PROTOCOL_ANALYSIS";
pub const ENV_PROTOCOL_TRACE: &str = "MARQDO_PROTOCOL_TRACE";
#[derive(Debug, Clone)]
pub struct CoreVersion {
pub version: Version,
/// Exact `marqdo --version` first line, kept for evidence output.
pub raw: String,
}
/// Parse the output of `marqdo --version` (`marqdo 3.0.0-beta.1`).
pub fn parse_version_output(output: &str) -> ViewResult<CoreVersion> {
let line = output
.lines()
.map(str::trim)
.find(|line| !line.is_empty())
.ok_or_else(|| ViewError::ProtocolIncompatible {
detail: "core printed no version text".to_string(),
})?;
let token = line
.split_whitespace()
.last()
.ok_or_else(|| ViewError::ProtocolIncompatible {
detail: format!("cannot parse core version from {line:?}"),
})?;
let version = Version::parse(token).map_err(|err| ViewError::ProtocolIncompatible {
detail: format!("core version {token:?} is not SemVer: {err}"),
})?;
Ok(CoreVersion {
version,
raw: line.to_string(),
})
}
/// True when `version` is inside the product range without relying on
/// prerelease quirks of `semver::VersionReq`: any 3.x at or above the first
/// beta is accepted, so a later `3.1.0-beta.1` keeps working.
pub fn product_is_compatible(version: &Version) -> bool {
let min = Version::parse(MIN_PRODUCT).expect("MIN_PRODUCT is valid SemVer");
version.major == 3 && version >= &min
}
/// Validate the negotiated environment for Tool Protocol v1.
///
/// Absence of `MARQDO_PROTOCOL_*` is allowed for a directly-run development
/// binary (`--marqdo-bin`), but presence of an unknown major is a hard error.
pub fn negotiate_protocol_env(
tool_protocol: Option<&str>,
analysis_protocol: Option<&str>,
trace_protocol: Option<&str>,
) -> ViewResult<()> {
if let Some(raw) = tool_protocol {
let value = parse_env_u32(ENV_TOOL_PROTOCOL, raw)?;
if value != TOOL_PROTOCOL {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"{ENV_TOOL_PROTOCOL}={value} is not supported (this View implements protocol {TOOL_PROTOCOL})"
),
});
}
}
if let Some(raw) = analysis_protocol {
let value = parse_env_u32(ENV_PROTOCOL_ANALYSIS, raw)?;
if value != ANALYSIS_PROTOCOL {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"{ENV_PROTOCOL_ANALYSIS}={value} is not supported (this View requires Analysis v{ANALYSIS_PROTOCOL})"
),
});
}
}
if let Some(raw) = trace_protocol {
let value = parse_env_u32(ENV_PROTOCOL_TRACE, raw)?;
if value != TRACE_PROTOCOL {
return Err(ViewError::ProtocolIncompatible {
detail: format!(
"{ENV_PROTOCOL_TRACE}={value} is not supported (this View requires Trace v{TRACE_PROTOCOL})"
),
});
}
}
Ok(())
}
fn parse_env_u32(name: &str, raw: &str) -> ViewResult<u32> {
raw.trim()
.parse::<u32>()
.map_err(|_| ViewError::ProtocolIncompatible {
detail: format!("{name}={raw:?} is not a positive integer protocol version"),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_official_version_line() {
let version = parse_version_output("marqdo 3.0.0-beta.1\n").unwrap();
assert_eq!(version.version.to_string(), "3.0.0-beta.1");
assert!(product_is_compatible(&version.version));
}
#[test]
fn rejects_stable_only_reinterpretation() {
// 2.9.1 is the old product line and must never be accepted.
let old = Version::parse("2.9.1").unwrap();
assert!(!product_is_compatible(&old));
// A future major is rejected too.
assert!(!product_is_compatible(&Version::parse("4.0.0").unwrap()));
// Later prereleases in the 3.x line remain compatible.
assert!(product_is_compatible(
&Version::parse("3.1.0-beta.1").unwrap()
));
assert!(product_is_compatible(&Version::parse("3.0.0").unwrap()));
}
#[test]
fn negotiates_known_protocols_only() {
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(Some("2"), None, 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, Some("two"), None).is_err());
}
}
+89
View File
@@ -0,0 +1,89 @@
//! CLI surface tests: this program owns its own help/subcommands and refuses
//! unsafe defaults. Exit codes follow RFC-VIEW-0001 §10.2.
mod common;
use common::run_view;
fn clean_env() -> Vec<(&'static str, Option<&'static str>)> {
vec![
("MARQDO_BIN", None),
("MARQDO_TOOL_PROTOCOL", None),
("MARQDO_PROTOCOL_ANALYSIS", None),
("MARQDO_PROTOCOL_TRACE", None),
]
}
#[test]
fn help_comes_from_view_not_core() {
let cwd = std::env::current_dir().unwrap();
let output = run_view(&["--help"], &cwd, &clean_env());
assert_eq!(output.status.code(), Some(0));
let stdout = String::from_utf8_lossy(&output.stdout);
for needle in ["marqdo-view", "export", "verify", "PATH", "--marqdo-bin"] {
assert!(
stdout.contains(needle),
"missing {needle} in help:\n{stdout}"
);
}
// The Core's own help wording must not leak here.
assert!(!stdout.contains("Statically check a document"));
}
#[test]
fn version_is_the_tool_version() {
let cwd = std::env::current_dir().unwrap();
let output = run_view(&["--version"], &cwd, &clean_env());
assert_eq!(output.status.code(), Some(0));
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(stdout.contains("marqdo-view 0.1.0"), "{stdout}");
}
#[test]
fn export_requires_an_output_directory() {
let cwd = std::env::current_dir().unwrap();
let output = run_view(&["export", "example.mq.md"], &cwd, &clean_env());
assert_eq!(output.status.code(), Some(2));
}
#[test]
fn non_loopback_bind_is_refused_by_default() {
let cwd = std::env::current_dir().unwrap();
let output = run_view(&["--host", "0.0.0.0"], &cwd, &clean_env());
assert_eq!(output.status.code(), Some(2));
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("view.bind_denied"), "{stderr}");
assert!(stderr.contains("--unsafe-expose"), "{stderr}");
}
#[test]
fn browse_without_core_reports_core_missing() {
// Browse is not implemented yet, but the reader must still fail with a
// stable View code and exit class rather than pretending to work.
let cwd = std::env::current_dir().unwrap();
let output = run_view(&[], &cwd, &clean_env());
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(2), "stderr: {stderr}");
assert!(
stderr.contains("view.unsupported") || stderr.contains("view.core_missing"),
"unexpected diagnostic: {stderr}"
);
}
#[test]
fn verify_without_core_is_an_argument_error() {
let project = common::TempProject::new("cli-verify-no-core");
project.marqdo_project("# @knowledge fixture\n");
let output = run_view(&["verify", "index.mq.md"], &project.dir, &clean_env());
assert_eq!(output.status.code(), Some(2));
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("view.core_missing"), "{stderr}");
}
#[test]
fn missing_document_is_an_io_error() {
let project = common::TempProject::new("cli-missing-doc");
let output = run_view(&["verify", "missing.mq.md"], &project.dir, &clean_env());
assert_eq!(output.status.code(), Some(1));
assert!(String::from_utf8_lossy(&output.stderr).contains("view.io"));
}
+228
View File
@@ -0,0 +1,228 @@
//! Shared test helpers for integration tests.
//!
//! Fake cores are real executables (never mocked Rust traits at the process
//! boundary) so argv, exit codes, stderr and temp artifacts are all exercised.
#![allow(dead_code)]
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
pub fn view_bin() -> &'static str {
env!("CARGO_BIN_EXE_marqdo-view")
}
pub fn temp_root(name: &str) -> PathBuf {
let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(name);
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("create test temp dir");
dir
}
pub struct TempProject {
pub dir: PathBuf,
}
impl TempProject {
pub fn new(name: &str) -> Self {
Self {
dir: temp_root(name),
}
}
pub fn write(&self, relative: &str, contents: &str) -> PathBuf {
let path = self.dir.join(relative);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).expect("create parent");
}
std::fs::write(&path, contents).expect("write fixture");
path
}
pub fn path(&self, relative: &str) -> PathBuf {
self.dir.join(relative)
}
pub fn marqdo_project(&self, source: &str) {
self.write(
"marqdo.yaml",
"project:\n name: fixture\n version: 0.1.0\n",
);
self.write("index.mq.md", source);
}
}
/// A scriptable shell-based fake core. Every behaviour is controlled by files
/// in its directory, so tests never mutate global environment variables.
pub struct FakeCore {
pub dir: PathBuf,
pub script: PathBuf,
}
impl FakeCore {
pub fn new(name: &str) -> Self {
let dir = temp_root(name);
let script = dir.join("marqdo");
let body = r#"#!/bin/sh
dir="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
{
printf 'invocation\n'
for arg in "$@"; do printf 'arg=%s\n' "$arg"; done
} >> "$dir/argv.txt"
if [ -f "$dir/sleep" ]; then
sleep "$(cat "$dir/sleep")"
fi
case "$1" in
--version)
if [ -f "$dir/version" ]; then cat "$dir/version"; else printf 'marqdo 3.0.0-beta.1\n'; fi
exit 0
;;
check)
if [ -f "$dir/check_stderr" ]; then cat "$dir/check_stderr" >&2; fi
emit=""
prev=""
for a in "$@"; do
if [ "$prev" = "--emit" ]; then emit="$a"; fi
prev="$a"
done
if [ -f "$dir/analysis.json" ] && [ -n "$emit" ]; then cp "$dir/analysis.json" "$emit"; fi
if [ -f "$dir/check_exit" ]; then exit "$(cat "$dir/check_exit")"; fi
exit 0
;;
run)
trace=""
prev=""
for a in "$@"; do
if [ "$prev" = "--trace-file" ]; then trace="$a"; fi
prev="$a"
done
if [ -f "$dir/trace.json" ] && [ -n "$trace" ]; then cp "$dir/trace.json" "$trace"; fi
if [ -f "$dir/run.json" ]; then cat "$dir/run.json"; else printf '{"command":"run","success":true}\n'; fi
if [ -f "$dir/run_exit" ]; then exit "$(cat "$dir/run_exit")"; fi
exit 0
;;
*)
printf 'fake core: unknown command %s\n' "$1" >&2
exit 64
;;
esac
"#;
std::fs::write(&script, body).expect("write fake core");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755))
.expect("chmod fake core");
}
Self { dir, script }
}
pub fn set_version(&self, text: &str) {
std::fs::write(self.dir.join("version"), text).expect("write version");
}
pub fn set_check(&self, exit_code: i32, stderr: &str) {
std::fs::write(self.dir.join("check_exit"), exit_code.to_string()).expect("write exit");
std::fs::write(self.dir.join("check_stderr"), stderr).expect("write stderr");
}
pub fn set_analysis(&self, analysis: &str) {
std::fs::write(self.dir.join("analysis.json"), analysis).expect("write analysis");
}
pub fn set_run(&self, exit_code: i32, json: &str, trace: Option<&str>) {
std::fs::write(self.dir.join("run_exit"), exit_code.to_string()).expect("write run exit");
std::fs::write(self.dir.join("run.json"), json).expect("write run json");
match trace {
Some(trace) => {
std::fs::write(self.dir.join("trace.json"), trace).expect("write trace");
}
None => {
let _ = std::fs::remove_file(self.dir.join("trace.json"));
}
}
}
pub fn set_sleep_seconds(&self, seconds: u32) {
std::fs::write(self.dir.join("sleep"), seconds.to_string()).expect("write sleep");
}
pub fn argv_lines(&self) -> Vec<String> {
std::fs::read_to_string(self.dir.join("argv.txt"))
.unwrap_or_default()
.lines()
.map(str::to_string)
.collect()
}
/// All argument values for the most recent invocation.
pub fn last_args(&self) -> Vec<String> {
self.argv_lines()
.into_iter()
.filter_map(|line| line.strip_prefix("arg=").map(str::to_string))
.collect()
}
}
pub fn run_view(args: &[&str], cwd: &Path, envs: &[(&str, Option<&str>)]) -> Output {
let mut command = Command::new(view_bin());
command.args(args).current_dir(cwd);
for (key, value) in envs {
match value {
Some(value) => {
command.env(key, value);
}
None => {
command.env_remove(key);
}
}
}
command.output().expect("run marqdo-view")
}
/// Minimal valid Analysis v2 JSON for a single module, with a caller-provided
/// source digest and schema version.
pub fn minimal_analysis(relative_path: &str, source_digest: &str, schema_version: u32) -> String {
serde_json::json!({
"schema": "marqdo.analysis",
"schema_version": schema_version,
"producer": {
"name": "marqdo",
"version": "3.0.0-beta.1",
"markdown_profile": "marqdo.md.v1"
},
"project": {
"root_id": "root:fixture@0.1.0",
"identity_kind": "manifest",
"lock_digest": "",
"stdlib": null
},
"modules": [{
"id": "root:fixture@0.1.0::index.mq.md",
"package_instance_id": "root:fixture@0.1.0",
"relative_path": relative_path,
"source_digest": source_digest,
"units": [],
"functions": [],
"imports": [],
"references": [],
"calls": [],
"resources": []
}],
"diagnostics": []
})
.to_string()
}
pub fn sha256_hex(bytes: &[u8]) -> String {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(bytes);
let digest = hasher.finalize();
let mut out = String::with_capacity(64);
for byte in digest {
use std::fmt::Write as _;
let _ = write!(out, "{byte:02x}");
}
out
}
+245
View File
@@ -0,0 +1,245 @@
//! Contract tests against a real fake-core executable: argv shape, exit codes,
//! stderr handling, temp artifacts and process-tree cleanup.
//!
//! The fake core is a shell script, not a mocked Rust trait, so everything at
//! the process boundary is exercised for real.
mod common;
use common::{minimal_analysis, sha256_hex, FakeCore, TempProject};
use marqdo_view::core_client::{CheckOptions, CoreClient, RunOptions};
use marqdo_view::project::Project;
fn fixture(name: &str) -> (TempProject, FakeCore) {
let project = TempProject::new(name);
project.marqdo_project("# @knowledge fixture\n");
let core = FakeCore::new(&format!("{name}-core"));
(project, core)
}
#[test]
fn check_returns_exact_analysis_bytes_and_digest() {
let (project, core) = fixture("check_ok");
let source = std::fs::read(project.path("index.mq.md")).unwrap();
let analysis = minimal_analysis("index.mq.md", &sha256_hex(&source), 2);
core.set_analysis(&analysis);
let client = CoreClient::with_bin(&core.script).unwrap();
let project = Project::open(&project.path("index.mq.md")).unwrap();
let entry = project.entry().relative.clone();
let output = client
.check(&project, &entry, &CheckOptions::default())
.unwrap();
assert_eq!(output.analysis_bytes, analysis.as_bytes());
assert_eq!(output.analysis_sha256, sha256_hex(analysis.as_bytes()));
assert_eq!(
output.analysis_digest,
format!("sha256:{}", sha256_hex(analysis.as_bytes()))
);
let args = core.last_args();
assert_eq!(args[0], "check");
assert!(args.contains(&"--emit".to_string()));
// No `--refs` unless requested.
assert!(!args.contains(&"--refs".to_string()));
}
#[test]
fn check_refs_is_forwarded_as_a_stricter_flag() {
let (project, core) = fixture("check_refs");
let source = std::fs::read(project.path("index.mq.md")).unwrap();
core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 2));
let client = CoreClient::with_bin(&core.script).unwrap();
let project = Project::open(&project.path("index.mq.md")).unwrap();
let entry = project.entry().relative.clone();
client
.check(
&project,
&entry,
&CheckOptions {
refs: true,
timeout: None,
},
)
.unwrap();
assert!(core.last_args().contains(&"--refs".to_string()));
}
#[test]
fn check_failure_preserves_core_stderr_and_code() {
let (project, core) = fixture("check_fail");
core.set_check(1, "index.mq.md:3:1: sem.unclosed_control\n");
let client = CoreClient::with_bin(&core.script).unwrap();
let project = Project::open(&project.path("index.mq.md")).unwrap();
let entry = project.entry().relative.clone();
let err = client
.check(&project, &entry, &CheckOptions::default())
.unwrap_err();
assert_eq!(err.code(), "view.analysis_failed");
assert_eq!(err.exit_code(), 1);
let text = err.to_string();
assert!(text.contains("sem.unclosed_control"), "{text}");
}
#[test]
fn run_returns_json_and_raw_trace() {
let (project, core) = fixture("run_ok");
core.set_run(
0,
r#"{"command":"run","success":true,"stdout":"ok","stderr":"","trace":[]}"#,
Some(r#"{"schema":"marqdo.trace","schema_version":2,"events":[]}"#),
);
let client = CoreClient::with_bin(&core.script).unwrap();
let project = Project::open(&project.path("index.mq.md")).unwrap();
let entry = project.entry().relative.clone();
let output = client
.run(&project, &entry, &RunOptions::default())
.unwrap();
assert_eq!(output.exit_code, 0);
assert_eq!(output.json["success"], true);
let trace = output.trace_bytes.expect("trace bytes");
assert_eq!(output.trace_sha256.unwrap(), sha256_hex(&trace));
// Mode is always explicit; pure is the View default.
let args = core.last_args();
assert!(args.contains(&"--mode".to_string()));
let mode_index = args.iter().position(|a| a == "--mode").unwrap();
assert_eq!(args[mode_index + 1], "pure");
assert!(args.contains(&"--json".to_string()));
assert!(args.contains(&"--trace-file".to_string()));
}
#[test]
fn run_without_trace_file_reports_no_trace() {
let (project, core) = fixture("run_no_trace");
core.set_run(
0,
r#"{"command":"run","success":true,"stdout":"","stderr":"","trace":[]}"#,
None,
);
let client = CoreClient::with_bin(&core.script).unwrap();
let project = Project::open(&project.path("index.mq.md")).unwrap();
let entry = project.entry().relative.clone();
let output = client
.run(&project, &entry, &RunOptions::default())
.unwrap();
assert!(output.trace_bytes.is_none());
assert!(output.trace_sha256.is_none());
}
#[test]
fn run_invalid_json_is_a_protocol_io_error() {
let (project, core) = fixture("run_bad_json");
core.set_run(0, "this is not json", None);
let client = CoreClient::with_bin(&core.script).unwrap();
let project = Project::open(&project.path("index.mq.md")).unwrap();
let entry = project.entry().relative.clone();
let err = client
.run(&project, &entry, &RunOptions::default())
.unwrap_err();
assert_eq!(err.code(), "view.io");
assert!(err.to_string().contains("exactly one JSON"));
}
#[test]
fn timeout_kills_the_process_group_and_reports_timeout() {
let (project, core) = fixture("run_timeout");
core.set_sleep_seconds(5);
core.set_run(0, r#"{"command":"run","success":true}"#, None);
let client = CoreClient::with_bin(&core.script).unwrap();
let project = Project::open(&project.path("index.mq.md")).unwrap();
let entry = project.entry().relative.clone();
let started = std::time::Instant::now();
let err = client
.run(
&project,
&entry,
&RunOptions {
view_timeout: Some(std::time::Duration::from_millis(300)),
..Default::default()
},
)
.unwrap_err();
let elapsed = started.elapsed();
assert_eq!(err.code(), "view.core_timeout");
assert!(
elapsed < std::time::Duration::from_secs(3),
"timeout took {elapsed:?}"
);
}
#[test]
fn incompatible_product_version_is_rejected_before_any_work() {
let (project, core) = fixture("version_old");
core.set_version("marqdo 2.9.1\n");
let client = CoreClient::with_bin(&core.script).unwrap();
let err = client.negotiate().unwrap_err();
assert_eq!(err.code(), "view.protocol_incompatible");
assert_eq!(err.exit_code(), 2);
// Only `--version` was invoked; no check/run happened.
assert_eq!(core.last_args(), vec!["--version".to_string()]);
let _ = project;
}
#[test]
fn missing_emit_after_success_is_an_analysis_failure() {
// Fake core exits 0 but writes nothing: never accept a phantom analysis.
let (project, core) = fixture("check_no_emit");
let client = CoreClient::with_bin(&core.script).unwrap();
let project = Project::open(&project.path("index.mq.md")).unwrap();
let entry = project.entry().relative.clone();
let err = client
.check(&project, &entry, &CheckOptions::default())
.unwrap_err();
assert_eq!(err.code(), "view.analysis_failed");
}
#[test]
fn cli_verify_end_to_end_against_fake_core() {
let (project, core) = fixture("verify_cli");
let source = std::fs::read(project.path("index.mq.md")).unwrap();
core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 2));
let script = core.script.to_str().unwrap().to_string();
let dir = project.dir.to_str().unwrap().to_string();
let output = common::run_view(
&["verify", "index.mq.md", "--marqdo-bin", &script],
std::path::Path::new(&dir),
&[
("MARQDO_BIN", None),
("MARQDO_TOOL_PROTOCOL", None),
("MARQDO_PROTOCOL_ANALYSIS", None),
("MARQDO_PROTOCOL_TRACE", None),
],
);
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(0), "stderr: {stderr}");
assert!(stdout.contains("result: PASS"), "{stdout}");
assert!(stdout.contains("marqdo 3.0.0-beta.1"), "{stdout}");
assert!(!stdout.contains(&dir), "absolute path leaked: {stdout}");
}
#[test]
fn cli_verify_rejects_schema_v3_and_digest_mismatch() {
let (project, core) = fixture("verify_negative");
let source = std::fs::read(project.path("index.mq.md")).unwrap();
let script = core.script.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));
let output = common::run_view(
&["verify", "index.mq.md", "--marqdo-bin", &script],
std::path::Path::new(&dir),
&[("MARQDO_BIN", None)],
);
assert_eq!(output.status.code(), Some(2));
assert!(String::from_utf8_lossy(&output.stderr).contains("view.protocol_incompatible"));
core.set_analysis(&minimal_analysis("index.mq.md", &"0".repeat(64), 2));
let output = common::run_view(
&["verify", "index.mq.md", "--marqdo-bin", &script],
std::path::Path::new(&dir),
&[("MARQDO_BIN", None)],
);
assert_eq!(output.status.code(), Some(1));
assert!(String::from_utf8_lossy(&output.stderr).contains("view.source_mismatch"));
}
+196
View File
@@ -0,0 +1,196 @@
//! Architectural gates (RFC-VIEW-0001 §17.2): no private Core crates, no
//! source-tree reads of the legacy repositories, no second renderer, no shell
//! execution, one CSS/JS entry point.
use std::path::{Path, PathBuf};
fn manifest_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
}
fn read(path: &Path) -> String {
std::fs::read_to_string(path).unwrap_or_else(|err| panic!("read {}: {err}", path.display()))
}
fn collect_files(dir: &Path, extension: &str, out: &mut Vec<PathBuf>) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
collect_files(&path, extension, out);
} else if path.extension().and_then(|e| e.to_str()) == Some(extension) {
out.push(path);
}
}
}
#[test]
fn no_private_core_crate_dependencies() {
let root = manifest_dir();
let forbidden = [
"marqdo",
"marqdo-cli",
"marqdo-ir",
"marqdo-runtime",
"marqdo-frontend",
"marqdo-host",
"marqdo-markdown",
"marqdo-span",
"marqdo-expression",
"marqdo-sema",
];
let mut in_dependency_section = false;
for line in read(&root.join("Cargo.toml")).lines() {
let trimmed = line.trim();
if trimmed.starts_with('[') {
in_dependency_section = trimmed.ends_with("dependencies]")
|| trimmed.contains("dependencies.")
|| trimmed.contains("dependencies]");
continue;
}
if !in_dependency_section || trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
let Some((name, _)) = trimmed.split_once('=') else {
continue;
};
let name = name.trim().trim_matches('"');
assert!(
!forbidden.contains(&name),
"Cargo.toml declares forbidden Core dependency {name:?}"
);
}
let lock = read(&root.join("Cargo.lock"));
for line in lock.lines() {
let Some(rest) = line.trim().strip_prefix("name = \"") else {
continue;
};
let name = rest.trim_end_matches('"');
if name == "marqdo-view" {
continue;
}
assert!(
!name.starts_with("marqdo") || name == "marqdo",
"Cargo.lock contains suspicious package {name:?}"
);
assert!(
!forbidden.contains(&name),
"Cargo.lock contains forbidden Core package {name:?}"
);
}
}
#[test]
fn source_never_reads_or_links_the_legacy_repositories() {
let root = manifest_dir();
let mut sources = Vec::new();
collect_files(&root.join("src"), "rs", &mut sources);
assert!(!sources.is_empty(), "src/ has no Rust sources");
let needles = [
["marqdo", "_ir"].concat(),
["marqdo", "-ir"].concat(),
["marqdo", "_runtime"].concat(),
["marqdo", "-runtime"].concat(),
["marqdo", "_frontend"].concat(),
["marqdo", "-frontend"].concat(),
["marqdo", "::"].concat(),
["..", "/marqdo"].concat(),
["..", "/marqdo-cli"].concat(),
["inspect", " --ir"].concat(),
["Command::new", "(\"sh\")"].concat(),
["Command::new", "(\"bash\")"].concat(),
["sh", " -c"].concat(),
["bash", " -c"].concat(),
];
for path in sources {
let text = read(&path);
for (line_number, line) in text.lines().enumerate() {
let trimmed = line.trim_start();
// Documentation may *name* forbidden APIs when explaining what is
// not used; the gate only scans executable source lines.
if trimmed.starts_with("//") {
continue;
}
for needle in &needles {
assert!(
!line.contains(needle.as_str()),
"{}:{} contains forbidden reference {:?}",
path.display(),
line_number + 1,
needle
);
}
}
}
}
#[test]
fn exactly_one_reader_theme_and_script_entry() {
let root = manifest_dir();
let assets = root.join("assets");
let mut css = Vec::new();
let mut js = Vec::new();
collect_files(&assets, "css", &mut css);
collect_files(&assets, "js", &mut js);
assert!(css.len() <= 1, "more than one CSS entry: {css:?}");
assert!(js.len() <= 1, "more than one JS entry: {js:?}");
for path in &css {
assert_eq!(
path.file_name().and_then(|n| n.to_str()),
Some("reader.css"),
"the only CSS entry must be assets/reader.css"
);
}
for path in &js {
assert_eq!(
path.file_name().and_then(|n| n.to_str()),
Some("reader.js"),
"the only JS entry must be assets/reader.js"
);
}
// The source tree must not reference legacy skin names at all.
let mut sources = Vec::new();
collect_files(&root.join("src"), "rs", &mut sources);
for path in sources {
let text = read(&path);
for needle in ["notebook-page", "reader-page", "legacy.css", "new.css"] {
assert!(
!text.contains(needle),
"{} references legacy skin marker {needle:?}",
path.display()
);
}
}
}
#[test]
fn tool_manifest_matches_package_and_protocols() {
let root = manifest_dir();
let raw = read(&root.join("tool.json"));
let tool: serde_json::Value = serde_json::from_str(&raw).expect("tool.json is JSON");
assert_eq!(tool["schema"], "marqdo.cli-tool");
assert_eq!(tool["schema_version"], 1);
assert_eq!(tool["name"], "marqdo-view");
assert_eq!(tool["command"], "view");
assert_eq!(tool["entrypoint"], "bin/marqdo-view");
assert_eq!(
tool["version"],
env!("CARGO_PKG_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"]["analysis"], serde_json::json!([2]));
assert_eq!(tool["compatibility"]["trace"], serde_json::json!([2]));
}
#[test]
fn release_lockfile_is_committed() {
let root = manifest_dir();
assert!(
root.join("Cargo.lock").is_file(),
"Cargo.lock must be committed for --locked release builds"
);
}
+13
View File
@@ -0,0 +1,13 @@
{
"schema": "marqdo.cli-tool",
"schema_version": 1,
"name": "marqdo-view",
"version": "0.1.0",
"command": "view",
"entrypoint": "bin/marqdo-view",
"compatibility": {
"marqdo": ">=3.0.0-beta.1,<4.0.0",
"analysis": [2],
"trace": [2]
}
}
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env bash
# Install the built bundle with a frozen marqdo CLI into an isolated tool home,
# then prove the command is served by this program (not by the Core).
#
# Usage: MARQDO_BIN=/abs/path/marqdo tools/install-smoke.sh [tool.json]
set -euo pipefail
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
manifest="${1:-$repo_root/dist/marqdo-view/tool.json}"
: "${MARQDO_BIN:?set MARQDO_BIN to the frozen marqdo binary}"
if [[ ! -x "$MARQDO_BIN" ]]; then
echo "error: MARQDO_BIN is not executable: $MARQDO_BIN" >&2
exit 1
fi
before="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)"
mkdir -p "$repo_root/dist"
tool_home="$(mktemp -d "$repo_root/dist/smoke-tool-home.XXXXXX")"
cleanup() {
rm -rf "$tool_home"
}
trap cleanup EXIT
export MARQDO_TOOL_HOME="$tool_home"
"$MARQDO_BIN" tool install "$manifest" >/dev/null
"$MARQDO_BIN" tool list | grep -q 'view'
help="$("$MARQDO_BIN" view --help)"
grep -q 'marqdo-view' <<<"$help"
grep -q 'export' <<<"$help"
grep -q 'verify' <<<"$help"
version="$("$MARQDO_BIN" view --version)"
grep -q 'marqdo-view' <<<"$version"
after="$(sha256sum "$MARQDO_BIN" | cut -d' ' -f1)"
if [[ "$before" != "$after" ]]; then
echo "error: frozen core binary changed during install smoke test" >&2
exit 1
fi
echo "install-smoke: PASS (core sha256 $before unchanged, tool home $tool_home)"
+118
View File
@@ -0,0 +1,118 @@
#!/usr/bin/env bash
# Build and assemble the Tool Protocol v1 release bundle.
#
# Produces:
# dist/marqdo-view/ stable bundle path (RFC §18)
# dist/marqdo-view-<version>-<target>.tar.gz (+ .sha256)
#
# The bundle contains only the runtime binary, the manifest and the legal /
# compatibility files. CSS/JS/images are compiled into the binary (ADR-0002),
# so there is exactly one asset source for Live and Export.
set -euo pipefail
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$repo_root"
: "${CARGO:=cargo}"
: "${MARQDO_BIN:=}"
version="$("$CARGO" metadata --no-deps --format-version 1 \
| python3 -c 'import json,sys; print(json.load(sys.stdin)["packages"][0]["version"])')"
target="$("$CARGO" -vV 2>/dev/null | sed -n 's/^host: //p')"
target="${target:-x86_64-unknown-linux-gnu}"
echo "==> cargo build --release --locked"
"$CARGO" build --release --locked
dist="$repo_root/dist"
bundle="$dist/marqdo-view"
rm -rf "$bundle"
mkdir -p "$bundle/bin"
binary="$repo_root/target/release/marqdo-view"
if [[ ! -x "$binary" ]]; then
echo "error: missing release binary $binary" >&2
exit 1
fi
cp "$binary" "$bundle/bin/marqdo-view"
chmod 755 "$bundle/bin/marqdo-view"
cp tool.json "$bundle/tool.json"
cp README.md COMPATIBILITY.md CHANGELOG.md LICENSE-MIT LICENSE-APACHE "$bundle/"
# Verify the tool manifest and the binary agree on the version.
manifest_version="$(python3 -c 'import json;print(json.load(open("tool.json"))["version"])')"
if [[ "$manifest_version" != "$version" ]]; then
echo "error: tool.json version $manifest_version != package version $version" >&2
exit 1
fi
binary_version="$("$bundle/bin/marqdo-view" --version | awk '{print $2}')"
if [[ "$binary_version" != "$version" ]]; then
echo "error: binary prints version $binary_version, package is $version" >&2
exit 1
fi
source_sha="unknown"
if git rev-parse --verify HEAD >/dev/null 2>&1; then
source_sha="$(git rev-parse HEAD)"
fi
printf '%s\n' "$source_sha" > "$bundle/SOURCE_SHA"
python3 - "$bundle" "$version" "$target" "$source_sha" <<'PY'
import hashlib
import json
import pathlib
import sys
bundle = pathlib.Path(sys.argv[1])
version, target, source_sha = sys.argv[2], sys.argv[3], sys.argv[4]
files = []
for path in sorted(bundle.rglob('*')):
if not path.is_file():
continue
rel = path.relative_to(bundle).as_posix()
if rel in ('RELEASE_INFO.json', 'SHA256SUMS'):
continue
data = path.read_bytes()
files.append({
'path': rel,
'size': len(data),
'sha256': hashlib.sha256(data).hexdigest(),
})
info = {
'schema': 'marqdo.view-release-info',
'schema_version': 1,
'tool_name': 'marqdo-view',
'tool_version': version,
'command': 'view',
'target': target,
'source_sha': source_sha,
'compatibility': {
'marqdo': '>=3.0.0-beta.1,<4.0.0',
'analysis': [2],
'trace': [2],
'tool_protocol': 1,
'markdown_profile': 'marqdo.md.v1',
},
'files': files,
}
(bundle / 'RELEASE_INFO.json').write_text(json.dumps(info, indent=2, sort_keys=True) + '\n')
with (bundle / 'SHA256SUMS').open('w') as out:
for entry in files:
out.write(f"{entry['sha256']} {entry['path']}\n")
PY
# Deterministic archive: sorted paths, fixed owner, gzip without timestamps.
archive="marqdo-view-${version}-${target}.tar.gz"
tar --sort=name --owner=0 --group=0 --numeric-owner --mtime='UTC 2026-01-01' \
-C "$dist" -cf - marqdo-view | gzip -n > "$dist/$archive"
( cd "$dist" && sha256sum "$archive" > "$archive.sha256" )
if [[ -n "$MARQDO_BIN" ]]; then
echo "==> smoke install against frozen core"
MARQDO_BIN="$MARQDO_BIN" "$repo_root/tools/install-smoke.sh" "$bundle/tool.json"
fi
echo "bundle: $bundle"
echo "archive: $dist/$archive"
echo "sha256: $(cut -d' ' -f1 "$dist/$archive.sha256")"