Files
marqdo-cli/crates/cli/tests/environment_report.rs
cflmy 0f87f856db
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/pr/main Pipeline was canceled
feat: add offline environment report and document-structure contract
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

212 lines
7.4 KiB
Rust

//! 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}"
);
}