feat: migrate View 0.3.0 to marqdo 3.0.0-rc.4 contracts
ci/woodpecker/push/woodpecker Pipeline was successful

Replace the retired rc.2 Analysis v2/Trace v2/Execution Events v1 stack with the
single current contract family:

- Analysis v3 (ADR-0069 public boundary): one check --emit artifact carries the
  exact source, Markdown AST, heading scopes (heading_span + complete span),
  anchors, state-bearing references, calls, resources and diagnostics; the old
  revision-3 shape is rejected with a rebuild hint.
- Observation v1: one run/call --output jsonl stream (+ atomic
  --observation-file snapshot) decoded by one decoder and projected into the
  reader/SSE/export layers; stale/malformed/truncated/incomplete never render
  as success.
- CLI Tool revision 1: requires {api_revision:1, analysis:3, observation:1},
  product range >=3.0.0-rc.3,<4.0.0, only MARQDO_BIN and
  MARQDO_API_REVISION are consumed.
- Remove compatibility branches, retired flags/env vars and duplicate decoders;
  re-record Analysis v3 and Observation v1 fixtures; rewrite contract,
  integration and security tests (173 passing locally).
- Add check-no-legacy/check-docs/check-observation gates, rc.4 pins in the
  CI pipelines, 0.3.0 Tool bundle and evidence manifest support.

See issues #4, #5 and #6; acceptance baseline is CLI source
452e9a32bd9e40dba427d4180691c58bab74449e, archive
9c3f166b5e5b8840d39d10019074e4e1c42432fc23e26c69670e64fdcf4e15d8.
This commit is contained in:
Marqdo View committed 2026-11-25 21:58:15 +08:00
1 parent 7b34199c96
commit a802f96b6e
109 files changed
+14000 -6461

No files matched your search

+2 -7
View File
@@ -6,12 +6,7 @@ use crate::common;
use common::run_view;
fn clean_env() -> Vec<(&'static str, Option<&'static str>)> {
vec![
("MARQDO_BIN", None),
("MARQDO_TOOL_PROTOCOL", None),
("MARQDO_PROTOCOL_ANALYSIS", None),
("MARQDO_PROTOCOL_TRACE", None),
]
vec![("MARQDO_BIN", None), ("MARQDO_API_REVISION", None)]
}
#[test]
@@ -36,7 +31,7 @@ fn version_is_the_tool_version() {
let output = run_view(&["--version"], &cwd, &clean_env());
assert_eq!(output.status.code(), Some(0));
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(stdout.contains("marqdo-view 0.2.0"), "{stdout}");
assert!(stdout.contains("marqdo-view 0.3.0"), "{stdout}");
}
#[test]
+397 -112
View File
@@ -1,5 +1,5 @@
//! Contract tests against a real fake-core executable: argv shape, exit codes,
//! stderr handling, temp artifacts and process-tree cleanup.
//! stderr handling, temp artifacts and the current Analysis v3 revision.
//!
//! The fake core is a shell script, not a mocked Rust trait, so everything at
//! the process boundary is exercised for real.
@@ -7,7 +7,9 @@
use crate::common;
use common::{minimal_analysis, sha256_hex, FakeCore, TempProject};
use marqdo_view::core_client::{CheckOptions, CheckResponse, CoreClient, RunOptions};
use marqdo_view::core_client::{
build_call_args, build_run_args, CheckOptions, CheckResponse, CoreClient, RunOptions,
};
use marqdo_view::reader::source::Project;
fn fixture(name: &str) -> (TempProject, FakeCore) {
@@ -17,11 +19,15 @@ fn fixture(name: &str) -> (TempProject, FakeCore) {
(project, core)
}
fn project_source(project: &TempProject) -> String {
std::fs::read_to_string(project.path("index.mq.md")).unwrap()
}
#[test]
fn check_returns_exact_analysis_bytes_and_digest() {
let (project, core) = fixture("check_ok");
let source = std::fs::read(project.path("index.mq.md")).unwrap();
let analysis = minimal_analysis("index.mq.md", &sha256_hex(&source), 2);
let source = project_source(&project);
let analysis = minimal_analysis("index.mq.md", &source, 3);
core.set_analysis(&analysis);
let client = CoreClient::with_bin(&core.script).unwrap();
@@ -42,15 +48,18 @@ fn check_returns_exact_analysis_bytes_and_digest() {
let args = core.last_args();
assert_eq!(args[0], "check");
assert!(args.contains(&"--emit".to_string()));
// No `--refs` unless requested.
assert!(!args.contains(&"--refs".to_string()));
// The retired Analysis v2 selector and trace flags never appear.
for retired in ["--trace-file", "--event-stream"] {
assert!(!args.contains(&retired.to_string()), "retired {retired}");
}
}
#[test]
fn check_refs_is_forwarded_as_a_stricter_flag() {
let (project, core) = fixture("check_refs");
let source = std::fs::read(project.path("index.mq.md")).unwrap();
core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 2));
let source = project_source(&project);
core.set_analysis(&minimal_analysis("index.mq.md", &source, 3));
let client = CoreClient::with_bin(&core.script).unwrap();
let project = Project::open(&project.path("index.mq.md")).unwrap();
let entry = project.entry().relative.clone();
@@ -85,107 +94,105 @@ fn check_failure_preserves_core_stderr_and_code() {
}
#[test]
fn run_returns_json_and_raw_trace() {
let (project, core) = fixture("run_ok");
core.set_run(
0,
r#"{"command":"run","success":true,"stdout":"ok","stderr":"","trace":[]}"#,
Some(r#"{"schema":"marqdo.trace","schema_version":2,"events":[]}"#),
fn run_and_call_argv_use_the_current_observation_flags_only() {
let args = build_run_args(
std::path::Path::new("/p/index.mq.md"),
std::path::Path::new("/t/observation.json"),
&RunOptions::default(),
);
let client = CoreClient::with_bin(&core.script).unwrap();
let project = Project::open(&project.path("index.mq.md")).unwrap();
let entry = project.entry().relative.clone();
let output = client
.run(&project, &entry, &RunOptions::default())
.unwrap();
assert_eq!(output.exit_code, 0);
assert_eq!(output.json["success"], true);
let trace = output.trace_bytes.expect("trace bytes");
assert_eq!(output.trace_sha256.unwrap(), sha256_hex(&trace));
// Mode is always explicit; pure is the View default.
let args = core.last_args();
assert!(args.contains(&"--mode".to_string()));
let mode_index = args.iter().position(|a| a == "--mode").unwrap();
assert_eq!(args[mode_index + 1], "pure");
assert!(args.contains(&"--json".to_string()));
assert!(args.contains(&"--trace-file".to_string()));
let text: Vec<String> = args
.iter()
.map(|arg| arg.to_string_lossy().to_string())
.collect();
assert_eq!(text[0], "run");
assert!(text.contains(&"--mode".to_string()));
assert!(text.contains(&"pure".to_string()));
assert!(text.contains(&"--output".to_string()));
assert!(text.contains(&"jsonl".to_string()));
assert!(text.contains(&"--observation-file".to_string()));
assert!(text.contains(&"--observe-max-events".to_string()));
assert!(text.contains(&"--observe-max-bytes".to_string()));
assert!(text.contains(&"--observe-max-value-bytes".to_string()));
for retired in [
"--json",
"--trace-file",
"--event-stream",
"--trace-max-events",
"--trace-max-bytes",
"--trace-max-value-bytes",
] {
assert!(
!text.contains(&retired.to_string()),
"retired flag {retired}"
);
}
assert!(!text
.iter()
.any(|token| token.contains(';') || token.contains('|') || token.contains('&')));
let args = build_call_args(
std::path::Path::new("/p/index.mq.md"),
"demo.calculate",
&[("n".to_string(), "3".to_string())],
std::path::Path::new("/t/observation.json"),
&RunOptions::default(),
);
let text: Vec<String> = args
.iter()
.map(|arg| arg.to_string_lossy().to_string())
.collect();
assert_eq!(text[0], "call");
assert!(text.contains(&"--arg".to_string()));
assert!(text.contains(&"n=3".to_string()));
assert!(text.contains(&"--observation-file".to_string()));
}
#[test]
fn run_without_trace_file_reports_no_trace() {
let (project, core) = fixture("run_no_trace");
core.set_run(
0,
r#"{"command":"run","success":true,"stdout":"","stderr":"","trace":[]}"#,
None,
);
let client = CoreClient::with_bin(&core.script).unwrap();
let project = Project::open(&project.path("index.mq.md")).unwrap();
let entry = project.entry().relative.clone();
let output = client
.run(&project, &entry, &RunOptions::default())
.unwrap();
assert!(output.trace_bytes.is_none());
assert!(output.trace_sha256.is_none());
}
#[test]
fn run_invalid_json_is_a_protocol_io_error() {
let (project, core) = fixture("run_bad_json");
core.set_run(0, "this is not json", None);
let client = CoreClient::with_bin(&core.script).unwrap();
let project = Project::open(&project.path("index.mq.md")).unwrap();
let entry = project.entry().relative.clone();
let err = client
.run(&project, &entry, &RunOptions::default())
.unwrap_err();
assert_eq!(err.code(), "view.io");
assert!(err.to_string().contains("exactly one JSON"));
}
#[test]
fn timeout_kills_the_process_group_and_reports_timeout() {
let (project, core) = fixture("run_timeout");
core.set_sleep_seconds(5);
core.set_run(0, r#"{"command":"run","success":true}"#, None);
let client = CoreClient::with_bin(&core.script).unwrap();
let project = Project::open(&project.path("index.mq.md")).unwrap();
let entry = project.entry().relative.clone();
let started = std::time::Instant::now();
let err = client
.run(
&project,
&entry,
&RunOptions {
view_timeout: Some(std::time::Duration::from_millis(300)),
..Default::default()
},
)
.unwrap_err();
let elapsed = started.elapsed();
assert_eq!(err.code(), "view.core_timeout");
assert!(
elapsed < std::time::Duration::from_secs(3),
"timeout took {elapsed:?}"
fn default_run_does_not_request_variable_or_parameter_values() {
let args = build_run_args(
std::path::Path::new("/p/index.mq.md"),
std::path::Path::new("/t/observation.json"),
&RunOptions::default(),
);
let text: Vec<String> = args
.iter()
.map(|arg| arg.to_string_lossy().to_string())
.collect();
// Budgets are explicit, but no value name is selected by default.
for flag in [
"--observe-variable",
"--observe-parameter",
"--observe-text-values",
] {
assert!(!text.contains(&flag.to_string()), "default {flag}");
}
}
#[test]
fn incompatible_product_version_is_rejected_before_any_work() {
let (project, core) = fixture("version_old");
core.set_version("marqdo 2.9.1\n");
let (_project, core) = fixture("version_old");
core.set_version("marqdo 3.0.0-rc.2\n");
let client = CoreClient::with_bin(&core.script).unwrap();
let err = client.negotiate().unwrap_err();
assert_eq!(err.code(), "view.protocol_incompatible");
assert_eq!(err.exit_code(), 2);
// Only `--version` was invoked; no check/run happened.
assert_eq!(core.last_args(), vec!["--version".to_string()]);
let _ = project;
}
#[test]
fn current_rc_version_is_accepted() {
let (_project, core) = fixture("version_rc4");
core.set_version("marqdo 3.0.0-rc.4\n");
let client = CoreClient::with_bin(&core.script).unwrap();
assert_eq!(
client.negotiate().unwrap().version.to_string(),
"3.0.0-rc.4"
);
}
#[test]
fn missing_emit_after_success_is_an_analysis_failure() {
// Fake core exits 0 but writes nothing: never accept a phantom analysis.
let (project, core) = fixture("check_no_emit");
let client = CoreClient::with_bin(&core.script).unwrap();
let project = Project::open(&project.path("index.mq.md")).unwrap();
@@ -196,11 +203,6 @@ fn missing_emit_after_success_is_an_analysis_failure() {
assert_eq!(err.code(), "view.analysis_failed");
}
fn expect_check_ok(response: CheckResponse) -> marqdo_view::core_client::CheckOutput {
assert!(response.success, "check failed: {:?}", response.diagnostics);
response.analysis.expect("analysis on success")
}
#[test]
fn failed_check_normalizes_diagnostics_without_absolute_paths() {
let (project, core) = fixture("check_diagnostics");
@@ -218,44 +220,152 @@ fn failed_check_normalizes_diagnostics_without_absolute_paths() {
assert_eq!(response.diagnostics.len(), 1);
assert_eq!(response.diagnostics[0].code, "sem.unclosed_control");
assert_eq!(response.diagnostics[0].line, Some(5));
// The raw absolute `file` field is not part of the normalized type at all.
let rendered = serde_json::to_string(&response.diagnostics).unwrap();
assert!(!rendered.contains("/home/secret"), "{rendered}");
}
#[test]
fn cli_verify_end_to_end_against_fake_core() {
let (project, core) = fixture("verify_cli");
let source = std::fs::read(project.path("index.mq.md")).unwrap();
core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 2));
fn analysis_v2_revision_is_a_hard_protocol_error() {
let (project, core) = fixture("analysis_v2");
let source = project_source(&project);
core.set_analysis(&minimal_analysis("index.mq.md", &source, 2));
let client = CoreClient::with_bin(&core.script).unwrap();
let project = Project::open(&project.path("index.mq.md")).unwrap();
let entry = project.entry().relative.clone();
let check = expect_check_ok(
client
.check(&project, &entry, &CheckOptions::default())
.unwrap(),
);
let err = marqdo_view::protocol::analysis_v3::verify_analysis(
&check.analysis_bytes,
entry.as_str(),
Some(&source),
)
.unwrap_err();
assert_eq!(err.code(), "view.protocol_incompatible");
assert_eq!(err.exit_code(), 2);
}
#[test]
fn retired_revision_3_shape_is_rejected_with_a_rebuild_hint() {
let (project, core) = fixture("analysis_old_shape");
let source = project_source(&project);
let mut analysis: serde_json::Value =
serde_json::from_str(&minimal_analysis("index.mq.md", &source, 3)).unwrap();
// An old same-revision artifact has no source/document/anchors/entry id.
let module = analysis["modules"][0].as_object_mut().unwrap();
module.remove("source");
module.remove("document");
module.remove("anchors");
analysis["project"]
.as_object_mut()
.unwrap()
.remove("entry_module_id");
core.set_analysis(&analysis.to_string());
let client = CoreClient::with_bin(&core.script).unwrap();
let project = Project::open(&project.path("index.mq.md")).unwrap();
let entry = project.entry().relative.clone();
let check = expect_check_ok(
client
.check(&project, &entry, &CheckOptions::default())
.unwrap(),
);
let err = marqdo_view::protocol::analysis_v3::verify_analysis(
&check.analysis_bytes,
entry.as_str(),
Some(&source),
)
.unwrap_err();
assert_eq!(err.code(), "view.protocol_incompatible");
assert!(err.to_string().contains("revision 3"), "{err}");
}
#[test]
fn source_digest_mismatch_is_not_silently_accepted() {
let (project, core) = fixture("analysis_digest_mismatch");
let source = project_source(&project);
core.set_analysis(&minimal_analysis("index.mq.md", "# another document\n", 3));
let client = CoreClient::with_bin(&core.script).unwrap();
let project = Project::open(&project.path("index.mq.md")).unwrap();
let entry = project.entry().relative.clone();
let check = expect_check_ok(
client
.check(&project, &entry, &CheckOptions::default())
.unwrap(),
);
let err = marqdo_view::protocol::analysis_v3::verify_analysis(
&check.analysis_bytes,
entry.as_str(),
Some(&source),
)
.unwrap_err();
assert_eq!(err.code(), "view.source_mismatch");
}
#[test]
fn tool_api_revision_environment_is_an_exact_expectation() {
// Pure validation: no process-global environment mutation (which would race
// with tests running in parallel).
use marqdo_view::protocol::tool_v1;
assert!(tool_v1::validate_api_revision_env(None).is_ok());
assert!(tool_v1::validate_api_revision_env(Some("1")).is_ok());
let err = tool_v1::validate_api_revision_env(Some("2")).unwrap_err();
assert_eq!(err.code(), "view.protocol_incompatible");
assert!(tool_v1::validate_api_revision_env(Some("nope")).is_err());
}
#[test]
fn installed_tool_api_revision_is_enforced_at_the_process_boundary() {
let (project, core) = fixture("api_revision_cli");
core.set_analysis(&minimal_analysis(
"index.mq.md",
&project_source(&project),
3,
));
let script = core.script.to_str().unwrap().to_string();
let dir = project.dir.to_str().unwrap().to_string();
let output = common::run_view(
&["verify", "index.mq.md", "--marqdo-bin", &script],
std::path::Path::new(&dir),
&[
("MARQDO_BIN", None),
("MARQDO_TOOL_PROTOCOL", None),
("MARQDO_PROTOCOL_ANALYSIS", None),
("MARQDO_PROTOCOL_TRACE", None),
],
&[("MARQDO_BIN", None), ("MARQDO_API_REVISION", Some("2"))],
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(2), "stderr: {stderr}");
assert!(
stderr.contains("view.protocol_incompatible"),
"stderr: {stderr}"
);
}
#[test]
fn cli_verify_end_to_end_against_fake_core() {
let (project, core) = fixture("verify_cli");
let source = project_source(&project);
core.set_analysis(&minimal_analysis("index.mq.md", &source, 3));
let script = core.script.to_str().unwrap().to_string();
let dir = project.dir.to_str().unwrap().to_string();
let output = common::run_view(
&["verify", "index.mq.md", "--marqdo-bin", &script],
std::path::Path::new(&dir),
&[("MARQDO_BIN", None), ("MARQDO_API_REVISION", None)],
);
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(0), "stderr: {stderr}");
assert!(stdout.contains("result: PASS"), "{stdout}");
assert!(stdout.contains("marqdo 3.0.0-beta.1"), "{stdout}");
assert!(stdout.contains("marqdo 3.0.0-rc.4"), "{stdout}");
assert!(!stdout.contains(&dir), "absolute path leaked: {stdout}");
}
#[test]
fn cli_verify_rejects_schema_v4_and_digest_mismatch() {
fn cli_verify_rejects_schema_v2_and_digest_mismatch() {
let (project, core) = fixture("verify_negative");
let source = std::fs::read(project.path("index.mq.md")).unwrap();
let source = project_source(&project);
let script = core.script.to_str().unwrap().to_string();
let dir = project.dir.to_str().unwrap().to_string();
core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 4));
core.set_analysis(&minimal_analysis("index.mq.md", &source, 2));
let output = common::run_view(
&["verify", "index.mq.md", "--marqdo-bin", &script],
std::path::Path::new(&dir),
@@ -264,12 +374,187 @@ fn cli_verify_rejects_schema_v4_and_digest_mismatch() {
assert_eq!(output.status.code(), Some(2));
assert!(String::from_utf8_lossy(&output.stderr).contains("view.protocol_incompatible"));
core.set_analysis(&minimal_analysis("index.mq.md", &"0".repeat(64), 2));
// A different, internally consistent document: the exact artifact does not
// bind to the checked source. This is a source-mismatch, not a silent retry.
core.set_analysis(&minimal_analysis(
"index.mq.md",
"# a different but internally consistent document\n",
3,
));
let output = common::run_view(
&["verify", "index.mq.md", "--marqdo-bin", &script],
std::path::Path::new(&dir),
&[("MARQDO_BIN", None)],
);
assert_eq!(output.status.code(), Some(1));
assert!(String::from_utf8_lossy(&output.stderr).contains("view.source_mismatch"));
assert_eq!(
output.status.code(),
Some(1),
"stderr: {}",
String::from_utf8_lossy(&output.stderr)
);
assert!(
String::from_utf8_lossy(&output.stderr).contains("view.source_mismatch"),
"stderr: {}",
String::from_utf8_lossy(&output.stderr)
);
// A forged source_digest is an internal artifact inconsistency.
let mut analysis: serde_json::Value =
serde_json::from_str(&minimal_analysis("index.mq.md", &source, 3)).unwrap();
analysis["modules"][0]["source_digest"] = serde_json::json!("0".repeat(64));
core.set_analysis(&analysis.to_string());
let output = common::run_view(
&["verify", "index.mq.md", "--marqdo-bin", &script],
std::path::Path::new(&dir),
&[("MARQDO_BIN", None)],
);
assert_eq!(
output.status.code(),
Some(1),
"stderr: {}",
String::from_utf8_lossy(&output.stderr)
);
assert!(
String::from_utf8_lossy(&output.stderr).contains("view.analysis_failed"),
"stderr: {}",
String::from_utf8_lossy(&output.stderr)
);
}
fn expect_check_ok(response: CheckResponse) -> marqdo_view::core_client::CheckOutput {
assert!(response.success, "check failed: {:?}", response.diagnostics);
response.analysis.expect("analysis on success")
}
#[test]
fn unknown_analysis_schema_name_or_major_is_rejected() {
// N02: an artifact with the wrong schema identity or an unknown major is a
// protocol error; there is no guess or fallback decoder.
let source = "# @knowledge fixture\n";
let mut analysis: serde_json::Value =
serde_json::from_str(&minimal_analysis("index.mq.md", source, 3)).unwrap();
analysis["schema"] = serde_json::json!("marqdo.analysis.legacy");
let err = marqdo_view::protocol::analysis_v3::verify_analysis(
analysis.to_string().as_bytes(),
"index.mq.md",
None,
)
.unwrap_err();
assert_eq!(err.code(), "view.protocol_incompatible");
let mut analysis: serde_json::Value =
serde_json::from_str(&minimal_analysis("index.mq.md", source, 3)).unwrap();
analysis["schema_version"] = serde_json::json!(5);
let err = marqdo_view::protocol::analysis_v3::verify_analysis(
analysis.to_string().as_bytes(),
"index.mq.md",
None,
)
.unwrap_err();
assert_eq!(err.code(), "view.protocol_incompatible");
}
#[test]
fn missing_required_analysis_fields_are_rejected() {
// N03: required fields are not optional; a missing module/document/unit field
// must never decode as an empty, successful document.
for field in ["modules", "diagnostics"] {
let source = "# @knowledge fixture\n";
let mut analysis: serde_json::Value =
serde_json::from_str(&minimal_analysis("index.mq.md", source, 3)).unwrap();
analysis.as_object_mut().unwrap().remove(field);
let err = marqdo_view::protocol::analysis_v3::verify_analysis(
analysis.to_string().as_bytes(),
"index.mq.md",
None,
)
.unwrap_err();
assert_eq!(err.code(), "view.protocol_incompatible", "field {field}");
}
let source = "# @knowledge fixture\n";
let mut analysis: serde_json::Value =
serde_json::from_str(&minimal_analysis("index.mq.md", source, 3)).unwrap();
analysis["modules"][0]
.as_object_mut()
.unwrap()
.remove("functions");
let err = marqdo_view::protocol::analysis_v3::verify_analysis(
analysis.to_string().as_bytes(),
"index.mq.md",
None,
)
.unwrap_err();
assert_eq!(err.code(), "view.protocol_incompatible");
}
#[test]
fn unknown_module_and_unit_references_are_rejected() {
// N08: resolved references, imports, functions and anchors must point at
// records that exist in the same artifact.
let source = "# @knowledge fixture\n";
let base = minimal_analysis("index.mq.md", source, 3);
let module_id = serde_json::from_str::<serde_json::Value>(&base).unwrap()["modules"][0]["id"]
.as_str()
.unwrap()
.to_string();
let mut analysis: serde_json::Value = serde_json::from_str(&base).unwrap();
analysis["modules"][0]["references"] = serde_json::json!([{
"source": module_id,
"source_unit": format!("{module_id}#missing"),
"url": "./theory.mq.md",
"span": {"start": 0, "end": 1},
"state": "resolved",
"target_kind": "module",
"target_module": module_id,
"target_unit": null,
"candidate_package_instance_id": "root:fixture@0.1.0",
"candidate_path": "theory.mq.md",
"fragment": null,
"candidates": []
}]);
let err = marqdo_view::protocol::analysis_v3::verify_analysis(
analysis.to_string().as_bytes(),
"index.mq.md",
None,
)
.unwrap_err();
assert_eq!(err.code(), "view.analysis_failed");
let mut analysis: serde_json::Value = serde_json::from_str(&base).unwrap();
analysis["modules"][0]["imports"] = serde_json::json!([{
"alias": "theory",
"target": "./theory.mq.md",
"resolved": "root:fixture@0.1.0::theory.mq.md",
"span": {"start": 0, "end": 1}
}]);
let err = marqdo_view::protocol::analysis_v3::verify_analysis(
analysis.to_string().as_bytes(),
"index.mq.md",
None,
)
.unwrap_err();
assert_eq!(err.code(), "view.analysis_failed");
}
#[test]
fn strict_mode_run_request_is_rejected_by_view_validation() {
// N13: View never passes a `strict` mode to the CLI. The request schema
// rejects it before any process starts (no retry with project).
let body = serde_json::json!({
"document": "index.mq.md",
"target": {"kind": "entry"},
"analysis_digest": format!("sha256:{}", "0".repeat(64)),
"mode": "strict",
"grants": {"read": [], "write": []},
"client_request_id": "strict-1"
})
.to_string();
let err = marqdo_view::execution::request::validate_request(body.as_bytes()).unwrap_err();
assert!(
matches!(err.code(), "view.run_invalid" | "view.run_denied"),
"strict mode must be refused before spawn, got {}",
err.code()
);
assert_eq!(err.exit_code(), 2);
}
+3 -3
View File
@@ -1,5 +1,5 @@
//! Contract suite: the frozen CLI black-box process contract, Analysis v2 /
//! Trace v2 validation, the View CLI surface, and architecture/asset gates.
//! Contract suite: the frozen CLI black-box process contract, Analysis v3 /
//! Observation v1 validation, the View CLI surface, and architecture/asset gates.
#[path = "../common/mod.rs"]
mod common;
@@ -8,5 +8,5 @@ mod asset_integrity;
mod cli_surface;
mod core_contract;
mod no_coupling;
mod observation_contract;
mod presentation_states;
mod trace_contract;
+60 -3
View File
@@ -181,9 +181,66 @@ fn tool_manifest_matches_package_and_protocols() {
env!("CARGO_PKG_VERSION"),
"tool.json version must match Cargo package version"
);
assert_eq!(tool["compatibility"]["marqdo"], ">=3.0.0-beta.1,<4.0.0");
assert_eq!(tool["compatibility"]["analysis"], serde_json::json!([2, 3]));
assert_eq!(tool["compatibility"]["trace"], serde_json::json!([2]));
assert_eq!(
tool["requires"],
serde_json::json!({"api_revision": 1, "analysis": 3, "observation": 1}),
"the manifest must declare exact current revisions"
);
assert!(
tool.get("compatibility").is_none(),
"the retired compatibility negotiation block must not return"
);
let keys: Vec<&str> = tool
.as_object()
.unwrap()
.keys()
.map(String::as_str)
.collect();
assert_eq!(
keys,
vec![
"command",
"entrypoint",
"name",
"requires",
"schema",
"schema_version",
"version"
],
"tool.json must not carry retired fields"
);
}
#[test]
fn source_has_no_legacy_protocol_or_runtime_probing() {
let root = manifest_dir();
let mut sources = Vec::new();
collect_files(&root.join("src"), "rs", &mut sources);
let banned = [
"analysis_v2",
"trace_v2",
"execution_events_v1",
"MARQDO_TOOL_PROTOCOL",
"MARQDO_PROTOCOL_ANALYSIS",
"MARQDO_PROTOCOL_TRACE",
"--trace-file",
"--event-stream",
"compatibility",
];
for path in sources {
// Unit-test modules may assert that a retired flag is absent; the gate
// scans production source only.
let text = read(&path);
let production = text.split("#[cfg(test)]").next().unwrap_or("").to_string();
for needle in banned {
assert!(
!production.contains(needle),
"{} still references retired contract marker {:?}",
path.display(),
needle
);
}
}
}
#[test]
+446
View File
@@ -0,0 +1,446 @@
//! Observation v1 contract: one JSONL event sequence decoded by one decoder,
//! schema/lifecycle/sequence/source-binding validation, the atomic snapshot
//! equivalence, and negative fail-closed cases.
use crate::common::golden_bytes;
use marqdo_view::protocol::analysis_v3::{verify_analysis, SemanticProjection};
use marqdo_view::protocol::observation_v1::{
decode_snapshot, ObservationDecoder, ObservedKind, RunDisplayState,
};
const ANALYSIS: &str = "tests/golden/analysis-v3/control-flow.json";
const JSONL: &str = "tests/golden/observation-v1/control-flow.jsonl";
const SNAPSHOT: &str = "tests/golden/observation-v1/control-flow.snapshot.json";
const TRUNCATED_JSONL: &str = "tests/golden/observation-v1/control-flow.truncated.jsonl";
const TRUNCATED_SNAPSHOT: &str = "tests/golden/observation-v1/control-flow.truncated.snapshot.json";
fn projection() -> SemanticProjection {
verify_analysis(&golden_bytes(ANALYSIS), "index.mq.md", None)
.expect("golden Analysis v3 verifies")
.projection
}
fn decode(jsonl: &str) -> Result<marqdo_view::protocol::observation_v1::RunProjection, String> {
let projection = projection();
let mut decoder = ObservationDecoder::new(&projection);
let frames = decoder.push(&golden_bytes(jsonl));
if let Some(detail) = decoder.invalid() {
return Err(detail.to_string());
}
assert!(!frames.is_empty(), "decoder published no browser frames");
decoder
.finish(0, "", false)
.map_err(|err| format!("{}: {err}", err.code()))
}
#[test]
fn real_jsonl_stream_verifies_and_binds_to_analysis_digest() {
let run = decode(JSONL).expect("real Observation v1 stream verifies");
assert_eq!(run.state, RunDisplayState::Succeeded);
assert_eq!(run.run_status, "ok");
assert_eq!(run.exit_code, 0);
assert!(run.source_verified);
assert_eq!(run.analysis_digest, projection().analysis_digest);
assert!(run.truncated.is_none());
assert_eq!(
run.events.first().map(|event| event.kind.clone()),
Some(ObservedKind::StreamOpened)
);
assert_eq!(
run.events.get(1).map(|event| event.kind.clone()),
Some(ObservedKind::RunStarted)
);
// Terminal is unique and last.
let terminals = run
.events
.iter()
.filter(|event| {
matches!(
event.kind,
ObservedKind::RunCompleted | ObservedKind::RunFailed | ObservedKind::RunRejected
)
})
.count();
assert_eq!(terminals, 1);
assert_eq!(
run.events.last().map(|event| event.kind.clone()),
Some(ObservedKind::RunCompleted)
);
assert!(run.counts.effect > 0);
assert!(run.counts.branch_eval > 0);
assert!(run.counts.loop_iteration > 0);
assert!(!run.stdout.is_empty(), "stdout chunks are decoded");
assert_eq!(
run.result_value.as_ref().map(|value| value.ty.as_str()),
Some("Int")
);
}
#[test]
fn stream_and_snapshot_of_the_same_run_agree() {
let projection = projection();
let from_stream = decode(JSONL).expect("stream decodes");
let from_snapshot =
decode_snapshot(&golden_bytes(SNAPSHOT), &projection).expect("snapshot decodes");
assert_eq!(from_stream.run_id, from_snapshot.run_id);
assert_eq!(from_stream.state, from_snapshot.state);
assert_eq!(from_stream.events.len(), from_snapshot.events.len());
for (stream, snapshot) in from_stream.events.iter().zip(from_snapshot.events.iter()) {
assert_eq!(stream.seq, snapshot.seq);
assert_eq!(stream.kind, snapshot.kind);
assert_eq!(stream.span, snapshot.span);
assert_eq!(stream.anchor_span, snapshot.anchor_span);
assert_eq!(stream.detail, snapshot.detail);
assert_eq!(stream.operation, snapshot.operation);
}
}
#[test]
fn truncated_observation_is_a_terminal_but_never_complete() {
let run = decode(TRUNCATED_JSONL).expect("truncated stream decodes");
assert_eq!(run.state, RunDisplayState::Truncated);
let truncated = run.truncated.clone().expect("observation.truncated");
assert_eq!(truncated.reason, "event_budget");
assert_eq!(truncated.limit, 5);
let terminals = run
.events
.iter()
.filter(|event| {
matches!(
event.kind,
ObservedKind::RunCompleted | ObservedKind::RunFailed | ObservedKind::RunRejected
)
})
.count();
assert_eq!(terminals, 1);
assert!(!run.is_success() || run.state == RunDisplayState::Truncated);
let projection = projection();
let snapshot = decode_snapshot(&golden_bytes(TRUNCATED_SNAPSHOT), &projection)
.expect("truncated snapshot decodes");
assert_eq!(snapshot.state, RunDisplayState::Truncated);
assert_eq!(
snapshot
.truncated
.as_ref()
.map(|value| value.reason.as_str()),
Some("event_budget")
);
}
#[test]
fn lifecycle_negative_cases_fail_closed() {
let projection = projection();
let module = projection.module_id.clone();
let digest = projection.analysis_digest.clone();
let root = projection.project_root_id.clone();
let cases: Vec<(&str, Vec<serde_json::Value>)> = vec![
("missing stream.opened", vec![started(0, &digest, &root)]),
(
"terminal without start",
vec![opened(0, &module), completed(1, &module)],
),
(
"unknown kind",
vec![
opened(0, &module),
started(1, &digest, &root),
event(2, "future.event", serde_json::json!({})),
],
),
(
"sequence gap",
vec![
opened(0, &module),
started(1, &digest, &root),
effect(3, &module),
],
),
(
"duplicate sequence",
vec![
opened(0, &module),
started(1, &digest, &root),
effect(2, &module),
effect(2, &module),
],
),
(
"mixed run id",
vec![
opened(0, &module),
event(
1,
"run.started",
serde_json::json!({
"entry": format!("{module}::main"),
"mode": "pure",
"source": {"root_id": root, "analysis_digest": digest}
}),
),
event_with_run(2, "other-run", "effect", effect_payload(&module)),
],
),
(
"continued after terminal",
vec![
opened(0, &module),
started(1, &digest, &root),
completed(2, &module),
effect(3, &module),
],
),
(
"two terminals",
vec![
opened(0, &module),
started(1, &digest, &root),
completed(2, &module),
completed(3, &module),
],
),
(
"span outside source",
vec![
opened(0, &module),
started(1, &digest, &root),
event(
2,
"effect",
serde_json::json!({
"frame_id": "f1", "operation": "fs.exists",
"result_code": "ok", "module_id": module,
"span": {"start": 0, "end": 999_999}
}),
),
],
),
(
"value without consent",
vec![
opened(0, &module),
started(1, &digest, &root),
event(
2,
"variable.assigned",
serde_json::json!({
"frame_id": "f1", "module_id": module, "name": "x",
"value_state": "observed", "value_type": "Int",
"span": {"start": 0, "end": 1},
"value": {"type": "int", "decimal": "1"}
}),
),
],
),
];
for (name, events) in cases {
let mut decoder = ObservationDecoder::new(&projection);
let bytes = encode(&events);
decoder.push(&bytes);
if let Some(detail) = decoder.invalid() {
// Push-time rejection is the expected fail-closed path.
assert!(!detail.is_empty(), "{name}");
continue;
}
let result = decoder.finish(0, "", false);
assert!(result.is_err(), "{name} was accepted as {result:?}");
}
}
#[test]
fn unknown_schema_and_revision_are_rejected() {
let projection = projection();
let module = projection.module_id.clone();
let mut event = opened(0, &module);
event["schema"] = serde_json::json!("marqdo.execution-events");
let mut decoder = ObservationDecoder::new(&projection);
decoder.push(&encode(&[event]));
assert!(decoder.invalid().is_some(), "old schema must be rejected");
let mut event = opened(0, &module);
event["schema_version"] = serde_json::json!(2);
let mut decoder = ObservationDecoder::new(&projection);
decoder.push(&encode(&[event]));
assert!(
decoder.invalid().is_some(),
"unknown revision must be rejected"
);
}
#[test]
fn stale_and_wrong_root_bindings_are_observation_stale() {
let projection = projection();
let module = projection.module_id.clone();
let wrong_digest = format!("sha256:{}", "0".repeat(64));
let events = vec![
opened(0, &module),
started(1, &wrong_digest, &projection.project_root_id),
completed(2, &module),
];
let mut decoder = ObservationDecoder::new(&projection);
decoder.push(&encode(&events));
let err = decoder.finish(0, "", false).unwrap_err();
assert_eq!(err.code(), "view.observation_stale");
assert!(!err.detail().is_empty());
let events = vec![
opened(0, &module),
started(1, &projection.analysis_digest, "root:other@0.1.0"),
completed(2, &module),
];
let mut decoder = ObservationDecoder::new(&projection);
decoder.push(&encode(&events));
let err = decoder.finish(0, "", false).unwrap_err();
assert_eq!(err.code(), "view.observation_stale");
}
#[test]
fn rejected_before_start_is_a_valid_failed_terminal() {
let projection = projection();
let module = projection.module_id.clone();
let events = vec![opened(0, &module), rejected(1, &module)];
let mut decoder = ObservationDecoder::new(&projection);
decoder.push(&encode(&events));
let run = decoder
.finish(1, "error[sem.unclosed_control]: refusing to run", false)
.expect("compile rejection is a valid terminal");
assert_eq!(run.state, RunDisplayState::Failed);
assert_eq!(run.run_status, "rejected");
assert_eq!(run.error_code.as_deref(), Some("sem.unclosed_control"));
assert!(!run.is_success());
}
#[test]
fn eof_without_terminal_is_incomplete_never_success() {
let projection = projection();
let module = projection.module_id.clone();
let events = vec![
opened(0, &module),
started(1, &projection.analysis_digest, &projection.project_root_id),
effect(2, &module),
];
let mut decoder = ObservationDecoder::new(&projection);
decoder.push(&encode(&events));
let run = decoder.finish(0, "", false).expect("no terminal decodes");
assert_eq!(run.state, RunDisplayState::Incomplete);
assert_eq!(
run.error_code.as_deref(),
Some("view.observation_incomplete")
);
assert!(!run.is_success());
assert!(!run.output_complete);
}
// ---------------------------------------------------------------------------
// Synthetic Observation v1 builders (only for negative-path tests).
// ---------------------------------------------------------------------------
fn encode(events: &[serde_json::Value]) -> Vec<u8> {
let mut bytes = Vec::new();
for event in events {
bytes.extend_from_slice(event.to_string().as_bytes());
bytes.push(b'\n');
}
bytes
}
fn envelope(seq: u64, kind: &str, payload: serde_json::Value) -> serde_json::Value {
serde_json::json!({
"schema": "marqdo.observation",
"schema_version": 1,
"run_id": "test-run-1",
"seq": seq,
"kind": kind,
"payload": payload
})
}
fn event(seq: u64, kind: &str, payload: serde_json::Value) -> serde_json::Value {
envelope(seq, kind, payload)
}
fn event_with_run(
seq: u64,
run: &str,
kind: &str,
payload: serde_json::Value,
) -> serde_json::Value {
let mut value = envelope(seq, kind, payload);
value["run_id"] = serde_json::json!(run);
value
}
fn opened(seq: u64, _module: &str) -> serde_json::Value {
envelope(
seq,
"stream.opened",
serde_json::json!({
"producer": {"name": "marqdo", "version": "3.0.0-rc.4"},
"observation": {
"level": "structural",
"values": false,
"selected_variables": [],
"selected_parameters": [],
"allow_text_values": false
},
"limits": {
"max_observation_events": 10000,
"max_observation_bytes": 4194304,
"max_value_bytes": 256
}
}),
)
}
fn started(seq: u64, digest: &str, root: &str) -> serde_json::Value {
let projection = projection();
envelope(
seq,
"run.started",
serde_json::json!({
"entry": format!("{}::main", projection.module_id),
"mode": "pure",
"source": {"root_id": root, "analysis_digest": digest},
"started_unix_ms": 1
}),
)
}
fn effect(seq: u64, module: &str) -> serde_json::Value {
event(seq, "effect", effect_payload(module))
}
fn effect_payload(module: &str) -> serde_json::Value {
serde_json::json!({
"frame_id": "f1",
"operation": "fs.exists",
"result_code": "ok",
"module_id": module,
"span": {"start": 0, "end": 1}
})
}
fn completed(seq: u64, _module: &str) -> serde_json::Value {
envelope(
seq,
"run.completed",
serde_json::json!({
"status": "ok",
"value": {"type": "int", "decimal": "3"},
"value_type": "Int"
}),
)
}
fn rejected(seq: u64, _module: &str) -> serde_json::Value {
envelope(
seq,
"run.rejected",
serde_json::json!({
"status": "rejected",
"phase": "compile",
"error": {"code": "sem.unclosed_control", "message": "`if` is not closed"}
}),
)
}
+166 -62
View File
@@ -1,11 +1,18 @@
//! Degradation/state matrix contract (RFC-VIEW-0001 S-05..S-07, §12.3):
//! prose stays readable while semantics become explicitly unusable.
//! Degradation/state matrix contract: prose stays readable while semantics
//! become explicitly unusable; run states never claim success from an incomplete or
//! truncated observation.
use crate::common;
use crate::common::{golden_bytes, minimal_analysis, FakeCore, TempProject};
use marqdo_view::protocol::analysis_v3::{verify_analysis, SemanticProjection};
use marqdo_view::protocol::observation_v1::{ObservationDecoder, RunDisplayState, RunProjection};
use marqdo_view::reader::assemble::{build, BuildInput, DocumentService};
use marqdo_view::reader::markdown::{DocumentIdentity, DocumentModel};
use marqdo_view::reader::model::{Navigation, SourceStatus};
use marqdo_view::reader::source::Project;
use common::{minimal_analysis, sha256_hex, FakeCore, TempProject};
use marqdo_view::reader::assemble::DocumentService;
use marqdo_view::reader::model::SourceStatus;
const ANALYSIS: &str = "tests/golden/analysis-v3/control-flow.json";
const JSONL: &str = "tests/golden/observation-v1/control-flow.jsonl";
const TRUNCATED_JSONL: &str = "tests/golden/observation-v1/control-flow.truncated.jsonl";
fn project(name: &str) -> (TempProject, FakeCore) {
let project = TempProject::new(name);
@@ -14,12 +21,53 @@ fn project(name: &str) -> (TempProject, FakeCore) {
(project, core)
}
fn projection() -> SemanticProjection {
verify_analysis(&golden_bytes(ANALYSIS), "index.mq.md", None)
.expect("control-flow golden verifies")
.projection
}
fn decode(jsonl: &str) -> RunProjection {
let projection = projection();
let mut decoder = ObservationDecoder::new(&projection);
decoder.push(&golden_bytes(jsonl));
assert!(decoder.invalid().is_none(), "{:?}", decoder.invalid());
decoder
.finish(0, "", false)
.expect("real observation stream verifies")
}
fn empty_model(
document: DocumentModel,
run: Option<&RunProjection>,
) -> marqdo_view::reader::model::PresentationModel {
build(BuildInput {
document,
analysis: None,
status: SourceStatus::CoreUnavailable,
status_note: Some("test".into()),
diagnostics: Vec::new(),
navigation: Navigation {
site_title: "test".into(),
documents: Vec::new(),
active: None,
welcome: false,
},
core_version: None,
run,
})
}
fn document_for(relative: &str, source: &str) -> DocumentModel {
let path = marqdo_view::reader::source::SafeRelativePath::parse(relative).unwrap();
DocumentModel::parse(source.to_string(), DocumentIdentity::placeholder(&path))
}
#[test]
fn failed_check_keeps_prose_and_shows_core_diagnostics() {
let (project, core) = project("state-check-fail");
let source = std::fs::read(project.path("index.mq.md")).unwrap();
// Emit a broken analysis too; it must NOT be used after a failed check.
core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 2));
let source = std::fs::read_to_string(project.path("index.mq.md")).unwrap();
core.set_analysis(&minimal_analysis("index.mq.md", &source, 3));
core.set_check(1, "");
core.set_check_json(
r#"{"command":"check","success":false,"errors":1,"diagnostics":[{"code":"sem.unclosed_control","column":1,"file":"/home/secret/index.mq.md","line":3,"message":"`if` is not closed by `end`","module":"root:fixture@0.1.0::index.mq.md","severity":"error"}]}"#,
@@ -38,14 +86,13 @@ fn failed_check_keeps_prose_and_shows_core_diagnostics() {
.iter()
.any(|diagnostic| diagnostic.code == "sem.unclosed_control"));
assert!(!model.source_status.semantics_usable());
// Pending run state is explicit, never a success claim.
assert_eq!(model.run_state().data_value(), "not-run");
}
#[test]
fn source_digest_mismatch_degrades_instead_of_misbinding() {
let (project, core) = project("state-source-mismatch");
core.set_analysis(&minimal_analysis("index.mq.md", &"0".repeat(64), 2));
core.set_analysis(&minimal_analysis("index.mq.md", "# 完全不同的源码\n", 3));
let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap();
let relative = context.project().entry().relative.clone();
let model = context.load(&relative).unwrap();
@@ -57,8 +104,8 @@ fn source_digest_mismatch_degrades_instead_of_misbinding() {
#[test]
fn unknown_analysis_schema_is_a_hard_protocol_error() {
let (project, core) = project("state-protocol");
let source = std::fs::read(project.path("index.mq.md")).unwrap();
core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 4));
let source = std::fs::read_to_string(project.path("index.mq.md")).unwrap();
core.set_analysis(&minimal_analysis("index.mq.md", &source, 4));
let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap();
let relative = context.project().entry().relative.clone();
let err = context.load(&relative).unwrap_err();
@@ -67,79 +114,69 @@ fn unknown_analysis_schema_is_a_hard_protocol_error() {
}
#[test]
fn invalid_core_span_is_dropped_with_an_explicit_warning() {
fn invalid_analysis_span_is_rejected_not_trimmed() {
// N09: an out-of-range/negative span in a protocol artifact is a hard
// failure; View must never clip it and claim success.
let (project, core) = project("state-span-invalid");
let source = std::fs::read(project.path("index.mq.md")).unwrap();
let source = std::fs::read_to_string(project.path("index.mq.md")).unwrap();
let mut analysis: serde_json::Value =
serde_json::from_str(&minimal_analysis("index.mq.md", &sha256_hex(&source), 2)).unwrap();
// A span in the middle of a multi-byte character / beyond EOF.
serde_json::from_str(&minimal_analysis("index.mq.md", &source, 3)).unwrap();
let module_id = analysis["modules"][0]["id"].as_str().unwrap().to_string();
analysis["modules"][0]["units"] = serde_json::json!([{
"id": "x", "name": "坏", "level": 1, "kind": "namespace", "function": null,
"span": {"start": 0, "end": 999_999}
"id": format!("{module_id}#坏"),
"path": ["坏"],
"parent_id": module_id,
"kind": "namespace",
"name": "坏",
"level": 1,
"mode": "knowledge",
"mode_origin": "explicit",
"mode_source_unit_id": format!("{module_id}#坏"),
"heading_span": {"start": 0, "end": 1},
"span": {"start": 0, "end": 999_999},
"function": null
}]);
core.set_analysis(&serde_json::to_string(&analysis).unwrap());
let bytes = analysis.to_string().into_bytes();
let err = verify_analysis(&bytes, "index.mq.md", Some(&source)).unwrap_err();
assert_eq!(err.code(), "view.analysis_failed");
// Through the reader the prose stays readable, but no annotation may be
// attached from the rejected artifact.
core.set_analysis(&analysis.to_string());
let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap();
let relative = context.project().entry().relative.clone();
let model = context.load(&relative).unwrap();
assert_eq!(model.source_status, SourceStatus::StaticOk);
assert!(model.semantic.as_ref().unwrap().units.is_empty());
assert!(model
.warnings
.iter()
.any(|warning| warning.code == "view.source_span_invalid"));
let _ = source;
assert!(model.semantic.is_none());
assert_eq!(model.source_status, SourceStatus::CoreError);
assert!(model.document.plain_text().contains("正文"));
}
#[test]
fn run_attached_to_changed_source_becomes_stale() {
let repo_root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let project = TempProject::new("state-stale-run");
project.write(
"marqdo.yaml",
"project:\n name: control-flow\n version: 0.1.0\n",
);
let source =
std::fs::read_to_string(repo_root.join("examples/control-flow/index.mq.md")).unwrap();
let source = golden_bytes("tests/golden/analysis-v3/control-flow.json");
let source = serde_json::from_slice::<serde_json::Value>(&source).unwrap()["modules"][0]
["source"]
.as_str()
.unwrap()
.to_string();
project.write("index.mq.md", &source);
let core = FakeCore::new("state-stale-run-core");
let analysis =
std::fs::read(repo_root.join("tests/golden/analysis-v2/control-flow.json")).unwrap();
let analysis = golden_bytes(ANALYSIS);
core.set_analysis(std::str::from_utf8(&analysis).unwrap());
let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap();
let relative = context.project().entry().relative.clone();
// Build a verified run directly from the golden trace + golden analysis.
let source_index = marqdo_view::reader::source::SourceIndex::new(&source);
let verified_analysis = marqdo_view::protocol::analysis_v2::verify_analysis(
&analysis,
&source,
&source_index,
"index.mq.md",
)
.unwrap();
let trace =
std::fs::read(repo_root.join("tests/golden/trace-v2/control-flow.trace.json")).unwrap();
let run_json: serde_json::Value = serde_json::from_slice(
&std::fs::read(repo_root.join("tests/golden/trace-v2/control-flow.run.json")).unwrap(),
)
.unwrap();
let run = marqdo_view::protocol::trace_v2::verify_trace(
marqdo_view::protocol::trace_v2::TraceVerificationInput {
trace_bytes: &trace,
analysis_bytes: &analysis,
semantic: &verified_analysis.projection,
modules: &verified_analysis.projection.modules,
source: &source,
source_index: &source_index,
run_json: &run_json,
exit_code: 0,
},
)
.unwrap();
let run = decode(JSONL);
let attached = context.load_with_run(&relative, Some(&run)).unwrap();
assert_eq!(attached.run_state().data_value(), "succeeded");
// Change the source and rebuild through the same server path.
// The document changed after the run; the same projection must never be
// re-anchored to the new source.
std::fs::write(
project.path("index.mq.md"),
format!("{source}\n<!-- changed -->\n"),
@@ -156,5 +193,72 @@ fn run_attached_to_changed_source_becomes_stale() {
if let Some(run) = &changed.run {
assert!(run.events.iter().all(|event| event.anchor_span.is_none()));
}
let _ = core;
}
#[test]
fn truncated_and_incomplete_runs_never_display_as_success() {
let run = decode(TRUNCATED_JSONL);
assert_eq!(run.state, RunDisplayState::Truncated);
assert!(run.truncated.is_some());
let model = empty_model(document_for("index.mq.md", "# @knowledge x\n"), Some(&run));
assert_eq!(model.run_state().data_value(), "truncated");
assert!(model.run_state().is_terminal());
assert_ne!(model.run_state().data_value(), "succeeded");
assert_eq!(model.run_state().label(), "观察已截断");
// A stream that ends before its terminal event is incomplete, not success.
let projection = projection();
let mut decoder = ObservationDecoder::new(&projection);
let mut lines = Vec::new();
for line in golden_bytes(JSONL).split(|byte| *byte == b'\n') {
if line.is_empty() {
continue;
}
let value: serde_json::Value = serde_json::from_slice(line).unwrap();
if value["kind"] == "run.completed" {
break;
}
lines.extend_from_slice(line);
lines.push(b'\n');
}
decoder.push(&lines);
let incomplete = decoder.finish(0, "", false).unwrap();
assert_eq!(incomplete.state, RunDisplayState::Incomplete);
assert!(!incomplete.is_success());
let model = empty_model(
document_for("index.mq.md", "# @knowledge x\n"),
Some(&incomplete),
);
assert_eq!(model.run_state().data_value(), "incomplete");
}
#[test]
fn missing_core_stays_readable_and_explicitly_unverified() {
let project = TempProject::new("state-no-core");
project.marqdo_project("# @knowledge fixture\n");
let context = DocumentService::open(
&project.dir,
Some(std::path::Path::new("/definitely/missing/marqdo-frozen")),
)
.unwrap();
let relative = context.project().entry().relative.clone();
let model = context.load(&relative).unwrap();
assert_eq!(model.source_status, SourceStatus::CoreUnavailable);
assert!(model.semantic.is_none());
assert!(model.status_note.is_some());
}
#[test]
fn external_projection_can_be_rendered_from_artifact_source() {
// The artifact source is the only source used to interpret spans, even when
// no checkout file exists for a dependency module.
let verified = verify_analysis(&golden_bytes(ANALYSIS), "index.mq.md", None).unwrap();
assert_eq!(
verified.projection.source,
verified.projection.entry_module().unwrap().source
);
let _ = Project::open(
&std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("examples/control-flow"),
)
.unwrap();
}
-270
View File
@@ -1,270 +0,0 @@
//! Trace v2 contract tests against goldens emitted by the frozen CLI. The
//! goldens bind to the committed Analysis v2 bytes by digest, so a changed
//! source cannot silently reuse an old trace.
use marqdo_view::protocol::analysis_v2 as semantic;
use marqdo_view::protocol::trace_v2::{verify_trace, RunDisplayState, TraceVerificationInput};
use marqdo_view::reader::source::{sha256_prefixed, SourceIndex};
use serde_json::Value;
struct Fixture {
source: String,
index: SourceIndex,
analysis: Vec<u8>,
semantic: semantic::VerifiedAnalysis,
}
fn fixture(analysis_golden: &str, source_path: &str) -> Fixture {
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let source = std::fs::read_to_string(root.join(source_path)).unwrap();
let index = SourceIndex::new(&source);
let analysis = std::fs::read(root.join(analysis_golden)).unwrap();
let semantic = semantic::verify_analysis(&analysis, &source, &index, "index.mq.md").unwrap();
Fixture {
source,
index,
analysis,
semantic,
}
}
fn golden_json(path: &str) -> Value {
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
serde_json::from_slice(&std::fs::read(root.join(path)).unwrap()).unwrap()
}
fn golden_bytes(path: &str) -> Vec<u8> {
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
std::fs::read(root.join(path)).unwrap()
}
fn verify(
fixture: &Fixture,
trace_golden: &str,
run_golden: &str,
exit_code: i32,
) -> marqdo_view::protocol::trace_v2::VerifiedRun {
let trace = golden_bytes(trace_golden);
let run_json = golden_json(run_golden);
verify_trace(TraceVerificationInput {
trace_bytes: &trace,
analysis_bytes: &fixture.analysis,
semantic: &fixture.semantic.projection,
modules: &fixture.semantic.projection.modules,
source: &fixture.source,
source_index: &fixture.index,
run_json: &run_json,
exit_code,
})
.expect("trace verifies")
}
#[test]
fn real_control_flow_trace_binds_and_projects_events() {
let fixture = fixture(
"tests/golden/analysis-v2/control-flow.json",
"examples/control-flow/index.mq.md",
);
let run = verify(
&fixture,
"tests/golden/trace-v2/control-flow.trace.json",
"tests/golden/trace-v2/control-flow.run.json",
0,
);
let projection = &run.projection;
assert_eq!(projection.state, RunDisplayState::Succeeded);
assert_eq!(projection.counts.total(), 27);
assert_eq!(projection.entry_event_count, 27);
assert_eq!(projection.other_event_count, 0);
assert_eq!(projection.run_status, "ok");
assert!(projection.truncated.is_none());
assert_eq!(projection.stdout, "0\n0\n2\n");
let value = projection.result_value.as_ref().expect("return value");
assert_eq!(value.ty, "int");
assert_eq!(value.display, "3");
// Public JSON final value only; never a per-assignment value claim.
assert!(projection.analysis_digest.starts_with("sha256:"));
// The loop header is evaluated four times (three iterations + exit).
let loop_span = projection
.events
.iter()
.find(|event| event.anchor_span.is_some() && event.detail.as_deref() == Some("exit"))
.and_then(|event| event.anchor_span)
.expect("loop anchor");
let summary = projection.anchor_summary(loop_span).expect("loop summary");
assert_eq!(summary.count, 4);
assert_eq!(summary.detail, "loop exit");
assert!(summary.kinds.contains(&"loop.iteration".to_string()));
let return_anchors: Vec<_> = projection
.events
.iter()
.filter(|event| event.anchor_span.is_some())
.collect();
assert!(!return_anchors.is_empty());
// Only entry-module events ever get statement anchors.
for event in &projection.events {
if event.anchor_span.is_some() {
assert_eq!(
event.module_id.as_deref(),
Some(fixture.semantic.projection.module_id.as_str())
);
}
}
}
#[test]
fn truncated_trace_is_explicitly_marked() {
let fixture = fixture(
"tests/golden/analysis-v2/control-flow.json",
"examples/control-flow/index.mq.md",
);
let run = verify(
&fixture,
"tests/golden/trace-v2/control-flow.truncated.trace.json",
"tests/golden/trace-v2/control-flow.truncated.run.json",
0,
);
let projection = &run.projection;
assert_eq!(projection.state, RunDisplayState::Truncated);
let truncated = projection.truncated.as_ref().expect("truncation");
assert_eq!(truncated.reason, "event_budget");
assert_eq!(truncated.limit, 5);
assert_eq!(truncated.written, 5);
assert!(truncated.label().contains("事件数量上限"));
assert_ne!(projection.state, RunDisplayState::Succeeded);
}
#[test]
fn failed_run_keeps_the_core_error_code() {
let fixture = fixture(
"tests/golden/analysis-v2/mixed-modes.json",
"examples/mixed-modes/index.mq.md",
);
let run = verify(
&fixture,
"tests/golden/trace-v2/mixed-modes.arity.trace.json",
"tests/golden/trace-v2/mixed-modes.arity.run.json",
1,
);
let projection = &run.projection;
assert_eq!(projection.state, RunDisplayState::Failed);
assert_eq!(projection.error_code.as_deref(), Some("call.arity"));
assert_eq!(projection.run_status, "call.arity");
assert!(projection.result_value.is_none());
assert_eq!(projection.state.label(), "运行失败");
}
#[test]
fn stale_analysis_bytes_are_rejected() {
let fixture = fixture(
"tests/golden/analysis-v2/control-flow.json",
"examples/control-flow/index.mq.md",
);
let mut tampered = fixture.analysis.clone();
tampered.push(b' ');
let trace = golden_bytes("tests/golden/trace-v2/control-flow.trace.json");
let run_json = golden_json("tests/golden/trace-v2/control-flow.run.json");
let err = verify_trace(TraceVerificationInput {
trace_bytes: &trace,
analysis_bytes: &tampered,
semantic: &fixture.semantic.projection,
modules: &fixture.semantic.projection.modules,
source: &fixture.source,
source_index: &fixture.index,
run_json: &run_json,
exit_code: 0,
})
.unwrap_err();
assert_eq!(err.code(), "view.trace_stale");
assert_eq!(err.exit_code(), 1);
}
#[test]
fn unknown_event_module_is_rejected() {
let fixture = fixture(
"tests/golden/analysis-v2/control-flow.json",
"examples/control-flow/index.mq.md",
);
let mut trace: Value = golden_json("tests/golden/trace-v2/control-flow.trace.json");
trace["events"][0]["module_id"] = Value::String("rogue::module.mq.md".to_string());
let trace_bytes = serde_json::to_vec(&trace).unwrap();
let run_json = golden_json("tests/golden/trace-v2/control-flow.run.json");
let err = verify_trace(TraceVerificationInput {
trace_bytes: &trace_bytes,
analysis_bytes: &fixture.analysis,
semantic: &fixture.semantic.projection,
modules: &fixture.semantic.projection.modules,
source: &fixture.source,
source_index: &fixture.index,
run_json: &run_json,
exit_code: 0,
})
.unwrap_err();
assert_eq!(err.code(), "view.trace_stale");
}
#[test]
fn non_monotonic_sequence_is_rejected() {
let fixture = fixture(
"tests/golden/analysis-v2/control-flow.json",
"examples/control-flow/index.mq.md",
);
let mut trace: Value = golden_json("tests/golden/trace-v2/control-flow.trace.json");
trace["events"][1]["seq"] = Value::Number(0.into());
let trace_bytes = serde_json::to_vec(&trace).unwrap();
let run_json = golden_json("tests/golden/trace-v2/control-flow.run.json");
let err = verify_trace(TraceVerificationInput {
trace_bytes: &trace_bytes,
analysis_bytes: &fixture.analysis,
semantic: &fixture.semantic.projection,
modules: &fixture.semantic.projection.modules,
source: &fixture.source,
source_index: &fixture.index,
run_json: &run_json,
exit_code: 0,
})
.unwrap_err();
assert_eq!(err.code(), "view.trace_stale");
}
#[test]
fn unknown_schema_major_is_a_protocol_error_not_a_stale_trace() {
let fixture = fixture(
"tests/golden/analysis-v2/control-flow.json",
"examples/control-flow/index.mq.md",
);
let mut trace: Value = golden_json("tests/golden/trace-v2/control-flow.trace.json");
trace["schema_version"] = Value::Number(3.into());
let trace_bytes = serde_json::to_vec(&trace).unwrap();
let run_json = golden_json("tests/golden/trace-v2/control-flow.run.json");
let err = verify_trace(TraceVerificationInput {
trace_bytes: &trace_bytes,
analysis_bytes: &fixture.analysis,
semantic: &fixture.semantic.projection,
modules: &fixture.semantic.projection.modules,
source: &fixture.source,
source_index: &fixture.index,
run_json: &run_json,
exit_code: 0,
})
.unwrap_err();
assert_eq!(err.code(), "view.protocol_incompatible");
assert_eq!(err.exit_code(), 2);
}
#[test]
fn golden_digest_is_really_sha256_of_analysis_bytes() {
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let analysis = std::fs::read(root.join("tests/golden/analysis-v2/control-flow.json")).unwrap();
let trace: Value = golden_json("tests/golden/trace-v2/control-flow.trace.json");
assert_eq!(
trace["source"]["analysis_digest"].as_str().unwrap(),
sha256_prefixed(&analysis)
);
assert_eq!(
trace["source"]["root_id"].as_str().unwrap(),
"root:control-flow@0.1.0"
);
}