Compare commits

...
Author SHA1 Message Date
cflmy 7a0e8c4e42 docs: pin the evidence baseline commit
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/pr/main Pipeline was successful
The evidence consistency gate requires a commit/security SHA in every
docs/evidence Markdown file; record the Bundle-0.3.0 baseline commit so the
document-access evidence passes the same gate as the other records.
2026-11-30 15:45:07 +08:00
cflmy d7dbce68b6 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.
2026-11-30 15:42:30 +08:00
cflmy 8ad2f2cffa Merge pull request #28 from codex/bundle-0.3.0
ci/woodpecker/push/main Pipeline was successful
feat: pin official Bundle 0.3.0 (paired candidate)
2026-11-30 13:20:09 +08:00
cflmy 8e43a3d82c docs: align current Bundle references with 0.3.0
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/pr/main Pipeline was successful
The architecture boundary test hardcodes the accepted Bundle version; the
developer limits doc and the environment-report spec example name the current
Bundle identity. Update them together with the pin bump so the candidate
combination has one current Bundle identity. Historical release/evidence
records keep their original versions.
2026-11-30 13:08:03 +08:00
cflmy bc05b0aa6c feat: pin the official Bundle 0.3.0 candidate
Update the CLI's single Bundle pin to version 0.3.0, tree digest
sha256:4e47b0ff... and the paired ecosystem root commit ad88b1e9 which pins
the merged std-data strict JSON entry. This is the CLI-side input for the same
candidate combination (root Bundle bump + CLI pin); it does not add a second
manifest or release path.
2026-11-30 13:05:44 +08:00
cflmy 36666ab52b Merge pull request #27 from codex/issue-25-26-environment-document-contract
ci/woodpecker/push/main Pipeline was successful
feat: offline environment report + document-structure contract (#25/#26/#20)
2026-11-30 12:04:17 +08:00
cflmy 79da4d2ca4 Merge remote-tracking branch 'origin/master' into codex/issue-25-26-environment-document-contract
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/pr/main Pipeline was successful
2026-11-30 11:53:06 +08:00
cflmy a9ccb3a6da docs: record environment-report and document-contract evidence
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/pr/main Pipeline was successful
Add the reproducible evidence record for candidate 0f87f856: pinned
ecosystem Bundle identity, the full source gate list (fmt/clippy/638
workspace tests/boundaries/independent-build), the environment-report probes,
the release archive built with the embedded source SHA (package identity check
+ smoke PASS) and the Woodpecker push/PR lanes. Windows/macOS native lanes and
the strict VM lane stay UNVERIFIED.

Links the record from docs/STATUS.md.
2026-11-30 11:41:37 +08:00
cflmy 0f87f856db feat: add offline environment report and document-structure contract
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/pr/main Pipeline was canceled
Implements the two CLI-owned P0 sub-issues of the ecosystem architecture
tickets without adding document-language syntax.

Environment report (marqdo-cli#26 §9.2, binding for #20):
- `marqdo inspect --environment [--json]` emits `marqdo.environment` v1:
  producer version and build-embedded source commit, platform/arch/glibc and
  real strict probe, adjacent provider-worker version/SHA (offline
  `--build-info`, bounded), verified Bundle identity, current protocol
  revisions and path-free diagnostics. Project-independent, offline, and
  exclusive with document inspection flags.
- Release builds embed `MARQDO_BUILD_SOURCE_SHA`; the CI `build` lane sets it.
  `tools/release/package.py` refuses to stage an archive whose binaries report
  another commit or Bundle digest, and `tools/release/smoke.py` re-verifies the
  extracted archive.
- Spec: `spec/environment.md`. Tests: `environment_report.rs` (5 cases) and
  in-module unit tests; docs/releasing/COMPATIBILITY/STATUS updated.

Document-structure contract (marqdo-cli#25):
- `spec/document-structure.md` states the current author/tool semantics once:
  heading mode inheritance (nearest ancestor, only Exec H2 callable), unit
  identity and duplicate-name rules, anchor collision numbering, byte-exact
  half-open spans, `index.mq.md` entry vs directory-dependency import meaning,
  link != import != call, Proposed annotations marked not implemented, and the
  Analysis fields consumers may rely on. It links the single authoritative
  specs instead of duplicating them.
- Tests: `document_structure.rs` (6 cases) + docs_consistency coverage.

No runtime behavior change, no new language surface, no new cross-repo
dependency. `docs_consistency` and `architecture_boundaries` remain green.
2026-11-30 11:35:24 +08:00
cflmy 123a54cb3e Merge pull request 'docs: align RC.6 release scope and baseline Bundle input' (#23) from codex/issue-10-rc6-readiness into master
ci/woodpecker/push/main Pipeline was successful
Merge PR #23: align RC.6 release scope and baseline Bundle input
2026-11-28 00:48:39 +08:00
43 changed files with 3048 additions and 15 deletions

No files matched your search

+3
View File
@@ -81,6 +81,9 @@ steps:
- apt-get install -y --no-install-recommends ca-certificates git openssl python3 python3-jsonschema build-essential
# Release archives must ship both binaries: the provider worker is the
# only supported transport and resolution is a sibling-of-CLI lookup.
# The release commit is embedded in both binaries so `inspect
# --environment` and package/smoke evidence bind to the exact source SHA.
- export MARQDO_BUILD_SOURCE_SHA="$CI_COMMIT_SHA"
- cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
- test -x target/release/marqdo-provider-worker
- python3 tools/ci/fetch_ecosystem_bundle.py --out target/ecosystem-stdlib
+2
View File
@@ -101,6 +101,7 @@ consume this candidate's `check --emit` output.
| Analysis `calls[].state/target` | v3 projection | Projected from the unique binding; official stdlib aliases appear as `function`. The private binding table is not serialized. |
| Extension selection | lock v4 | `marqdo.yaml.extensions` only `./path` or `@alias/path`; declaration is not a grant; declared identity must match the lock (`ext.extension_lock_mismatch`). |
| Foreign wire | v1 | One-shot request envelope; provider descriptors are explicit. |
| Environment report | v1 | `inspect --environment --json` (`marqdo.environment`). Additive fields are compatible; code/semantic changes need a schema revision (spec/environment.md). It never projects paths, credentials or source. |
## Platform / feature evidence
@@ -124,6 +125,7 @@ portable/tested locally but the native platform lane has not run here;
| External conformance repository (`marqdo-extension-conformance`, frozen CLI) | PASS (7/7 categories against the published archive, fixture repo `015ff8ac…`; see the rc.3 evidence bundle) | UNVERIFIED | UNVERIFIED |
| Analysis v3 + Observation v1 + Python consumers | PASS (same-SHA CI contract lane and archive smoke; independent consumers) | UNVERIFIED | UNVERIFIED |
| CLI Tool revision 1 + independent consumers | PASS | UNVERIFIED | UNVERIFIED |
| Environment report (`inspect --environment`, embedded source SHA, Bundle identity) | PASS (workspace tests + CI build identity embedding) | UNVERIFIED | UNVERIFIED |
| Native ABI (`plugin inspect`, trusted call) | PASS (C fixture) | UNVERIFIED (host-native fixture) | **UNSUPPORTED** |
| Worker ABI + `fs.read` bridge | PASS (Unix) | UNVERIFIED | **UNSUPPORTED** (Unix-gated) |
| Foreign Python/Node | PASS (system `python3`/`node`) | UNVERIFIED | UNVERIFIED |
Generated
+1
View File
@@ -416,6 +416,7 @@ version = "3.0.0-rc.6"
dependencies = [
"clap",
"hex",
"libc",
"marqdo-expression",
"marqdo-foreign",
"marqdo-frontend",
+11 -1
View File
@@ -102,6 +102,7 @@ marqdo run index.mq.md # executes ## @exec main
marqdo run index.mq.md --output jsonl # live Observation JSON Lines
marqdo inspect index.mq.md --ast
marqdo inspect index.mq.md --signature
marqdo inspect --environment --json # offline installed-identity report
marqdo call index.mq.md main
```
@@ -270,6 +271,12 @@ 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.
`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.
Run everything:
@@ -399,7 +406,10 @@ tests/ conformance/negative corpus, embedding consumer an
[`plugin-abi.md`](spec/plugin-abi.md), [`math.md`](spec/math.md),
[`foreign.md`](spec/foreign.md), [`cli-tool.md`](spec/cli-tool.md),
[`analysis.md`](spec/analysis.md), [`observation.md`](spec/observation.md),
[`worker-ipc.md`](spec/worker-ipc.md);
[`worker-ipc.md`](spec/worker-ipc.md),
[`environment.md`](spec/environment.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.
+1
View File
@@ -30,6 +30,7 @@ hex = { workspace = true }
sha2 = { workspace = true }
semver = { workspace = true }
tempfile = { workspace = true }
libc = { workspace = true }
[[bin]]
name = "marqdo"
+28
View File
@@ -0,0 +1,28 @@
//! Embed the release source commit when the build supplies it.
//!
//! The release pipeline builds the archive from one commit and records the
//! same commit in `SOURCE_SHA`/`RELEASE_INFO.json`; embedding it here lets
//! `marqdo inspect --environment --json` report the exact product identity
//! without reading files next to the binary (marqdo-cli#26 §9.2). An ordinary
//! development build simply has no embedded commit and reports `null` instead
//! of guessing.
fn main() {
println!("cargo:rerun-if-env-changed=MARQDO_BUILD_SOURCE_SHA");
let Ok(sha) = std::env::var("MARQDO_BUILD_SOURCE_SHA") else {
return;
};
let sha = sha.trim();
let valid = sha.len() == 40
&& sha
.chars()
.all(|ch| ch.is_ascii_hexdigit() && !ch.is_ascii_uppercase());
if valid {
println!("cargo:rustc-env=MARQDO_BUILD_SOURCE_SHA={sha}");
} else {
println!(
"cargo:warning=MARQDO_BUILD_SOURCE_SHA is not a full lowercase 40-hex commit; \
the environment report will not claim a source commit"
);
}
}
+1 -1
View File
@@ -31,7 +31,7 @@ pub const SCHEMA: &str = "marqdo.analysis";
/// Current public revision.
pub const SCHEMA_VERSION: u32 = 3;
/// Markdown profile recorded by the producer.
const MARKDOWN_PROFILE: &str = "marqdo.md.v1";
pub const MARKDOWN_PROFILE: &str = "marqdo.md.v1";
/// Projection shared with `inspect --ast`.
pub fn document_projection(root: &marqdo_markdown::MdNode, source_len: usize) -> Value {
+11
View File
@@ -19,9 +19,20 @@ pub struct InspectFlags {
pub platform: bool,
/// Show declared/loaded extension identities (never grants).
pub extensions: bool,
/// Print the offline installed-environment diagnostic report.
///
/// Exclusive with document inspection: it needs no project and must not be
/// combined with project flags (enforced by the argument parser).
pub environment: bool,
}
pub fn inspect(file: Option<&Path>, flags: &InspectFlags, json: bool, plugins: &[PathBuf]) -> i32 {
// The installed-environment report is project-independent and must not
// prepare, load or execute anything. The argument parser rejects combining
// it with document-inspection flags.
if flags.environment {
return crate::environment::emit(json);
}
let prepared = match prepare_project(file, json, plugins) {
Ok(prepared) => prepared,
Err(code) => return code,
+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())
}
+443
View File
@@ -0,0 +1,443 @@
//! Offline installed-environment report (`marqdo inspect --environment`).
//!
//! This is the stable machine-readable diagnostic export required by
//! marqdo-cli#26 §9.2 / marqdo#56 §9.4. It reads only installed identity and
//! process-platform facts:
//!
//! * it never executes project code, opens a provider session, loads a plugin
//! or accesses the network;
//! * it never prints credentials, Analysis/source content, user data or
//! absolute host paths;
//! * a degraded installation is reported as data (`status` + stable
//! `diagnostics[].code`) instead of being hidden.
//!
//! The report schema is `marqdo.environment` version 1. It is intentionally
//! separate from the Analysis/Observation/CLI-Tool protocols: it describes the
//! installation used for feedback, not a project.
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use serde_json::{json, Value};
use marqdo_value::codes;
use crate::output;
/// Report schema name.
pub const SCHEMA: &str = "marqdo.environment";
/// Current report revision.
pub const SCHEMA_VERSION: u32 = 1;
/// Build-time source commit, when the release build supplied one.
const BUILD_SOURCE_SHA: Option<&str> = option_env!("MARQDO_BUILD_SOURCE_SHA");
/// Upper bound for reading the adjacent worker's offline build identity.
///
/// The command prints one small JSON line; the bound keeps a replaced or
/// broken sibling binary from hanging the diagnostic export.
const WORKER_BUILD_INFO_TIMEOUT: Duration = Duration::from_millis(750);
/// Build the complete environment report.
pub fn report() -> Value {
let mut diagnostics: Vec<Value> = Vec::new();
let producer = producer_json();
let platform = platform_json();
let worker = worker_json(&mut diagnostics);
let bundle = bundle_json(&mut diagnostics);
json!({
"schema": SCHEMA,
"schema_version": SCHEMA_VERSION,
"producer": producer,
"platform": platform,
"worker": worker,
"bundle": bundle,
"protocols": protocols_json(),
"diagnostics": diagnostics,
})
}
/// Print the report and return the process exit code.
///
/// Emitting a report always succeeds: a degraded installation is data, not a
/// command failure. Usage errors (for example combining `--environment` with a
/// project-inspection flag) are rejected by the argument parser before this
/// function runs.
pub fn emit(json_output: bool) -> i32 {
let report = report();
if json_output {
output::print_json(&report);
return 0;
}
let producer = &report["producer"];
let source = producer["source"]["sha"].as_str().unwrap_or("unavailable");
println!(
"marqdo {} (source {source})",
producer["version"].as_str().unwrap_or("unknown")
);
let platform = &report["platform"];
println!(
"platform: {}/{} ({})",
platform["os"].as_str().unwrap_or("unknown"),
platform["arch"].as_str().unwrap_or("unknown"),
platform["family"].as_str().unwrap_or("unknown")
);
if let Some(libc) = platform["libc"].as_object() {
let version = libc.get("version").and_then(Value::as_str).unwrap_or("");
println!(
"libc: {}{}",
libc.get("family")
.and_then(Value::as_str)
.unwrap_or("unknown"),
if version.is_empty() {
String::new()
} else {
format!(" {version}")
}
);
}
println!(
"worker: {}",
report["worker"]["status"].as_str().unwrap_or("unknown")
);
let bundle = &report["bundle"];
match bundle["status"].as_str().unwrap_or("unknown") {
"verified" => println!(
"bundle: {} {} (tree {})",
bundle["name"].as_str().unwrap_or("unknown"),
bundle["version"].as_str().unwrap_or("unknown"),
bundle["tree_digest"].as_str().unwrap_or("unknown")
),
status => println!("bundle: {status}"),
}
let protocols = &report["protocols"];
println!(
"protocols: analysis={} observation={} cli-tool={} plugin-abi={} provider-manifest={} lock={}",
protocols["analysis"],
protocols["observation"],
protocols["cli_tool"]["version"],
protocols["plugin_abi"]["version"].as_str().unwrap_or("unknown"),
protocols["provider_manifest"],
protocols["package_lock"]
);
let diagnostics = report["diagnostics"]
.as_array()
.cloned()
.unwrap_or_default();
if diagnostics.is_empty() {
println!("diagnostics: none");
} else {
for diagnostic in diagnostics {
println!(
"diagnostics: [{}] {}",
diagnostic["code"].as_str().unwrap_or("unknown"),
diagnostic["message"].as_str().unwrap_or("")
);
}
}
0
}
fn producer_json() -> Value {
let source = match BUILD_SOURCE_SHA {
Some(sha) => json!({"sha": sha, "origin": "embedded"}),
None => json!({"sha": null, "origin": "unavailable"}),
};
json!({
"name": "marqdo",
"version": env!("CARGO_PKG_VERSION"),
"source": source,
})
}
fn platform_json() -> Value {
let capabilities = marqdo_sandbox::PlatformCapabilities::detect();
json!({
"os": capabilities.os,
"arch": capabilities.arch,
"family": std::env::consts::FAMILY,
"libc": libc_json(),
"strict": serde_json::to_value(capabilities.strict).unwrap_or(Value::Null),
"worker_processes": capabilities.worker_processes,
})
}
fn libc_json() -> Value {
#[cfg(all(target_os = "linux", target_env = "gnu"))]
{
// SAFETY: `gnu_get_libc_version` returns a pointer to a static
// NUL-terminated string owned by the C library for the process
// lifetime; it is copied immediately and never retained.
let version = unsafe {
let pointer = libc::gnu_get_libc_version();
if pointer.is_null() {
None
} else {
Some(
std::ffi::CStr::from_ptr(pointer)
.to_string_lossy()
.into_owned(),
)
}
};
json!({"family": "glibc", "version": version})
}
#[cfg(target_env = "musl")]
{
json!({"family": "musl", "version": null})
}
#[cfg(not(any(all(target_os = "linux", target_env = "gnu"), target_env = "musl")))]
{
Value::Null
}
}
fn sibling_program(name: &str) -> Option<PathBuf> {
let executable = std::env::current_exe().ok()?;
let directory = executable.parent()?;
let file_name = if cfg!(windows) {
format!("{name}.exe")
} else {
name.to_string()
};
let candidate = directory.join(file_name);
candidate.is_file().then_some(candidate)
}
fn worker_json(diagnostics: &mut Vec<Value>) -> Value {
let Some(worker) = sibling_program("marqdo-provider-worker") else {
return json!({
"name": "marqdo-provider-worker",
"status": "absent",
"version": null,
"source_sha": null,
});
};
match read_worker_build_info(&worker) {
Ok((version, source_sha)) => json!({
"name": "marqdo-provider-worker",
"status": "present",
"version": version,
"source_sha": source_sha,
}),
Err(reason) => {
diagnostics.push(json!({
"code": codes::ENV_WORKER_INFO_UNAVAILABLE,
"message": "the adjacent provider worker did not report its offline build identity",
"detail": reason,
}));
json!({
"name": "marqdo-provider-worker",
"status": "present",
"version": null,
"source_sha": null,
})
}
}
}
/// Read the worker's single-shot `--build-info` document.
///
/// Only the version and a validated source SHA are retained; no path or
/// environment value is projected. The child is bounded and killed if the
/// installed binary does not answer in time.
fn read_worker_build_info(worker: &Path) -> Result<(String, Option<String>), String> {
let mut child = Command::new(worker)
.arg("--build-info")
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.map_err(|error| format!("cannot execute the adjacent provider worker: {error}"))?;
let deadline = Instant::now() + WORKER_BUILD_INFO_TIMEOUT;
loop {
match child.try_wait() {
Ok(Some(status)) => {
if !status.success() {
return Err("the adjacent provider worker rejected `--build-info`".to_string());
}
break;
}
Ok(None) => {
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
return Err("the adjacent provider worker did not answer in time".to_string());
}
std::thread::sleep(Duration::from_millis(10));
}
Err(error) => return Err(format!("cannot wait for the provider worker: {error}")),
}
}
let mut output = String::new();
child
.stdout
.take()
.ok_or_else(|| "the provider worker produced no output".to_string())?
.read_to_string(&mut output)
.map_err(|error| format!("cannot read the provider worker output: {error}"))?;
let value: Value = serde_json::from_str(output.trim())
.map_err(|_| "the provider worker output is not one JSON document".to_string())?;
if value.get("schema").and_then(Value::as_str) != Some("marqdo.build-info")
|| value.get("schema_version").and_then(Value::as_u64) != Some(1)
|| value.get("product").and_then(Value::as_str) != Some("marqdo-provider-worker")
{
return Err("the provider worker build identity is not a current document".to_string());
}
let version = value
.get("version")
.and_then(Value::as_str)
.filter(|version| !version.is_empty())
.ok_or_else(|| "the provider worker build identity has no version".to_string())?
.to_string();
let source_sha = match value.get("source_sha") {
Some(Value::Null) | None => None,
Some(Value::String(sha)) if is_source_sha(sha) => Some(sha.clone()),
Some(_) => {
return Err(
"the provider worker build identity has an invalid source commit".to_string(),
)
}
};
Ok((version, source_sha))
}
fn is_source_sha(sha: &str) -> bool {
sha.len() == 40
&& sha
.chars()
.all(|ch| ch.is_ascii_hexdigit() && !ch.is_ascii_uppercase())
}
fn bundle_json(diagnostics: &mut Vec<Value>) -> Value {
let origin = if std::env::var_os(crate::stdlib::STDLIB_DIR_ENV).is_some() {
"explicit-env"
} else {
"sibling"
};
match crate::stdlib::StdlibBundle::discover() {
Ok(Some(bundle)) => json!({
"status": "verified",
"origin": origin,
"name": bundle.name(),
"version": bundle.version(),
"tree_digest": bundle.digest(),
"instance_id": bundle.instance_id(),
}),
Ok(None) => json!({
"status": "absent",
"origin": null,
"name": null,
"version": null,
"tree_digest": null,
"instance_id": null,
}),
Err(error) => {
let (code, message) = categorize_bundle_error(&error);
diagnostics.push(json!({"code": code, "message": message}));
json!({
"status": "invalid",
"origin": origin,
"name": null,
"version": null,
"tree_digest": null,
"instance_id": null,
})
}
}
}
/// Map one bundle load failure to a stable code and a path-free message.
///
/// The raw loader error can contain an absolute host path, so it is never
/// projected: diagnostics carry a stable code and a fixed message.
fn categorize_bundle_error(error: &str) -> (&'static str, &'static str) {
if error.contains("digest mismatch") || error.contains("alias metadata digest") {
(
codes::ENV_STDLIB_DIGEST_MISMATCH,
"the installed stdlib Bundle does not match its declared digest",
)
} else if error.contains("cannot read")
|| error.contains("cannot open")
|| error.contains("cannot open stdlib directory")
{
(
codes::ENV_STDLIB_UNREADABLE,
"the installed stdlib Bundle cannot be read",
)
} else {
(
codes::ENV_STDLIB_INVALID,
"the installed stdlib Bundle is not a current verified Bundle",
)
}
}
fn protocols_json() -> Value {
json!({
"markdown_profile": crate::analysis::MARKDOWN_PROFILE,
"analysis": crate::analysis::SCHEMA_VERSION,
"observation": crate::observation::SCHEMA_VERSION,
"cli_tool": {
"version": crate::tool::PROTOCOL_VERSION,
"api_revision": crate::tool::API_REVISION,
},
"plugin_abi": {
"version": marqdo_plugin_abi::ABI_VERSION_STRING,
"major": marqdo_plugin_abi::ABI_MAJOR,
"minor": marqdo_plugin_abi::ABI_MINOR,
},
"provider_manifest": crate::provider_manifest::PROVIDER_SCHEMA_VERSION,
"package_lock": marqdo_package::LOCK_VERSION,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn report_is_one_current_document() {
let report = report();
assert_eq!(report["schema"], SCHEMA);
assert_eq!(report["schema_version"], 1);
assert_eq!(report["producer"]["name"], "marqdo");
assert_eq!(report["producer"]["version"], env!("CARGO_PKG_VERSION"));
assert!(report["platform"]["os"].is_string());
assert!(report["protocols"]["analysis"].is_number());
assert!(report["protocols"]["package_lock"].is_number());
assert!(report["diagnostics"].is_array());
}
#[test]
fn report_never_projects_absolute_host_paths_or_secrets() {
let text = serde_json::to_string(&report()).unwrap();
assert!(!text.contains("/root/"), "{text}");
assert!(!text.contains("\\Users\\"), "{text}");
assert!(!text.contains("token"), "{text}");
assert!(!text.contains("api_key"), "{text}");
assert!(!text.contains("secret"), "{text}");
}
#[test]
fn bundle_failures_map_to_stable_path_free_codes() {
let (code, message) =
categorize_bundle_error("stdlib digest mismatch: declared sha256:aa, actual sha256:bb");
assert_eq!(code, codes::ENV_STDLIB_DIGEST_MISMATCH);
assert!(!message.contains('/'));
let (code, _) = categorize_bundle_error("cannot read `/root/private/stdlib.json`: denied");
assert_eq!(code, codes::ENV_STDLIB_UNREADABLE);
let (code, _) = categorize_bundle_error("`/root/x` has no name");
assert_eq!(code, codes::ENV_STDLIB_INVALID);
}
#[test]
fn source_sha_validation_is_strict() {
assert!(is_source_sha("63776735e924ade279cdf59d5c733dc24bfdabbb"));
assert!(!is_source_sha("6377673"));
assert!(!is_source_sha("63776735E924ADE279CDF59D5C733DC24BFDABBB"));
assert!(!is_source_sha("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"));
}
}
+14 -1
View File
@@ -8,6 +8,8 @@ mod analysis;
mod args;
mod commands;
mod document_refs;
mod document_snapshot;
mod environment;
mod extension_descriptors;
mod extension_selection;
mod loader;
@@ -97,7 +99,7 @@ enum Command {
Call(CallArgs),
/// Statically check a document without executing it.
Check(CheckArgs),
/// Inspect AST, units, signatures, IR, references or platform support.
/// Inspect AST, units, signatures, IR, references, platform support or the installed environment.
Inspect(InspectArgs),
/// Conservative formatting: normalises line endings and trailing newlines.
Fmt(FmtArgs),
@@ -298,6 +300,16 @@ struct InspectArgs {
/// Print declared/loaded extension identities (never grants).
#[arg(long)]
extensions: bool,
/// Print the offline installed-environment diagnostic report.
///
/// Reads only installed identity and platform facts: no project code is
/// executed, no provider session is started and no absolute path,
/// credential or source content is printed (marqdo-cli#26 §9.2).
#[arg(
long,
conflicts_with_all = ["file", "ast", "units", "signature", "ir", "refs", "platform", "extensions", "plugin"]
)]
environment: bool,
/// Explicitly selected plugin manifest for extension inspection (repeatable).
#[arg(long = "plugin", value_name = "PATH")]
plugin: Vec<PathBuf>,
@@ -462,6 +474,7 @@ fn dispatch() -> i32 {
refs: args.refs,
platform: args.platform,
extensions: args.extensions,
environment: args.environment,
};
commands::inspect(args.file.as_deref(), &flags, args.json, &args.plugin)
}
+5
View File
@@ -156,6 +156,11 @@ impl StdlibBundle {
}
/// Declared stdlib version.
/// Declared Bundle name.
pub fn name(&self) -> &str {
&self.name
}
pub fn version(&self) -> &str {
&self.version
}
+2 -2
View File
@@ -16,12 +16,12 @@ use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
const SCHEMA: &str = "marqdo.cli-tool";
const PROTOCOL_VERSION: u32 = 1;
pub(crate) const PROTOCOL_VERSION: u32 = 1;
const RECORD_VERSION: u32 = 2;
const MAX_BUNDLE_FILES: usize = 4096;
const MAX_BUNDLE_BYTES: u64 = 256 * 1024 * 1024;
const API_REVISION: u32 = 1;
pub(crate) const API_REVISION: u32 = 1;
const BUILTIN_COMMANDS: &[&str] = &[
"init", "run", "call", "check", "inspect", "fmt", "plugin", "add", "remove", "lock", "sync",
+3 -1
View File
@@ -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",
+127
View File
@@ -300,3 +300,130 @@ fn current_contract_documents_do_not_reference_retired_interfaces() {
}
}
}
#[test]
fn environment_report_contract_is_documented_once() {
let root = repo_root();
let spec = read(&root.join("spec/environment.md"));
for needle in [
"marqdo.environment",
"schema_version: 1",
"inspect --environment",
"MARQDO_BUILD_SOURCE_SHA",
"env.stdlib_digest_mismatch",
"never project",
] {
assert!(
spec.contains(needle),
"spec/environment.md is missing `{needle}`"
);
}
assert!(
!root.join("spec/environment-v1.md").exists(),
"the environment report must have one current specification"
);
let readme = read(&root.join("README.md"));
assert!(
readme.contains("spec/environment.md"),
"README.md does not link the environment report spec"
);
let releasing = read(&root.join("docs/releasing.md"));
assert!(
releasing.contains("inspect --environment")
&& releasing.contains("MARQDO_BUILD_SOURCE_SHA"),
"docs/releasing.md does not document the identity binding"
);
let compatibility = read(&root.join("COMPATIBILITY.md"));
assert!(
compatibility.contains("Environment report"),
"COMPATIBILITY.md does not list the environment report contract"
);
}
#[test]
fn document_structure_contract_has_one_overview_and_author_entry_points() {
let root = repo_root();
let spec = read(&root.join("spec/document-structure.md"));
for needle in [
"## 1. Document root and heading modes",
"index.mq.md",
"link, import, call",
"Proposed",
] {
assert!(
spec.contains(needle),
"spec/document-structure.md is missing `{needle}`"
);
}
for linked in [
"mapping.md",
"analysis.md",
"references.md",
"package-format.md",
"heading-annotations-v1.md",
] {
assert!(
spec.contains(linked),
"spec/document-structure.md must link the single source {linked}"
);
}
assert!(
!root.join("spec/document-structure-v1.md").exists(),
"the document structure must have one current overview"
);
let readme = read(&root.join("README.md"));
assert!(
readme.contains("spec/document-structure.md"),
"README.md does not link the document structure contract"
);
let developers = read(&root.join("docs/developers/README.md"));
assert!(
developers.contains("document-structure.md"),
"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"
);
}
+203
View File
@@ -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"]);
}
+376
View File
@@ -0,0 +1,376 @@
//! Contract tests for `spec/document-structure.md` (marqdo-cli#25).
//!
//! These drive the real binary and assert only the current, implemented
//! document-structure semantics: heading modes and inheritance, unit identity
//! and scope rules, anchor collision numbering, byte-exact spans, `index.mq.md`
//! entry/import meaning, and the link ≠ import ≠ call separation.
#[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-structure-{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();
}
fn write_bytes(&self, relative: &str, contents: &[u8]) {
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 stderr(output: &Output) -> String {
String::from_utf8_lossy(&output.stderr).to_string()
}
fn check_document(dir: &Path, document: &str, artifact: &Path) -> serde_json::Value {
let output = cli(
&["check", document, "--emit", artifact.to_str().unwrap()],
dir,
);
assert!(
output.status.success(),
"check {document} failed: {}",
stderr(&output)
);
serde_json::from_slice(&std::fs::read(artifact).unwrap()).unwrap()
}
fn units(analysis: &serde_json::Value) -> Vec<&serde_json::Value> {
analysis["modules"][0]["units"]
.as_array()
.unwrap()
.iter()
.collect()
}
fn unit<'a>(analysis: &'a serde_json::Value, path: &[&str]) -> &'a serde_json::Value {
let path: Vec<String> = path.iter().map(|segment| segment.to_string()).collect();
units(analysis)
.into_iter()
.find(|unit| {
unit["path"]
.as_array()
.unwrap()
.iter()
.map(|segment| segment.as_str().unwrap())
.eq(path.iter().map(String::as_str))
})
.unwrap_or_else(|| panic!("missing unit {path:?}"))
}
#[test]
fn heading_modes_inherit_from_the_nearest_ancestor_not_a_sibling() {
let dir = TempDir::new("modes");
dir.write(
"index.mq.md",
"# @knowledge 数学\n\n\
## @exec main\n\n`return 1`\n\n\
## 普通说明\n\n这段是知识叙述。\n\n\
### 子节\n\n更多知识。\n\n\
## @exec 计算力\n\n`return 2`\n\n\
### 细节\n\n`return 3`\n",
);
let artifact = dir.path().join("analysis.json");
let analysis = check_document(dir.path(), "index.mq.md", &artifact);
let root = &units(&analysis)[0];
assert_eq!(root["path"], serde_json::json!([]));
assert_eq!(root["kind"], "root");
assert_eq!(root["mode"], "knowledge");
assert_eq!(root["mode_origin"], "default");
let namespace = unit(&analysis, &["数学"]);
assert_eq!(namespace["kind"], "namespace");
assert_eq!(namespace["parent_id"], root["id"]);
let main = unit(&analysis, &["数学", "main"]);
assert_eq!(main["kind"], "function");
assert_eq!(main["mode"], "exec");
assert_eq!(main["mode_origin"], "explicit");
assert!(main["function"].is_string());
assert_eq!(main["parent_id"], namespace["id"]);
// A sibling heading without a marker inherits the Knowledge H1, never the
// preceding Exec H2.
let knowledge = unit(&analysis, &["数学", "普通说明"]);
assert_eq!(knowledge["kind"], "knowledge");
assert_eq!(knowledge["mode"], "knowledge");
assert_eq!(knowledge["mode_origin"], "inherited");
assert_eq!(knowledge["mode_source_unit_id"], namespace["id"]);
assert!(knowledge["function"].is_null());
// An H3 under an Exec H2 is Exec and belongs to that function.
let section = unit(&analysis, &["数学", "计算力", "细节"]);
assert_eq!(section["kind"], "section");
assert_eq!(section["mode"], "exec");
assert_eq!(section["mode_origin"], "inherited");
assert_eq!(
section["parent_id"],
unit(&analysis, &["数学", "计算力"])["id"]
);
assert_eq!(
section["function"],
unit(&analysis, &["数学", "计算力"])["function"]
);
// A level-3 section under Knowledge never becomes callable.
let knowledge_section = unit(&analysis, &["数学", "普通说明", "子节"]);
assert_eq!(knowledge_section["kind"], "section");
assert!(knowledge_section["function"].is_null());
}
#[test]
fn same_name_is_addressable_in_different_parents_but_rejected_in_one_scope() {
let allowed = TempDir::new("same-name-allowed");
allowed.write(
"index.mq.md",
"# @knowledge 甲\n\n## 说明\n\nA\n\n# @knowledge 乙\n\n## 说明\n\nB\n",
);
let analysis = check_document(
allowed.path(),
"index.mq.md",
&allowed.path().join("analysis.json"),
);
let first = unit(&analysis, &["甲", "说明"]);
let second = unit(&analysis, &["乙", "说明"]);
assert_ne!(first["id"], second["id"]);
let anchors = analysis["modules"][0]["anchors"].as_array().unwrap();
assert_eq!(anchors.len(), 4);
assert_eq!(
anchors
.iter()
.find(|anchor| anchor["anchor"] == "说明")
.unwrap()["unit_id"],
first["id"]
);
assert_eq!(
anchors
.iter()
.find(|anchor| anchor["anchor"] == "说明-2")
.unwrap()["unit_id"],
second["id"]
);
let rejected = TempDir::new("same-name-rejected");
rejected.write(
"index.mq.md",
"# @knowledge 数学\n\n## @exec 计算\n\n`return 1`\n\n## @exec 计算\n\n`return 2`\n",
);
let artifact = rejected.path().join("analysis.json");
let output = cli(
&["check", "index.mq.md", "--emit", artifact.to_str().unwrap()],
rejected.path(),
);
assert_eq!(output.status.code(), Some(1));
assert!(
stderr(&output).contains("sem.duplicate_unit_name"),
"unexpected stderr: {}",
stderr(&output)
);
assert!(
!artifact.exists(),
"a failed check must not leave an Analysis artifact"
);
}
#[test]
fn spans_are_half_open_utf8_bytes_even_with_bom_crlf_and_no_final_newline() {
let dir = TempDir::new("spans");
let mut bytes = Vec::new();
bytes.extend_from_slice(b"\xef\xbb\xbf"); // UTF-8 BOM
bytes.extend_from_slice("# @knowledge 数学\r\n\r\n## @exec 计算\r\n\r\n`return 1`".as_bytes()); // CRLF line endings, no trailing newline
dir.write_bytes("index.mq.md", &bytes);
let analysis = check_document(dir.path(), "index.mq.md", &dir.path().join("analysis.json"));
let module = &analysis["modules"][0];
let source = module["source"].as_str().unwrap();
assert_eq!(source.as_bytes(), bytes.as_slice());
assert_eq!(module["document"]["span"]["start"], 0);
assert_eq!(module["document"]["span"]["end"], bytes.len());
for unit in units(&analysis) {
let start = unit["span"]["start"].as_u64().unwrap() as usize;
let end = unit["span"]["end"].as_u64().unwrap() as usize;
assert!(start <= end && end <= bytes.len(), "span out of range");
assert!(
std::str::from_utf8(&bytes[start..end]).is_ok(),
"span is not on UTF-8 boundaries"
);
if let Some(heading) = unit["heading_span"].as_object() {
let hs = heading["start"].as_u64().unwrap() as usize;
let he = heading["end"].as_u64().unwrap() as usize;
assert_eq!(bytes[hs], b'#', "heading_span must start at the heading");
assert!(std::str::from_utf8(&bytes[hs..he]).is_ok());
}
}
// The function section runs to EOF because it is the last heading.
let function = unit(&analysis, &["数学", "计算"]);
assert_eq!(
function["span"]["end"].as_u64().unwrap() as usize,
bytes.len()
);
let heading_start = function["heading_span"]["start"].as_u64().unwrap() as usize;
assert_eq!(&bytes[heading_start..heading_start + 2], b"##");
}
#[test]
fn index_md_is_the_entry_and_a_directory_dependency_resolves_to_its_index() {
let dir = TempDir::new("index-entry");
dir.write(
"marqdo.yaml",
"project:\n name: demo\n version: 0.1.0\ndependencies:\n geo:\n path: ./geometry\n",
);
dir.write(
"geometry/index.mq.md",
"# @knowledge 几何\n\n## @exec 面积\n\n`return 6`\n",
);
dir.write(
"index.mq.md",
"---\nimport:\n geo: '@geo'\n---\n\n# @knowledge 主\n\n## @exec main\n\n`return 1`\n",
);
let lock = cli(&["lock"], dir.path());
assert!(lock.status.success(), "lock failed: {}", stderr(&lock));
let analysis = check_document(dir.path(), "index.mq.md", &dir.path().join("analysis.json"));
assert_eq!(
analysis["project"]["entry_module_id"],
"root:demo@0.1.0::index.mq.md"
);
let modules = analysis["modules"].as_array().unwrap();
assert_eq!(modules.len(), 2, "no implicit modules may be loaded");
let dependency = modules
.iter()
.find(|module| module["id"].as_str().unwrap().starts_with("dep:geo@"))
.expect("dependency module");
assert!(
dependency["id"]
.as_str()
.unwrap()
.ends_with("::index.mq.md"),
"a directory dependency resolves to its index.mq.md"
);
let root = modules
.iter()
.find(|module| module["id"] == "root:demo@0.1.0::index.mq.md")
.unwrap();
assert_eq!(
root["imports"][0]["resolved"], dependency["id"],
"the explicit import names the dependency index module"
);
assert!(
dependency["units"]
.as_array()
.unwrap()
.iter()
.any(|unit| unit["path"] == serde_json::json!(["几何", "面积"])),
"the dependency index is a normal document with normal units"
);
}
#[test]
fn a_markdown_link_is_neither_an_import_nor_a_call() {
let dir = TempDir::new("link-only");
dir.write(
"index.mq.md",
"# @knowledge 主\n\n[另一个文稿](other.mq.md)\n\n## @exec main\n\n`return 1`\n",
);
dir.write("other.mq.md", "# @knowledge 其他\n\n## 说明\n\n正文\n");
let plain = check_document(dir.path(), "index.mq.md", &dir.path().join("plain.json"));
assert_eq!(plain["modules"].as_array().unwrap().len(), 1);
let reference = &plain["modules"][0]["references"][0];
assert_eq!(reference["state"], "not_loaded");
assert!(plain["modules"][0]["imports"]
.as_array()
.unwrap()
.is_empty());
assert!(plain["modules"][0]["calls"].as_array().unwrap().is_empty());
// `check --refs` verifies local link targets through the explicit
// verification catalog; it still does not import the target or add it to
// the program, and the emitted Analysis keeps the loaded-only reference
// projection (`not_loaded` means "not part of this program", not "missing").
let refs_artifact = dir.path().join("refs.json");
let output = cli(
&[
"check",
"index.mq.md",
"--refs",
"--emit",
refs_artifact.to_str().unwrap(),
],
dir.path(),
);
assert!(output.status.success(), "{}", stderr(&output));
assert!(
!stderr(&output).contains("ref."),
"an existing local link target must not produce a refs diagnostic: {}",
stderr(&output)
);
let refs: serde_json::Value =
serde_json::from_slice(&std::fs::read(&refs_artifact).unwrap()).unwrap();
assert_eq!(refs["modules"].as_array().unwrap().len(), 1);
assert_eq!(refs["modules"][0]["references"][0]["state"], "not_loaded");
assert!(refs["modules"][0]["imports"].as_array().unwrap().is_empty());
assert!(refs["modules"][0]["calls"].as_array().unwrap().is_empty());
}
#[test]
fn unknown_mode_markers_are_still_hard_errors() {
let dir = TempDir::new("bad-marker");
dir.write("index.mq.md", "# @knowledge 数学\n\n## @foo 标题\n\n正文\n");
let artifact = dir.path().join("analysis.json");
let output = cli(
&["check", "index.mq.md", "--emit", artifact.to_str().unwrap()],
dir.path(),
);
assert_eq!(output.status.code(), Some(1));
assert!(
stderr(&output).contains("sem.invalid_mode_marker"),
"unexpected stderr: {}",
stderr(&output)
);
assert!(!artifact.exists());
}
+211
View File
@@ -0,0 +1,211 @@
//! Black-box tests for `marqdo inspect --environment` (marqdo-cli#26 §9.2).
//!
//! The report is the offline diagnostic export used by feedback tooling. These
//! tests drive the real binary and assert the stable schema, the honest
//! degraded-installation representation, the argument boundary and the
//! no-secret/no-absolute-path rule.
#[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-environment-{tag}-{}-{nanos}",
std::process::id()
));
std::fs::create_dir_all(&path).unwrap();
Self(path)
}
fn path(&self) -> &Path {
&self.0
}
}
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 stdout(output: &Output) -> String {
String::from_utf8_lossy(&output.stdout).to_string()
}
fn json(output: &Output) -> serde_json::Value {
serde_json::from_slice(&output.stdout).unwrap_or_else(|error| {
panic!(
"stdout is not JSON: {error}\n{}",
String::from_utf8_lossy(&output.stdout)
)
})
}
#[test]
fn environment_report_is_stable_and_project_independent() {
let dir = TempDir::new("no-project");
let output = cli(&["inspect", "--environment", "--json"], dir.path());
assert!(
output.status.success(),
"inspect --environment failed: {}",
String::from_utf8_lossy(&output.stderr)
);
let report = json(&output);
assert_eq!(report["schema"], "marqdo.environment");
assert_eq!(report["schema_version"], 1);
assert_eq!(report["producer"]["name"], "marqdo");
assert_eq!(report["producer"]["version"], env!("CARGO_PKG_VERSION"));
let source_sha = &report["producer"]["source"]["sha"];
if let Some(sha) = source_sha.as_str() {
assert_eq!(sha.len(), 40, "embedded source SHA must be a full commit");
assert!(sha
.chars()
.all(|ch| ch.is_ascii_hexdigit() && !ch.is_ascii_uppercase()));
} else {
assert_eq!(report["producer"]["source"]["origin"], "unavailable");
}
assert!(report["platform"]["os"].is_string());
assert!(report["platform"]["arch"].is_string());
assert!(report["platform"]["strict"].is_object());
assert_eq!(report["protocols"]["analysis"], 3);
assert_eq!(report["protocols"]["observation"], 1);
assert_eq!(report["protocols"]["cli_tool"]["api_revision"], 1);
assert_eq!(report["protocols"]["package_lock"], 4);
assert_eq!(report["protocols"]["markdown_profile"], "marqdo.md.v1");
assert!(report["worker"]["status"].is_string());
assert!(report["bundle"]["status"].is_string());
assert!(report["diagnostics"].is_array());
// The report is deterministic: the same installation emits the same bytes.
let again = cli(&["inspect", "--environment", "--json"], dir.path());
assert_eq!(output.stdout, again.stdout);
}
#[test]
fn environment_report_never_leaks_paths_or_secrets() {
let dir = TempDir::new("no-leak");
let output = cli(&["inspect", "--environment", "--json"], dir.path());
assert!(output.status.success());
let text = stdout(&output);
assert!(!text.contains(dir.path().to_str().unwrap()), "{text}");
assert!(!text.contains("/root/"), "{text}");
assert!(!text.contains("\\Users\\"), "{text}");
for forbidden in [
"token",
"api_key",
"secret",
"password",
"BEGIN PRIVATE KEY",
] {
assert!(
!text.to_ascii_lowercase().contains(forbidden),
"report contains forbidden field {forbidden}: {text}"
);
}
// No project source is ever projected.
assert!(!text.contains("@exec"), "{text}");
assert!(!text.contains("source_bytes"), "{text}");
}
/// Write a syntactically valid Bundle whose declared digest matches its tree.
///
/// This exercises the report's verified path without network access; the real
/// product Bundle is verified by the stdlib/product tests.
fn write_valid_bundle(root: &Path) -> serde_json::Value {
std::fs::write(root.join("io.mq.md"), "# @knowledge io\n\n`print`\n").unwrap();
let digest = stdlib_support::tree_digest(root).unwrap();
let manifest = serde_json::json!({
"name": "marqdo-stdlib",
"version": "0.0.0-test",
"digest": digest,
});
std::fs::write(
root.join("stdlib.json"),
serde_json::to_string_pretty(&manifest).unwrap(),
)
.unwrap();
manifest
}
#[test]
fn verified_bundle_is_reported_with_its_public_identity() {
let bundle = TempDir::new("bundle");
let manifest = write_valid_bundle(bundle.path());
let dir = TempDir::new("bundle-project");
let output = stdlib_support::cli_command()
.args(["inspect", "--environment", "--json"])
.env("MARQDO_STDLIB_DIR", bundle.path())
.current_dir(dir.path())
.output()
.unwrap();
assert!(output.status.success());
let report = json(&output);
assert_eq!(report["bundle"]["status"], "verified");
assert_eq!(report["bundle"]["origin"], "explicit-env");
assert_eq!(report["bundle"]["name"], manifest["name"]);
assert_eq!(report["bundle"]["version"], manifest["version"]);
assert_eq!(report["bundle"]["tree_digest"], manifest["digest"]);
assert_eq!(
report["bundle"]["tree_digest"].as_str().unwrap(),
stdlib_support::tree_digest(bundle.path()).unwrap()
);
assert!(report["diagnostics"].as_array().unwrap().is_empty());
let text = stdout(&output);
assert!(!text.contains(bundle.path().to_str().unwrap()), "{text}");
}
#[test]
fn invalid_bundle_is_reported_as_data_with_a_stable_path_free_code() {
let bundle = TempDir::new("bad-bundle");
std::fs::write(
bundle.path().join("stdlib.json"),
"{\"name\":\"broken\",\"version\":\"0.0.0\",\"digest\":\"sha256:00\"}",
)
.unwrap();
let dir = TempDir::new("bad-bundle-project");
let output = stdlib_support::cli_command()
.args(["inspect", "--environment", "--json"])
.env("MARQDO_STDLIB_DIR", bundle.path())
.current_dir(dir.path())
.output()
.unwrap();
// A degraded installation is reported, not turned into a command failure.
assert!(output.status.success());
let report = json(&output);
assert_eq!(report["bundle"]["status"], "invalid");
assert_eq!(report["bundle"]["origin"], "explicit-env");
let diagnostics = report["diagnostics"].as_array().unwrap();
assert_eq!(diagnostics.len(), 1);
assert_eq!(diagnostics[0]["code"], "env.stdlib_digest_mismatch");
let text = stdout(&output);
assert!(!text.contains(bundle.path().to_str().unwrap()), "{text}");
}
#[test]
fn environment_is_exclusive_with_document_inspection() {
let dir = TempDir::new("exclusive");
let output = cli(&["inspect", "--environment", "--platform"], dir.path());
assert_eq!(output.status.code(), Some(2));
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
stderr.contains("cannot be used with"),
"unexpected stderr: {stderr}"
);
}
@@ -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>,
}
+41
View File
@@ -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>;
+2
View File
@@ -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;
+232 -1
View File
@@ -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)
}
+21
View File
@@ -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,
+25
View File
@@ -0,0 +1,25 @@
//! Embed the release source commit when the build supplies it.
//!
//! `marqdo inspect --environment --json` reports the adjacent worker build
//! identity through the worker's offline `--build-info` command. The commit is
//! optional: a development build reports `null` rather than a guessed SHA.
fn main() {
println!("cargo:rerun-if-env-changed=MARQDO_BUILD_SOURCE_SHA");
let Ok(sha) = std::env::var("MARQDO_BUILD_SOURCE_SHA") else {
return;
};
let sha = sha.trim();
let valid = sha.len() == 40
&& sha
.chars()
.all(|ch| ch.is_ascii_hexdigit() && !ch.is_ascii_uppercase());
if valid {
println!("cargo:rustc-env=MARQDO_BUILD_SOURCE_SHA={sha}");
} else {
println!(
"cargo:warning=MARQDO_BUILD_SOURCE_SHA is not a full lowercase 40-hex commit; \
the worker build-info will not claim a source commit"
);
}
}
+27
View File
@@ -14,6 +14,15 @@ const ABI_VERSION: u32 = 1;
const MAX_FRAME_BYTES: usize = 1024 * 1024;
const ERROR_MAX: usize = 1024;
/// Offline build identity printed by `--build-info`.
///
/// `marqdo inspect --environment --json` runs this single-shot command to
/// report the adjacent worker version/SHA without opening a provider session
/// (marqdo-cli#26 §9.2).
const BUILD_INFO_SCHEMA: &str = "marqdo.build-info";
const BUILD_INFO_SCHEMA_VERSION: u32 = 1;
const BUILD_SOURCE_SHA: Option<&str> = option_env!("MARQDO_BUILD_SOURCE_SHA");
type AbiVersionFn = unsafe extern "C" fn() -> u32;
type OpenFn = unsafe extern "C" fn(*const c_char, *const c_char, *const c_char, *mut u64) -> i32;
type ReadFn = unsafe extern "C" fn(u64, *mut u8, u32, *mut u32, *mut i32) -> i32;
@@ -144,7 +153,25 @@ fn fail(message: &str) -> Json {
json!({"ok": false, "code": "host.error", "message": message})
}
/// Print one deterministic build-identity document and exit.
fn print_build_info() {
println!(
"{}",
json!({
"schema": BUILD_INFO_SCHEMA,
"schema_version": BUILD_INFO_SCHEMA_VERSION,
"product": "marqdo-provider-worker",
"version": env!("CARGO_PKG_VERSION"),
"source_sha": BUILD_SOURCE_SHA,
})
);
}
fn main() {
if std::env::args_os().nth(1).as_deref() == Some(std::ffi::OsStr::new("--build-info")) {
print_build_info();
return;
}
let Some(path) = std::env::args_os().nth(1) else {
eprintln!("usage: marqdo-provider-worker <c-abi-library>");
std::process::exit(2);
@@ -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,
+41
View File
@@ -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,
+8
View File
@@ -78,6 +78,14 @@ pub mod codes {
pub const REF_INVALID: &str = "ref.invalid";
/// A Markdown reference target was not verified by the current catalog.
pub const REF_NOT_LOADED: &str = "ref.not_loaded";
/// The installed stdlib Bundle cannot be read (`inspect --environment`).
pub const ENV_STDLIB_UNREADABLE: &str = "env.stdlib_unreadable";
/// The installed stdlib Bundle is not a current verified Bundle.
pub const ENV_STDLIB_INVALID: &str = "env.stdlib_invalid";
/// The installed stdlib Bundle does not match its declared digest.
pub const ENV_STDLIB_DIGEST_MISMATCH: &str = "env.stdlib_digest_mismatch";
/// The adjacent provider worker did not report its build identity.
pub const ENV_WORKER_INFO_UNAVAILABLE: &str = "env.worker_info_unavailable";
/// The requested math operation is outside the supported subset.
pub const MATH_UNSUPPORTED: &str = "math.unsupported";
/// A foreign language kernel is not available on this machine.
+51
View File
@@ -79,6 +79,57 @@ 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
current author/tool semantics in one place: heading mode inheritance (nearest
ancestor, never a sibling; only Exec H2 callable), unit identity and
`sem.duplicate_unit_name`, anchor slug collision numbering, byte-exact
half-open spans (BOM/CRLF/missing final newline), `index.mq.md` entry vs
directory-dependency import meaning, and the link ≠ import ≠ call separation.
It links the authoritative `mapping.md`/`analysis.md`/`references.md`/
`package-format.md` facts instead of duplicating them, marks heading annotations
as Proposed (not implemented) and lists the Analysis fields consumers may rely
on. Contract tests: `crates/cli/tests/document_structure.rs` (6 cases) plus
`docs_consistency`. No document-language syntax was added; no runtime behavior
changed.
## 0.12 Installed-environment diagnostic report — issue #26 §9.2 (unreleased)
`marqdo inspect --environment --json` emits the `marqdo.environment` v1 report:
product version, build-embedded source commit, platform (including the real
strict probe and glibc version), adjacent provider-worker build identity,
verified Bundle name/version/tree digest, current protocol revisions and
path-free diagnostics. It is offline and project-independent: it does not load
a module, start a provider session, open a plugin or print a path/credential.
* Spec: [`spec/environment.md`](../spec/environment.md).
* Tests: `crates/cli/tests/environment_report.rs` (schema, determinism,
no-leak, verified/invalid Bundle, argument exclusivity) and unit tests in
`crates/cli/src/environment.rs`.
* Release binding: the release build embeds `MARQDO_BUILD_SOURCE_SHA`;
`tools/release/package.py` refuses an archive whose binary reports another
commit, and `tools/release/smoke.py` re-verifies the extracted archive. CI's
`build` lane exports the variable before `cargo build --release`.
* Window/macOS native lanes are **UNVERIFIED**; the report is Linux-verified
only. This work is not part of the tagged rc.6 release record.
* Evidence: [`evidence/2026-11-30-cli-environment-and-document-contract.md`](evidence/2026-11-30-cli-environment-and-document-contract.md)
(source gates, workspace tests, archive identity binding and smoke PASS).
## 0.11 Explicit stdlib Bundle input — issue #11 Phase A (unreleased)
Phase A lands the build-input boundary only: the stdlib production sources and
+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.
+13 -2
View File
@@ -40,9 +40,15 @@ Foreign wire v1, Provider manifest v2, lock v4 and markdown profile
providers, extension selection and lock v4.
5. [analysis-observation.md](analysis-observation.md) — the public static/dynamic data
contracts and digest binding.
6. [compatibility.md](compatibility.md) — version axes, platform matrix and the
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. [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.
7. [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
@@ -82,8 +88,13 @@ export MARQDO_BIN=/absolute/path/to/marqdo
# Put marqdo-provider-worker next to it for provider tests, exactly as the
# release archive does.
$MARQDO_BIN --version
$MARQDO_BIN inspect --environment --json # version, embedded source SHA, Bundle, protocols
```
The environment report is the supported way to record which CLI/Bundle a
consumer tested against; see [`../../spec/environment.md`](../../spec/environment.md).
It reads only installed identity and prints no host paths or credentials.
Compute the binary SHA-256 before and after your suite; it must not move. The
reference implementation of this gate is
[`marqdo-extension-conformance`](https://git.cflmy.cn/cflmy/marqdo-extension-conformance)
+1 -1
View File
@@ -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,141 @@
# CLI 0f87f85 — offline environment report, release identity binding and document-structure contract
Date: 2026-11-30.
Repository: `cflmy/marqdo-cli`.
Candidate commit: `0f87f856dba28e34bbd2743d23b8f9b1fe96424a`
(branch `codex/issue-25-26-environment-document-contract`, PR
[#27](https://git.cflmy.cn/cflmy/marqdo-cli/pulls/27)).
Issues: [marqdo-cli#26](https://git.cflmy.cn/cflmy/marqdo-cli/issues/26) §9.2
(P1), [marqdo-cli#25](https://git.cflmy.cn/cflmy/marqdo-cli/issues/25),
[marqdo-cli#20](https://git.cflmy.cn/cflmy/marqdo-cli/issues/20) binding.
Parent tickets: `marqdo#55`, `marqdo#56`.
Executed host: Linux x86_64, glibc 2.43
(`rustc 1.100.0 (0ef1bc386 2026-11-09)`, `cargo 1.100.0 (3acc79c0c 2026-11-05)`,
Python 3.14.4). Windows/macOS native lanes were **not** run (no runner in this
environment) and remain `UNVERIFIED`.
## 1. Bundle input
`python3 tools/ci/fetch_ecosystem_bundle.py --out target/ecosystem-stdlib`
materialized the pinned ecosystem Bundle (pin commit
`48189243f747d5f73d5a38a565010e64e2db74e7`, components
`stdlib/{collections,data,fs,io,system,text}` at their pinned gitlinks):
```text
name: marqdo-stdlib
version: 0.2.0
tree_digest: sha256:db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7
aliases_digest: sha256:5f513c0fdbb3c1e9829be3c9fa23a2d1e89cb8510073fb5eb1e8e2f5265a83bb
files: 18
```
All workspace tests below ran with
`MARQDO_TEST_STDLIB_BUNDLE="$PWD/target/ecosystem-stdlib"`.
## 2. Source-level gates
| Command | Result |
|---|---|
| `cargo fmt --all -- --check` | PASS |
| `cargo clippy --workspace --all-targets -- -D warnings` | PASS |
| `cargo test --workspace --locked` | PASS: 638 passed, 0 failed, 2 ignored (74 suites) |
| `cargo test -p marqdo-cli --test docs_consistency` | PASS: 9 passed |
| `cargo test -p marqdo-cli --test environment_report` | PASS: 5 passed |
| `cargo test -p marqdo-cli --test document_structure` | PASS: 6 passed |
| `python3 tools/ci/check_dependency_boundaries.py` | PASS |
| `python3 tools/ci/check_engine_boundary.py` | PASS |
| `python3 tools/ci/check_plugin_sdk.py` | PASS |
| `python3 tools/ci/independent_build.py` | PASS (PASS payload, clean target dir) |
| `python3 -m unittest discover -s tools/ci -p 'test_*.py'` | PASS: 80 tests |
| `python3 -m unittest discover -s tools/ci -p 'test_release*.py'` | PASS: 29 tests (10 skipped by platform guards) |
Note: `cargo clippy` must be invoked as
`cargo clippy --workspace --all-targets -- -D warnings` (one `--`). A doubled
separator makes clippy-driver treat `-D` as a second input file; that failure
was a local invocation error, not a code failure.
## 3. `inspect --environment` probes
```console
$ marqdo inspect --environment --json
{"schema":"marqdo.environment","schema_version":1,
"producer":{"name":"marqdo","version":"3.0.0-rc.6",
"source":{"sha":null,"origin":"unavailable"}}, # dev binary
"platform":{"os":"linux","arch":"x86_64","family":"unix",
"libc":{"family":"glibc","version":"2.43"},
"strict":{"state":"unavailable","reason":"..."},"worker_processes":true},
"worker":{"name":"marqdo-provider-worker","status":"present",
"version":"3.0.0-rc.6","source_sha":null},
"bundle":{"status":"absent", ...},
"protocols":{"analysis":3,"observation":1,"cli_tool":{"version":1,"api_revision":1},
"plugin_abi":{"version":"1.0","major":1,"minor":0},
"provider_manifest":2,"package_lock":4,"markdown_profile":"marqdo.md.v1"},
"diagnostics":[]}
$ marqdo inspect --environment --platform # argument boundary
error: the argument '--environment' cannot be used with '--platform' # exit 2
```
The integration test also builds a valid synthetic Bundle and an invalid one:
`verified` identity is reported for the valid tree, and a digest mismatch is
reported as `status: invalid` + `env.stdlib_digest_mismatch` without printing
the Bundle path. Two consecutive invocations are byte-identical.
## 4. Release archive (identity binding, #20/#26)
Release build and archive were produced from the candidate commit with
`MARQDO_BUILD_SOURCE_SHA=0f87f856dba28e34bbd2743d23b8f9b1fe96424a`:
```console
$ cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
Finished `release` profile in 51.40s
$ python3 tools/release/package.py --source-sha 0f87f856... --version 3.0.0-rc.6 \
--stdlib-dir target/ecosystem-stdlib --bundle-pin tools/stdlib/bundle-pin.json
{"archive":"dist/marqdo-3.0.0-rc.6-x86_64-unknown-linux-gnu.tar.gz",
"sha256":"58f4ea3a317ac2cf311804f94462d49699b7f159d6ef308a60f2728dad707a9a",
"size":4928069,"source_sha":"0f87f856...","version":"3.0.0-rc.6",
"target":"x86_64-unknown-linux-gnu"}
$ python3 tools/release/smoke.py --archive dist/marqdo-3.0.0-rc.6-x86_64-unknown-linux-gnu.tar.gz --skip-strict
smoke: verified stdlib 0.2.0 tree=sha256:db905508... files=18
smoke: archive version 3.0.0-rc.6, source 0f87f856dba28e34bbd2743d23b8f9b1fe96424a
smoke: bundled stdlib missing -> fail-closed OK
smoke: language-only program runs without the bundled stdlib
smoke: PASS
```
`package.py` now runs the staged binary's `inspect --environment --json` and
refuses to stage when `producer.source.sha`/`worker.source_sha` differ from
`--source-sha`, when the Bundle is not `verified`, or when its tree digest
differs from the archived Bundle. `smoke.py` repeats the check from the
extracted archive. The PASS above therefore proves the archive carries the
exact release commit in both binaries and the exact shipped Bundle.
Strict mode is `UNVERIFIED` on this shared host (`bwrap` cannot create the
required namespaces); `smoke.py --skip-strict` records that honestly rather
than turning a refusal into a PASS.
## 5. CI
| Pipeline | Result |
|---|---|
| Woodpecker push [#155](https://ci.cflmy.cn/repos/1/pipeline/155) (candidate `0f87f856`) | PASS: clone, contract, test, independent-build, minimum-rust, build all success |
| Woodpecker pull_request [#156](https://ci.cflmy.cn/repos/1/pipeline/156) (PR #27) | PASS: same six steps success on the candidate tree |
| Woodpecker push (docs evidence commit, branch head) | re-runs the same six steps; result recorded in the PR once complete |
Steps `contract`/`test`/`independent-build`/`minimum-rust`/`build` are the
release-relevant lanes; the Windows `cargo check` cross gate runs inside
`test`, but native Windows/macOS runs remain out of scope here.
## 6. Not verified / limits
- Native macOS and Windows build/run lanes (§3 target matrix): no runner in
this environment; `UNVERIFIED`. Only the Linux cross-compile check runs.
- Strict VM lane (`bwrap` namespaces): `UNVERIFIED`; strict stays fail-closed.
- MQDH/consumer acceptance of the release archive: consumer repositories own
their own acceptance; this record proves the CLI-side archive identity only.
- A formal tagged Release is not created by this change: publication remains a
reviewed owner step (`docs/releasing.md` §6). The archive above is a local
candidate, not a published asset.
+18
View File
@@ -217,6 +217,24 @@ shared-node exception applies, pass
Stable releases use `--profile stable --require-release` and require native
Windows and macOS PASS in addition to the Linux and contract gates.
### 5.1 Environment identity binding
Release builds must embed the release commit in both binaries:
```bash
export MARQDO_BUILD_SOURCE_SHA="$(git rev-parse HEAD)"
cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
```
`tools/release/package.py` runs the staged `marqdo inspect --environment --json`
and refuses to stage an archive unless `producer.source.sha` and
`worker.source_sha` equal `--source-sha` and the adjacent Bundle reports
`status: verified` with the archived `tree_digest`.
`tools/release/smoke.py` re-runs the same check from the extracted archive, so
a release asset cannot claim a source commit it was not built from. The report
is specified by [`../spec/environment.md`](../spec/environment.md); it never
prints credentials, Analysis content or absolute host paths.
## 6. Tagging and publication (owner approval required)
Only after all gates above are green on the frozen SHA:
+126
View File
@@ -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.
+191
View File
@@ -0,0 +1,191 @@
# Marqdo Document Structure and Entry Semantics
This is the author/tool-facing overview of **what a `.mq.md` document is** and
**how a document becomes a program**: heading modes, unit identity, anchors,
spans, `index.mq.md` entry meaning, and the three document relations (link,
import, call). It states only semantics that are implemented today.
Normative detail lives in one place per fact: syntax and the Markdown→program
mapping are
[`mapping.md`](mapping.md) / [`../docs/architecture/RFC-LANG-0002-unified-semantics.md`](../docs/architecture/RFC-LANG-0002-unified-semantics.md);
the public static projection is [`analysis.md`](analysis.md); link/reference
resolution is [`references.md`](references.md); package and entry resolution is
[`package-format.md`](package-format.md) plus [`references.md`](references.md)
§3.1. This document links those facts for readers and states the consumer
stability contract; it does not create a second specification.
## 1. Document root and heading modes
A document is one CommonMark/GFM AST. Headings are sibling blocks, so scopes
are derived from heading levels, never from container nesting.
| Heading | `kind` | Callable? | Notes |
|---|---|---|---|
| (document root) | `root` | no | Mode `knowledge`, level `0`, path `[]`. |
| H1 | `namespace` | no | Namespace for nested functions. |
| H2 with `@exec` | `function` | **yes** | The only callable document unit. |
| H2 with `@knowledge` | `knowledge` | no | Inert knowledge section. |
| H3–H6 | `section` | no | Section of the enclosing unit; never callable. |
Rules (implemented by `marqdo-frontend`):
* The **document root is Knowledge**. A document with no mode marker still has
a knowledge root and cannot be called.
* Only ATX headings may declare `@exec`/`@knowledge`; Setext headings never
declare. The marker must be the heading's first `Text` child; any other
`@word` marker is the hard error `sem.invalid_mode_marker` (there is no
per-file mode or second selector).
* A heading without a marker **inherits the nearest ancestor's effective
mode**, never a sibling's. Inheritance pops same-or-higher-level ancestors
first, which is why a `###` section under an Exec H2 is Exec while the next
`##` sibling under a Knowledge H1 is Knowledge.
* Only a level-2 Exec heading creates a `FunctionId`. A section inside it
reports the owning function; a section outside one has no function.
* Executable payloads outside an owning Exec H2 are
`sem.exec_without_function`. Prose is inert everywhere.
* Headings inside lists, block quotes or fenced code do not create units.
* Mode declarations are not a navigation feature: adding `@knowledge`/`@exec`
declares meaning, it does not select a different parser or execution path.
Heading annotations (`{#id}`-style) are **Proposed** in
[`heading-annotations-v1.md`](heading-annotations-v1.md) and are not current
capability: the CLI currently rejects unknown `@` markers with
`sem.invalid_mode_marker`. Do not build tools on the proposal.
## 2. Units, identity, anchors and spans
A heading that participates in the language creates an addressable **unit**.
The root is always `units[0]`; all units are in document order.
* `id` is the canonical identity and may contain escapes for `/`, `#` and `%`.
`path` is the authoritative structural name; consumers must not split `id`
into segments.
* `parent_id` is the nearest real ancestor unit (not the Markdown DOM parent).
* Two headings with the same canonical name in the **same scope** are a hard
error (`sem.duplicate_unit_name`); they are not auto-suffixed. The same name
under different parents is allowed and addressable by `path`/`id`.
* `anchors` is a separate namespace of navigation names derived from heading
text with the GitHub-style slug algorithm. Slug collisions get the numbered
suffix `-2`, `-3`, … in document order. An anchor is a navigation name, not
an identity: resolve it to `unit_id`, never to a function or execution right.
* `heading_span` is the original heading AST span. `span` is the complete
section range: from the heading start through the next heading of the same or
higher level, or EOF; it includes child headings and excludes the next
sibling. The root `span` covers the whole source including a BOM.
* All spans are **half-open UTF-8 byte offsets** into `modules[].source`.
Slicing `source.as_bytes()[span.start..span.end]` is exact, including for a
BOM, CRLF line endings, combining characters, a missing trailing newline and
multi-byte text. `analyze`/`check --emit` and `check --refs` are different
projections; bind a digest when mixing artifacts (see `analysis.md` §1).
## 3. `index.mq.md` and entry semantics
`index.mq.md` is an **ordinary `.mq.md` document**. The file name is a
convention, not a language keyword and not a second document type.
* The **project entry** is the file passed to `check`/`run`/`call`/`inspect`.
Analysis records it as `project.entry_module_id`; it must occur exactly once
in `modules`. A second entry of the same project gets its own Analysis and is
never merged by basename.
* `marqdo init` generates a starter `index.mq.md`. That is a project template
choice, not execution semantics.
* A **path dependency** whose `marqdo.yaml` `path:` names a directory resolves
to `<directory>/index.mq.md` when the dependency is imported; the loaded
module keeps the dependency's package instance identity
(`dep:<name>@<version>[#<digest>]::index.mq.md`). That is import resolution,
not "the project entry is whatever index file is nearby".
* Nothing scans directories, auto-loads `index.mq.md`, or treats a directory
link as an import. Imports come only from the explicit YAML front matter.
* An `index.mq.md` used as navigation content does not change execution. Any
`@exec` H2 in it is a normal callable function with normal capability rules;
links inside it are static references only.
* Unresolved imports/missing modules are diagnostics (`module.unresolved`,
`ref.*`); there is no fuzzy search or basename fallback. See
[`references.md`](references.md) §3 and §5.
## 4. Three relations: link, import, call
The three must not be conflated; none is inferred from another.
| Relation | Syntax | Effect | Public projection |
|---|---|---|---|
| **Link** | Markdown `[text](url)` / image | Static reference only. Never loads a module, never imports, never grants read/execute. | `modules[].references[]` with state `resolved`, `not_loaded`, `missing`, `ambiguous`, `external`, `outside_scope` or `invalid`. |
| **Import** | YAML front matter `import: {alias: target}` in a module | Loads exactly the named module (`@dependency`, `std:<relative>` or relative path). Explicit, depth-first, no directory scan. | `modules[].imports[]` with `resolved` module id or `null` for a diagnostic import. |
| **Call** | Expression inside an executable payload | Binds statically to one callable; runs only under `run`/`call` with capability authorization. | `modules[].calls[]` with state `function`, `builtin`, `plugin` or `unresolved`. |
Partition rules:
* A link **never** imports or executes. A document may link to a module it did
not import; ordinary Analysis reports its state honestly (`not_loaded` when
the catalog did not verify existence), and `check --refs` verifies local
files without adding them to the program.
* `ref("#anchor")` returns a static `Formula | Code | FunctionRef` handle; it
does not read a section body and does not grant execution.
* Only an Exec H2 function can be called; calling a knowledge unit, namespace,
section or plain Markdown heading is not part of the language.
* Dynamic (`unresolved`/`dynamic`) calls are legal runtime values; they do not
become a second binding table.
## 5. Authoring guidance (not a CLI enforcement layer)
`marqdo#55` defines repository-level documentation expectations (project
entry, navigation, minimum per-document purpose). The CLI does **not** enforce
those editorial rules: Markdown structure checks belong to `marqdo-lint`, and
navigation/index policy belongs to the consumer repository. A `.mq.md` document
must be independently meaningful to a human reader; adding a new document or a
new knowledge file must not require new CLI syntax.
## 6. Not supported / deferred
* Heading annotations (`heading-annotations-v1.md`, Proposed) and any
`{#id}`/attribute syntax.
* AI-specific metadata, decorators, sidecar indexes or a second document
format.
* Automatic execution of prose or knowledge paragraphs, or "execute this
section" navigation commands.
* A second mode selector (`map_v1`, `--legacy`, per-file syntax switch) or
compatibility fallback for retired syntax.
* Implicit imports from links, file names or directory scans; directory-based
project entry inference.
* Anchor-based execution rights: an anchor resolves to a unit identity only.
## 7. Consumer stability contract
Tools may rely on the following public projection without reading CLI source.
Changes require an Analysis schema/ADR change and consumer updates; there is
no private-structure dependency.
| Fact | Field | Stability |
|---|---|---|
| Project entry | `project.entry_module_id`, `project.root_id`, `project.identity_kind` | Stable. |
| Module identity | `modules[].id`, `package_instance_id`, `relative_path`, `source_digest`, `source` | Stable; bind `AnalysisDigest` when mixing projections. |
| Heading tree | `units[].id/path/parent_id/kind/name/level`, document order, root first | Stable. |
| Modes | `units[].mode`, `mode_origin`, `mode_source_unit_id`, `function` | Stable. |
| Navigation | `units[].heading_span/span`, `anchors[]` | Stable; byte offsets. |
| Relations | `imports[].resolved`, `references[]` states, `calls[]` states/targets | Stable vocabulary; see `analysis.md` §5–§7. |
| Inert payloads | `resources[]` `formula`/`code` kinds | Stable. |
A consumer that needs a structural fact not in that table must request an
Analysis field through the schema process; it must not parse Markdown or IR
privately. Lint/Knowledge/AI consumers specifically may depend on: entry module
identity, heading tree, mode/mode_source, anchors, exact spans, import/call
separation and reference states.
## 8. Contract tests
| Test | Asserts |
|---|---|
| `crates/cli/tests/document_structure.rs` | heading modes/inheritance, same-name scope rules, anchor collision numbering, byte-exact spans with BOM/CRLF/no-final-newline, `index.mq.md` entry and directory-dependency resolution, link≠import≠call, invalid `@word` rejection. |
| `crates/cli/tests/heading_inheritance.rs` | sibling/ancestor inheritance through real `check`/`run`/`call`. |
| `crates/cli/tests/conformance_semantics.rs` | mapping and diagnostics for unit/heading semantics. |
| `crates/cli/tests/analysis_boundary.rs` | Analysis v3 shape and consumer validation. |
## 9. Change rules
* New document-language semantics require a language ADR plus `spec/mapping.md`
and `RFC-LANG-0002` updates; a tool requirement alone is not a reason to add
syntax (`marqdo#55` §13.4).
* A new Analysis field requires an `analysis.md`/schema change and a consumer
candidate on the same contract; no private projection is exposed.
* No second document-structure specification is maintained here or in Lint,
Knowledge, AI or the parent repository. This page links the single sources.
+181
View File
@@ -0,0 +1,181 @@
# Marqdo Environment Report
Current public contract for `marqdo inspect --environment`. The command emits
one offline installation report used by user feedback, release evidence and
diagnostic tooling. It is implemented by the CLI composition root
(`crates/cli/src/environment.rs`); this document is the only normative
specification for its shape. Release binding is defined by
[marqdo-cli#20](https://git.cflmy.cn/cflmy/marqdo-cli/issues/20) and
[marqdo-cli#26](https://git.cflmy.cn/cflmy/marqdo-cli/issues/26) §9.2.
Schema name: `marqdo.environment`, current `schema_version: 1`.
## 1. Invariants
`inspect --environment`:
* never executes project code, loads a module, starts a provider session,
opens a plugin, or accesses the network;
* takes no document and is rejected by the argument parser when combined with
a project-inspection flag (`--ast`, `--units`, `--signature`, `--ir`,
`--refs`, `--platform`, `--extensions`, `--plugin`, `FILE`);
* prints no credential, no Analysis or source content, no user data and no
absolute host path — the Bundle name/version/digest and the product version
are the only installation identity shown;
* reports a degraded installation as data (`status` plus a stable
`diagnostics[].code`) and still exits `0`; the report is the diagnostic, not
a command failure. Argument misuse remains a `2` usage error;
* is deterministic for one installation: two invocations print identical bytes.
The adjacent provider worker is queried only through its single-shot
`--build-info` command, bounded to 750&nbsp;ms and killed on timeout. That is
not a provider session: no library is loaded and no framed request is sent.
## 2. Output
```json
{
"schema": "marqdo.environment",
"schema_version": 1,
"producer": {
"name": "marqdo",
"version": "3.0.0-rc.6",
"source": {
"sha": "63776735e924ade279cdf59d5c733dc24bfdabbb",
"origin": "embedded"
}
},
"platform": {
"os": "linux",
"arch": "x86_64",
"family": "unix",
"libc": {"family": "glibc", "version": "2.39"},
"strict": {"state": "unavailable", "reason": "bubblewrap cannot create the required namespaces: ..."},
"worker_processes": true
},
"worker": {
"name": "marqdo-provider-worker",
"status": "present",
"version": "3.0.0-rc.6",
"source_sha": "63776735e924ade279cdf59d5c733dc24bfdabbb"
},
"bundle": {
"status": "verified",
"origin": "sibling",
"name": "marqdo-stdlib",
"version": "0.3.0",
"tree_digest": "sha256:...",
"instance_id": "stdlib:marqdo-stdlib@0.3.0"
},
"protocols": {
"markdown_profile": "marqdo.md.v1",
"analysis": 3,
"observation": 1,
"cli_tool": {"version": 1, "api_revision": 1},
"plugin_abi": {"version": "1.0", "major": 1, "minor": 0},
"provider_manifest": 2,
"package_lock": 4
},
"diagnostics": []
}
```
### 2.1 Producer identity
| Field | Meaning |
|---|---|
| `producer.name` | Always `marqdo`. |
| `producer.version` | Product SemVer of the running binary (`marqdo --version` without the name prefix). |
| `producer.source.sha` | Full lowercase 40-hex commit embedded by the release build, or `null`. |
| `producer.source.origin` | `embedded` when the build supplied `MARQDO_BUILD_SOURCE_SHA`; otherwise `unavailable`. This is a build fact, not a claim: a development build reports `null`. |
`MARQDO_BUILD_SOURCE_SHA` is a build-time environment variable consumed by
`crates/cli/build.rs` and `crates/marqdo-provider-worker/build.rs`. It must be
the exact 40-hex release commit. The release pipeline sets it from
`CI_COMMIT_SHA`; `tools/release/package.py` refuses to stage an archive whose
binary does not report the `--source-sha` commit, and
`tools/release/smoke.py` re-verifies it from the archive alone.
### 2.2 Platform
| Field | Meaning |
|---|---|
| `platform.os`, `platform.arch` | `std::env::consts::OS` / `ARCH` of the running binary. |
| `platform.family` | `std::env::consts::FAMILY` (`unix`/`windows`). |
| `platform.libc` | `{"family": "glibc", "version": "<gnu_get_libc_version>"}` on linux-gnu, `{"family": "musl", "version": null}` on musl, `null` elsewhere. A version is a runtime fact, not a support claim. |
| `platform.strict` | The current strict-isolation probe result, `{"state": "available"|"unavailable", ...}` (ADR-0021). `unavailable` includes the probe refusal reason and is contractual. |
| `platform.worker_processes` | Whether the built host can spawn isolated worker processes. |
Platform support claims live only in [`COMPATIBILITY.md`](../COMPATIBILITY.md);
this report states what the running installation is, never that a platform is
supported.
### 2.3 Adjacent provider worker
| Field | Meaning |
|---|---|
| `worker.status` | `present` when `marqdo-provider-worker` is a regular file next to the running binary; `absent` otherwise. |
| `worker.version` | Worker product version from its `--build-info` document, or `null`. |
| `worker.source_sha` | Full lowercase 40-hex commit from the worker `--build-info` document, or `null`. |
When a present worker cannot produce a current build-info document within the
bound, the report keeps `status: present`, leaves both identity fields `null`,
and appends the `env.worker_info_unavailable` diagnostic. No path or error text
from the worker is projected.
### 2.4 Bundle
| Field | Meaning |
|---|---|
| `bundle.status` | `verified` (manifest/alias digests and tree digest match), `absent` (no `MARQDO_STDLIB_DIR` and no sibling `stdlib/`), or `invalid` (an explicit or sibling Bundle failed verification). |
| `bundle.origin` | `explicit-env` when `MARQDO_STDLIB_DIR` selected the Bundle, `sibling` when the adjacent `stdlib/` directory did, `null` when absent. |
| `bundle.name`, `bundle.version` | Declared Bundle identity, or `null`. |
| `bundle.tree_digest` | `sha256:` + verified content digest of all `.mq.md` files, or `null`. |
| `bundle.instance_id` | Canonical verified instance id, or `null`. |
An explicit `MARQDO_STDLIB_DIR` is authoritative: a bad value reports
`invalid` and does not silently fall back to a sibling Bundle. Bundle load
errors never project the underlying path: they map to `env.stdlib_unreadable`,
`env.stdlib_invalid` or `env.stdlib_digest_mismatch`.
### 2.5 Protocol versions
`protocols` repeats the current revisions of the contracts documented in
[`../COMPATIBILITY.md`](../COMPATIBILITY.md): markdown profile, Analysis,
Observation, CLI Tool revision/API revision, Plugin ABI, Resource Provider
manifest and lock. These are the revisions this binary is built to, not a
negotiation result for a project.
### 2.6 Diagnostics
`diagnostics` is a list of `{code, message}` records. Codes are stable and
path-free:
| Code | Meaning |
|---|---|
| `env.stdlib_unreadable` | The installed Bundle directory/manifest cannot be read. |
| `env.stdlib_invalid` | The installed Bundle is not a current verified Bundle. |
| `env.stdlib_digest_mismatch` | Tree or alias digests do not match the manifest. |
| `env.worker_info_unavailable` | An adjacent worker exists but did not report a current build identity. |
A verified installation reports an empty list. New codes are additive within
`schema_version: 1`; renaming or removing a code is a schema change.
## 3. Consumer usage
```sh
marqdo inspect --environment --json | jq -r '.producer.version, .platform.os,
.bundle.status, .bundle.tree_digest'
```
Human-readable output (no `--json`) prints the same facts as stable
`key: value` lines; scripts must use `--json`. Consumers that need the report
for feedback must attach it as text, not upload source or credentials.
## 4. Stability
The report is a public CLI output contract. Adding a field is compatible;
changing a field's meaning, removing it or changing a diagnostic code requires
a `schema_version` change and a consumer update. The report does not replace
Analysis (static project facts), Observation (execution facts) or CLI Tool
(revision negotiation), and must not be used as any of them.
+9
View File
@@ -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
+53
View File
@@ -187,6 +187,55 @@ def copy_tree(source: Path, destination: Path) -> None:
shutil.copytree(source, destination, dirs_exist_ok=True)
def verify_binary_identity(
stage_dir: Path, version: str, source_sha: str, stdlib_info: dict
) -> None:
"""Prove the staged binaries embed the release commit and shipped Bundle.
`inspect --environment` is the same offline report users export for
feedback (marqdo-cli#26 §9.2). The archive is not allowed to claim a source
commit it was not built from, so packaging fails closed when the release
build did not receive `MARQDO_BUILD_SOURCE_SHA` (marqdo-cli#20).
"""
result = subprocess.run(
[str(stage_dir / "marqdo"), "inspect", "--environment", "--json"],
cwd=stage_dir,
capture_output=True,
text=True,
timeout=60,
)
if result.returncode != 0:
fail(
"the staged marqdo binary cannot report its environment: "
f"exit {result.returncode}\n{result.stderr}"
)
try:
report = json.loads(result.stdout)
except json.JSONDecodeError as error:
fail(f"the staged environment report is not JSON: {error}\n{result.stdout}")
if report.get("schema") != "marqdo.environment" or report.get("schema_version") != 1:
fail("the staged environment report is not marqdo.environment v1")
if report.get("producer", {}).get("version") != version:
fail("the staged marqdo binary version does not match RELEASE_INFO.json")
embedded = report.get("producer", {}).get("source", {}).get("sha")
if embedded != source_sha:
fail(
f"the staged marqdo binary embeds source {embedded!r}, not {source_sha}; "
"rebuild with MARQDO_BUILD_SOURCE_SHA set to the release commit"
)
worker = report.get("worker", {})
if worker.get("status") != "present" or worker.get("source_sha") != source_sha:
fail(
"the staged provider worker does not report the release commit; "
"rebuild it with MARQDO_BUILD_SOURCE_SHA set to the release commit"
)
bundle = report.get("bundle", {})
if bundle.get("status") != "verified":
fail("the staged archive does not contain a verified adjacent stdlib Bundle")
if bundle.get("tree_digest") != stdlib_info.get("tree_digest"):
fail("the staged environment report does not match the archived Bundle digest")
def stage(
stage_dir: Path,
version: str,
@@ -216,6 +265,10 @@ def stage(
# side effect: copy the verified tree next to the binary (ADR/SPEC H-08).
copy_tree(stdlib_dir, stage_dir / "stdlib")
# The archive binds product identity to the shipped Bundle before any
# checksum or RELEASE_INFO.json is written.
verify_binary_identity(stage_dir, version, source_sha, stdlib_info)
# Examples without local build output, then the freshly built extension
# artifacts so a clean install can run every example without a compiler.
copy_tree(ROOT / "examples", stage_dir / "examples")
+46
View File
@@ -175,6 +175,51 @@ ANALYSIS_CASES = {
}
def verify_environment_report(
runner: "Runner", install: Path, version: str, source_sha: str, info: dict
) -> None:
"""The packaged binaries must report their real release identity.
`inspect --environment` is the offline diagnostic export for feedback
(marqdo-cli#26 §9.2). This also proves the archive was built from the
recorded commit and ships the recorded Bundle, not a build-machine tree.
"""
report = runner.json(["inspect", "--environment"])
if report.get("schema") != "marqdo.environment" or report.get("schema_version") != 1:
fail("inspect --environment is not marqdo.environment v1")
producer = report.get("producer", {})
if producer.get("version") != version:
fail("inspect --environment producer version does not match RELEASE_INFO.json")
embedded = producer.get("source", {}).get("sha")
if embedded != source_sha:
fail(
f"inspect --environment reports source {embedded!r}, expected {source_sha}; "
"the archive was not built with MARQDO_BUILD_SOURCE_SHA"
)
worker = report.get("worker", {})
if worker.get("status") != "present" or worker.get("source_sha") != source_sha:
fail("the adjacent provider worker does not report the release commit")
bundle = report.get("bundle", {})
declared = info["stdlib"]
if bundle.get("status") != "verified":
fail("inspect --environment does not see the adjacent Bundle")
for field in ("name", "version", "tree_digest"):
if bundle.get(field) != declared.get(field):
fail(
f"inspect --environment bundle.{field} does not match RELEASE_INFO.json "
f"({bundle.get(field)!r} != {declared.get(field)!r})"
)
if report.get("diagnostics"):
fail(f"a verified installation must not report diagnostics: {report['diagnostics']}")
text = json.dumps(report)
if str(install) in text:
fail("inspect --environment contains an absolute host path")
lowered = text.lower()
for forbidden in ("api_key", "password", "private key"):
if forbidden in lowered:
fail(f"inspect --environment contains forbidden field {forbidden!r}")
def verify_analysis_metadata(protocols: dict) -> None:
if protocols.get("analysis") != ANALYSIS_VERSION or "analysis_versions" in protocols:
fail("RELEASE_INFO.json must identify only the current Analysis revision")
@@ -263,6 +308,7 @@ def main(argv: list[str]) -> int:
version_out = runner.run(["--version"]).stdout.strip()
if version_out != f"marqdo {version}":
fail(f"--version printed {version_out!r}, expected 'marqdo {version}'")
verify_environment_report(runner, install, version, source_sha, info)
runner.run(["--help"])
runner.run(["check", "examples/multi-module/index.mq.md"])
hello = runner.run(["run", "examples/hello.mq.md"]).stdout
+4 -4
View File
@@ -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"
}