feat: expose the loaded document snapshot to runtime programs
ci/woodpecker/push/main Pipeline failed
ci/woodpecker/pr/main Pipeline was canceled

Implement marqdo-cli#24 (AI-U1): ordinary .mq.md programs can read the
document snapshot that `prepare` already loaded, without a parser, host paths
or a second knowledge body.

- marqdo-host-contract gains the neutral read-only DocumentModule/DocumentUnit
  projection (canonical ids, path/parent/level/mode/anchors, exact section and
  heading spans, source digest, exact source) and two default-unavailable Host
  methods.
- The composition root builds the snapshot from the same load as Analysis
  (entry + explicit import closure only; no extra reads) and attaches it to the
  native host. StdHost only slices the immutable source; it never executes
  project code, loads modules, parses Markdown or touches the network.
- New builtins: document.outline(module?, parent?, limit?) and
  document.read(module, unit, expected_digest?, max_bytes?). Expected states
  (not loaded, unknown unit, stale source, over budget, invalid span) are
  structured result maps with stable document.* codes, so ordinary control flow
  can branch instead of crashing.
- Specification: spec/document-access.md, spec/evaluation.md §8, ADR-0074,
  README/developers/STATUS links and a docs-consistency gate for the single
  current contract.
- Tests: document_access.rs checks byte-exact agreement with check --emit
  Analysis (module/unit ids, digests, spans, cross-module anchor read) and all
  failure codes; the ADR-0064 builtin review table records the two additions.

Binary budgets are explicit (snapshot 128 modules/16 MiB; outline 1024/4096;
read 256 KiB/1 MiB) and over-budget requests report document.too_large rather
than truncating.
This commit is contained in:
cflmy committed 2026-11-30 15:42:30 +08:00
1 parent 8ad2f2cffa
commit d7dbce68b6
20 files changed
+1121 -6

No files matched your search

+14
View File
@@ -79,6 +79,20 @@ The `spec/` tree contains only current contracts; retired specifications are in
Git history and tagged archives. The earlier release records below describe
their tagged binaries and are not current protocol claims.
## 0.14 Runtime document access — issue #24 (unreleased)
Ordinary `.mq.md` programs can now read the loaded document snapshot through
`document.outline(module?, parent?, limit?)` and
`document.read(module, unit, expected_digest?, max_bytes?)`. The snapshot is
built during `prepare` from the same load as Analysis: canonical module/unit
ids, anchors, exact UTF-8 spans, source digests and source text; reads are pure
byte slices and never open files, parse Markdown, load modules dynamically or
execute project code. Expected states (not loaded, unknown unit, stale digest,
over budget) return structured `document.*` codes so programs can branch.
Spec: [`spec/document-access.md`](../spec/document-access.md); ADR-0074; tests:
`crates/cli/tests/document_access.rs` (Analysis-consistency, anchor/UTF-8 and
negative cases). No Analysis/Observation/Tool protocol change.
## 0.13 Document structure contract — issue #25 (unreleased)
[`spec/document-structure.md`](../spec/document-structure.md) now states the
+84
View File
@@ -0,0 +1,84 @@
# ADR-0074 — Read-only loaded-document snapshot and two runtime document builtins
Status: **Accepted** (2026-11-30).
Related: [marqdo-cli#24](https://git.cflmy.cn/cflmy/marqdo-cli/issues/24),
`marqdo-ext-ai#2` (AI-U1), [ADR-0064](0064-new-builtin-hostop-value-and-top-level-command-policy.md),
[ADR-0069](0069-public-analysis-boundary.md), [ADR-0071](0071-engine-host-contract-boundary.md).
## Context
The public Analysis revision 3 projection already lets external tools see every
loaded module, unit identity, anchor and exact UTF-8 span. Ordinary `.mq.md`
programs have no equivalent runtime access: `ref("#anchor")` returns an inert
`Formula | Code | FunctionRef`, and there is no way to walk the loaded heading
tree or read one exact section without copying the CLI parser or reading host
files privately. The AI extension (AI-U1 / I08: select anchor → read exact
section → judge → compute → explain) is blocked on this, and any ordinary
document-navigation program has the same gap.
The engine must not read files or parse Markdown. The loader already holds one
immutable snapshot (`prepare` = the same load used by `check`, `run`, `call`,
`inspect` and Analysis), so the missing piece is a controlled projection of that
snapshot through the neutral Host contract.
## Decision
1. The composition root builds a read-only `DocumentModule` snapshot in the
`prepare`-derived load: canonical module id, exact source text, lowercase
SHA-256 source digest, and units in document order with canonical unit id,
path, parent id, level, effective mode, anchors, complete section span and
heading span. Only modules already loaded for this run are included (entry
plus explicit import closure); nothing is read from disk again.
2. `marqdo-host-contract` gains the neutral snapshot types and two default-
unavailable Host methods:
`document_outline(module?, parent?, limit)` and
`document_read(module, unit, expected_digest?, max_bytes)`.
The native host serves them from the snapshot; the embedded/test host may
leave them unavailable.
3. Two pure builtins expose them to programs: `document.outline` (all optional
`module`, `parent`, `limit`) and `document.read` (`module`, `unit`, optional
`expected_digest`, `max_bytes`). Both return structured result maps
(`{ok: true, ...}` / `{ok: false, code, message}`) so callers can branch on
stale sources, unknown units or budget failures instead of crashing.
4. Specification: `spec/document-access.md`; builtin table in
`spec/evaluation.md` §8. Analysis is unchanged; the snapshot and the
Analysis projection are produced from the same load and must agree on
module/unit ids, source digests and byte spans (contract test).
## Boundaries
- The engine continues to depend only on `marqdo-host-contract`; it never sees
the loader, filesystem, Markdown AST or host paths.
- The host only slices the immutable source by the frontend's exact section
span; it does not parse, normalise, execute `@knowledge`, expand links, or
start workers/models.
- No dynamic import, no extra files, no absolute paths, no second knowledge
body: the snapshot exposes only already-loaded modules, and the returned text
is the exact source slice.
- Budgets are explicit and bounded: outline limit (default 1024, max 4096),
read `max_bytes` (default 256 KiB, max 1 MiB), snapshot module count (128) and
total source bytes (16 MiB). Over-budget requests/installations report
`document.too_large`, never silent truncation.
## Rejected alternatives
- **Exposing host paths or a file-read builtin**: would let programs read
arbitrary files and bypass the package/import authority model.
- **A CLI Tool subprocess for reading**: adds a process boundary and a second
protocol for an in-process, already-loaded fact.
- **Copying the Markdown/unit index into the runtime**: duplicates the parser
and violates ADR-0071; the frontend already owns the authoritative index.
- **Returning runtime errors for expected states**: stale/unknown/too-large are
expected data states in document workflows; structured result maps let
ordinary control flow decide.
## Consequences
- AI-U1 can read exact sections from the same snapshot as Analysis; the AI
extension keeps its context boundary and does not need a second index.
- Ordinary programs can implement catalog/read/navigation flows with the same
bytes that `check --emit` reports.
- A new public builtin and Host surface exist; they are read-only and do not
add capabilities, grants, network access or execution paths.
- Future changes to unit identity/span semantics remain CLI-owned and must keep
this contract in lockstep.
+5 -2
View File
@@ -43,9 +43,12 @@ Foreign wire v1, Provider manifest v2, lock v4 and markdown profile
6. [document-structure.md](../../spec/document-structure.md) — heading modes,
units/anchors/spans, `index.mq.md` entry meaning and the link≠import≠call
separation (single author/tool overview).
7. [compatibility.md](compatibility.md) — version axes, platform matrix and the
7. [document-access.md](../../spec/document-access.md) — runtime
`document.outline`/`document.read` over the prepared snapshot: exact units,
spans, source digests and structured failure codes (ADR-0074).
8. [compatibility.md](compatibility.md) — version axes, platform matrix and the
prerelease policy.
8. [release-limits.md](release-limits.md) — the honest beta limitations (this
9. [release-limits.md](release-limits.md) — the honest beta limitations (this
file ships in the archive as `KNOWN_LIMITATIONS.md`).
The full worked handbook is
@@ -0,0 +1,56 @@
# CLI 运行期文稿访问能力 — issue #24
Date: 2026-11-30. Branch: `codex/issue-24-document-runtime-read`.
Issue: [marqdo-cli#24](https://git.cflmy.cn/cflmy/marqdo-cli/issues/24)
(AI-U1 for `marqdo-ext-ai`).
## 交付
- `marqdo-host-contract`:新增只读 `DocumentModule`/`DocumentUnit` 快照类型与
两个默认不可用的 Host 方法(`document_outline`、`document_read`);
引擎仍只依赖中立 Host contract。
- `crates/cli/src/document_snapshot.rs`:从 `prepare` 的同一加载快照构建模块目录
(canonical module/unit id、path/parent/level/mode/anchors、完整 section span、
heading span、source digest、exact source);只包含本次 run/call 已加载的模块
(入口 + 显式导入闭包),不再读盘/解析。
- 运行时 builtin:`document.outline(module?, parent?, limit?)` 与
`document.read(module, unit, expected_digest?, max_bytes?)`;返回结构化
result map(ok/失败 code),预期状态不崩溃。
- 原生宿主 `StdHost` 从快照做精确 byte slice;不执行文稿、不加载模块、不联网。
- 规范:`spec/document-access.md`、`spec/evaluation.md` §8;
ADR-0074;`spec/document-structure.md`/README/developers/STATUS 链接。
- 测试:`crates/cli/tests/document_access.rs` 2 例(与 `check --emit` Analysis
的 module/unit/digest/span 逐字节一致;跨模块 anchor 读取;stale/unknown/not_loaded/
too_large;同名标题 anchor 区分);`docs_consistency` 单一契约检查;
architecture boundary 的 builtin 评审表更新。
## 本地验证(Linux x86_64 / glibc 2.43;Bundle 0.3.0)
```text
cargo fmt --all -- --check PASS
cargo clippy --workspace --all-targets -- -D warnings PASS
MARQDO_TEST_STDLIB_BUNDLE=<0.3.0> cargo test --workspace --locked 641 passed, 0 failed, 2 ignored
cargo test -p marqdo-cli --test document_access 2 passed
cargo test -p marqdo-cli --test docs_consistency 10 passed
check_dependency_boundaries / check_engine_boundary / check_plugin_sdk PASS
independent_build PASS
```
手工探针(真实 CLI):
```text
document.outline() → {ok:true, count:4, source_digest:<same as Analysis>}
document.read(module, unit-id) → 精确 section 原文
document.read(module, "说明") → anchor 命中同一 unit
stale digest → {ok:false, code:"document.stale_source"}
unknown unit → {ok:false, code:"document.unknown_unit"}
```
## 已知限制 / 未验证
- 快照预算:≤128 模块、≤16 MiB 源码;outline limit 默认 1024/最大 4096;
read 默认 256 KiB/最大 1 MiB;超限返回 `document.too_large`,不静默裁剪。
- `check`/`inspect` 不执行,因此不暴露该能力;strict 子进程重新按同一 prepare
构建快照,不依赖父进程内存。
- Windows/macOS 原生 lane、strict VM 仍 UNVERIFIED(平台 runner 限制)。
- AI 扩展移除预写全文/词法兜底等消费切换在 ext-ai 侧另行验证。