Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7a0e8c4e42 | ||
|
|
d7dbce68b6 | ||
|
|
8ad2f2cffa | ||
|
|
8e43a3d82c | ||
|
|
bc05b0aa6c | ||
|
|
36666ab52b |
No files matched your search
@@ -271,7 +271,10 @@ rules are [`RFC-LANG-0002`](docs/architecture/RFC-LANG-0002-unified-semantics.md
|
||||
[Observation](spec/observation.md) delivers the same run as live JSONL or
|
||||
a JSON snapshot. [CLI Tool](spec/cli-tool.md) installs independently built
|
||||
commands with exact protocol requirements and verifies their entire bundle.
|
||||
`inspect --environment --json` reports the offline installed identity
|
||||
`document.outline`/`document.read` expose the already loaded document
|
||||
snapshot (exact unit spans/digests) to ordinary programs without a parser
|
||||
(`spec/document-access.md`). `inspect --environment --json` reports the
|
||||
offline installed identity
|
||||
(version, embedded source commit, platform, Bundle, protocol revisions) for
|
||||
feedback and release evidence.
|
||||
|
||||
@@ -405,7 +408,8 @@ tests/ conformance/negative corpus, embedding consumer an
|
||||
[`analysis.md`](spec/analysis.md), [`observation.md`](spec/observation.md),
|
||||
[`worker-ipc.md`](spec/worker-ipc.md),
|
||||
[`environment.md`](spec/environment.md),
|
||||
[`document-structure.md`](spec/document-structure.md);
|
||||
[`document-structure.md`](spec/document-structure.md),
|
||||
[`document-access.md`](spec/document-access.md);
|
||||
JSON Schemas in [`spec/schemas/`](spec/schemas/).
|
||||
* [`tests/README.md`](tests/README.md) — conformance corpus and `UPDATE_GOLDENS`
|
||||
workflow.
|
||||
|
||||
@@ -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()));
|
||||
}
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
@@ -8,6 +8,7 @@ mod analysis;
|
||||
mod args;
|
||||
mod commands;
|
||||
mod document_refs;
|
||||
mod document_snapshot;
|
||||
mod environment;
|
||||
mod extension_descriptors;
|
||||
mod extension_selection;
|
||||
|
||||
@@ -154,7 +154,7 @@ fn stdlib_sources_live_in_the_ecosystem_not_in_this_repository() {
|
||||
"the accepted Bundle pin must name the ecosystem source, not a vendored path"
|
||||
);
|
||||
assert_eq!(pin.name, "marqdo-stdlib");
|
||||
assert_eq!(pin.version, "0.2.0");
|
||||
assert_eq!(pin.version, "0.3.0");
|
||||
assert_eq!(pin.source_commit.len(), 40);
|
||||
let root = stdlib_support::bundle_dir();
|
||||
let manifest: serde_json::Value =
|
||||
@@ -434,6 +434,8 @@ fn builtin_names_and_aliases_are_reviewed() {
|
||||
assert_eq!(
|
||||
names,
|
||||
[
|
||||
"document.outline",
|
||||
"document.read",
|
||||
"float",
|
||||
"foreign.call",
|
||||
"foreign.run",
|
||||
|
||||
@@ -382,3 +382,48 @@ fn document_structure_contract_has_one_overview_and_author_entry_points() {
|
||||
"docs/developers/README.md does not point authors at the structure contract"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_document_access_contract_is_documented_once() {
|
||||
let root = repo_root();
|
||||
let spec = read(&root.join("spec/document-access.md"));
|
||||
for needle in [
|
||||
"document.outline",
|
||||
"document.read",
|
||||
"document.not_loaded",
|
||||
"document.unknown_unit",
|
||||
"document.stale_source",
|
||||
"document.too_large",
|
||||
"half-open byte offsets",
|
||||
] {
|
||||
assert!(
|
||||
spec.contains(needle),
|
||||
"spec/document-access.md is missing `{needle}`"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
!root.join("spec/document-access-v1.md").exists(),
|
||||
"the runtime document access contract must have one current specification"
|
||||
);
|
||||
let readme = read(&root.join("README.md"));
|
||||
assert!(
|
||||
readme.contains("spec/document-access.md"),
|
||||
"README.md does not link the runtime document access spec"
|
||||
);
|
||||
let evaluation = read(&root.join("spec/evaluation.md"));
|
||||
for builtin in ["document.outline", "document.read"] {
|
||||
assert!(
|
||||
evaluation.contains(builtin),
|
||||
"spec/evaluation.md §8 is missing {builtin}"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
root.join("docs/adr/0074-document-runtime-read.md").exists(),
|
||||
"the runtime document access decision is not recorded as an ADR"
|
||||
);
|
||||
let developers = read(&root.join("docs/developers/README.md"));
|
||||
assert!(
|
||||
developers.contains("document-access.md"),
|
||||
"docs/developers/README.md does not point at the runtime document access spec"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
//! 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"]);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
//! Read-only document snapshot exposed to the language runtime.
|
||||
//!
|
||||
//! The engine must not read project files, parse Markdown or depend on the
|
||||
//! loader. The composition root builds one immutable snapshot of the modules
|
||||
//! that were already statically loaded (`check`/`run`/`call` share the same
|
||||
//! `prepare` step) and hands it to the host. The host exposes two read-only
|
||||
//! operations over that snapshot; nothing here can execute code, load a module,
|
||||
//! start a worker or access the network.
|
||||
//!
|
||||
//! Identity and spans follow the public Analysis revision 3 projection:
|
||||
//! canonical module/unit ids, UTF-8 half-open byte spans, exact source text and
|
||||
//! the module `source_digest`. Reading a section never re-parses the document.
|
||||
|
||||
use marqdo_span::Span;
|
||||
|
||||
/// One unit of a loaded document snapshot.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct DocumentUnit {
|
||||
/// Canonical unit identity (same rendering as Analysis `units[].id`).
|
||||
pub id: String,
|
||||
/// Canonical heading path (empty for the document root).
|
||||
pub path: Vec<String>,
|
||||
/// Parent unit id (`None` for the root).
|
||||
pub parent_id: Option<String>,
|
||||
/// Heading level (0 for the root).
|
||||
pub level: u8,
|
||||
/// Effective mode: `exec` or `knowledge`.
|
||||
pub mode: String,
|
||||
/// GitHub-style navigation anchors naming this unit (sorted, unique).
|
||||
pub anchors: Vec<String>,
|
||||
/// Complete section span: heading through the next same-or-higher heading
|
||||
/// or EOF. The root covers the whole source.
|
||||
pub span: Span,
|
||||
/// Heading span (`None` for the root).
|
||||
pub heading_span: Option<Span>,
|
||||
}
|
||||
|
||||
/// One statically loaded module in the snapshot.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct DocumentModule {
|
||||
/// Canonical module identity (same rendering as Analysis `modules[].id`).
|
||||
pub id: String,
|
||||
/// SHA-256 of the exact source bytes, lowercase hex (no prefix).
|
||||
pub source_digest: String,
|
||||
/// Exact UTF-8 source text.
|
||||
pub source: String,
|
||||
/// Units in document order, root first.
|
||||
pub units: Vec<DocumentUnit>,
|
||||
}
|
||||
@@ -142,6 +142,47 @@ pub trait Host {
|
||||
))
|
||||
}
|
||||
|
||||
/// Read-only outline of the statically loaded document snapshot.
|
||||
///
|
||||
/// `module` defaults to the calling module. `parent` filters direct
|
||||
/// children of one unit id; `limit` bounds the number of returned units.
|
||||
/// Default: unavailable for hosts that do not own a document snapshot.
|
||||
/// The native CLI host returns a `{ok: ...}` result map; it never executes
|
||||
/// project code or loads a module.
|
||||
fn document_outline(
|
||||
&mut self,
|
||||
_module: Option<&str>,
|
||||
_parent: Option<&str>,
|
||||
_limit: usize,
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
ctx.span,
|
||||
"this host does not provide a loaded document snapshot",
|
||||
))
|
||||
}
|
||||
|
||||
/// Read one exact section of the loaded document snapshot.
|
||||
///
|
||||
/// `unit` is a canonical unit id or one of its navigation anchors.
|
||||
/// `expected_digest` optionally binds the read to one exact module source
|
||||
/// digest; `max_bytes` bounds the returned text. Default: unavailable.
|
||||
fn document_read(
|
||||
&mut self,
|
||||
_module: &str,
|
||||
_unit: &str,
|
||||
_expected_digest: Option<&str>,
|
||||
_max_bytes: usize,
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
ctx.span,
|
||||
"this host does not provide a loaded document snapshot",
|
||||
))
|
||||
}
|
||||
|
||||
/// Consume evaluation fuel.
|
||||
fn consume_fuel(&mut self, amount: u64, span: Option<Span>) -> Result<(), RuntimeError>;
|
||||
|
||||
|
||||
@@ -15,11 +15,13 @@
|
||||
//! owned by the trusted host implementation that consumes this contract.
|
||||
|
||||
pub mod context;
|
||||
pub mod document;
|
||||
pub mod host;
|
||||
pub mod observe;
|
||||
pub mod resource;
|
||||
|
||||
pub use context::ExecutionContext;
|
||||
pub use document::{DocumentModule, DocumentUnit};
|
||||
pub use host::{Host, HostOp};
|
||||
pub use observe::{FrameId, LoopTransfer, ParameterSource, RuntimeObservation};
|
||||
pub use resource::ResourceRead;
|
||||
@@ -13,7 +13,7 @@ use crate::plugin::{
|
||||
CapabilityHandler, HostTarget, LoadOptions, LoadedPlugin, PluginKind, PluginManifest,
|
||||
};
|
||||
use marqdo_host_contract::{
|
||||
ExecutionContext, FrameId, Host, HostOp, ResourceRead, RuntimeObservation,
|
||||
DocumentModule, ExecutionContext, FrameId, Host, HostOp, ResourceRead, RuntimeObservation,
|
||||
};
|
||||
use marqdo_plugin_abi::{ErrorKind as PluginErrorKind, PluginError};
|
||||
use marqdo_span::Span;
|
||||
@@ -81,6 +81,8 @@ pub struct StdHost {
|
||||
resource_providers: BTreeMap<String, (String, SharedResourceProvider)>,
|
||||
observation: Option<ObservationState>,
|
||||
observation_error: Option<String>,
|
||||
/// Immutable loaded-document snapshot for the read-only document builtins.
|
||||
documents: Vec<DocumentModule>,
|
||||
}
|
||||
|
||||
struct PluginSlot {
|
||||
@@ -143,9 +145,18 @@ impl StdHost {
|
||||
resource_providers: BTreeMap::new(),
|
||||
observation: None,
|
||||
observation_error: None,
|
||||
documents: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Attach the immutable loaded-document snapshot for `document.outline`
|
||||
/// and `document.read`. The composition root builds it from the same
|
||||
/// `prepare` step as Analysis; the host only serves exact bytes.
|
||||
pub fn with_documents(mut self, documents: Vec<DocumentModule>) -> Self {
|
||||
self.documents = documents;
|
||||
self
|
||||
}
|
||||
|
||||
/// Add one explicit TLS root certificate (DER) for `resource.open("tls")`.
|
||||
///
|
||||
/// System roots are always tried first; this adds a private CA for
|
||||
@@ -622,6 +633,209 @@ impl Host for StdHost {
|
||||
self.request_compatibility_operation(operation, args, ctx)
|
||||
}
|
||||
|
||||
fn document_outline(
|
||||
&mut self,
|
||||
module: Option<&str>,
|
||||
parent: Option<&str>,
|
||||
limit: usize,
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
const DEFAULT_LIMIT: usize = 1024;
|
||||
const MAX_LIMIT: usize = 4096;
|
||||
let module_id = module.unwrap_or(&ctx.module_id);
|
||||
let Some(document) = self
|
||||
.documents
|
||||
.iter()
|
||||
.find(|candidate| candidate.id == module_id)
|
||||
else {
|
||||
return Ok(document_failure(
|
||||
"document.not_loaded",
|
||||
format!("module `{module_id}` is not part of the loaded snapshot"),
|
||||
));
|
||||
};
|
||||
let limit = if limit == 0 { DEFAULT_LIMIT } else { limit };
|
||||
if limit > MAX_LIMIT {
|
||||
return Ok(document_failure(
|
||||
"document.too_large",
|
||||
format!("outline limit {limit} exceeds the maximum {MAX_LIMIT}"),
|
||||
));
|
||||
}
|
||||
let units: Vec<_> = document
|
||||
.units
|
||||
.iter()
|
||||
.filter(|unit| match parent.filter(|value| !value.is_empty()) {
|
||||
None => true,
|
||||
Some(parent) => unit.parent_id.as_deref() == Some(parent),
|
||||
})
|
||||
.collect();
|
||||
if units.len() > limit {
|
||||
return Ok(document_failure(
|
||||
"document.too_large",
|
||||
format!(
|
||||
"{} matching units exceed the outline limit {limit}",
|
||||
units.len()
|
||||
),
|
||||
));
|
||||
}
|
||||
let projected = units
|
||||
.iter()
|
||||
.map(|unit| {
|
||||
let mut entry = BTreeMap::new();
|
||||
entry.insert("id".to_string(), Value::text(unit.id.clone()));
|
||||
entry.insert(
|
||||
"path".to_string(),
|
||||
Value::List(
|
||||
unit.path
|
||||
.iter()
|
||||
.map(|part| Value::text(part.clone()))
|
||||
.collect(),
|
||||
),
|
||||
);
|
||||
entry.insert(
|
||||
"parent_id".to_string(),
|
||||
match &unit.parent_id {
|
||||
Some(parent) => Value::text(parent.clone()),
|
||||
None => Value::None,
|
||||
},
|
||||
);
|
||||
entry.insert("level".to_string(), Value::int(unit.level as i64));
|
||||
entry.insert("mode".to_string(), Value::text(unit.mode.clone()));
|
||||
entry.insert(
|
||||
"anchors".to_string(),
|
||||
Value::List(
|
||||
unit.anchors
|
||||
.iter()
|
||||
.map(|anchor| Value::text(anchor.clone()))
|
||||
.collect(),
|
||||
),
|
||||
);
|
||||
entry.insert("span".to_string(), span_value(unit.span));
|
||||
entry.insert(
|
||||
"heading_span".to_string(),
|
||||
match unit.heading_span {
|
||||
Some(span) => span_value(span),
|
||||
None => Value::None,
|
||||
},
|
||||
);
|
||||
Value::Map(entry)
|
||||
})
|
||||
.collect();
|
||||
let mut result = BTreeMap::new();
|
||||
result.insert("ok".to_string(), Value::Bool(true));
|
||||
result.insert("module".to_string(), Value::text(document.id.clone()));
|
||||
result.insert(
|
||||
"source_digest".to_string(),
|
||||
Value::text(document.source_digest.clone()),
|
||||
);
|
||||
result.insert("count".to_string(), Value::int(units.len() as i64));
|
||||
result.insert("units".to_string(), Value::List(projected));
|
||||
Ok(Value::Map(result))
|
||||
}
|
||||
|
||||
fn document_read(
|
||||
&mut self,
|
||||
module: &str,
|
||||
unit: &str,
|
||||
expected_digest: Option<&str>,
|
||||
max_bytes: usize,
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
const DEFAULT_MAX_BYTES: usize = 256 * 1024;
|
||||
const MAX_READ_BYTES: usize = 1024 * 1024;
|
||||
let Some(document) = self
|
||||
.documents
|
||||
.iter()
|
||||
.find(|candidate| candidate.id == module)
|
||||
else {
|
||||
return Ok(document_failure(
|
||||
"document.not_loaded",
|
||||
format!("module `{module}` is not part of the loaded snapshot"),
|
||||
));
|
||||
};
|
||||
if let Some(expected) = expected_digest.filter(|value| !value.is_empty()) {
|
||||
if expected != document.source_digest {
|
||||
return Ok(document_failure(
|
||||
"document.stale_source",
|
||||
format!(
|
||||
"expected source digest {expected}, loaded snapshot is {}",
|
||||
document.source_digest
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
let Some(selected) = document
|
||||
.units
|
||||
.iter()
|
||||
.find(|candidate| candidate.id == unit)
|
||||
.or_else(|| {
|
||||
document
|
||||
.units
|
||||
.iter()
|
||||
.find(|candidate| candidate.anchors.iter().any(|anchor| anchor == unit))
|
||||
})
|
||||
else {
|
||||
return Ok(document_failure(
|
||||
"document.unknown_unit",
|
||||
format!("module `{module}` has no unit or anchor `{unit}`"),
|
||||
));
|
||||
};
|
||||
let max_bytes = if max_bytes == 0 {
|
||||
DEFAULT_MAX_BYTES
|
||||
} else {
|
||||
max_bytes
|
||||
};
|
||||
if max_bytes > MAX_READ_BYTES {
|
||||
return Ok(document_failure(
|
||||
"document.too_large",
|
||||
format!("max_bytes {max_bytes} exceeds the maximum {MAX_READ_BYTES}"),
|
||||
));
|
||||
}
|
||||
let span = selected.span;
|
||||
if span.end < span.start || span.end > document.source.len() {
|
||||
return Ok(document_failure(
|
||||
"document.invalid_request",
|
||||
"the selected section span is outside the snapshot source".to_string(),
|
||||
));
|
||||
}
|
||||
if span.end - span.start > max_bytes {
|
||||
return Ok(document_failure(
|
||||
"document.too_large",
|
||||
format!(
|
||||
"section is {} bytes, above max_bytes {max_bytes}",
|
||||
span.end - span.start
|
||||
),
|
||||
));
|
||||
}
|
||||
let Some(text) = document.source.get(span.start..span.end) else {
|
||||
return Ok(document_failure(
|
||||
"document.invalid_request",
|
||||
"the selected section span is not on UTF-8 boundaries".to_string(),
|
||||
));
|
||||
};
|
||||
let mut result = BTreeMap::new();
|
||||
result.insert("ok".to_string(), Value::Bool(true));
|
||||
result.insert("module".to_string(), Value::text(document.id.clone()));
|
||||
result.insert("unit".to_string(), Value::text(selected.id.clone()));
|
||||
result.insert(
|
||||
"anchors".to_string(),
|
||||
Value::List(
|
||||
selected
|
||||
.anchors
|
||||
.iter()
|
||||
.map(|anchor| Value::text(anchor.clone()))
|
||||
.collect(),
|
||||
),
|
||||
);
|
||||
result.insert(
|
||||
"source_digest".to_string(),
|
||||
Value::text(document.source_digest.clone()),
|
||||
);
|
||||
result.insert("span".to_string(), span_value(span));
|
||||
result.insert("text".to_string(), Value::text(text.to_string()));
|
||||
let _ = ctx;
|
||||
Ok(Value::Map(result))
|
||||
}
|
||||
|
||||
fn consume_fuel(&mut self, amount: u64, span: Option<Span>) -> Result<(), RuntimeError> {
|
||||
if let Some(message) = &self.observation_error {
|
||||
return Err(RuntimeError::new(
|
||||
@@ -892,3 +1106,20 @@ pub fn arity(span: Option<Span>, name: &str, expected: usize, actual: usize) ->
|
||||
format!("`{name}` expects {expected} argument(s), got {actual}"),
|
||||
)
|
||||
}
|
||||
|
||||
/// Project one exact byte span as `{start, end}`.
|
||||
fn span_value(span: Span) -> Value {
|
||||
let mut value = BTreeMap::new();
|
||||
value.insert("start".to_string(), Value::int(span.start as i64));
|
||||
value.insert("end".to_string(), Value::int(span.end as i64));
|
||||
Value::Map(value)
|
||||
}
|
||||
|
||||
/// One structured document-access failure (never an execution crash).
|
||||
fn document_failure(code: &str, message: String) -> Value {
|
||||
let mut value = BTreeMap::new();
|
||||
value.insert("ok".to_string(), Value::Bool(false));
|
||||
value.insert("code".to_string(), Value::text(code.to_string()));
|
||||
value.insert("message".to_string(), Value::text(message));
|
||||
Value::Map(value)
|
||||
}
|
||||
@@ -230,6 +230,25 @@ const TABLE_ROW: Builtin = Builtin {
|
||||
named_only: false,
|
||||
effectful: false,
|
||||
};
|
||||
const DOCUMENT_OUTLINE: Builtin = Builtin {
|
||||
name: "document.outline",
|
||||
aliases: &[],
|
||||
params: &[opt("module"), opt("parent"), opt("limit")],
|
||||
named_only: false,
|
||||
effectful: false,
|
||||
};
|
||||
const DOCUMENT_READ: Builtin = Builtin {
|
||||
name: "document.read",
|
||||
aliases: &[],
|
||||
params: &[
|
||||
req("module"),
|
||||
req("unit"),
|
||||
opt("expected_digest"),
|
||||
opt("max_bytes"),
|
||||
],
|
||||
named_only: false,
|
||||
effectful: false,
|
||||
};
|
||||
const RESOURCE_OPEN: Builtin = Builtin {
|
||||
name: "resource.open",
|
||||
aliases: &[],
|
||||
@@ -315,6 +334,8 @@ pub const BUILTINS: &[Builtin] = &[
|
||||
TABLE_COLUMNS,
|
||||
TABLE_ROW,
|
||||
TABLE_CELL,
|
||||
DOCUMENT_OUTLINE,
|
||||
DOCUMENT_READ,
|
||||
RESOURCE_OPEN,
|
||||
RESOURCE_READ,
|
||||
RESOURCE_WRITE,
|
||||
|
||||
@@ -154,6 +154,19 @@ pub(crate) fn dispatch(
|
||||
&module,
|
||||
)
|
||||
}
|
||||
"document.outline" => {
|
||||
let target = optional_text(&bound, "module", builtin, span)?;
|
||||
let parent = optional_text(&bound, "parent", builtin, span)?;
|
||||
let limit = optional_count(&bound, "limit", builtin, span)?;
|
||||
interpreter.host_document_outline(target, parent, limit, span, &module)
|
||||
}
|
||||
"document.read" => {
|
||||
let target = required_text(&bound, "module", builtin, span)?;
|
||||
let unit = required_text(&bound, "unit", builtin, span)?;
|
||||
let digest = optional_text(&bound, "expected_digest", builtin, span)?;
|
||||
let max_bytes = optional_count(&bound, "max_bytes", builtin, span)?;
|
||||
interpreter.host_document_read(target, unit, digest, max_bytes, span, &module)
|
||||
}
|
||||
"memory.new" => {
|
||||
let initial_pages = page_count(take(&bound, "initial_pages", builtin, span)?, span)?;
|
||||
let max_pages = page_count(take(&bound, "max_pages", builtin, span)?, span)?;
|
||||
@@ -453,6 +466,63 @@ pub(crate) fn dispatch(
|
||||
}
|
||||
}
|
||||
|
||||
fn required_text(
|
||||
bound: &BTreeMap<String, Value>,
|
||||
name: &str,
|
||||
builtin: &Builtin,
|
||||
span: Option<Span>,
|
||||
) -> Result<String, RuntimeError> {
|
||||
match take(bound, name, builtin, span)? {
|
||||
Value::Text(text) => Ok(text),
|
||||
_ => Err(RuntimeError::type_error(
|
||||
span,
|
||||
format!("`{}` argument `{name}` must be Text", builtin.name),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn optional_text(
|
||||
bound: &BTreeMap<String, Value>,
|
||||
name: &str,
|
||||
builtin: &Builtin,
|
||||
span: Option<Span>,
|
||||
) -> Result<Option<String>, RuntimeError> {
|
||||
match bound.get(name) {
|
||||
None => Ok(None),
|
||||
Some(Value::Text(text)) => Ok(Some(text.clone())),
|
||||
Some(_) => Err(RuntimeError::type_error(
|
||||
span,
|
||||
format!("`{}` argument `{name}` must be Text", builtin.name),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn optional_count(
|
||||
bound: &BTreeMap<String, Value>,
|
||||
name: &str,
|
||||
builtin: &Builtin,
|
||||
span: Option<Span>,
|
||||
) -> Result<usize, RuntimeError> {
|
||||
match bound.get(name) {
|
||||
None => Ok(0),
|
||||
Some(Value::Int(value)) => num_traits::ToPrimitive::to_usize(value)
|
||||
.filter(|value| *value > 0)
|
||||
.ok_or_else(|| {
|
||||
RuntimeError::type_error(
|
||||
span,
|
||||
format!(
|
||||
"`{}` argument `{name}` must be a positive Int",
|
||||
builtin.name
|
||||
),
|
||||
)
|
||||
}),
|
||||
Some(_) => Err(RuntimeError::type_error(
|
||||
span,
|
||||
format!("`{}` argument `{name}` must be Int", builtin.name),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn take(
|
||||
bound: &BTreeMap<String, Value>,
|
||||
name: &str,
|
||||
|
||||
@@ -974,6 +974,47 @@ impl<'a> Interpreter<'a> {
|
||||
}
|
||||
|
||||
/// Call a builtin-read host operation on behalf of a frame's module.
|
||||
pub(crate) fn host_document_outline(
|
||||
&mut self,
|
||||
module: Option<String>,
|
||||
parent: Option<String>,
|
||||
limit: usize,
|
||||
span: Option<Span>,
|
||||
caller: &ModuleId,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
let context = ExecutionContext::new(caller.to_string(), span);
|
||||
self.host
|
||||
.document_outline(module.as_deref(), parent.as_deref(), limit, &context)
|
||||
.map_err(|mut error| {
|
||||
error.mark_callsite();
|
||||
error
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn host_document_read(
|
||||
&mut self,
|
||||
module: String,
|
||||
unit: String,
|
||||
expected_digest: Option<String>,
|
||||
max_bytes: usize,
|
||||
span: Option<Span>,
|
||||
caller: &ModuleId,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
let context = ExecutionContext::new(caller.to_string(), span);
|
||||
self.host
|
||||
.document_read(
|
||||
&module,
|
||||
&unit,
|
||||
expected_digest.as_deref(),
|
||||
max_bytes,
|
||||
&context,
|
||||
)
|
||||
.map_err(|mut error| {
|
||||
error.mark_callsite();
|
||||
error
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn host_invoke(
|
||||
&mut self,
|
||||
op: HostOp,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
@@ -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
|
||||
|
||||
@@ -64,7 +64,7 @@ Even when available:
|
||||
* The product version is independent of protocol versions: Analysis,
|
||||
Observation, CLI Tool, Plugin ABI v1, Foreign wire v1, Provider manifest v2
|
||||
and lock v4 keep their own identifiers.
|
||||
* The official bundled stdlib keeps its independent package version `0.2.0`.
|
||||
* The official bundled stdlib keeps its independent package version `0.3.0`.
|
||||
A plugin `.mq.md` package version such as `0.1.0` is also independent.
|
||||
* `project.marqdo` in `marqdo.yaml` is enforced in this release. SemVer
|
||||
prerelease rules apply: `>=3.0.0,<4.0.0` does **not** accept a prerelease core. Packages and Tools can use a prerelease range such as
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
# CLI 运行期文稿访问能力 — issue #24
|
||||
|
||||
Date: 2026-11-30. Branch: `codex/issue-24-document-runtime-read`.
|
||||
Baseline CLI commit: `8ad2f2cffabcea1072f772b4748606eb01dd0744`
|
||||
(the Bundle 0.3.0 pin merge; the candidate is the branch commit on top).
|
||||
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 侧另行验证。
|
||||
@@ -0,0 +1,126 @@
|
||||
# Marqdo Runtime Document Access
|
||||
|
||||
Current public contract for the read-only runtime view of already loaded
|
||||
documents: the `document.outline` and `document.read` builtins. It is
|
||||
implemented by the composition root's immutable snapshot
|
||||
(`crates/cli/src/document_snapshot.rs`), the neutral Host contract
|
||||
(`marqdo-host-contract`) and the native host (ADR-0074). Analysis revision 3
|
||||
remains the static external projection; this contract lets ordinary `.mq.md`
|
||||
programs read the same snapshot without a parser or host paths.
|
||||
|
||||
## 1. Snapshot scope and invariants
|
||||
|
||||
The snapshot contains exactly the modules `prepare` already loaded for this
|
||||
`run`/`call`: the entry module plus its explicit import closure. `check` and
|
||||
`inspect` never execute and therefore never expose it.
|
||||
|
||||
* Identity, ordering and spans match the Analysis revision 3 projection from
|
||||
the same load: canonical module id, canonical unit id, `path`,
|
||||
`parent_id`, level, effective mode, anchors, complete section `span`,
|
||||
`heading_span`, module `source_digest` (lowercase hex SHA-256) and the exact
|
||||
`source`.
|
||||
* The section `span` is the heading through the next heading of the same or a
|
||||
higher level, or EOF; the root covers the whole source. Spans are UTF-8
|
||||
half-open byte offsets into the exact module `source`.
|
||||
* Reading is pure and read-only: no file is opened, no module is loaded
|
||||
dynamically, no Markdown is parsed, no `@knowledge` is executed, no link is
|
||||
expanded, no worker/model/network is started.
|
||||
* The same run is deterministic: the same snapshot returns the same bytes,
|
||||
identities and ordering.
|
||||
* Snapshot budget: at most 128 modules and 16 MiB total source bytes per run.
|
||||
A project over budget keeps running, but document access reports
|
||||
`document.too_large` instead of serving a truncated view.
|
||||
|
||||
## 2. `document.outline(module?, parent?, limit?)`
|
||||
|
||||
All arguments are optional.
|
||||
|
||||
| Argument | Meaning |
|
||||
|---|---|
|
||||
| `module` | Target loaded module id. Defaults to the calling module. |
|
||||
| `parent` | Only direct children of this unit id. Empty/absent = all units. |
|
||||
| `limit` | Maximum units to return. Default 1024, maximum 4096. |
|
||||
|
||||
Success result:
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": true,
|
||||
"module": "root:demo@0.1.0::index.mq.md",
|
||||
"source_digest": "<64 lowercase hex>",
|
||||
"count": 3,
|
||||
"units": [
|
||||
{
|
||||
"id": "root:demo@0.1.0::index.mq.md#力学",
|
||||
"path": ["力学"],
|
||||
"parent_id": "root:demo@0.1.0::index.mq.md#",
|
||||
"level": 1,
|
||||
"mode": "knowledge",
|
||||
"anchors": ["力学"],
|
||||
"span": {"start": 0, "end": 120},
|
||||
"heading_span": {"start": 0, "end": 12}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
`units` is in document order (root first). The root has `path: []`,
|
||||
`parent_id: null`, `level: 0`, `heading_span: null` and its `span` covers the
|
||||
whole source. When more units match than `limit`, the result is
|
||||
`{ok: false, code: "document.too_large", ...}` — units are never silently
|
||||
dropped.
|
||||
|
||||
## 3. `document.read(module, unit, expected_digest?, max_bytes?)`
|
||||
|
||||
| Argument | Meaning |
|
||||
|---|---|
|
||||
| `module` | Target loaded module id (required). |
|
||||
| `unit` | Canonical unit id **or** one of its navigation anchors (required). |
|
||||
| `expected_digest` | Optional exact module source digest. Absent/empty = no binding. |
|
||||
| `max_bytes` | Maximum returned text bytes. Default 262144, maximum 1048576. |
|
||||
|
||||
Success result:
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": true,
|
||||
"module": "root:demo@0.1.0::index.mq.md",
|
||||
"unit": "root:demo@0.1.0::index.mq.md#力学/计算力",
|
||||
"anchors": ["计算力"],
|
||||
"source_digest": "<64 lowercase hex>",
|
||||
"span": {"start": 100, "end": 180},
|
||||
"text": "<exact UTF-8 source slice>"
|
||||
}
|
||||
```
|
||||
|
||||
`text` is exactly `source[span.start..span.end]` of the same snapshot; it is not
|
||||
a copy of a second knowledge body or a re-rendered document. Calling programs
|
||||
must treat it as data (never as system instructions).
|
||||
|
||||
## 4. Failure codes
|
||||
|
||||
Failures are result maps (`ok: false`), not execution crashes:
|
||||
|
||||
| Code | Meaning |
|
||||
|---|---|
|
||||
| `document.not_loaded` | The module is not part of this run's loaded snapshot. |
|
||||
| `document.unknown_unit` | The module has no unit id or anchor matching `unit`. |
|
||||
| `document.stale_source` | `expected_digest` is non-empty and differs from the loaded module digest. |
|
||||
| `document.too_large` | A limit/size (outline units, section bytes, snapshot budget) is exceeded. |
|
||||
| `document.invalid_request` | The selected span is outside the source or not on UTF-8 boundaries (defensive). |
|
||||
|
||||
Callers can branch on these codes with ordinary `if`/`else`; no exception or
|
||||
second result protocol exists.
|
||||
|
||||
## 5. Non-goals
|
||||
|
||||
* No arbitrary file, directory, network or package-cache access.
|
||||
* No dynamic import or loading of modules outside the prepared closure.
|
||||
* No execution of `@exec` functions from a read; `document.read` never runs
|
||||
project code.
|
||||
* No new Markdown/document syntax, no AI-specific metadata and no second
|
||||
document structure specification. The semantic authority remains
|
||||
`spec/mapping.md`, `spec/analysis.md` and `spec/document-structure.md`.
|
||||
* No guarantee about files changed on disk after preparation: the snapshot is
|
||||
the prepared load, and `expected_digest` reports whether the caller and the
|
||||
snapshot agree.
|
||||
+2
-2
@@ -63,9 +63,9 @@ not a provider session: no library is loaded and no framed request is sent.
|
||||
"status": "verified",
|
||||
"origin": "sibling",
|
||||
"name": "marqdo-stdlib",
|
||||
"version": "0.2.0",
|
||||
"version": "0.3.0",
|
||||
"tree_digest": "sha256:...",
|
||||
"instance_id": "stdlib:marqdo-stdlib@0.2.0"
|
||||
"instance_id": "stdlib:marqdo-stdlib@0.3.0"
|
||||
},
|
||||
"protocols": {
|
||||
"markdown_profile": "marqdo.md.v1",
|
||||
|
||||
@@ -367,6 +367,8 @@ host boundary. Names are stable; adding one requires a spec update.
|
||||
| `table.columns` | `(table: Table) -> List` | header names in column order |
|
||||
| `table.row` | `(table: Table, row: Int) -> List` | new list of row cells; non-negative coordinate |
|
||||
| `table.cell` | `(table: Table, row: Int, column: Int) -> Value` | cell value; non-negative coordinates |
|
||||
| `document.outline` | `(module?: Text, parent?: Text, limit?: Int) -> Map` | read-only outline of the prepared loaded-document snapshot; `{ok, module, source_digest, count, units}` (ADR-0074, spec/document-access.md) |
|
||||
| `document.read` | `(module: Text, unit: Text, expected_digest?: Text, max_bytes?: Int) -> Map` | exact UTF-8 source slice of one loaded unit id/anchor; `{ok, module, unit, anchors, source_digest, span, text}` or a structured `document.*` failure (ADR-0074) |
|
||||
| `resource.open` | `(kind: Text, descriptor: Text, rights: List) -> Resource` | capability-checked stream open (ADR-0025) |
|
||||
| `resource.read` | `(handle, memory: Memory, offset: Int, max_bytes: Int) -> Result` | bounded chunk read into Memory; `{count,eof}` |
|
||||
| `resource.write` | `(handle, memory: Memory, offset: Int, length: Int) -> Result` | bounded byte write; `{count}` |
|
||||
@@ -377,6 +379,13 @@ host boundary. Names are stable; adding one requires a spec update.
|
||||
| `foreign.run/call` | see `spec/foreign.md` | P5, capability-gated |
|
||||
| `fs.read/write` | see `spec/security.md` | capability-gated |
|
||||
|
||||
The `document.*` builtins read the immutable snapshot prepared by the same
|
||||
`prepare` step as Analysis. They never open files, parse Markdown, load a
|
||||
module dynamically, execute project code or access the network; a read is a
|
||||
byte-exact section slice. Expected data states (not loaded, unknown unit,
|
||||
stale digest, over budget) are structured result maps, not execution errors.
|
||||
See `spec/document-access.md` and ADR-0074.
|
||||
|
||||
`打印/print` is **Compat-C** (ADR-0031): the legacy `HostOp::Print` and its
|
||||
`Value::display()` formatting path are removed. When a loaded module calls the
|
||||
builtin, the loader injects `stdlib/io.mq.md` and sets a program-level
|
||||
|
||||
@@ -2,14 +2,14 @@
|
||||
"schema": "marqdo.stdlib-bundle-pin",
|
||||
"schema_version": 1,
|
||||
"name": "marqdo-stdlib",
|
||||
"version": "0.2.0",
|
||||
"version": "0.3.0",
|
||||
"source": {
|
||||
"kind": "ecosystem",
|
||||
"repository": "cflmy/marqdo",
|
||||
"commit": "48189243f747d5f73d5a38a565010e64e2db74e7",
|
||||
"commit": "ad88b1e9e50aec978cb23d4e5fe316bbb779967f",
|
||||
"producer": "scripts/build-stdlib.py",
|
||||
"note": "Phase B (ADR-0070): the accepted Bundle is assembled by the ecosystem root commit that pins the component gitlinks. No stdlib source tree exists in this repository."
|
||||
"note": "Phase B (ADR-0070): the accepted Bundle is assembled by the ecosystem root commit that pins the component gitlinks. 0.3.0 adds the merged std-data strict JSON entry; candidate root commit ad88b1e9 is the paired ecosystem input."
|
||||
},
|
||||
"tree_digest": "sha256:db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7",
|
||||
"tree_digest": "sha256:4e47b0ff4b1e17d252cc74f20837014298fed4831050d65ca0c69f9cbdac55e9",
|
||||
"aliases_digest": "sha256:5f513c0fdbb3c1e9829be3c9fa23a2d1e89cb8510073fb5eb1e8e2f5265a83bb"
|
||||
}
|
||||
Reference in new issue
Block a user