tests: verify the closed Analysis boundary with independent consumers
Add black-box tests for exact source/AST projection, complete heading scopes, explicit reference states, output safety (input/symlink/hardlink/directory and owner-only bytes), Observation digest binding, multi-entry snapshot context and the protocol mutation gate. Upgrade the Python consumer into a full independent semantic validator, add view/lint/knowledge consumer fixtures driven by the real CLI, and run schema plus semantic mutation checks from validate_protocols.
This commit is contained in:
1 parent
99789616a4
commit
6d4209bf32
8 files changed
+1332
-67
No files matched your search
@@ -417,7 +417,7 @@ pub fn resolve_link(
|
|||||||
url: &str,
|
url: &str,
|
||||||
span: Span,
|
span: Span,
|
||||||
) -> Reference {
|
) -> Reference {
|
||||||
let mut reference = Reference::placeholder(source, &units, url, span);
|
let mut reference = Reference::placeholder(source, units, url, span);
|
||||||
|
|
||||||
// Empty destination and `#...` both address the current document.
|
// Empty destination and `#...` both address the current document.
|
||||||
if url.is_empty() {
|
if url.is_empty() {
|
||||||
|
|||||||
@@ -0,0 +1,490 @@
|
|||||||
|
//! Public Analysis boundary tests (issue #10, ADR-0069).
|
||||||
|
//!
|
||||||
|
//! These drive the real CLI binary: exact source/AST/scope projection, explicit
|
||||||
|
//! reference states, output safety, Observation digest binding, independent
|
||||||
|
//! consumers and schema/semantic mutation rejection.
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::{Command, Output};
|
||||||
|
use std::sync::atomic::{AtomicU32, Ordering};
|
||||||
|
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
static COUNTER: AtomicU32 = AtomicU32::new(0);
|
||||||
|
|
||||||
|
struct TempDir(PathBuf);
|
||||||
|
|
||||||
|
impl TempDir {
|
||||||
|
fn new(tag: &str) -> Self {
|
||||||
|
let id = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||||
|
let path = std::env::temp_dir().join(format!(
|
||||||
|
"marqdo-analysis-boundary-{}-{id}-{tag}",
|
||||||
|
std::process::id()
|
||||||
|
));
|
||||||
|
let _ = std::fs::remove_dir_all(&path);
|
||||||
|
std::fs::create_dir_all(&path).unwrap();
|
||||||
|
Self(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn path(&self) -> &Path {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write(&self, name: &str, source: &str) -> PathBuf {
|
||||||
|
let path = self.0.join(name);
|
||||||
|
if let Some(parent) = path.parent() {
|
||||||
|
std::fs::create_dir_all(parent).unwrap();
|
||||||
|
}
|
||||||
|
std::fs::write(&path, source).unwrap();
|
||||||
|
path
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read(&self, name: &str) -> String {
|
||||||
|
std::fs::read_to_string(self.0.join(name)).unwrap()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for TempDir {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let _ = std::fs::remove_dir_all(&self.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn binary() -> &'static str {
|
||||||
|
env!("CARGO_BIN_EXE_marqdo")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cli(dir: &Path, args: &[&str]) -> Output {
|
||||||
|
Command::new(binary())
|
||||||
|
.args(args)
|
||||||
|
.current_dir(dir)
|
||||||
|
.output()
|
||||||
|
.expect("run marqdo")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn emit(dir: &Path, entry: &str, output: &str, extra: &[&str]) -> Output {
|
||||||
|
let mut args = vec!["check", entry, "--emit", output];
|
||||||
|
args.extend_from_slice(extra);
|
||||||
|
cli(dir, &args)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn analysis(dir: &Path, name: &str) -> serde_json::Value {
|
||||||
|
serde_json::from_slice(&std::fs::read(dir.join(name)).unwrap()).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn digest(bytes: &[u8]) -> String {
|
||||||
|
let mut hasher = Sha256::new();
|
||||||
|
hasher.update(bytes);
|
||||||
|
hex::encode(hasher.finalize())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn repo_root() -> PathBuf {
|
||||||
|
Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||||
|
.parent()
|
||||||
|
.unwrap()
|
||||||
|
.parent()
|
||||||
|
.unwrap()
|
||||||
|
.to_path_buf()
|
||||||
|
}
|
||||||
|
|
||||||
|
const DOCUMENT: &str = "\u{feff}# @knowledge 数学\r\n\r\n## @exec 计算\r\n\r\n`params(n: Int)`\r\n\r\n`return n + 1`\r\n\r\n### 细节\r\n\r\n正文\r\n";
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn analysis_projects_exact_source_document_and_complete_scopes() {
|
||||||
|
let dir = TempDir::new("scope");
|
||||||
|
dir.write("index.mq.md", DOCUMENT);
|
||||||
|
let output = emit(dir.path(), "index.mq.md", "analysis.json", &[]);
|
||||||
|
assert!(
|
||||||
|
output.status.success(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&output.stderr)
|
||||||
|
);
|
||||||
|
let value = analysis(dir.path(), "analysis.json");
|
||||||
|
let module = &value["modules"][0];
|
||||||
|
assert_eq!(module["source"], DOCUMENT);
|
||||||
|
assert_eq!(module["source_digest"], digest(DOCUMENT.as_bytes()));
|
||||||
|
assert_eq!(value["project"]["entry_module_id"], module["id"]);
|
||||||
|
|
||||||
|
let document = &module["document"];
|
||||||
|
assert_eq!(document["kind"], "document");
|
||||||
|
assert_eq!(document["span"]["start"], 0);
|
||||||
|
assert_eq!(
|
||||||
|
document["span"]["end"].as_u64().unwrap() as usize,
|
||||||
|
DOCUMENT.len()
|
||||||
|
);
|
||||||
|
let heading = document["children"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.find(|node| node["kind"] == "heading" && node["level"] == 1)
|
||||||
|
.expect("level-1 heading");
|
||||||
|
assert!(heading["children"].is_array());
|
||||||
|
assert!(heading["children"].as_array().unwrap().iter().any(|node| {
|
||||||
|
node["kind"] == "text"
|
||||||
|
&& node["literal"]
|
||||||
|
.as_str()
|
||||||
|
.is_some_and(|literal| literal.contains("数学"))
|
||||||
|
}));
|
||||||
|
|
||||||
|
let units = module["units"].as_array().unwrap();
|
||||||
|
let by_name = |name: &str| {
|
||||||
|
units
|
||||||
|
.iter()
|
||||||
|
.find(|unit| unit["name"] == name)
|
||||||
|
.unwrap_or_else(|| panic!("missing unit {name}"))
|
||||||
|
};
|
||||||
|
let root = &units[0];
|
||||||
|
assert_eq!(root["kind"], "root");
|
||||||
|
assert_eq!(root["parent_id"], serde_json::Value::Null);
|
||||||
|
assert_eq!(root["heading_span"], serde_json::Value::Null);
|
||||||
|
assert_eq!(root["span"]["start"], 0);
|
||||||
|
assert_eq!(
|
||||||
|
root["span"]["end"].as_u64().unwrap() as usize,
|
||||||
|
DOCUMENT.len()
|
||||||
|
);
|
||||||
|
|
||||||
|
let namespace = by_name("数学");
|
||||||
|
assert_eq!(namespace["kind"], "namespace");
|
||||||
|
assert_eq!(namespace["parent_id"], root["id"]);
|
||||||
|
assert_eq!(namespace["mode"], "knowledge");
|
||||||
|
assert_eq!(namespace["mode_origin"], "explicit");
|
||||||
|
assert_eq!(namespace["mode_source_unit_id"], namespace["id"]);
|
||||||
|
|
||||||
|
let function = by_name("计算");
|
||||||
|
assert_eq!(function["kind"], "function");
|
||||||
|
assert_eq!(function["parent_id"], namespace["id"]);
|
||||||
|
assert_eq!(function["mode"], "exec");
|
||||||
|
assert_eq!(function["mode_origin"], "explicit");
|
||||||
|
assert!(function["function"].is_string());
|
||||||
|
assert_ne!(function["span"], function["heading_span"]);
|
||||||
|
|
||||||
|
let section = by_name("细节");
|
||||||
|
assert_eq!(section["kind"], "section");
|
||||||
|
assert_eq!(section["parent_id"], function["id"]);
|
||||||
|
assert_eq!(section["mode"], "exec");
|
||||||
|
assert_eq!(section["mode_origin"], "inherited");
|
||||||
|
assert_eq!(section["mode_source_unit_id"], function["id"]);
|
||||||
|
// The complete function range includes the H3 child and runs to EOF.
|
||||||
|
assert_eq!(
|
||||||
|
function["span"]["end"].as_u64().unwrap() as usize,
|
||||||
|
DOCUMENT.len()
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
section["span"]["end"].as_u64().unwrap() as usize,
|
||||||
|
DOCUMENT.len()
|
||||||
|
);
|
||||||
|
let heading_start = DOCUMENT.find("## @exec 计算").unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
function["heading_span"]["start"].as_u64().unwrap() as usize,
|
||||||
|
heading_start
|
||||||
|
);
|
||||||
|
|
||||||
|
let anchors = module["anchors"].as_array().unwrap();
|
||||||
|
assert!(anchors.iter().any(|anchor| anchor["anchor"] == "计算"));
|
||||||
|
let signature = &module["functions"][0]["signature"];
|
||||||
|
assert_eq!(signature["kind"], "explicit");
|
||||||
|
assert_eq!(signature["params"][0]["name"], "n");
|
||||||
|
assert_eq!(signature["params"][0]["type"], "Int");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reference_states_are_distinct_and_explicit_refs_do_not_change_the_program() {
|
||||||
|
let dir = TempDir::new("references");
|
||||||
|
dir.write(
|
||||||
|
"index.mq.md",
|
||||||
|
"## @exec main\n\n[本地](./other.mq.md#公式) [外链](https://example.com) [本文](#main)\n\n`return 1`\n",
|
||||||
|
);
|
||||||
|
dir.write("other.mq.md", "## @knowledge 公式\n\n正文\n");
|
||||||
|
let ordinary = emit(dir.path(), "index.mq.md", "ordinary.json", &[]);
|
||||||
|
assert!(
|
||||||
|
ordinary.status.success(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&ordinary.stderr)
|
||||||
|
);
|
||||||
|
let value = analysis(dir.path(), "ordinary.json");
|
||||||
|
assert_eq!(value["modules"].as_array().unwrap().len(), 1);
|
||||||
|
let references = value["modules"][0]["references"].as_array().unwrap();
|
||||||
|
let state = |url: &str| {
|
||||||
|
references
|
||||||
|
.iter()
|
||||||
|
.find(|reference| reference["url"] == url)
|
||||||
|
.unwrap_or_else(|| panic!("missing reference {url}"))["state"]
|
||||||
|
.as_str()
|
||||||
|
.unwrap()
|
||||||
|
.to_string()
|
||||||
|
};
|
||||||
|
assert_eq!(state("./other.mq.md#公式"), "not_loaded");
|
||||||
|
assert_eq!(state("https://example.com"), "external");
|
||||||
|
assert_eq!(state("#main"), "resolved");
|
||||||
|
// The ordinary artifact still describes only the loaded program.
|
||||||
|
assert_eq!(value["modules"].as_array().unwrap().len(), 1);
|
||||||
|
|
||||||
|
// Explicit refs verify the direct target and keep the same ordinary bytes'
|
||||||
|
// module set. The emitted Analysis still uses the loaded catalog.
|
||||||
|
let verified = emit(dir.path(), "index.mq.md", "verified.json", &["--refs"]);
|
||||||
|
assert!(
|
||||||
|
verified.status.success(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&verified.stderr)
|
||||||
|
);
|
||||||
|
let verified_value = analysis(dir.path(), "verified.json");
|
||||||
|
assert_eq!(verified_value["modules"].as_array().unwrap().len(), 1);
|
||||||
|
let verified_refs = verified_value["modules"][0]["references"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
verified_refs
|
||||||
|
.iter()
|
||||||
|
.find(|reference| reference["url"] == "./other.mq.md#公式")
|
||||||
|
.unwrap()["state"],
|
||||||
|
"not_loaded",
|
||||||
|
"the emitted artifact must keep the loaded catalog"
|
||||||
|
);
|
||||||
|
let inspected = cli(dir.path(), &["inspect", "index.mq.md", "--refs", "--json"]);
|
||||||
|
assert!(inspected.status.success());
|
||||||
|
let inspected: serde_json::Value = serde_json::from_slice(&inspected.stdout).unwrap();
|
||||||
|
let resolved = inspected["refs"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.find(|reference| reference["url"] == "./other.mq.md#公式")
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(resolved["state"], "resolved");
|
||||||
|
assert_eq!(resolved["target_kind"], "module");
|
||||||
|
assert!(resolved["target_module"]
|
||||||
|
.as_str()
|
||||||
|
.unwrap()
|
||||||
|
.ends_with("::other.mq.md"));
|
||||||
|
|
||||||
|
// A broken explicitly verified target is an error and publishes no artifact.
|
||||||
|
dir.write(
|
||||||
|
"broken.mq.md",
|
||||||
|
"## @exec main\n\n[坏](./other.mq.md#不存在)\n\n`return 1`\n",
|
||||||
|
);
|
||||||
|
let broken = emit(dir.path(), "broken.mq.md", "broken.json", &["--refs"]);
|
||||||
|
assert_eq!(broken.status.code(), Some(1), "{broken:?}");
|
||||||
|
assert!(!dir.path().join("broken.json").exists());
|
||||||
|
assert!(String::from_utf8_lossy(&broken.stderr).contains("ref.unresolved"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn emit_refuses_inputs_symlinks_hardlinks_and_directories() {
|
||||||
|
let dir = TempDir::new("emit-safety");
|
||||||
|
let source = "## @exec main\n\n`return 1`\n";
|
||||||
|
let entry = dir.write("index.mq.md", source);
|
||||||
|
|
||||||
|
let self_emit = emit(dir.path(), "index.mq.md", "index.mq.md", &[]);
|
||||||
|
assert_eq!(self_emit.status.code(), Some(2), "{self_emit:?}");
|
||||||
|
assert_eq!(dir.read("index.mq.md"), source);
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
std::os::unix::fs::symlink(&entry, dir.path().join("link.json")).unwrap();
|
||||||
|
let symlink_emit = emit(dir.path(), "index.mq.md", "link.json", &[]);
|
||||||
|
assert_eq!(symlink_emit.status.code(), Some(2), "{symlink_emit:?}");
|
||||||
|
assert_eq!(dir.read("index.mq.md"), source);
|
||||||
|
|
||||||
|
std::fs::hard_link(&entry, dir.path().join("hard.json")).unwrap();
|
||||||
|
let hard_emit = emit(dir.path(), "index.mq.md", "hard.json", &[]);
|
||||||
|
assert_eq!(hard_emit.status.code(), Some(2), "{hard_emit:?}");
|
||||||
|
assert_eq!(dir.read("index.mq.md"), source);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::fs::create_dir(dir.path().join("outdir")).unwrap();
|
||||||
|
let directory_emit = emit(dir.path(), "index.mq.md", "outdir", &[]);
|
||||||
|
assert_eq!(directory_emit.status.code(), Some(2), "{directory_emit:?}");
|
||||||
|
|
||||||
|
let ok = emit(dir.path(), "index.mq.md", "analysis.json", &[]);
|
||||||
|
assert!(ok.status.success(), "{ok:?}");
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
let mode = std::fs::metadata(dir.path().join("analysis.json"))
|
||||||
|
.unwrap()
|
||||||
|
.permissions()
|
||||||
|
.mode()
|
||||||
|
& 0o777;
|
||||||
|
assert_eq!(mode, 0o600, "Analysis output must be owner-only");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn observation_binds_the_exact_emitted_analysis_bytes() {
|
||||||
|
let dir = TempDir::new("digest");
|
||||||
|
dir.write(
|
||||||
|
"index.mq.md",
|
||||||
|
"## @exec main\n\n`params(n: Int)`\n\n`return n + 1`\n",
|
||||||
|
);
|
||||||
|
let emitted = emit(dir.path(), "index.mq.md", "analysis.json", &[]);
|
||||||
|
assert!(
|
||||||
|
emitted.status.success(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&emitted.stderr)
|
||||||
|
);
|
||||||
|
let bytes = std::fs::read(dir.path().join("analysis.json")).unwrap();
|
||||||
|
let expected = format!("sha256:{}", digest(&bytes));
|
||||||
|
|
||||||
|
let run = cli(
|
||||||
|
dir.path(),
|
||||||
|
&[
|
||||||
|
"call",
|
||||||
|
"index.mq.md",
|
||||||
|
"main",
|
||||||
|
"--arg",
|
||||||
|
"n=1",
|
||||||
|
"--output",
|
||||||
|
"json",
|
||||||
|
"--observation-file",
|
||||||
|
"observation.json",
|
||||||
|
],
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
run.status.success(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&run.stderr)
|
||||||
|
);
|
||||||
|
let observation = analysis(dir.path(), "observation.json");
|
||||||
|
let started = observation["events"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.find(|event| event["kind"] == "run.started")
|
||||||
|
.expect("run.started");
|
||||||
|
assert_eq!(started["payload"]["source"]["analysis_digest"], expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn independent_view_lint_and_knowledge_consumers_drive_the_real_cli() {
|
||||||
|
let dir = TempDir::new("consumers");
|
||||||
|
dir.write(
|
||||||
|
"marqdo.yaml",
|
||||||
|
"project:\n name: consumers\n version: 0.1.0\n",
|
||||||
|
);
|
||||||
|
dir.write("theory.mq.md", "## @knowledge 公式\n\n正文\n");
|
||||||
|
dir.write(
|
||||||
|
"index.mq.md",
|
||||||
|
"---\nimport:\n theory: \"./theory.mq.md\"\n---\n\n## @exec main\n\n[公式](./theory.mq.md#公式) [未加载](./notes.mq.md)\n\n`return 1`\n",
|
||||||
|
);
|
||||||
|
dir.write("notes.mq.md", "## @exec main\n\n`return 2`\n");
|
||||||
|
assert!(emit(dir.path(), "index.mq.md", "index.json", &[])
|
||||||
|
.status
|
||||||
|
.success());
|
||||||
|
assert!(emit(dir.path(), "notes.mq.md", "notes.json", &[])
|
||||||
|
.status
|
||||||
|
.success());
|
||||||
|
|
||||||
|
let consumers = repo_root().join("tests/consumers");
|
||||||
|
let run = |script: &str, args: &[&Path]| -> Output {
|
||||||
|
let mut command = Command::new("python3");
|
||||||
|
command.arg(consumers.join(script));
|
||||||
|
for arg in args {
|
||||||
|
command.arg(arg);
|
||||||
|
}
|
||||||
|
command.output().expect("python3 consumer")
|
||||||
|
};
|
||||||
|
let index_json = dir.path().join("index.json");
|
||||||
|
let notes_json = dir.path().join("notes.json");
|
||||||
|
|
||||||
|
let view = run("view_consumer.py", &[&index_json]);
|
||||||
|
assert!(
|
||||||
|
view.status.success(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&view.stderr)
|
||||||
|
);
|
||||||
|
assert!(String::from_utf8_lossy(&view.stdout).contains("view: rendered=1"));
|
||||||
|
|
||||||
|
let lint = run("lint_consumer.py", &[&index_json]);
|
||||||
|
assert!(
|
||||||
|
lint.status.success(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&lint.stderr)
|
||||||
|
);
|
||||||
|
let lint_text = String::from_utf8_lossy(&lint.stdout);
|
||||||
|
assert!(lint_text.contains("state=not_loaded"));
|
||||||
|
assert!(lint_text.contains("unresolved=1"));
|
||||||
|
|
||||||
|
let knowledge = run("knowledge_consumer.py", &[&index_json, ¬es_json]);
|
||||||
|
assert!(
|
||||||
|
knowledge.status.success(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&knowledge.stderr)
|
||||||
|
);
|
||||||
|
let knowledge_text = String::from_utf8_lossy(&knowledge.stdout);
|
||||||
|
assert!(knowledge_text.contains("entries=2"));
|
||||||
|
assert!(knowledge_text.contains("not_loaded=1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn protocol_validator_accepts_current_bytes_and_rejects_mutations() {
|
||||||
|
let dir = TempDir::new("protocol-validator");
|
||||||
|
dir.write(
|
||||||
|
"index.mq.md",
|
||||||
|
"---\nimport:\n theory: \"./theory.mq.md\"\n---\n\n## @exec main\n\n$$x^2$$\n\n```python\nprint(1)\n```\n\n[公式](./theory.mq.md#公式)\n\n`结果 = theory.加一(1)`\n\n`return 结果`\n",
|
||||||
|
);
|
||||||
|
dir.write(
|
||||||
|
"theory.mq.md",
|
||||||
|
"## @exec 加一\n\n`params(n: Int)`\n\n`return n + 1`\n\n## @knowledge 公式\n\n正文\n",
|
||||||
|
);
|
||||||
|
let check = emit(dir.path(), "index.mq.md", "analysis.json", &[]);
|
||||||
|
assert!(
|
||||||
|
check.status.success(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&check.stderr)
|
||||||
|
);
|
||||||
|
let run = cli(
|
||||||
|
dir.path(),
|
||||||
|
&[
|
||||||
|
"call",
|
||||||
|
"index.mq.md",
|
||||||
|
"main",
|
||||||
|
"--output",
|
||||||
|
"json",
|
||||||
|
"--observation-file",
|
||||||
|
"observation.json",
|
||||||
|
],
|
||||||
|
);
|
||||||
|
assert!(run.status.success(), "{run:?}");
|
||||||
|
let validator = repo_root().join("tests/consumers/validate_protocols.py");
|
||||||
|
let output = Command::new("python3")
|
||||||
|
.arg(&validator)
|
||||||
|
.arg(dir.path().join("analysis.json"))
|
||||||
|
.arg(dir.path().join("observation.json"))
|
||||||
|
.arg(repo_root().join("examples/tool-unknown-name/tool.json"))
|
||||||
|
.output()
|
||||||
|
.expect("python3 protocol validator");
|
||||||
|
assert!(
|
||||||
|
output.status.success(),
|
||||||
|
"{}",
|
||||||
|
String::from_utf8_lossy(&output.stderr)
|
||||||
|
);
|
||||||
|
assert!(String::from_utf8_lossy(&output.stdout).contains("validated analysis"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn two_entries_keep_their_own_snapshot_context() {
|
||||||
|
let dir = TempDir::new("entries");
|
||||||
|
for (name, body) in [("first", "1"), ("second", "2")] {
|
||||||
|
dir.write(
|
||||||
|
&format!("{name}.mq.md"),
|
||||||
|
&format!("## @exec main\n\n`return {body}`\n"),
|
||||||
|
);
|
||||||
|
let output = emit(
|
||||||
|
dir.path(),
|
||||||
|
&format!("{name}.mq.md"),
|
||||||
|
&format!("{name}.json"),
|
||||||
|
&[],
|
||||||
|
);
|
||||||
|
assert!(output.status.success(), "{output:?}");
|
||||||
|
}
|
||||||
|
let first = analysis(dir.path(), "first.json");
|
||||||
|
let second = analysis(dir.path(), "second.json");
|
||||||
|
assert!(first["project"]["entry_module_id"]
|
||||||
|
.as_str()
|
||||||
|
.unwrap()
|
||||||
|
.ends_with("::first.mq.md"));
|
||||||
|
assert!(second["project"]["entry_module_id"]
|
||||||
|
.as_str()
|
||||||
|
.unwrap()
|
||||||
|
.ends_with("::second.mq.md"));
|
||||||
|
assert_ne!(first["project"]["root_id"], second["project"]["root_id"]);
|
||||||
|
}
|
||||||
@@ -466,7 +466,12 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
heading_infos.push(info.clone());
|
heading_infos.push(info.clone());
|
||||||
stack.push((level, info.path.clone(), mode, info.mode_source_unit_id.clone()));
|
stack.push((
|
||||||
|
level,
|
||||||
|
info.path.clone(),
|
||||||
|
mode,
|
||||||
|
info.mode_source_unit_id.clone(),
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Complete section ranges: from this heading to the next heading of the
|
// Complete section ranges: from this heading to the next heading of the
|
||||||
@@ -763,13 +768,22 @@ mod tests {
|
|||||||
assert_eq!(calc.full_span.end, note.span.start);
|
assert_eq!(calc.full_span.end, note.span.start);
|
||||||
assert_eq!(detail.full_span.end, note.span.start);
|
assert_eq!(detail.full_span.end, note.span.start);
|
||||||
assert_eq!(note.full_span.end, source.len());
|
assert_eq!(note.full_span.end, source.len());
|
||||||
assert_eq!(detail.parent_id.path, vec!["力学".to_string(), "计算力".to_string()]);
|
assert_eq!(
|
||||||
|
detail.parent_id.path,
|
||||||
|
vec!["力学".to_string(), "计算力".to_string()]
|
||||||
|
);
|
||||||
assert_eq!(calc.parent_id.path, vec!["力学".to_string()]);
|
assert_eq!(calc.parent_id.path, vec!["力学".to_string()]);
|
||||||
let root = &index.units[0];
|
let root = &index.units[0];
|
||||||
assert_eq!(root.span, marqdo_span::Span::new(0, source.len()));
|
assert_eq!(root.span, marqdo_span::Span::new(0, source.len()));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
calc.parent_id,
|
calc.parent_id,
|
||||||
index.units.iter().find(|u| u.name == "力学").unwrap().id.clone()
|
index
|
||||||
|
.units
|
||||||
|
.iter()
|
||||||
|
.find(|u| u.name == "力学")
|
||||||
|
.unwrap()
|
||||||
|
.id
|
||||||
|
.clone()
|
||||||
);
|
);
|
||||||
assert_eq!(by_name("力学").parent_id, root.id);
|
assert_eq!(by_name("力学").parent_id, root.id);
|
||||||
}
|
}
|
||||||
@@ -788,13 +802,22 @@ mod tests {
|
|||||||
};
|
};
|
||||||
let namespace = by_name("数学");
|
let namespace = by_name("数学");
|
||||||
assert_eq!(namespace.mode_origin, ModeOrigin::Explicit);
|
assert_eq!(namespace.mode_origin, ModeOrigin::Explicit);
|
||||||
assert_eq!(namespace.mode_source_unit_id, namespace_unit(&index, "数学"));
|
assert_eq!(
|
||||||
|
namespace.mode_source_unit_id,
|
||||||
|
namespace_unit(&index, "数学")
|
||||||
|
);
|
||||||
let calc = by_name("计算");
|
let calc = by_name("计算");
|
||||||
assert_eq!(calc.mode_origin, ModeOrigin::Explicit);
|
assert_eq!(calc.mode_origin, ModeOrigin::Explicit);
|
||||||
assert_eq!(calc.mode_source_unit_id.path, vec!["数学".to_string(), "计算".to_string()]);
|
assert_eq!(
|
||||||
|
calc.mode_source_unit_id.path,
|
||||||
|
vec!["数学".to_string(), "计算".to_string()]
|
||||||
|
);
|
||||||
let detail = by_name("细节");
|
let detail = by_name("细节");
|
||||||
assert_eq!(detail.mode_origin, ModeOrigin::Inherited);
|
assert_eq!(detail.mode_origin, ModeOrigin::Inherited);
|
||||||
assert_eq!(detail.mode_source_unit_id.path, calc.mode_source_unit_id.path);
|
assert_eq!(
|
||||||
|
detail.mode_source_unit_id.path,
|
||||||
|
calc.mode_source_unit_id.path
|
||||||
|
);
|
||||||
let note = by_name("说明");
|
let note = by_name("说明");
|
||||||
assert_eq!(note.mode_origin, ModeOrigin::Inherited);
|
assert_eq!(note.mode_origin, ModeOrigin::Inherited);
|
||||||
assert_eq!(note.mode_source_unit_id.path, vec!["数学".to_string()]);
|
assert_eq!(note.mode_source_unit_id.path, vec!["数学".to_string()]);
|
||||||
@@ -825,7 +848,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn innermost_unit_owns_a_linked_span() {
|
fn innermost_unit_owns_a_linked_span() {
|
||||||
let source = "# @knowledge 数学\n\n## @exec 计算\n\n见[链接](#细节)。\n\n### 细节\n\n`return 1`\n";
|
let source = "前置说明。\n\n# @knowledge 数学\n\n## @exec 计算\n\n见[链接](#细节)。\n\n### 细节\n\n`return 1`\n";
|
||||||
let index = index_of(source);
|
let index = index_of(source);
|
||||||
let link_start = source.find("[链接]").unwrap();
|
let link_start = source.find("[链接]").unwrap();
|
||||||
let owner = index
|
let owner = index
|
||||||
|
|||||||
@@ -1,77 +1,523 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""Independent Analysis consumer: no Marqdo/Rust imports."""
|
"""Independent semantic consumer for `marqdo.analysis`.
|
||||||
|
|
||||||
|
This script imports only the Python standard library. It validates the public
|
||||||
|
invariants that JSON Schema cannot express: source digests, span ownership,
|
||||||
|
heading trees, mode origins, function/anchor/call ownership, reference state
|
||||||
|
consistency and resource attribution. It never links a private Rust crate and
|
||||||
|
never executes a document.
|
||||||
|
|
||||||
|
usage: analysis_consumer.py ANALYSIS.json [--require-transfers]
|
||||||
|
"""
|
||||||
|
import hashlib
|
||||||
import json
|
import json
|
||||||
|
import re
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
def visit(body, loop_span=None):
|
SCHEMA = "marqdo.analysis"
|
||||||
|
SCHEMA_VERSION = 3
|
||||||
|
STATES = {
|
||||||
|
"resolved",
|
||||||
|
"not_loaded",
|
||||||
|
"missing",
|
||||||
|
"ambiguous",
|
||||||
|
"external",
|
||||||
|
"outside_scope",
|
||||||
|
"invalid",
|
||||||
|
}
|
||||||
|
DIGEST64 = re.compile(r"^[0-9a-f]{64}$")
|
||||||
|
STATEMENT_KINDS = {
|
||||||
|
"assign",
|
||||||
|
"expression",
|
||||||
|
"branch",
|
||||||
|
"loop",
|
||||||
|
"return",
|
||||||
|
"break",
|
||||||
|
"continue",
|
||||||
|
}
|
||||||
|
EXPRESSION_KINDS = {
|
||||||
|
"literal",
|
||||||
|
"variable",
|
||||||
|
"list",
|
||||||
|
"record",
|
||||||
|
"unary",
|
||||||
|
"binary",
|
||||||
|
"member",
|
||||||
|
"index",
|
||||||
|
"call",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidAnalysis(Exception):
|
||||||
|
"""The artifact violates the current public contract."""
|
||||||
|
|
||||||
|
|
||||||
|
def fail(path, message):
|
||||||
|
raise InvalidAnalysis(f"{path}: {message}")
|
||||||
|
|
||||||
|
|
||||||
|
def validate(analysis):
|
||||||
|
"""Validate a parsed Analysis document; raise InvalidAnalysis on failure."""
|
||||||
|
if not isinstance(analysis, dict):
|
||||||
|
fail("$", "analysis must be an object")
|
||||||
|
if analysis.get("schema") != SCHEMA:
|
||||||
|
fail("$.schema", "unexpected schema")
|
||||||
|
if analysis.get("schema_version") != SCHEMA_VERSION:
|
||||||
|
fail("$.schema_version", "unsupported revision")
|
||||||
|
producer = analysis.get("producer") or {}
|
||||||
|
if producer.get("name") != "marqdo":
|
||||||
|
fail("$.producer.name", "unexpected producer")
|
||||||
|
if producer.get("markdown_profile") != "marqdo.md.v1":
|
||||||
|
fail("$.producer.markdown_profile", "unexpected Markdown profile")
|
||||||
|
|
||||||
|
project = analysis.get("project") or {}
|
||||||
|
modules = analysis.get("modules")
|
||||||
|
if not isinstance(modules, list) or not modules:
|
||||||
|
fail("$.modules", "at least one module is required")
|
||||||
|
by_id = {}
|
||||||
|
for index, module in enumerate(modules):
|
||||||
|
path = f"$.modules[{index}]"
|
||||||
|
module_id = module.get("id")
|
||||||
|
if not isinstance(module_id, str) or "::" not in module_id:
|
||||||
|
fail(path + ".id", "invalid module id")
|
||||||
|
if module_id in by_id:
|
||||||
|
fail(path + ".id", "duplicate module id")
|
||||||
|
by_id[module_id] = module
|
||||||
|
if project.get("entry_module_id") not in by_id:
|
||||||
|
fail("$.project.entry_module_id", "does not name a module")
|
||||||
|
if project.get("identity_kind") not in ("manifest", "workspace_snapshot"):
|
||||||
|
fail("$.project.identity_kind", "invalid identity kind")
|
||||||
|
for field in ("lock_digest", "manifest_digest"):
|
||||||
|
value = project.get(field)
|
||||||
|
if not isinstance(value, str) or not (
|
||||||
|
value == "" or re.fullmatch(r"sha256:[0-9a-f]{64}", value)
|
||||||
|
):
|
||||||
|
fail(f"$.project.{field}", "invalid snapshot digest")
|
||||||
|
if project.get("root_id") not in (None, "") and not isinstance(
|
||||||
|
project["root_id"], str
|
||||||
|
):
|
||||||
|
fail("$.project.root_id", "invalid root id")
|
||||||
|
extensions = project.get("extensions")
|
||||||
|
if not isinstance(extensions, list):
|
||||||
|
fail("$.project.extensions", "must be an array")
|
||||||
|
for index, extension in enumerate(extensions):
|
||||||
|
path = f"$.project.extensions[{index}]"
|
||||||
|
if extension.get("kind") not in ("plugin", "kernel", "provider"):
|
||||||
|
fail(path + ".kind", "invalid extension kind")
|
||||||
|
for field in ("manifest_digest", "artifact_digest"):
|
||||||
|
if not re.fullmatch(r"sha256:[0-9a-f]{64}", extension.get(field, "")):
|
||||||
|
fail(f"{path}.{field}", "invalid extension digest")
|
||||||
|
|
||||||
|
function_ids = set()
|
||||||
|
module_units = {}
|
||||||
|
for index, module in enumerate(modules):
|
||||||
|
path = f"$.modules[{index}]"
|
||||||
|
unit_ids = {unit.get("id") for unit in module.get("units", [])}
|
||||||
|
module_units[module["id"]] = unit_ids
|
||||||
|
function_ids.update(
|
||||||
|
function.get("id") for function in module.get("functions", [])
|
||||||
|
)
|
||||||
|
|
||||||
|
for index, module in enumerate(modules):
|
||||||
|
path = f"$.modules[{index}]"
|
||||||
|
source = module.get("source")
|
||||||
|
if not isinstance(source, str):
|
||||||
|
fail(path + ".source", "exact source must be a string")
|
||||||
|
encoded = source.encode("utf-8")
|
||||||
|
digest = module.get("source_digest")
|
||||||
|
if digest != hashlib.sha256(encoded).hexdigest():
|
||||||
|
fail(path + ".source_digest", "does not match source bytes")
|
||||||
|
digest = module.get("document", {}).get("span")
|
||||||
|
if not isinstance(module.get("document"), dict):
|
||||||
|
fail(path + ".document", "missing document AST")
|
||||||
|
ast_index = {}
|
||||||
|
validate_ast(module["document"], encoded, path + ".document", ast_index)
|
||||||
|
document_span = module["document"].get("span") or {}
|
||||||
|
if document_span.get("start") != 0 or document_span.get("end") != len(encoded):
|
||||||
|
fail(path + ".document.span", "root does not cover the source")
|
||||||
|
|
||||||
|
units = module.get("units") or []
|
||||||
|
if not units:
|
||||||
|
fail(path + ".units", "missing root unit")
|
||||||
|
unit_by_id = {}
|
||||||
|
for unit in units:
|
||||||
|
if unit.get("id") in unit_by_id:
|
||||||
|
fail(path + ".units", "duplicate unit id")
|
||||||
|
unit_by_id[unit["id"]] = unit
|
||||||
|
roots = [unit for unit in units if unit.get("kind") == "root"]
|
||||||
|
if len(roots) != 1:
|
||||||
|
fail(path + ".units", "expected exactly one root unit")
|
||||||
|
root = roots[0]
|
||||||
|
if root.get("parent_id") is not None or root.get("path") != []:
|
||||||
|
fail(path + ".units.root", "root must not have a parent or path")
|
||||||
|
if root.get("heading_span") is not None or root.get("level") != 0:
|
||||||
|
fail(path + ".units.root", "root must not carry a heading")
|
||||||
|
for unit in units:
|
||||||
|
upath = f"{path}.units[{unit['id']}]"
|
||||||
|
check_span(unit.get("span"), encoded, upath + ".span")
|
||||||
|
if unit.get("heading_span") is not None:
|
||||||
|
check_span(unit.get("heading_span"), encoded, upath + ".heading_span")
|
||||||
|
if unit is root:
|
||||||
|
continue
|
||||||
|
parent = unit_by_id.get(unit.get("parent_id"))
|
||||||
|
if parent is None:
|
||||||
|
fail(upath + ".parent_id", "missing parent unit")
|
||||||
|
expected = list(parent.get("path") or []) + [unit.get("name")]
|
||||||
|
if expected != unit.get("path"):
|
||||||
|
fail(upath + ".path", "does not match parent path plus name")
|
||||||
|
unit_span = unit.get("span") or {}
|
||||||
|
parent_span = parent.get("span") or {}
|
||||||
|
if not (
|
||||||
|
parent_span.get("start", 0) <= unit_span.get("start", 0)
|
||||||
|
and unit_span.get("end", -1) <= parent_span.get("end", -2)
|
||||||
|
):
|
||||||
|
fail(upath + ".span", "escapes the parent span")
|
||||||
|
if unit.get("mode") not in ("exec", "knowledge"):
|
||||||
|
fail(upath + ".mode", "invalid mode")
|
||||||
|
if unit.get("mode_origin") not in ("explicit", "inherited"):
|
||||||
|
fail(upath + ".mode_origin", "non-root unit must be explicit or inherited")
|
||||||
|
if not in_ancestor_chain(unit, unit.get("mode_source_unit_id"), unit_by_id):
|
||||||
|
fail(upath + ".mode_source_unit_id", "is not an ancestor")
|
||||||
|
function = unit.get("function")
|
||||||
|
if function is not None:
|
||||||
|
if unit.get("kind") not in ("function", "section"):
|
||||||
|
fail(upath + ".function", "only Exec H2/section units own a function")
|
||||||
|
if function not in function_ids:
|
||||||
|
fail(upath + ".function", "names a missing function")
|
||||||
|
if root.get("mode_origin") != "default":
|
||||||
|
fail(path + ".units.root.mode_origin", "root origin must be default")
|
||||||
|
|
||||||
|
anchors = module.get("anchors") or []
|
||||||
|
previous = None
|
||||||
|
for anchor in anchors:
|
||||||
|
if previous is not None and previous >= anchor.get("anchor"):
|
||||||
|
fail(path + ".anchors", "not strictly sorted")
|
||||||
|
previous = anchor.get("anchor")
|
||||||
|
if anchor.get("unit_id") not in unit_by_id:
|
||||||
|
fail(path + ".anchors", "names a missing unit")
|
||||||
|
|
||||||
|
seen_functions = set()
|
||||||
|
for function in module.get("functions") or []:
|
||||||
|
fpath = f"{path}.functions[{function.get('id')}]"
|
||||||
|
if function.get("id") in seen_functions:
|
||||||
|
fail(fpath, "duplicate function")
|
||||||
|
seen_functions.add(function.get("id"))
|
||||||
|
unit = unit_by_id.get(function.get("unit_id"))
|
||||||
|
if unit is None or unit.get("kind") != "function":
|
||||||
|
fail(fpath + ".unit_id", "not an Exec H2 unit")
|
||||||
|
if unit.get("function") != function.get("id"):
|
||||||
|
fail(fpath + ".id", "unit/function link mismatch")
|
||||||
|
check_span(function.get("span"), encoded, fpath + ".span")
|
||||||
|
check_span(function.get("heading_span"), encoded, fpath + ".heading_span")
|
||||||
|
for statement in function.get("body") or []:
|
||||||
|
validate_statement(statement, encoded, fpath)
|
||||||
|
|
||||||
|
for import_record in module.get("imports") or []:
|
||||||
|
check_span(import_record.get("span"), encoded, f"{path}.imports")
|
||||||
|
resolved = import_record.get("resolved")
|
||||||
|
if resolved is not None and resolved not in by_id:
|
||||||
|
fail(path + ".imports", "resolved target is not a module")
|
||||||
|
|
||||||
|
for reference in module.get("references") or []:
|
||||||
|
validate_reference(reference, by_id, module_units, encoded, path)
|
||||||
|
|
||||||
|
seen_call_sites = set()
|
||||||
|
for call in module.get("calls") or []:
|
||||||
|
cpath = f"{path}.calls"
|
||||||
|
check_span(call.get("span"), encoded, cpath)
|
||||||
|
key = (call.get("function"), call["span"]["start"], call["span"]["end"])
|
||||||
|
if key in seen_call_sites:
|
||||||
|
fail(cpath, "duplicate call site")
|
||||||
|
seen_call_sites.add(key)
|
||||||
|
if call.get("function") not in function_ids:
|
||||||
|
fail(cpath, "missing caller function")
|
||||||
|
state = call.get("state")
|
||||||
|
if state == "function":
|
||||||
|
if call.get("target_kind") != "function":
|
||||||
|
fail(cpath, "function call has wrong target kind")
|
||||||
|
if call.get("target") not in function_ids:
|
||||||
|
fail(cpath, "function target does not exist")
|
||||||
|
elif state == "builtin":
|
||||||
|
if call.get("target_kind") != "builtin" or not call.get("target"):
|
||||||
|
fail(cpath, "builtin call is incomplete")
|
||||||
|
elif state == "plugin":
|
||||||
|
if call.get("target_kind") != "plugin" or not call.get("target_owner"):
|
||||||
|
fail(cpath, "plugin call lacks its owner")
|
||||||
|
elif state == "unresolved":
|
||||||
|
if call.get("target") is not None or call.get("target_kind") is not None:
|
||||||
|
fail(cpath, "unresolved call carries a target")
|
||||||
|
if call.get("reason") not in ("dynamic", "unbound"):
|
||||||
|
fail(cpath, "unresolved call lacks a reason")
|
||||||
|
else:
|
||||||
|
fail(cpath, "invalid call state")
|
||||||
|
|
||||||
|
seen_resources = set()
|
||||||
|
for resource in module.get("resources") or []:
|
||||||
|
rpath = f"{path}.resources"
|
||||||
|
if resource.get("id") in seen_resources:
|
||||||
|
fail(rpath, "duplicate resource id")
|
||||||
|
seen_resources.add(resource.get("id"))
|
||||||
|
if resource.get("module_id") != module["id"]:
|
||||||
|
fail(rpath, "resource module mismatch")
|
||||||
|
if resource.get("unit_id") not in unit_by_id:
|
||||||
|
fail(rpath, "resource names a missing unit")
|
||||||
|
check_span(resource.get("span"), encoded, rpath)
|
||||||
|
if resource.get("kind") not in ("formula", "code"):
|
||||||
|
fail(rpath, "unknown resource kind")
|
||||||
|
if not DIGEST64.fullmatch(resource.get("content_digest", "")):
|
||||||
|
fail(rpath, "invalid resource digest")
|
||||||
|
if resource["kind"] == "formula" and not isinstance(
|
||||||
|
resource.get("display"), bool
|
||||||
|
):
|
||||||
|
fail(rpath, "formula display must be a bool")
|
||||||
|
if resource["kind"] == "code" and resource.get("display") is not None:
|
||||||
|
fail(rpath, "code display must be null")
|
||||||
|
node = ast_index.get(
|
||||||
|
(resource["span"]["start"], resource["span"]["end"])
|
||||||
|
)
|
||||||
|
if node is None:
|
||||||
|
fail(rpath, "resource span does not name an AST payload node")
|
||||||
|
expected_kinds = (
|
||||||
|
("math", "math_block")
|
||||||
|
if resource["kind"] == "formula"
|
||||||
|
else ("code_block",)
|
||||||
|
)
|
||||||
|
if node.get("kind") not in expected_kinds:
|
||||||
|
fail(rpath, "resource kind does not match its AST node")
|
||||||
|
payload = node.get("literal", "").encode("utf-8")
|
||||||
|
if resource["content_digest"] != hashlib.sha256(payload).hexdigest():
|
||||||
|
fail(rpath, "content_digest does not match the AST payload")
|
||||||
|
|
||||||
|
diagnostics = analysis.get("diagnostics")
|
||||||
|
if not isinstance(diagnostics, list):
|
||||||
|
fail("$.diagnostics", "must be an array")
|
||||||
|
for diagnostic in diagnostics:
|
||||||
|
if diagnostic.get("module") not in by_id:
|
||||||
|
fail("$.diagnostics", "names a missing module")
|
||||||
|
if diagnostic.get("severity") == "error":
|
||||||
|
fail("$.diagnostics", "successful Analysis contains an error")
|
||||||
|
span = diagnostic.get("span")
|
||||||
|
if span is not None:
|
||||||
|
module = by_id[diagnostic["module"]]
|
||||||
|
check_span(span, module["source"].encode("utf-8"), "$.diagnostics.span")
|
||||||
|
return analysis
|
||||||
|
|
||||||
|
|
||||||
|
def check_span(span, encoded, path):
|
||||||
|
if not isinstance(span, dict):
|
||||||
|
fail(path, "missing span")
|
||||||
|
start, end = span.get("start"), span.get("end")
|
||||||
|
if not isinstance(start, int) or not isinstance(end, int):
|
||||||
|
fail(path, "span endpoints must be integers")
|
||||||
|
if start < 0 or start > end or end > len(encoded):
|
||||||
|
fail(path, "span is outside the source")
|
||||||
|
for offset in (start, end):
|
||||||
|
try:
|
||||||
|
encoded[offset:].decode("utf-8")
|
||||||
|
except UnicodeDecodeError:
|
||||||
|
fail(path, "span is not on a UTF-8 boundary")
|
||||||
|
|
||||||
|
|
||||||
|
def in_ancestor_chain(unit, target, unit_by_id):
|
||||||
|
current = unit
|
||||||
|
while current is not None:
|
||||||
|
if current.get("id") == target:
|
||||||
|
return True
|
||||||
|
parent = current.get("parent_id")
|
||||||
|
current = unit_by_id.get(parent) if parent else None
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def validate_ast(node, encoded, path, ast_index=None):
|
||||||
|
if not isinstance(node, dict):
|
||||||
|
fail(path, "AST node must be an object")
|
||||||
|
kind = node.get("kind")
|
||||||
|
if not isinstance(kind, str):
|
||||||
|
fail(path + ".kind", "missing node kind")
|
||||||
|
if kind.startswith("footnote"):
|
||||||
|
fail(path + ".kind", "disabled profile node")
|
||||||
|
check_span(node.get("span"), encoded, path + ".span")
|
||||||
|
children = node.get("children")
|
||||||
|
if not isinstance(children, list):
|
||||||
|
fail(path + ".children", "must be an array")
|
||||||
|
if kind in {
|
||||||
|
"text",
|
||||||
|
"code",
|
||||||
|
"code_block",
|
||||||
|
"math",
|
||||||
|
"math_block",
|
||||||
|
"html_block",
|
||||||
|
"html_inline",
|
||||||
|
"front_matter",
|
||||||
|
"thematic_break",
|
||||||
|
"soft_break",
|
||||||
|
"line_break",
|
||||||
|
} and children:
|
||||||
|
fail(path + ".children", "leaf node has children")
|
||||||
|
if ast_index is not None and kind in ("code_block", "math", "math_block"):
|
||||||
|
span = node.get("span") or {}
|
||||||
|
ast_index[(span.get("start"), span.get("end"))] = node
|
||||||
|
for index, child in enumerate(children):
|
||||||
|
validate_ast(child, encoded, f"{path}.children[{index}]", ast_index)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_statement(statement, encoded, path):
|
||||||
|
if not isinstance(statement, dict):
|
||||||
|
fail(path, "statement must be an object")
|
||||||
|
kind = statement.get("kind")
|
||||||
|
if kind not in STATEMENT_KINDS:
|
||||||
|
fail(path + ".kind", "unknown statement kind")
|
||||||
|
check_span(statement.get("span"), encoded, path + ".span")
|
||||||
|
if kind == "assign":
|
||||||
|
validate_place(statement.get("target"), encoded, path + ".target")
|
||||||
|
validate_expression(statement.get("value"), encoded, path + ".value")
|
||||||
|
elif kind == "expression":
|
||||||
|
validate_expression(statement.get("value"), encoded, path + ".value")
|
||||||
|
elif kind == "return":
|
||||||
|
validate_expression(statement.get("value"), encoded, path + ".value")
|
||||||
|
elif kind == "branch":
|
||||||
|
arms = statement.get("arms")
|
||||||
|
if not isinstance(arms, list) or not arms:
|
||||||
|
fail(path + ".arms", "branch needs at least one arm")
|
||||||
|
for arm in arms:
|
||||||
|
validate_expression(arm.get("condition"), encoded, path + ".condition")
|
||||||
|
check_span(arm.get("condition_span"), encoded, path + ".condition_span")
|
||||||
|
for nested in arm.get("body") or []:
|
||||||
|
validate_statement(nested, encoded, path + ".arm")
|
||||||
|
elif kind == "loop":
|
||||||
|
validate_expression(statement.get("condition"), encoded, path + ".condition")
|
||||||
|
check_span(statement.get("condition_span"), encoded, path + ".condition_span")
|
||||||
|
for nested in statement.get("body") or []:
|
||||||
|
validate_statement(nested, encoded, path + ".body")
|
||||||
|
elif kind in ("break", "continue"):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def validate_place(place, encoded, path):
|
||||||
|
if isinstance(place, str):
|
||||||
|
if not place:
|
||||||
|
fail(path, "empty local target")
|
||||||
|
return
|
||||||
|
if not isinstance(place, dict) or place.get("kind") != "index":
|
||||||
|
fail(path, "invalid assignment target")
|
||||||
|
validate_expression(place.get("base"), encoded, path + ".base")
|
||||||
|
validate_expression(place.get("index"), encoded, path + ".index")
|
||||||
|
check_span(place.get("span"), encoded, path + ".span")
|
||||||
|
|
||||||
|
|
||||||
|
def validate_expression(expression, encoded, path):
|
||||||
|
if not isinstance(expression, dict):
|
||||||
|
fail(path, "expression must be an object")
|
||||||
|
kind = expression.get("kind")
|
||||||
|
if kind not in EXPRESSION_KINDS:
|
||||||
|
fail(path + ".kind", "unknown expression kind")
|
||||||
|
check_span(expression.get("span"), encoded, path + ".span")
|
||||||
|
if kind == "literal":
|
||||||
|
literal_type = expression.get("type")
|
||||||
|
if literal_type not in ("int", "float", "text", "bool", "none"):
|
||||||
|
fail(path + ".type", "unknown literal type")
|
||||||
|
if literal_type == "int":
|
||||||
|
if not re.fullmatch(r"-?[0-9]+", expression.get("value", "")):
|
||||||
|
fail(path + ".value", "integer literal must be a decimal string")
|
||||||
|
elif literal_type == "none":
|
||||||
|
if "value" in expression:
|
||||||
|
fail(path + ".value", "none literal carries a value")
|
||||||
|
elif kind == "variable":
|
||||||
|
if not expression.get("name"):
|
||||||
|
fail(path + ".name", "empty variable name")
|
||||||
|
elif kind == "list":
|
||||||
|
for item in expression.get("items") or []:
|
||||||
|
validate_expression(item, encoded, path + ".items")
|
||||||
|
elif kind == "record":
|
||||||
|
for entry in expression.get("entries") or []:
|
||||||
|
validate_expression(entry.get("value"), encoded, path + ".entry")
|
||||||
|
elif kind == "unary":
|
||||||
|
validate_expression(expression.get("operand"), encoded, path + ".operand")
|
||||||
|
elif kind in ("binary",):
|
||||||
|
validate_expression(expression.get("left"), encoded, path + ".left")
|
||||||
|
validate_expression(expression.get("right"), encoded, path + ".right")
|
||||||
|
elif kind == "member":
|
||||||
|
validate_expression(expression.get("base"), encoded, path + ".base")
|
||||||
|
elif kind == "index":
|
||||||
|
validate_expression(expression.get("base"), encoded, path + ".base")
|
||||||
|
validate_expression(expression.get("index"), encoded, path + ".index")
|
||||||
|
elif kind == "call":
|
||||||
|
validate_expression(expression.get("callee"), encoded, path + ".callee")
|
||||||
|
for argument in expression.get("args") or []:
|
||||||
|
validate_expression(argument.get("value"), encoded, path + ".arg")
|
||||||
|
|
||||||
|
|
||||||
|
def validate_reference(reference, by_id, module_units, encoded, path):
|
||||||
|
rpath = f"{path}.references"
|
||||||
|
check_span(reference.get("span"), encoded, rpath + ".span")
|
||||||
|
if reference.get("source_unit") not in module_units.get(reference.get("source"), set()):
|
||||||
|
fail(rpath + ".source_unit", "not a unit of the source module")
|
||||||
|
state = reference.get("state")
|
||||||
|
if state not in STATES:
|
||||||
|
fail(rpath + ".state", "unknown state")
|
||||||
|
target_module = reference.get("target_module")
|
||||||
|
target_unit = reference.get("target_unit")
|
||||||
|
target_kind = reference.get("target_kind")
|
||||||
|
if state == "resolved":
|
||||||
|
if target_kind == "module":
|
||||||
|
if target_module not in by_id:
|
||||||
|
fail(rpath + ".target_module", "does not name a module")
|
||||||
|
if target_unit is not None and target_unit not in module_units.get(
|
||||||
|
target_module, set()
|
||||||
|
):
|
||||||
|
fail(rpath + ".target_unit", "does not name a target unit")
|
||||||
|
elif target_kind == "file":
|
||||||
|
if target_module is not None or target_unit is not None:
|
||||||
|
fail(rpath, "file target must not name a module/unit")
|
||||||
|
else:
|
||||||
|
fail(rpath + ".target_kind", "resolved reference has no target kind")
|
||||||
|
elif state == "missing":
|
||||||
|
if target_unit is not None:
|
||||||
|
fail(rpath + ".target_unit", "missing reference carries a unit")
|
||||||
|
elif state == "ambiguous":
|
||||||
|
if target_unit is not None or len(reference.get("candidates") or []) < 2:
|
||||||
|
fail(rpath, "ambiguous reference needs several candidates")
|
||||||
|
else:
|
||||||
|
if target_module is not None or target_unit is not None or target_kind is not None:
|
||||||
|
fail(rpath, "non-resolved reference carries a target")
|
||||||
|
|
||||||
|
|
||||||
|
def visit_transfers(body, loop_span=None):
|
||||||
for statement in body:
|
for statement in body:
|
||||||
kind = statement["kind"]
|
kind = statement["kind"]
|
||||||
if kind == "loop":
|
if kind == "loop":
|
||||||
yield from visit(statement["body"], statement["span"])
|
yield from visit_transfers(statement["body"], statement["span"])
|
||||||
elif kind == "branch":
|
elif kind == "branch":
|
||||||
for arm in statement["arms"]:
|
for arm in statement["arms"]:
|
||||||
yield from visit(arm["body"], loop_span)
|
yield from visit_transfers(arm["body"], loop_span)
|
||||||
elif kind in ("break", "continue"):
|
elif kind in ("break", "continue"):
|
||||||
if loop_span is None:
|
if loop_span is None:
|
||||||
raise SystemExit(f"{kind} outside a projected loop")
|
fail("$", f"{kind} outside a projected loop")
|
||||||
span = statement["span"]
|
span = statement["span"]
|
||||||
if not 0 <= loop_span["start"] < span["start"] < span["end"]:
|
if not 0 <= loop_span["start"] < span["start"] < span["end"]:
|
||||||
raise SystemExit(f"invalid {kind} carrier span")
|
fail("$", f"invalid {kind} carrier span")
|
||||||
yield kind, loop_span["start"]
|
yield kind, loop_span["start"]
|
||||||
elif kind not in ("assign", "expression", "return"):
|
|
||||||
raise SystemExit(f"unsupported statement kind {kind}")
|
|
||||||
|
|
||||||
|
|
||||||
if sys.argv[2:] not in ([], ["--require-transfers"]) or len(sys.argv) < 2:
|
def main(argv):
|
||||||
raise SystemExit("usage: analysis_consumer.py ANALYSIS.json [--require-transfers]")
|
if len(argv) not in (2, 3) or (len(argv) == 3 and argv[2] != "--require-transfers"):
|
||||||
|
raise SystemExit(
|
||||||
|
"usage: analysis_consumer.py ANALYSIS.json [--require-transfers]"
|
||||||
|
)
|
||||||
|
with open(argv[1], encoding="utf-8") as handle:
|
||||||
|
analysis = json.load(handle)
|
||||||
|
validate(analysis)
|
||||||
|
transfers = []
|
||||||
|
functions = 0
|
||||||
|
for module in analysis["modules"]:
|
||||||
|
for function in module["functions"]:
|
||||||
|
functions += 1
|
||||||
|
transfers.extend(visit_transfers(function["body"]))
|
||||||
|
if len(argv) == 3 and not transfers:
|
||||||
|
raise SystemExit("missing loop transfers")
|
||||||
|
print(f"functions={functions}")
|
||||||
|
print(f"transfers={len(transfers)}")
|
||||||
|
|
||||||
with open(sys.argv[1], encoding="utf-8") as handle:
|
|
||||||
analysis = json.load(handle)
|
|
||||||
|
|
||||||
if analysis.get("schema") != "marqdo.analysis":
|
if __name__ == "__main__":
|
||||||
raise SystemExit("unexpected schema")
|
main(sys.argv)
|
||||||
if analysis.get("schema_version") != 3:
|
|
||||||
raise SystemExit("unsupported schema_version")
|
|
||||||
|
|
||||||
project = analysis["project"]
|
|
||||||
if project.get("identity_kind") not in ("manifest", "workspace_snapshot"):
|
|
||||||
raise SystemExit("bad project identity")
|
|
||||||
if not isinstance(project.get("root_id"), str) or not project["root_id"]:
|
|
||||||
raise SystemExit("bad root_id")
|
|
||||||
|
|
||||||
functions = []
|
|
||||||
transfers = []
|
|
||||||
for module in analysis["modules"]:
|
|
||||||
module_id = module["id"]
|
|
||||||
if "::" not in module_id or not module_id.startswith(("root:", "dep:", "std:")):
|
|
||||||
raise SystemExit("unexpected module identity")
|
|
||||||
if not isinstance(module["source_digest"], str) or len(module["source_digest"]) != 64:
|
|
||||||
raise SystemExit("bad source digest")
|
|
||||||
resources = module.get("resources")
|
|
||||||
if not isinstance(resources, list):
|
|
||||||
raise SystemExit("resources must be an array")
|
|
||||||
seen = set()
|
|
||||||
for resource in resources:
|
|
||||||
if resource.get("id") in seen:
|
|
||||||
raise SystemExit("duplicate resource id")
|
|
||||||
seen.add(resource.get("id"))
|
|
||||||
if resource.get("kind") not in ("formula", "code"):
|
|
||||||
raise SystemExit("unknown resource kind")
|
|
||||||
if resource.get("module_id") != module["id"]:
|
|
||||||
raise SystemExit("resource module mismatch")
|
|
||||||
if not isinstance(resource.get("content_digest"), str) or len(resource["content_digest"]) != 64:
|
|
||||||
raise SystemExit("bad resource digest")
|
|
||||||
span = resource.get("span") or {}
|
|
||||||
if not isinstance(span.get("start"), int) or not isinstance(span.get("end"), int):
|
|
||||||
raise SystemExit("bad resource span")
|
|
||||||
for function in module["functions"]:
|
|
||||||
transfers.extend(visit(function["body"]))
|
|
||||||
functions.append(function["id"])
|
|
||||||
|
|
||||||
if not functions:
|
|
||||||
raise SystemExit("no functions")
|
|
||||||
print("functions=" + str(len(functions)))
|
|
||||||
|
|
||||||
if len(sys.argv) == 3 and not transfers:
|
|
||||||
raise SystemExit("missing loop transfers")
|
|
||||||
print(f"transfers={len(transfers)}")
|
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Knowledge-like independent consumer of several explicit program entries.
|
||||||
|
|
||||||
|
Each entry is a separate `marqdo check --emit` artifact with its own project
|
||||||
|
snapshot. This fixture deduplicates modules by canonical id plus source digest,
|
||||||
|
keeps the real entry context, and reports links the loaded catalog did not
|
||||||
|
verify. It never scans a directory and never asks the CLI to build a combined
|
||||||
|
program.
|
||||||
|
|
||||||
|
usage: knowledge_consumer.py ANALYSIS...
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv):
|
||||||
|
if len(argv) < 2:
|
||||||
|
raise SystemExit("usage: knowledge_consumer.py ANALYSIS...")
|
||||||
|
entries = 0
|
||||||
|
modules = {}
|
||||||
|
unverified = 0
|
||||||
|
projects = set()
|
||||||
|
for path in argv[1:]:
|
||||||
|
with open(path, encoding="utf-8") as handle:
|
||||||
|
analysis = json.load(handle)
|
||||||
|
if analysis.get("schema") != "marqdo.analysis":
|
||||||
|
raise SystemExit(f"knowledge: unexpected schema in {path}")
|
||||||
|
project = analysis["project"]
|
||||||
|
project_key = (
|
||||||
|
project["root_id"],
|
||||||
|
project["entry_module_id"],
|
||||||
|
project.get("manifest_digest", ""),
|
||||||
|
project.get("lock_digest", ""),
|
||||||
|
)
|
||||||
|
if project_key in projects:
|
||||||
|
raise SystemExit("knowledge: duplicate entry contribution")
|
||||||
|
projects.add(project_key)
|
||||||
|
entries += 1
|
||||||
|
module_ids = {module["id"] for module in analysis["modules"]}
|
||||||
|
if project["entry_module_id"] not in module_ids:
|
||||||
|
raise SystemExit("knowledge: entry is not in modules")
|
||||||
|
for module in analysis["modules"]:
|
||||||
|
key = (module["id"], module["source_digest"])
|
||||||
|
existing = modules.get(key)
|
||||||
|
if existing is not None and existing != module["source"]:
|
||||||
|
raise SystemExit("knowledge: same id/digest carries different source")
|
||||||
|
modules[key] = module["source"]
|
||||||
|
for reference in module["references"]:
|
||||||
|
if reference["state"] == "not_loaded":
|
||||||
|
unverified += 1
|
||||||
|
print(f"knowledge: entries={entries} modules={len(modules)}")
|
||||||
|
print(f"knowledge: not_loaded={unverified}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main(sys.argv))
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Lint-like independent consumer of public references and diagnostics.
|
||||||
|
|
||||||
|
Reports unresolved/ambiguous/out-of-scope links with their exact module and
|
||||||
|
source span. It never reads a private AST/IR and never fixes a reference.
|
||||||
|
|
||||||
|
usage: lint_consumer.py ANALYSIS.json
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
def line_col(source, span):
|
||||||
|
prefix = source.encode("utf-8")[: span["start"]].decode("utf-8")
|
||||||
|
line = prefix.count("\n") + 1
|
||||||
|
column = len(prefix.rsplit("\n", 1)[-1]) + 1
|
||||||
|
return line, column
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv):
|
||||||
|
if len(argv) != 2:
|
||||||
|
raise SystemExit("usage: lint_consumer.py ANALYSIS.json")
|
||||||
|
with open(argv[1], encoding="utf-8") as handle:
|
||||||
|
analysis = json.load(handle)
|
||||||
|
if analysis.get("schema") != "marqdo.analysis":
|
||||||
|
raise SystemExit("lint: unexpected analysis schema")
|
||||||
|
modules = {module["id"]: module for module in analysis["modules"]}
|
||||||
|
problems = 0
|
||||||
|
for module in analysis["modules"]:
|
||||||
|
source = module["source"]
|
||||||
|
for reference in module["references"]:
|
||||||
|
state = reference["state"]
|
||||||
|
if state in ("resolved", "external"):
|
||||||
|
continue
|
||||||
|
line, column = line_col(source, reference["span"])
|
||||||
|
print(
|
||||||
|
f"lint: {reference['url']} state={state} "
|
||||||
|
f"{module['relative_path']}:{line}:{column}"
|
||||||
|
)
|
||||||
|
if state in ("ambiguous",):
|
||||||
|
print("lint: candidates=" + ",".join(reference["candidates"]))
|
||||||
|
problems += 1
|
||||||
|
for diagnostic in analysis["diagnostics"]:
|
||||||
|
if diagnostic["severity"] != "error":
|
||||||
|
continue
|
||||||
|
raise SystemExit(
|
||||||
|
"lint: a successful artifact must not contain an error diagnostic"
|
||||||
|
)
|
||||||
|
for diagnostic in analysis["diagnostics"]:
|
||||||
|
module = modules[diagnostic["module"]]
|
||||||
|
span = diagnostic["span"]
|
||||||
|
location = module["relative_path"]
|
||||||
|
if span is not None:
|
||||||
|
line, column = line_col(module["source"], span)
|
||||||
|
location = f"{location}:{line}:{column}"
|
||||||
|
print(f"lint: {diagnostic['code']} {location}")
|
||||||
|
print(f"lint: unresolved={problems}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main(sys.argv))
|
||||||
@@ -11,6 +11,9 @@ import sys
|
|||||||
|
|
||||||
from jsonschema import Draft202012Validator
|
from jsonschema import Draft202012Validator
|
||||||
|
|
||||||
|
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||||
|
from analysis_consumer import InvalidAnalysis, validate as validate_analysis
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# jsonschema >= 4.18 resolves the external event schema through
|
# jsonschema >= 4.18 resolves the external event schema through
|
||||||
# `referencing`. The CI image may ship an older jsonschema, so keep the
|
# `referencing`. The CI image may ship an older jsonschema, so keep the
|
||||||
@@ -62,6 +65,29 @@ def require_invalid(schema_name, document, label):
|
|||||||
raise SystemExit(f"{label}: expected schema validation to fail")
|
raise SystemExit(f"{label}: expected schema validation to fail")
|
||||||
|
|
||||||
|
|
||||||
|
def semantic_error(document):
|
||||||
|
try:
|
||||||
|
validate_analysis(document)
|
||||||
|
except InvalidAnalysis as error:
|
||||||
|
return str(error)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def require_rejected(schema_name, document, label):
|
||||||
|
"""A mutation must be rejected by the schema or the semantic validator."""
|
||||||
|
schema_errors = list(validator(load_schema(schema_name)).iter_errors(document))
|
||||||
|
error = semantic_error(document)
|
||||||
|
if not schema_errors and error is None:
|
||||||
|
raise SystemExit(f"{label}: expected schema or semantic validation to fail")
|
||||||
|
|
||||||
|
|
||||||
|
def drop(document, path):
|
||||||
|
parent = document
|
||||||
|
for key in path[:-1]:
|
||||||
|
parent = parent[key]
|
||||||
|
del parent[path[-1]]
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
if len(sys.argv) != 4:
|
if len(sys.argv) != 4:
|
||||||
raise SystemExit(
|
raise SystemExit(
|
||||||
@@ -74,9 +100,38 @@ def main():
|
|||||||
|
|
||||||
analysis_schema = "analysis.schema.json"
|
analysis_schema = "analysis.schema.json"
|
||||||
require_valid(analysis_schema, analysis, "analysis")
|
require_valid(analysis_schema, analysis, "analysis")
|
||||||
|
error = semantic_error(analysis)
|
||||||
|
if error is not None:
|
||||||
|
raise SystemExit(f"analysis: semantic validation failed: {error}")
|
||||||
require_valid("observation-file.schema.json", observation, "observation")
|
require_valid("observation-file.schema.json", observation, "observation")
|
||||||
require_valid("cli-tool.schema.json", tool, "tool")
|
require_valid("cli-tool.schema.json", tool, "tool")
|
||||||
|
|
||||||
|
# V01: every newly required field is load-bearing. Removing it must be
|
||||||
|
# rejected by the current schema or the semantic validator; an old
|
||||||
|
# same-revision artifact is not accepted.
|
||||||
|
required_paths = [
|
||||||
|
["project", "entry_module_id"],
|
||||||
|
["project", "manifest_digest"],
|
||||||
|
["project", "extensions"],
|
||||||
|
["modules", 0, "source"],
|
||||||
|
["modules", 0, "document"],
|
||||||
|
["modules", 0, "anchors"],
|
||||||
|
["modules", 0, "units", 0, "path"],
|
||||||
|
["modules", 0, "units", 0, "parent_id"],
|
||||||
|
["modules", 0, "units", 0, "mode_origin"],
|
||||||
|
["modules", 0, "units", 0, "mode_source_unit_id"],
|
||||||
|
["modules", 0, "units", 0, "heading_span"],
|
||||||
|
["modules", 0, "units", 0, "span"],
|
||||||
|
["modules", 0, "functions"],
|
||||||
|
["modules", 0, "references"],
|
||||||
|
["modules", 0, "calls"],
|
||||||
|
["modules", 0, "resources"],
|
||||||
|
]
|
||||||
|
for path in required_paths:
|
||||||
|
bad = copy.deepcopy(analysis)
|
||||||
|
drop(bad, path)
|
||||||
|
require_rejected(analysis_schema, bad, "analysis missing " + "/".join(map(str, path)))
|
||||||
|
|
||||||
# Negative mutations: structure, version and traversal must fail closed.
|
# Negative mutations: structure, version and traversal must fail closed.
|
||||||
bad = copy.deepcopy(analysis)
|
bad = copy.deepcopy(analysis)
|
||||||
bad["schema_version"] = 2
|
bad["schema_version"] = 2
|
||||||
@@ -90,6 +145,81 @@ def main():
|
|||||||
bad["modules"][0]["resources"] = 3
|
bad["modules"][0]["resources"] = 3
|
||||||
require_invalid(analysis_schema, bad, "analysis resources integer")
|
require_invalid(analysis_schema, bad, "analysis resources integer")
|
||||||
|
|
||||||
|
# V02/V03: tampered digests and spans must never be accepted.
|
||||||
|
bad = copy.deepcopy(analysis)
|
||||||
|
bad["modules"][0]["source"] = bad["modules"][0]["source"] + "x"
|
||||||
|
require_rejected(analysis_schema, bad, "analysis tampered source")
|
||||||
|
|
||||||
|
bad = copy.deepcopy(analysis)
|
||||||
|
bad["modules"][0]["source_digest"] = "0" * 64
|
||||||
|
require_rejected(analysis_schema, bad, "analysis tampered source digest")
|
||||||
|
|
||||||
|
bad = copy.deepcopy(analysis)
|
||||||
|
bad["modules"][0]["document"]["span"]["end"] = 10**12
|
||||||
|
require_rejected(analysis_schema, bad, "analysis out-of-range span")
|
||||||
|
|
||||||
|
bad = copy.deepcopy(analysis)
|
||||||
|
bad["modules"].append(copy.deepcopy(bad["modules"][0]))
|
||||||
|
require_rejected(analysis_schema, bad, "analysis duplicate module id")
|
||||||
|
|
||||||
|
# V04: heading tree and ownership invariants are semantic.
|
||||||
|
units = analysis["modules"][0]["units"]
|
||||||
|
if len(units) >= 3:
|
||||||
|
bad = copy.deepcopy(analysis)
|
||||||
|
bad_units = bad["modules"][0]["units"]
|
||||||
|
bad_units[1]["parent_id"] = bad_units[2]["id"]
|
||||||
|
bad_units[2]["parent_id"] = bad_units[1]["id"]
|
||||||
|
require_rejected(analysis_schema, bad, "analysis parent cycle")
|
||||||
|
bad = copy.deepcopy(analysis)
|
||||||
|
bad["modules"][0]["units"][1]["mode_source_unit_id"] = "root:missing"
|
||||||
|
require_rejected(analysis_schema, bad, "analysis mode source outside ancestors")
|
||||||
|
|
||||||
|
# V05: call, reference and resource targets are semantic.
|
||||||
|
module = analysis["modules"][0]
|
||||||
|
function_ids = {fn["id"] for module_iter in analysis["modules"] for fn in module_iter["functions"]}
|
||||||
|
for call in module["calls"]:
|
||||||
|
if call["state"] == "function":
|
||||||
|
bad = copy.deepcopy(analysis)
|
||||||
|
for candidate in bad["modules"][0]["calls"]:
|
||||||
|
if candidate["span"] == call["span"] and candidate["function"] == call["function"]:
|
||||||
|
candidate["target"] = "root:missing::missing"
|
||||||
|
require_rejected(analysis_schema, bad, "analysis missing call target")
|
||||||
|
break
|
||||||
|
references = [ref for module_iter in analysis["modules"] for ref in module_iter["references"]]
|
||||||
|
for reference in references:
|
||||||
|
if reference["state"] == "resolved" and reference["target_unit"] is not None:
|
||||||
|
bad = copy.deepcopy(analysis)
|
||||||
|
for module_iter in bad["modules"]:
|
||||||
|
for candidate in module_iter["references"]:
|
||||||
|
if (
|
||||||
|
candidate["span"] == reference["span"]
|
||||||
|
and candidate["source"] == reference["source"]
|
||||||
|
):
|
||||||
|
candidate["target_unit"] = "root:missing#missing"
|
||||||
|
require_rejected(analysis_schema, bad, "analysis missing reference unit")
|
||||||
|
break
|
||||||
|
for resource in module["resources"]:
|
||||||
|
bad = copy.deepcopy(analysis)
|
||||||
|
bad["modules"][0]["resources"][0]["content_digest"] = "0" * 64
|
||||||
|
require_rejected(analysis_schema, bad, "analysis tampered resource digest")
|
||||||
|
break
|
||||||
|
|
||||||
|
bad = copy.deepcopy(analysis)
|
||||||
|
bad["diagnostics"].append(
|
||||||
|
{
|
||||||
|
"module": module["id"],
|
||||||
|
"relative_path": module["relative_path"],
|
||||||
|
"span": None,
|
||||||
|
"line": None,
|
||||||
|
"column": None,
|
||||||
|
"severity": "error",
|
||||||
|
"code": "test.injected",
|
||||||
|
"message": "injected error",
|
||||||
|
"hints": [],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
require_rejected(analysis_schema, bad, "analysis successful output with an error")
|
||||||
|
|
||||||
bad = copy.deepcopy(observation)
|
bad = copy.deepcopy(observation)
|
||||||
bad["events"][0]["seq"] = "zero"
|
bad["events"][0]["seq"] = "zero"
|
||||||
require_invalid("observation-file.schema.json", bad, "observation event sequence type")
|
require_invalid("observation-file.schema.json", bad, "observation event sequence type")
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""View-like independent consumer of the public Analysis artifact.
|
||||||
|
|
||||||
|
Uses only the JSON document: section ranges, source text and function headings.
|
||||||
|
Never imports a Marqdo/Rust crate and never executes the document.
|
||||||
|
|
||||||
|
usage: view_consumer.py ANALYSIS.json
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
def utf8_slice(source, span):
|
||||||
|
data = source.encode("utf-8")
|
||||||
|
return data[span["start"] : span["end"]].decode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv):
|
||||||
|
if len(argv) != 2:
|
||||||
|
raise SystemExit("usage: view_consumer.py ANALYSIS.json")
|
||||||
|
with open(argv[1], encoding="utf-8") as handle:
|
||||||
|
analysis = json.load(handle)
|
||||||
|
if analysis.get("schema") != "marqdo.analysis":
|
||||||
|
raise SystemExit("view: unexpected analysis schema")
|
||||||
|
rendered = 0
|
||||||
|
for module in analysis["modules"]:
|
||||||
|
source = module["source"]
|
||||||
|
units = module["units"]
|
||||||
|
if not units:
|
||||||
|
raise SystemExit("view: module has no units")
|
||||||
|
by_id = {unit["id"]: unit for unit in units}
|
||||||
|
for unit in units:
|
||||||
|
parent = unit.get("parent_id")
|
||||||
|
if parent is not None and parent not in by_id:
|
||||||
|
raise SystemExit("view: dangling unit parent")
|
||||||
|
if unit["span"]["start"] > unit["span"]["end"]:
|
||||||
|
raise SystemExit("view: reversed section span")
|
||||||
|
for unit in units:
|
||||||
|
if unit["kind"] != "function":
|
||||||
|
continue
|
||||||
|
section = utf8_slice(source, unit["span"])
|
||||||
|
heading = utf8_slice(source, unit["heading_span"])
|
||||||
|
if not heading.strip():
|
||||||
|
raise SystemExit("view: empty function heading")
|
||||||
|
if not section.startswith(heading):
|
||||||
|
raise SystemExit("view: function section does not start at its heading")
|
||||||
|
label = "/".join(unit["path"])
|
||||||
|
print(f"view: {module['id']}#{label} [{len(section)} bytes]")
|
||||||
|
rendered += 1
|
||||||
|
if not rendered:
|
||||||
|
raise SystemExit("view: no callable section to render")
|
||||||
|
print(f"view: rendered={rendered}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main(sys.argv))
|
||||||
Reference in new issue
Block a user