diff --git a/.woodpecker/main.yml b/.woodpecker/main.yml index 3fa188a..66c7f53 100644 --- a/.woodpecker/main.yml +++ b/.woodpecker/main.yml @@ -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 diff --git a/COMPATIBILITY.md b/COMPATIBILITY.md index f2d29ac..421f9e0 100644 --- a/COMPATIBILITY.md +++ b/COMPATIBILITY.md @@ -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 | diff --git a/Cargo.lock b/Cargo.lock index 51966e8..0eb7cbd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -416,6 +416,7 @@ version = "3.0.0-rc.6" dependencies = [ "clap", "hex", + "libc", "marqdo-expression", "marqdo-foreign", "marqdo-frontend", diff --git a/README.md b/README.md index e71953c..5bd9b5c 100644 --- a/README.md +++ b/README.md @@ -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,9 @@ rules are [`RFC-LANG-0002`](docs/architecture/RFC-LANG-0002-unified-semantics.md [Observation](spec/observation.md) delivers the same run as live JSONL or a JSON snapshot. [CLI Tool](spec/cli-tool.md) installs independently built commands with exact protocol requirements and verifies their entire bundle. + `inspect --environment --json` reports the offline installed identity + (version, embedded source commit, platform, Bundle, protocol revisions) for + feedback and release evidence. Run everything: @@ -399,7 +403,9 @@ 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); JSON Schemas in [`spec/schemas/`](spec/schemas/). * [`tests/README.md`](tests/README.md) — conformance corpus and `UPDATE_GOLDENS` workflow. diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index b98e0a1..7b9c5dc 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -30,6 +30,7 @@ hex = { workspace = true } sha2 = { workspace = true } semver = { workspace = true } tempfile = { workspace = true } +libc = { workspace = true } [[bin]] name = "marqdo" diff --git a/crates/cli/build.rs b/crates/cli/build.rs new file mode 100644 index 0000000..ced216a --- /dev/null +++ b/crates/cli/build.rs @@ -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" + ); + } +} diff --git a/crates/cli/src/analysis/mod.rs b/crates/cli/src/analysis/mod.rs index c888143..9b51be2 100644 --- a/crates/cli/src/analysis/mod.rs +++ b/crates/cli/src/analysis/mod.rs @@ -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 { diff --git a/crates/cli/src/commands/inspect.rs b/crates/cli/src/commands/inspect.rs index 1e48fc9..5dc2355 100644 --- a/crates/cli/src/commands/inspect.rs +++ b/crates/cli/src/commands/inspect.rs @@ -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, diff --git a/crates/cli/src/environment.rs b/crates/cli/src/environment.rs new file mode 100644 index 0000000..c97da42 --- /dev/null +++ b/crates/cli/src/environment.rs @@ -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 = 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 { + 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 { + 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> { + 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 { + 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")); + } +} diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 576ff42..8b45cde 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -8,6 +8,7 @@ mod analysis; mod args; mod commands; mod document_refs; +mod environment; mod extension_descriptors; mod extension_selection; mod loader; @@ -97,7 +98,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 +299,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, @@ -462,6 +473,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) } diff --git a/crates/cli/src/stdlib.rs b/crates/cli/src/stdlib.rs index cff3582..b21725f 100644 --- a/crates/cli/src/stdlib.rs +++ b/crates/cli/src/stdlib.rs @@ -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 } diff --git a/crates/cli/src/tool.rs b/crates/cli/src/tool.rs index adcb4d0..00f230a 100644 --- a/crates/cli/src/tool.rs +++ b/crates/cli/src/tool.rs @@ -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", diff --git a/crates/cli/tests/docs_consistency.rs b/crates/cli/tests/docs_consistency.rs index ca73428..1fbc929 100644 --- a/crates/cli/tests/docs_consistency.rs +++ b/crates/cli/tests/docs_consistency.rs @@ -300,3 +300,85 @@ 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" + ); +} diff --git a/crates/cli/tests/document_structure.rs b/crates/cli/tests/document_structure.rs new file mode 100644 index 0000000..2e66f20 --- /dev/null +++ b/crates/cli/tests/document_structure.rs @@ -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 = 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()); +} diff --git a/crates/cli/tests/environment_report.rs b/crates/cli/tests/environment_report.rs new file mode 100644 index 0000000..7d67fe9 --- /dev/null +++ b/crates/cli/tests/environment_report.rs @@ -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}" + ); +} diff --git a/crates/marqdo-provider-worker/build.rs b/crates/marqdo-provider-worker/build.rs new file mode 100644 index 0000000..9bedf4d --- /dev/null +++ b/crates/marqdo-provider-worker/build.rs @@ -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" + ); + } +} diff --git a/crates/marqdo-provider-worker/src/main.rs b/crates/marqdo-provider-worker/src/main.rs index eca2157..a5743ba 100644 --- a/crates/marqdo-provider-worker/src/main.rs +++ b/crates/marqdo-provider-worker/src/main.rs @@ -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 "); std::process::exit(2); diff --git a/crates/marqdo-value/src/diagnostic.rs b/crates/marqdo-value/src/diagnostic.rs index d855627..7fb9f1f 100644 --- a/crates/marqdo-value/src/diagnostic.rs +++ b/crates/marqdo-value/src/diagnostic.rs @@ -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. diff --git a/docs/STATUS.md b/docs/STATUS.md index e756d4b..1fb3ddb 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -79,6 +79,43 @@ 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.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 diff --git a/docs/developers/README.md b/docs/developers/README.md index d76bb29..64ce3d6 100644 --- a/docs/developers/README.md +++ b/docs/developers/README.md @@ -40,9 +40,12 @@ 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. [compatibility.md](compatibility.md) — version axes, platform matrix and the prerelease policy. -7. [release-limits.md](release-limits.md) — the honest beta limitations (this +8. [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 +85,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) diff --git a/docs/evidence/2026-11-30-cli-environment-and-document-contract.md b/docs/evidence/2026-11-30-cli-environment-and-document-contract.md new file mode 100644 index 0000000..f223dcd --- /dev/null +++ b/docs/evidence/2026-11-30-cli-environment-and-document-contract.md @@ -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. diff --git a/docs/releasing.md b/docs/releasing.md index f870abf..00c1632 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -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: diff --git a/spec/document-structure.md b/spec/document-structure.md new file mode 100644 index 0000000..f4eb748 --- /dev/null +++ b/spec/document-structure.md @@ -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 `/index.mq.md` when the dependency is imported; the loaded + module keeps the dependency's package instance identity + (`dep:@[#]::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:` 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. diff --git a/spec/environment.md b/spec/environment.md new file mode 100644 index 0000000..1b40cfa --- /dev/null +++ b/spec/environment.md @@ -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 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.2.0", + "tree_digest": "sha256:...", + "instance_id": "stdlib:marqdo-stdlib@0.2.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": ""}` 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. diff --git a/tools/release/package.py b/tools/release/package.py index a65d3ce..206888f 100644 --- a/tools/release/package.py +++ b/tools/release/package.py @@ -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") diff --git a/tools/release/smoke.py b/tools/release/smoke.py index 6c62cdd..aff37c7 100644 --- a/tools/release/smoke.py +++ b/tools/release/smoke.py @@ -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