Files
marqdo-cli/crates/cli/tests/document_access.rs
T
cflmy d7dbce68b6
ci/woodpecker/push/main Pipeline failed
ci/woodpecker/pr/main Pipeline was canceled
feat: expose the loaded document snapshot to runtime programs
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.
2026-11-30 15:42:30 +08:00

204 lines
7.4 KiB
Rust

//! Contract tests for the runtime document snapshot (`document.outline` /
//! `document.read`, marqdo-cli#24).
//!
//! The tests drive the real binary and compare every read with the public
//! Analysis revision 3 projection: same module/unit identity, same source
//! digest, same exact UTF-8 byte span. They also cover the structured failure
//! results (not loaded, unknown unit, stale source, too large).
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf};
use std::process::Output;
struct TempDir(PathBuf);
impl TempDir {
fn new(tag: &str) -> Self {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|duration| duration.as_nanos())
.unwrap_or(0);
let path = std::env::temp_dir().join(format!(
"marqdo-document-access-{tag}-{}-{nanos}",
std::process::id()
));
std::fs::create_dir_all(&path).unwrap();
Self(path)
}
fn path(&self) -> &Path {
&self.0
}
fn write(&self, relative: &str, contents: &str) {
let path = self.path().join(relative);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).unwrap();
}
std::fs::write(path, contents).unwrap();
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn cli(args: &[&str], dir: &Path) -> Output {
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.output()
.unwrap()
}
fn run_program(dir: &Path) -> serde_json::Value {
let output = cli(&["run", "index.mq.md", "--output", "json"], dir);
assert!(
output.status.success(),
"run failed: {}",
String::from_utf8_lossy(&output.stderr)
);
let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
let terminal = report["events"]
.as_array()
.unwrap()
.iter()
.find(|event| event["kind"] == "run.completed")
.expect("run.completed event");
terminal["payload"]["value"].clone()
}
fn fixture() -> TempDir {
let dir = TempDir::new("fixture");
dir.write(
"index.mq.md",
"---\nimport:\n other: ./other.mq.md\n---\n\n# @knowledge 主\n\n## 说明\n\n主正文。\n\n## @exec main\n\n\
**`纲 = document.outline()`**\n\n\
**`别的纲 = document.outline(\"root:default::other.mq.md\")`**\n\n\
**`读 = document.read(纲.module, \"root:default::index.mq.md#主/说明\")`**\n\n\
**`按锚点 = document.read(\"root:default::other.mq.md\", \"远程说明\")`**\n\n\
**`过期 = document.read(纲.module, \"说明\", \"sha256:0000000000000000000000000000000000000000000000000000000000000000\")`**\n\n\
**`缺模块 = document.read(\"root:default::missing.mq.md\", \"x\")`**\n\n\
**`超限 = document.read(纲.module, \"说明\", \"\", 2)`**\n\n\
**`限纲 = document.outline(纲.module, \"\", 1)`**\n\n\
`return [纲.ok, 纲.count, 纲.source_digest, 别的纲.ok, 别的纲.count, 读.ok, 读.text, 按锚点.ok, 按锚点.text, 过期.ok, 过期.code, 缺模块.ok, 缺模块.code, 超限.code, 限纲.code]`\n",
);
dir.write(
"other.mq.md",
"# @knowledge 远程\n\n## 远程说明\n\n远程正文。\n",
);
dir
}
#[test]
fn outline_and_read_match_the_public_analysis_projection() {
let dir = fixture();
let values = run_program(dir.path());
let items = values["items"].as_array().unwrap();
// Analysis is produced by the same candidate and the same load.
let artifact = dir.path().join("analysis.json");
let check = cli(
&["check", "index.mq.md", "--emit", artifact.to_str().unwrap()],
dir.path(),
);
assert!(check.status.success());
let analysis: serde_json::Value =
serde_json::from_slice(&std::fs::read(&artifact).unwrap()).unwrap();
let modules = analysis["modules"].as_array().unwrap();
let entry = modules
.iter()
.find(|module| module["id"] == "root:default::index.mq.md")
.unwrap();
let other = modules
.iter()
.find(|module| module["id"] == "root:default::other.mq.md")
.unwrap();
assert_eq!(items[0]["value"], serde_json::Value::Bool(true));
assert_eq!(
items[1]["decimal"]
.as_str()
.unwrap()
.parse::<usize>()
.unwrap(),
entry["units"].as_array().unwrap().len()
);
let entry_digest = entry["source_digest"].as_str().unwrap();
assert_eq!(items[2]["value"].as_str().unwrap(), entry_digest);
assert_eq!(items[3]["value"], serde_json::Value::Bool(true));
assert_eq!(
items[4]["decimal"]
.as_str()
.unwrap()
.parse::<usize>()
.unwrap(),
other["units"].as_array().unwrap().len()
);
// Exact source slice for the unit, byte-for-byte.
let read = items[6]["value"].as_str().unwrap();
let section = entry["units"]
.as_array()
.unwrap()
.iter()
.find(|unit| unit["id"] == "root:default::index.mq.md#主/说明")
.unwrap();
let start = section["span"]["start"].as_u64().unwrap() as usize;
let end = section["span"]["end"].as_u64().unwrap() as usize;
let source = entry["source"].as_str().unwrap();
assert_eq!(
read,
&source[start..end],
"read must be the exact section slice"
);
assert!(read.contains("主正文。"));
// Anchor read resolves to the same unit and exact text in the imported module.
let remote = items[8]["value"].as_str().unwrap();
let remote_section = other["units"]
.as_array()
.unwrap()
.iter()
.find(|unit| unit["id"] == "root:default::other.mq.md#远程/远程说明")
.unwrap();
let remote_start = remote_section["span"]["start"].as_u64().unwrap() as usize;
let remote_end = remote_section["span"]["end"].as_u64().unwrap() as usize;
assert_eq!(
remote,
&other["source"].as_str().unwrap()[remote_start..remote_end]
);
// Structured failures, not execution crashes.
assert_eq!(items[9]["value"], serde_json::Value::Bool(false));
assert_eq!(items[10]["value"], "document.stale_source");
assert_eq!(items[11]["value"], serde_json::Value::Bool(false));
assert_eq!(items[12]["value"], "document.not_loaded");
assert_eq!(items[13]["value"], "document.too_large");
assert_eq!(items[14]["value"], "document.too_large");
}
#[test]
fn document_read_anchors_use_canonical_unit_paths_and_utf8_bytes() {
let dir = TempDir::new("anchors");
dir.write(
"index.mq.md",
"# @knowledge 甲\n\n## 说明\n\n第一段。\n\n# @knowledge 乙\n\n## 说明\n\n第二段。\n\n## @exec main\n\n\
**`one = document.read(\"root:default::index.mq.md\", \"说明\")`**\n\n\
**`two = document.read(\"root:default::index.mq.md\", \"说明-2\")`**\n\n\
`return [one.ok, two.ok, one.text, two.text]`\n",
);
let values = run_program(dir.path());
let items = values["items"].as_array().unwrap();
assert_eq!(items[0]["value"], serde_json::Value::Bool(true));
assert_eq!(items[1]["value"], serde_json::Value::Bool(true));
assert!(items[2]["value"].as_str().unwrap().contains("第一段。"));
assert!(items[3]["value"].as_str().unwrap().contains("第二段。"));
assert_ne!(items[2]["value"], items[3]["value"]);
}