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

+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;
}