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

+3 -1
View File
@@ -185,7 +185,9 @@ pub fn execute(
}
};
let stdin = read_stdin();
let mut host = StdHost::new(mode, capabilities, project.root.clone()).with_stdin(stdin);
let mut host = StdHost::new(mode, capabilities, project.root.clone())
.with_stdin(stdin)
.with_documents(crate::document_snapshot::catalog(&project));
if let Some(stream) = stream {
host = host.with_observation(stream.config(), Box::new(stream.host_sink()));
}
+111
View File
@@ -0,0 +1,111 @@
//! Build the immutable read-only document snapshot for the runtime.
//!
//! The snapshot contains exactly the modules that `prepare` already loaded for
//! this run/call (the entry plus its explicit import closure). It reuses the
//! frontend unit index that Analysis revision 3 projects, so `document.outline`
//! and `document.read` return the same identities and byte spans as
//! `check --emit` — without reading files again, parsing Markdown or executing
//! anything.
use std::collections::{BTreeMap, BTreeSet};
use marqdo_host_contract::{DocumentModule, DocumentUnit};
use marqdo_span::Span;
use crate::loader::LoadedProject;
/// Maximum number of modules exposed to the runtime in one run.
const MAX_MODULES: usize = 128;
/// Maximum total source bytes exposed to the runtime in one run.
const MAX_TOTAL_BYTES: usize = 16 * 1024 * 1024;
/// Build the snapshot, or an empty catalog when the loaded project exceeds the
/// documented snapshot budget.
///
/// An over-budget project keeps running normally but the document builtins
/// report `document.too_large` instead of silently serving a truncated view.
pub fn catalog(project: &LoadedProject) -> Vec<DocumentModule> {
if project.files.len() > MAX_MODULES {
return Vec::new();
}
let total: usize = project.files.values().map(|file| file.source.len()).sum();
if total > MAX_TOTAL_BYTES {
return Vec::new();
}
project
.files
.iter()
.map(|(module_id, file)| {
let index = &file.analysis.units;
let mut anchors_by_unit: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
for (anchor, unit_id) in &index.anchors {
anchors_by_unit
.entry(unit_id.to_string())
.or_default()
.insert(anchor.clone());
}
let units = index
.units
.iter()
.map(|unit| {
let id = unit.id.to_string();
let (span, heading_span, mode, parent_id, anchors) = if unit.level == 0 {
(
Span::new(0, file.source.len()),
None,
"knowledge".to_string(),
None,
Vec::new(),
)
} else {
let heading = index
.headings
.iter()
.find(|heading| heading.path == unit.id.path);
let full_span = heading
.map(|heading| heading.full_span)
.unwrap_or(unit.span);
let mode = match heading.map(|heading| heading.mode) {
Some(marqdo_frontend::units::SemanticMode::Exec) => "exec".to_string(),
_ => "knowledge".to_string(),
};
let parent_id = heading.map(|heading| heading.parent_id.to_string());
(
full_span,
Some(unit.span),
mode,
parent_id,
anchors_by_unit
.get(&id)
.map(|anchors| anchors.iter().cloned().collect())
.unwrap_or_default(),
)
};
DocumentUnit {
id,
path: unit.id.path.clone(),
parent_id,
level: unit.level,
mode,
anchors,
span,
heading_span,
}
})
.collect();
DocumentModule {
id: module_id.canonical(),
source_digest: source_digest(&file.source),
source: file.source.clone(),
units,
}
})
.collect()
}
fn source_digest(source: &str) -> String {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(source.as_bytes());
hex::encode(hasher.finalize())
}
+1
View File
@@ -8,6 +8,7 @@ mod analysis;
mod args;
mod commands;
mod document_refs;
mod document_snapshot;
mod environment;
mod extension_descriptors;
mod extension_selection;