feat(analysis): consume the current public Analysis v3 contract

- add the process boundary for the core CLI: explicit MARQDO_BIN/--marqdo-bin
  only (never PATH), argv-only invocation of check ENTRY --emit, bounded
  timeout, private temp artifact, exit checks and absolute-path sanitisation
- deserialize every Analysis record with closed serde shapes and validate
  semantic invariants that JSON Schema cannot express: identities, source
  digests, UTF-8 spans, unit tree/order/mode ancestry, anchors, functions and
  signatures, references states, calls, resources, diagnostics and budgets
- validate statement/expression trees structurally with depth and span checks
- convert accepted modules into DocumentFacts, preserving honest upstream
  reference states and one node per Exec unit/function
- merge modules across entry contexts only when identity and source agree,
  otherwise report knowledge.analysis_context_conflict
- add the real rc.4 Analysis positive fixture (with provenance and regeneration
  script), tamper negative tests and optional real-binary integration tests
This commit is contained in:
marqdo-knowledge committed 2026-11-26 00:29:19 +08:00
1 parent 682717a610
commit 59d5afe10b
14 files changed
+3474 -57

No files matched your search

Generated
-21
View File
@@ -381,7 +381,6 @@ dependencies = [
"serde_yaml",
"sha2",
"tempfile",
"thiserror",
"unicode-normalization",
]
@@ -636,26 +635,6 @@ dependencies = [
"windows-sys",
]
[[package]]
name = "thiserror"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tinyvec"
version = "1.13.3"
-1
View File
@@ -27,7 +27,6 @@ serde_json = "=1.0.154"
serde_yaml = "=0.9.34"
sha2 = "=0.10.9"
tempfile = "=3.27.0"
thiserror = "=2.0.21"
unicode-normalization = "=0.1.26"
[profile.release]
+62
View File
@@ -0,0 +1,62 @@
#!/bin/sh
# Regenerate the committed Analysis positive fixture with a real core CLI.
#
# Usage: scripts/regenerate-analysis-fixture.sh /path/to/marqdo
# The emitted artefact is recorded together with the producer identity in
# tests/fixtures/analysis/README.md. Never hand-edit the fixture.
set -eu
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
BIN=${1:?usage: $0 /path/to/marqdo}
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
mkdir -p "$WORK/project/physics"
cat > "$WORK/project/marqdo.yaml" <<'YAML'
project:
name: demo
version: 0.1.0
marqdo: ">=3.0.0-beta.1,<4.0.0"
dependencies: {}
YAML
cat > "$WORK/project/physics/mechanics.mq.md" <<'MD'
---
type: Theory
title: 经典力学
tags: [physics, mechanics]
---
# 经典力学
## @knowledge 牛顿第二定律
合外力等于质量与加速度的乘积。
$$
F = ma
$$
| 符号 | 含义 |
| --- | --- |
| m | 质量 |
| a | 加速度 |
计算入口:[计算力](#计算力)。
## @exec 计算力
`params(m, a)`
依据[牛顿第二定律](#牛顿第二定律)。
`return m * a`
MD
(
cd "$WORK/project"
"$BIN" check physics/mechanics.mq.md --emit "$WORK/analysis.json"
)
cp "$WORK/analysis.json" "$ROOT/tests/fixtures/analysis/mechanics.json"
(
cd "$ROOT/tests/fixtures/analysis"
sha256sum mechanics.json > mechanics.json.sha256
)
"$BIN" --version
sha256sum "$BIN"
+8 -11
View File
@@ -338,15 +338,14 @@ fn validate_embedding(
"semantic search requires --embedding-url, --embedding-model and --embedding-revision",
));
}
if configured {
if embedding.embedding_url.is_none()
if configured
&& (embedding.embedding_url.is_none()
|| embedding.embedding_model.is_none()
|| embedding.embedding_revision.is_none()
{
return Err(KnowledgeError::usage(
"--embedding-url, --embedding-model and --embedding-revision must be given together",
));
}
|| embedding.embedding_revision.is_none())
{
return Err(KnowledgeError::usage(
"--embedding-url, --embedding-model and --embedding-revision must be given together",
));
}
Ok(())
}
@@ -421,11 +420,9 @@ fn render_check_human(json_text: &str) -> Result<String, KnowledgeError> {
}
/// Exit code helper for commands that produce knowledge diagnostics.
pub fn exit_code_for(errors: usize, warnings: usize) -> i32 {
pub fn exit_code_for(errors: usize, _warnings: usize) -> i32 {
if errors > 0 {
EXIT_INPUT
} else if warnings > 0 {
EXIT_OK
} else {
EXIT_OK
}
+2223 -3
View File
File diff suppressed because it is too large. Load diff
+392
View File
@@ -0,0 +1,392 @@
//! Process boundary for the core Marqdo CLI.
//!
//! The tool never executes knowledge. It invokes one explicit static command:
//!
//! ```text
//! "$MARQDO_BIN" check ENTRY --emit ARTIFACT
//! ```
//!
//! Rules: argv only (no shell), explicit binary path (never a `PATH` guess),
//! bounded timeout, private unique output path, exit code and fresh artifact
//! verification, bounded captured output, machine absolute paths sanitised out
//! of diagnostics, and no implicit network/install/lock mutation.
use crate::diagnostic::code;
use crate::error::KnowledgeError;
use crate::model::{sha256_prefixed, Span};
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
/// Current tool API revision this binary implements.
pub const API_REVISION: &str = "1";
/// Wall-clock budget for one static Analysis invocation.
pub const ANALYSIS_TIMEOUT: Duration = Duration::from_secs(120);
/// Version probe budget.
const VERSION_TIMEOUT: Duration = Duration::from_secs(10);
/// Maximum capture size for a child's stderr/stdout.
const OUTPUT_CAPTURE_LIMIT: u64 = 64 * 1024;
/// Maximum accepted Analysis artifact size.
pub const ARTIFACT_LIMIT: u64 = 256 * 1024 * 1024;
/// Maximum core binary size accepted for identity hashing.
const BINARY_LIMIT: u64 = 512 * 1024 * 1024;
/// Verified identity of the core CLI.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CoreIdentity {
pub version: String,
/// `sha256:` + lowercase hex of the exact binary bytes.
pub binary_digest: String,
pub api_revision: Option<String>,
}
impl CoreIdentity {
/// Deterministic identity string used in build metadata.
pub fn describe(&self) -> String {
format!("marqdo@{}/{}", self.version, self.binary_digest)
}
}
#[derive(Debug, Clone)]
pub struct CoreCli {
pub path: PathBuf,
pub identity: CoreIdentity,
}
/// The exact bytes emitted by one `check --emit` invocation.
#[derive(Debug, Clone)]
pub struct AnalysisBytes {
pub bytes: Vec<u8>,
/// Diagnostic text from the child, already sanitised and bounded.
pub stderr: String,
}
impl CoreCli {
/// Locate and verify the core CLI. Never scans `PATH`.
pub fn locate(explicit: Option<&Path>) -> Result<Self, KnowledgeError> {
let api_revision = std::env::var("MARQDO_API_REVISION").ok();
if let Some(revision) = &api_revision {
if revision != API_REVISION {
return Err(KnowledgeError::environment(
code::ANALYSIS_UNSUPPORTED,
format!(
"tool API revision {revision} is not supported; this build requires revision {API_REVISION}"
),
)
.with_hint("launch this tool through `marqdo knowledge` with a matching core CLI"));
}
}
let explicit_path = explicit.map(Path::to_path_buf);
let env_path = std::env::var_os("MARQDO_BIN").map(PathBuf::from);
let candidate = match (explicit_path, env_path) {
(Some(path), _) => Some(path),
(None, Some(path)) => Some(path),
(None, None) => None,
};
let Some(candidate) = candidate else {
if api_revision.is_some() {
return Err(KnowledgeError::environment(
code::CORE_CLI_MISSING,
"MARQDO_BIN is not set; the core CLI path is unknown",
));
}
return Err(KnowledgeError::environment(
code::NOT_LAUNCHED_BY_MARQDO,
"core CLI path is unknown",
)
.with_hint(
"launch through `marqdo knowledge ...` or pass --marqdo-bin PATH for development",
));
};
let metadata = std::fs::symlink_metadata(&candidate).map_err(|error| {
KnowledgeError::environment(
code::CORE_CLI_MISSING,
format!("core CLI cannot be inspected: {error}"),
)
})?;
if !metadata.is_file() {
return Err(KnowledgeError::environment(
code::CORE_CLI_MISSING,
"core CLI path is not a regular file",
));
}
let canonical = std::fs::canonicalize(&candidate).map_err(|error| {
KnowledgeError::environment(
code::CORE_CLI_MISSING,
format!("core CLI cannot be resolved: {error}"),
)
})?;
if metadata.len() > BINARY_LIMIT {
return Err(KnowledgeError::environment(
code::BUDGET_EXCEEDED,
"core CLI binary exceeds the identity hashing budget",
));
}
let bytes = std::fs::read(&canonical).map_err(|error| {
KnowledgeError::environment(
code::CORE_CLI_MISSING,
format!("core CLI cannot be read: {error}"),
)
})?;
let binary_digest = sha256_prefixed(&bytes);
let version = probe_version(&canonical)?;
Ok(Self {
path: canonical,
identity: CoreIdentity {
version,
binary_digest,
api_revision,
},
})
}
/// Run one static Analysis invocation for a root-relative entry.
pub fn emit_analysis(
&self,
root: &Path,
entry_rel: &str,
) -> Result<AnalysisBytes, KnowledgeError> {
crate::document::discovery::validate_relative_path(entry_rel).map_err(|message| {
KnowledgeError::environment(
code::SCOPE_ESCAPE,
format!("entry path is not a safe root-relative path: {message}"),
)
})?;
if !self.path.is_file() {
return Err(KnowledgeError::environment(
code::CORE_CLI_MISSING,
"core CLI is no longer a regular file",
));
}
let temp = tempfile::Builder::new()
.prefix("marqdo-knowledge-analysis-")
.tempdir()
.map_err(|error| {
KnowledgeError::environment(
code::IO,
format!("cannot create a private Analysis directory: {error}"),
)
})?;
let artifact_path = temp.path().join("analysis.json");
let stdout_path = temp.path().join("stdout.log");
let stderr_path = temp.path().join("stderr.log");
let stdout_file = File::create(&stdout_path)?;
let stderr_file = File::create(&stderr_path)?;
let mut child = Command::new(&self.path)
.arg("check")
.arg(entry_rel)
.arg("--emit")
.arg(&artifact_path)
.current_dir(root)
.stdin(Stdio::null())
.stdout(Stdio::from(stdout_file))
.stderr(Stdio::from(stderr_file))
.spawn()
.map_err(|error| {
KnowledgeError::environment(
code::CORE_CLI_FAILED,
format!("core CLI cannot be started: {error}"),
)
})?;
let deadline = Instant::now() + ANALYSIS_TIMEOUT;
let status = loop {
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) => {
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
return Err(KnowledgeError::environment(
code::CORE_CLI_TIMEOUT,
format!(
"core CLI did not finish within {} seconds for `{entry_rel}`",
ANALYSIS_TIMEOUT.as_secs()
),
));
}
std::thread::sleep(Duration::from_millis(20));
}
Err(error) => {
let _ = child.kill();
let _ = child.wait();
return Err(KnowledgeError::environment(
code::CORE_CLI_FAILED,
format!("core CLI wait failed: {error}"),
));
}
}
};
let stderr = String::from_utf8_lossy(
&read_bounded(&stderr_path, OUTPUT_CAPTURE_LIMIT).unwrap_or_default(),
)
.replace(&root.display().to_string(), ".");
let stdout = read_bounded(&stdout_path, OUTPUT_CAPTURE_LIMIT).unwrap_or_default();
if !status.success() {
let detail = first_lines(&stderr, 8);
let mut message = format!(
"core CLI `check --emit` failed for `{entry_rel}` with exit code {:?}",
status.code()
);
if !detail.is_empty() {
message.push_str(": ");
message.push_str(&detail);
}
return Err(KnowledgeError::input(code::CORE_CLI_FAILED, message));
}
let bytes = read_bounded(&artifact_path, ARTIFACT_LIMIT).ok_or_else(|| {
KnowledgeError::input(
code::ANALYSIS_MISSING,
format!("core CLI produced no Analysis artifact for `{entry_rel}`"),
)
})?;
if bytes.is_empty() {
return Err(KnowledgeError::input(
code::ANALYSIS_MISSING,
format!("core CLI produced an empty Analysis artifact for `{entry_rel}`"),
));
}
let _ = stdout;
// The temporary directory is removed when `temp` drops (including every
// error path above).
Ok(AnalysisBytes { bytes, stderr })
}
}
fn probe_version(binary: &Path) -> Result<String, KnowledgeError> {
let temp = tempfile::tempdir().map_err(|error| {
KnowledgeError::environment(
code::IO,
format!("cannot create version probe directory: {error}"),
)
})?;
let stdout_path = temp.path().join("version.log");
let stderr_path = temp.path().join("version.err");
let stdout_file = File::create(&stdout_path)?;
let stderr_file = File::create(&stderr_path)?;
let mut child = Command::new(binary)
.arg("--version")
.stdin(Stdio::null())
.stdout(Stdio::from(stdout_file))
.stderr(Stdio::from(stderr_file))
.spawn()
.map_err(|error| {
KnowledgeError::environment(
code::CORE_CLI_FAILED,
format!("core CLI version probe failed to start: {error}"),
)
})?;
let deadline = Instant::now() + VERSION_TIMEOUT;
let status = loop {
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) => {
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
return Err(KnowledgeError::environment(
code::CORE_CLI_TIMEOUT,
"core CLI version probe timed out",
));
}
std::thread::sleep(Duration::from_millis(10));
}
Err(error) => {
let _ = child.kill();
let _ = child.wait();
return Err(KnowledgeError::environment(
code::CORE_CLI_FAILED,
format!("core CLI version probe failed: {error}"),
));
}
}
};
if !status.success() {
return Err(KnowledgeError::environment(
code::CORE_CLI_FAILED,
"core CLI does not report a version; it is not a compatible marqdo binary",
));
}
let stdout_bytes = read_bounded(&stdout_path, OUTPUT_CAPTURE_LIMIT).unwrap_or_default();
let stdout = String::from_utf8_lossy(&stdout_bytes);
let first = stdout.lines().next().unwrap_or("").trim().to_string();
let mut parts = first.split_whitespace();
let name = parts.next().unwrap_or("");
let version = parts.next().unwrap_or("");
if name != "marqdo" || version.is_empty() {
return Err(KnowledgeError::environment(
code::CORE_CLI_FAILED,
"core CLI version output is not `marqdo <version>`",
));
}
Ok(version.to_string())
}
fn read_bounded(path: &Path, limit: u64) -> Option<Vec<u8>> {
let metadata = std::fs::metadata(path).ok()?;
if !metadata.is_file() {
return None;
}
let mut file = File::open(path).ok()?;
let mut buffer = Vec::new();
file.by_ref().take(limit).read_to_end(&mut buffer).ok()?;
Some(buffer)
}
fn first_lines(text: &str, count: usize) -> String {
let mut out = String::new();
for line in text.lines().take(count) {
if !out.is_empty() {
out.push_str(" | ");
}
out.push_str(line.trim());
}
out
}
/// Helper for validating a span inside a concrete source buffer.
pub fn span_in_source(span: Span, source: &[u8]) -> bool {
span.on_utf8_boundaries(source)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn missing_core_and_missing_env_do_not_scan_path() {
// The test environment may define MARQDO_BIN; only assert the failure
// path when it is absent.
if std::env::var_os("MARQDO_BIN").is_some() {
return;
}
let error = CoreCli::locate(Some(Path::new("/nonexistent/marqdo"))).unwrap_err();
assert_eq!(error.code, code::CORE_CLI_MISSING);
}
#[test]
fn entry_paths_are_validated_before_spawning() {
let cli = CoreCli {
path: PathBuf::from("/nonexistent"),
identity: CoreIdentity {
version: "0".into(),
binary_digest: "sha256:0".into(),
api_revision: None,
},
};
let error = cli
.emit_analysis(Path::new("/tmp"), "../escape.mq.md")
.unwrap_err();
assert_eq!(error.code, code::SCOPE_ESCAPE);
}
#[test]
fn version_output_parsing_requires_marqdo_prefix() {
assert!(first_lines("a\nb\n", 1) == "a");
}
}
+3 -6
View File
@@ -120,12 +120,9 @@ pub fn discover(scope: &Scope) -> Result<SourceSnapshot, KnowledgeError> {
KnowledgeError::environment(code::SCOPE_ESCAPE, format!("invalid root file: {message}"))
})?;
let abs = scope.root.join(single);
match read_document(scope, &abs, single, &mut diagnostics)? {
Some(file) => {
total_bytes += file.len();
files.push(file);
}
None => {}
if let Some(file) = read_document(scope, &abs, single, &mut diagnostics)? {
total_bytes += file.len();
files.push(file);
}
} else {
walk(
+9 -9
View File
@@ -49,14 +49,14 @@ pub fn parse_plain(file: &SourceFile) -> DocumentFacts {
.push(Diagnostic::error(code::MARKDOWN_INVALID, message).with_path(&file.rel_path));
}
let front_matter = extract_front_matter(&ast, &mut diagnostics, &file.rel_path);
let front_matter = front_matter_fact(&ast, &mut diagnostics, &file.rel_path);
let mut units = build_units(&ast, file);
fix_unit_spans(&mut units, source.len() as u64);
let anchors = build_anchors(&units);
let title = document_title(&units, &file.rel_path);
let references = extract_references(&ast, &units);
let blocks = extract_blocks(&ast, &units);
let blocks = searchable_blocks(&ast, &units);
DocumentFacts {
rel_path: file.rel_path.clone(),
@@ -358,12 +358,12 @@ fn fix_unit_spans(units: &mut [UnitFact], source_len: u64) {
.map(|span| span.start)
.unwrap_or(units[index].span.start);
let mut end = source_len;
for later in index + 1..units.len() {
if units[later].level <= level {
end = units[later]
for later in units.iter().skip(index + 1) {
if later.level <= level {
end = later
.heading_span
.map(|span| span.start)
.unwrap_or(units[later].span.start);
.unwrap_or(later.span.start);
break;
}
}
@@ -446,7 +446,7 @@ fn document_title(units: &[UnitFact], rel_path: &str) -> String {
file.to_string()
}
fn extract_front_matter(
pub(crate) fn front_matter_fact(
ast: &AstNode,
diagnostics: &mut DiagnosticSet,
rel_path: &str,
@@ -631,7 +631,7 @@ fn extract_references(ast: &AstNode, units: &[UnitFact]) -> Vec<ReferenceFact> {
references
}
fn innermost_unit(units: &[UnitFact], span: Span) -> usize {
pub(crate) fn innermost_unit(units: &[UnitFact], span: Span) -> usize {
let mut best = 0usize;
let mut best_level = 0u8;
for (index, unit) in units.iter().enumerate() {
@@ -646,7 +646,7 @@ fn innermost_unit(units: &[UnitFact], span: Span) -> usize {
best
}
fn extract_blocks(ast: &AstNode, units: &[UnitFact]) -> Vec<BlockFact> {
pub(crate) fn searchable_blocks(ast: &AstNode, units: &[UnitFact]) -> Vec<BlockFact> {
let mut blocks = Vec::new();
for child in &ast.children {
if child.kind == AstKind::FrontMatter || child.kind == AstKind::Heading {
+7 -5
View File
@@ -7,6 +7,7 @@
pub mod analysis;
pub mod ast;
pub mod core_cli;
pub mod discovery;
pub mod markdown;
pub mod okf;
@@ -530,11 +531,12 @@ impl DocumentFacts {
let mut best = 0usize;
let mut best_level = 0u8;
for (index, unit) in self.units.iter().enumerate() {
if unit.span.contains(span) && (index == 0 || unit.level >= best_level) {
if index == 0 || unit.level >= best_level {
best = index;
best_level = unit.level;
}
if index == 0 {
continue;
}
if unit.span.contains(span) && unit.level >= best_level {
best = index;
best_level = unit.level;
}
}
best
+1 -1
View File
@@ -41,7 +41,7 @@ impl Span {
/// Return the exact source slice when the span is valid and lies on UTF-8
/// boundaries. Never panics on hostile offsets.
pub fn slice<'a>(self, source: &'a [u8]) -> Option<&'a str> {
pub fn slice(self, source: &[u8]) -> Option<&str> {
if self.start > self.end || self.end > source.len() as u64 {
return None;
}
+98
View File
@@ -0,0 +1,98 @@
//! Integration tests for the core CLI boundary and Analysis adapter.
//!
//! These tests need a real `marqdo` binary. Set `MARQDO_TEST_BIN` to run them;
//! without it they report a skip and do not claim evidence. The repository
//! keeps real captured artefacts under `tests/fixtures/analysis/` for the
//! offline contract tests.
use marqdo_knowledge::document::analysis;
use marqdo_knowledge::document::core_cli::CoreCli;
use std::path::{Path, PathBuf};
fn core_bin() -> Option<PathBuf> {
let value = std::env::var_os("MARQDO_TEST_BIN")?;
let path = PathBuf::from(value);
if path.is_file() {
Some(path)
} else {
None
}
}
fn write_project(root: &Path) {
std::fs::create_dir_all(root.join("physics")).unwrap();
std::fs::write(
root.join("marqdo.yaml"),
"project:\n name: demo\n version: 0.1.0\n marqdo: \">=3.0.0-beta.1,<4.0.0\"\ndependencies: {}\n",
)
.unwrap();
std::fs::write(
root.join("physics/mechanics.mq.md"),
"---\ntype: Theory\ntitle: 经典力学\n---\n\n# 经典力学\n\n## @knowledge 牛顿第二定律\n\n合外力等于质量与加速度的乘积。\n\n计算入口:[计算力](#计算力)。\n\n## @exec 计算力\n\n`params(m, a)`\n\n依据[牛顿第二定律](#牛顿第二定律)。\n\n`return m * a`\n",
)
.unwrap();
std::fs::write(
root.join("bad.mq.md"),
"# bad\n\n## @exec broken\n\n`return this is not valid ))`\n",
)
.unwrap();
}
#[test]
fn real_core_cli_emits_a_valid_analysis_artifact() {
let Some(bin) = core_bin() else {
eprintln!("skip: MARQDO_TEST_BIN is not set");
return;
};
let temp = tempfile::tempdir().unwrap();
write_project(temp.path());
let core = CoreCli::locate(Some(&bin)).unwrap();
assert!(core.identity.version.starts_with('3'));
let emitted = core
.emit_analysis(temp.path(), "physics/mechanics.mq.md")
.unwrap();
let artifact = analysis::parse_and_validate(&emitted.bytes).unwrap();
assert_eq!(artifact.schema_version, 3);
assert!(artifact
.modules
.iter()
.any(|module| module.relative_path == "physics/mechanics.mq.md"));
let batch =
analysis::analyze_core(temp.path(), &["physics/mechanics.mq.md".to_string()], &core);
assert!(!batch.diagnostics.has_errors(), "{:?}", batch.diagnostics);
let module = batch
.module_for_path("physics/mechanics.mq.md")
.expect("valid module facts");
assert!(module
.facts
.functions
.iter()
.any(|function| function.local_name == "计算力"));
}
#[test]
fn invalid_marqdo_document_fails_analysis_without_an_artifact() {
let Some(bin) = core_bin() else {
eprintln!("skip: MARQDO_TEST_BIN is not set");
return;
};
let temp = tempfile::tempdir().unwrap();
write_project(temp.path());
let core = CoreCli::locate(Some(&bin)).unwrap();
let batch = analysis::analyze_core(temp.path(), &["bad.mq.md".to_string()], &core);
assert!(batch.diagnostics.has_errors());
assert_eq!(batch.modules.len(), 0);
assert_eq!(batch.failed_entries, vec!["bad.mq.md".to_string()]);
}
#[test]
fn analysis_core_cli_identity_is_recorded() {
let Some(bin) = core_bin() else {
eprintln!("skip: MARQDO_TEST_BIN is not set");
return;
};
let core = CoreCli::locate(Some(&bin)).unwrap();
assert!(core.identity.version.starts_with('3'));
assert!(core.identity.binary_digest.starts_with("sha256:"));
assert_eq!(core.identity.binary_digest.len(), 71);
}
+23
View File
@@ -0,0 +1,23 @@
# Analysis fixture provenance
`mechanics.json` is a real `marqdo.analysis` revision-3 artefact captured from
the upstream release candidate, not a hand-written example. Tests use it as the
positive fixture for the closed-shape and semantic validator and for the
`DocumentFacts` conversion.
- Producer: `marqdo 3.0.0-rc.4` (`4bbefc92449ee480c8a2c89b0308feb4cda8d0e7`),
Linux x86_64.
- Command (captured from the project directory):
```sh
"$MARQDO_BIN" check physics/mechanics.mq.md --emit analysis.json
```
- Source project: a minimal `marqdo.yaml` plus one document with a namespace,
a Knowledge H2, an Exec H2 with parameters, a Markdown link to an anchor, a
formula, a table and a front matter block.
- Fixture SHA-256: see `mechanics.json.sha256`.
- Regenerate with `scripts/regenerate-analysis-fixture.sh SHA256_OF_CORE_BINARY`
and record the new producer version and binary digest if the contract changes.
A revision that cannot be consumed by the current validator must be treated as
a broken producer/consumer pair, never patched into the tests.
+647
View File
@@ -0,0 +1,647 @@
{
"schema": "marqdo.analysis",
"schema_version": 3,
"producer": {
"name": "marqdo",
"version": "3.0.0-rc.4",
"markdown_profile": "marqdo.md.v1"
},
"project": {
"root_id": "root:demo@0.1.0",
"identity_kind": "manifest",
"entry_module_id": "root:demo@0.1.0::physics/mechanics.mq.md",
"lock_digest": "",
"manifest_digest": "sha256:ee4f20fb5156741127f6a4d947b73b9a8f9700a368992974601a958861939a82",
"stdlib": null,
"extensions": []
},
"modules": [
{
"id": "root:demo@0.1.0::physics/mechanics.mq.md",
"package_instance_id": "root:demo@0.1.0",
"relative_path": "physics/mechanics.mq.md",
"source_digest": "27815c2e64ca85343ac4e43213e5c842e458a0dd2ee98e499965fb9da2b37607",
"source": "---\ntype: Theory\ntitle: 经典力学\ntags: [physics, mechanics]\n---\n\n# 经典力学\n\n## @knowledge 牛顿第二定律\n\n合外力等于质量与加速度的乘积。\n\n$$\nF = ma\n$$\n\n| 符号 | 含义 |\n| --- | --- |\n| m | 质量 |\n| a | 加速度 |\n\n计算入口:[计算力](#计算力)。\n\n## @exec 计算力\n\n`params(m, a)`\n\n依据[牛顿第二定律](#牛顿第二定律)。\n\n`return m * a`\n",
"document": {
"children": [
{
"children": [],
"kind": "front_matter",
"literal": "---\ntype: Theory\ntitle: 经典力学\ntags: [physics, mechanics]\n---\n\n",
"span": {
"end": 67,
"start": 0
}
},
{
"children": [
{
"children": [],
"kind": "text",
"literal": "经典力学",
"span": {
"end": 83,
"start": 71
}
}
],
"kind": "heading",
"level": 1,
"setext": false,
"span": {
"end": 83,
"start": 69
}
},
{
"children": [
{
"children": [],
"kind": "text",
"literal": "@knowledge 牛顿第二定律",
"span": {
"end": 117,
"start": 88
}
}
],
"kind": "heading",
"level": 2,
"setext": false,
"span": {
"end": 117,
"start": 85
}
},
{
"children": [
{
"children": [],
"kind": "text",
"literal": "合外力等于质量与加速度的乘积。",
"span": {
"end": 164,
"start": 119
}
}
],
"kind": "paragraph",
"span": {
"end": 164,
"start": 119
}
},
{
"children": [],
"kind": "math_block",
"literal": "F = ma\n",
"span": {
"end": 178,
"start": 166
}
},
{
"alignments": [
"none",
"none"
],
"children": [
{
"children": [
{
"children": [
{
"children": [],
"kind": "text",
"literal": "符号",
"span": {
"end": 188,
"start": 182
}
}
],
"kind": "table_cell",
"span": {
"end": 189,
"start": 181
}
},
{
"children": [
{
"children": [],
"kind": "text",
"literal": "含义",
"span": {
"end": 197,
"start": 191
}
}
],
"kind": "table_cell",
"span": {
"end": 198,
"start": 190
}
}
],
"header": true,
"kind": "table_row",
"span": {
"end": 199,
"start": 180
}
},
{
"children": [
{
"children": [
{
"children": [],
"kind": "text",
"literal": "m",
"span": {
"end": 217,
"start": 216
}
}
],
"kind": "table_cell",
"span": {
"end": 218,
"start": 215
}
},
{
"children": [
{
"children": [],
"kind": "text",
"literal": "质量",
"span": {
"end": 226,
"start": 220
}
}
],
"kind": "table_cell",
"span": {
"end": 227,
"start": 219
}
}
],
"header": false,
"kind": "table_row",
"span": {
"end": 228,
"start": 214
}
},
{
"children": [
{
"children": [
{
"children": [],
"kind": "text",
"literal": "a",
"span": {
"end": 232,
"start": 231
}
}
],
"kind": "table_cell",
"span": {
"end": 233,
"start": 230
}
},
{
"children": [
{
"children": [],
"kind": "text",
"literal": "加速度",
"span": {
"end": 244,
"start": 235
}
}
],
"kind": "table_cell",
"span": {
"end": 245,
"start": 234
}
}
],
"header": false,
"kind": "table_row",
"span": {
"end": 246,
"start": 229
}
}
],
"kind": "table",
"span": {
"end": 246,
"start": 180
}
},
{
"children": [
{
"children": [],
"kind": "text",
"literal": "计算入口:",
"span": {
"end": 263,
"start": 248
}
},
{
"children": [
{
"children": [],
"kind": "text",
"literal": "计算力",
"span": {
"end": 273,
"start": 264
}
}
],
"kind": "link",
"span": {
"end": 286,
"start": 263
},
"title": "",
"url": "#计算力"
},
{
"children": [],
"kind": "text",
"literal": "。",
"span": {
"end": 289,
"start": 286
}
}
],
"kind": "paragraph",
"span": {
"end": 289,
"start": 248
}
},
{
"children": [
{
"children": [],
"kind": "text",
"literal": "@exec 计算力",
"span": {
"end": 309,
"start": 294
}
}
],
"kind": "heading",
"level": 2,
"setext": false,
"span": {
"end": 309,
"start": 291
}
},
{
"children": [
{
"children": [],
"kind": "code",
"literal": "params(m, a)",
"span": {
"end": 325,
"start": 311
},
"ticks": 1
}
],
"kind": "paragraph",
"span": {
"end": 325,
"start": 311
}
},
{
"children": [
{
"children": [],
"kind": "text",
"literal": "依据",
"span": {
"end": 333,
"start": 327
}
},
{
"children": [
{
"children": [],
"kind": "text",
"literal": "牛顿第二定律",
"span": {
"end": 352,
"start": 334
}
}
],
"kind": "link",
"span": {
"end": 374,
"start": 333
},
"title": "",
"url": "#牛顿第二定律"
},
{
"children": [],
"kind": "text",
"literal": "。",
"span": {
"end": 377,
"start": 374
}
}
],
"kind": "paragraph",
"span": {
"end": 377,
"start": 327
}
},
{
"children": [
{
"children": [],
"kind": "code",
"literal": "return m * a",
"span": {
"end": 393,
"start": 379
},
"ticks": 1
}
],
"kind": "paragraph",
"span": {
"end": 393,
"start": 379
}
}
],
"kind": "document",
"span": {
"end": 394,
"start": 0
}
},
"units": [
{
"id": "root:demo@0.1.0::physics/mechanics.mq.md#",
"path": [],
"parent_id": null,
"kind": "root",
"name": "",
"level": 0,
"mode": "knowledge",
"mode_origin": "default",
"mode_source_unit_id": "root:demo@0.1.0::physics/mechanics.mq.md#",
"heading_span": null,
"span": {
"start": 0,
"end": 394
},
"function": null
},
{
"id": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学",
"path": [
"经典力学"
],
"parent_id": "root:demo@0.1.0::physics/mechanics.mq.md#",
"kind": "namespace",
"name": "经典力学",
"level": 1,
"mode": "knowledge",
"mode_origin": "inherited",
"mode_source_unit_id": "root:demo@0.1.0::physics/mechanics.mq.md#",
"heading_span": {
"start": 69,
"end": 83
},
"span": {
"start": 69,
"end": 394
},
"function": null
},
{
"id": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学/牛顿第二定律",
"path": [
"经典力学",
"牛顿第二定律"
],
"parent_id": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学",
"kind": "knowledge",
"name": "牛顿第二定律",
"level": 2,
"mode": "knowledge",
"mode_origin": "explicit",
"mode_source_unit_id": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学/牛顿第二定律",
"heading_span": {
"start": 85,
"end": 117
},
"span": {
"start": 85,
"end": 291
},
"function": null
},
{
"id": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学/计算力",
"path": [
"经典力学",
"计算力"
],
"parent_id": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学",
"kind": "function",
"name": "计算力",
"level": 2,
"mode": "exec",
"mode_origin": "explicit",
"mode_source_unit_id": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学/计算力",
"heading_span": {
"start": 291,
"end": 309
},
"span": {
"start": 291,
"end": 394
},
"function": "root:demo@0.1.0::physics/mechanics.mq.md::经典力学.计算力"
}
],
"anchors": [
{
"anchor": "牛顿第二定律",
"unit_id": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学/牛顿第二定律"
},
{
"anchor": "经典力学",
"unit_id": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学"
},
{
"anchor": "计算力",
"unit_id": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学/计算力"
}
],
"functions": [
{
"id": "root:demo@0.1.0::physics/mechanics.mq.md::经典力学.计算力",
"unit_id": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学/计算力",
"local_name": "计算力",
"namespace": "经典力学",
"span": {
"start": 291,
"end": 393
},
"heading_span": {
"start": 291,
"end": 309
},
"signature": {
"kind": "explicit",
"params": [
{
"name": "m",
"required": true,
"type": null,
"default": null,
"span": {
"start": 315,
"end": 316
}
},
{
"name": "a",
"required": true,
"type": null,
"default": null,
"span": {
"start": 320,
"end": 322
}
}
]
},
"effects": [
"unknown"
],
"body": [
{
"kind": "return",
"span": {
"end": 393,
"start": 379
},
"value": {
"kind": "binary",
"left": {
"kind": "variable",
"name": "m",
"span": {
"end": 388,
"start": 387
}
},
"op": "mul",
"right": {
"kind": "variable",
"name": "a",
"span": {
"end": 392,
"start": 391
}
},
"span": {
"end": 392,
"start": 387
}
}
}
]
}
],
"imports": [],
"references": [
{
"source": "root:demo@0.1.0::physics/mechanics.mq.md",
"source_unit": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学/牛顿第二定律",
"url": "#计算力",
"span": {
"start": 263,
"end": 286
},
"state": "resolved",
"target_kind": "module",
"target_module": "root:demo@0.1.0::physics/mechanics.mq.md",
"target_unit": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学/计算力",
"candidate_package_instance_id": null,
"candidate_path": null,
"fragment": "计算力",
"candidates": []
},
{
"source": "root:demo@0.1.0::physics/mechanics.mq.md",
"source_unit": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学/计算力",
"url": "#牛顿第二定律",
"span": {
"start": 333,
"end": 374
},
"state": "resolved",
"target_kind": "module",
"target_module": "root:demo@0.1.0::physics/mechanics.mq.md",
"target_unit": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学/牛顿第二定律",
"candidate_package_instance_id": null,
"candidate_path": null,
"fragment": "牛顿第二定律",
"candidates": []
}
],
"calls": [],
"resources": [
{
"id": "root:demo@0.1.0::physics/mechanics.mq.md#resource:formula-1",
"module_id": "root:demo@0.1.0::physics/mechanics.mq.md",
"unit_id": "root:demo@0.1.0::physics/mechanics.mq.md#经典力学/牛顿第二定律",
"kind": "formula",
"span": {
"start": 166,
"end": 178
},
"content_digest": "377d9d34e57777c470a2b3e3ddea6839c9d257cafab6df1640b4d9598d840df6",
"language": null,
"display": true
}
]
}
],
"diagnostics": []
}
+1
View File
@@ -0,0 +1 @@
37e8049262f119388d7934190814b117a33820782547fd9ea70f988818ea9577 tests/fixtures/analysis/mechanics.json