Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/patches/2eccb70d00bc405d # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aien-sovereign-core-mv#542 (code only) closed derived `2eccb70d00bc405d` #542 Imported from GitHub aien-dev/aien-sovereign-core-mv#542 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `e3b36d5869b8f10bc5a5cc2e3158afa6214512d5` · Head `217e81acb0f83ff35c08e7f3e99782e93c50b797` ### Fetch it A git bundle of the pull request's head, 34478 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/2eccb70d00bc405d.bundle -o 2eccb70d00bc405d.bundle git fetch 2eccb70d00bc405d.bundle refs/pull/542/head ``` Raw bundle · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-sovereign-core-mv 542 217e81acb0f83ff35c08e7f3e99782e93c50b797 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":542,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/542","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:26Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index f6ca8755..1fd7faf8 100644 --- a/.crumb +++ b/.crumb @@ -100,8 +100,8 @@ "purpose": "" }, { - "digest": "4696ee460c13e9a19a44104036e26407ddefd300f9d2221b4308208ba249980e", - "last_commit": "360b251", + "digest": "5f09d70a65f15a35b71b895eca7a3b1f0ce9e457906efdac9faba79a39c0d757", + "last_commit": "99914e0", "name": "scripts", "purpose": "" }, @@ -118,15 +118,15 @@ "purpose": "Local CI sandbox exec contract (C8), aien-run user/caches install, Forgejo trigger hook, health " } ], - "children_root": "sha256:ae01b8c79c2072b524de0b6d93e85a82159dee5db6884c0b703391d262e35f26", - "compiled_at": "2026-10-15T18:57:48Z", + "children_root": "sha256:28849a38a519b49ffe4a4c3a5d3af2bae3b6381f2c25e91a7fe1a485ea0d11b4", + "compiled_at": "2026-10-15T19:22:15Z", "compiler": "crumb-compile/1", - "digest": "sha256:315ffa3655495fce926f308987ad63bcdc9daaa5887b802fa079f57499f3bbef", + "digest": "sha256:60ca4e64fed54d530cb5b993a4f84fef18ed7535064da2e958ef60f07bcdc228", "evidence_files": 1473, "evidence_root": "sha256:4b50c518bd48f66d380c02c38af70107336af0c384a988a43d7c3233a0e5a95c", - "files": 5431, - "generated_at_commit": "58d1b1666c9ee89c492127c5998e57b0dace2c66", - "source_tree": "sha256:52bf329dcf226a544975e6adb96dffcc274abc386c3f5d70875d8d0ce62e96e4" + "files": 5433, + "generated_at_commit": "1787b0e4944c88cfa3c5bf56b4b2f55f3bf1a5f2", + "source_tree": "sha256:a4cc7a8a363fc12f80362f91b16284a4303521662acac5003ec7d76a1f5cf40f" } }, "history": [], diff --git a/Cargo.lock b/Cargo.lock index ffc44939..2a21d2c4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4334,6 +4334,8 @@ dependencies = [ name = "spark-harness" version = "0.1.0" dependencies = [ + "aien-proof", + "blake3", "chrono", "clap", "crumb-spec", diff --git a/crates/spark-harness/Cargo.toml b/crates/spark-harness/Cargo.toml index 3215eac5..d0a40bd2 100644 --- a/crates/spark-harness/Cargo.toml +++ b/crates/spark-harness/Cargo.toml @@ -20,6 +20,8 @@ reqwest = { version = "0.12", default-features = false, features = ["json", "rus tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } jsonschema = { version = "0.17", default-features = false } +aien-proof = { path = "../aien-proof" } +blake3 = "1.8" [[bin]] name = "spark-harness" diff --git a/crates/spark-harness/schemas/harness_change.json b/crates/spark-harness/schemas/harness_change.json index d109dc2e..4e834226 100644 --- a/crates/spark-harness/schemas/harness_change.json +++ b/crates/spark-harness/schemas/harness_change.json @@ -9,6 +9,7 @@ "why": { "type": "string", "minLength": 8 }, "replay_report": { "type": "string", "minLength": 8 }, "eval_results": { "type": "array", "minItems": 1, "items": { "type": "string", "minLength": 4 } }, - "rollback": { "type": "string", "minLength": 8 } + "rollback": { "type": "string", "minLength": 8 }, + "evidence": { "type": "array", "minItems": 1, "items": { "type": "string", "minLength": 2 } } } } diff --git a/crates/spark-harness/schemas/research_handoff.json b/crates/spark-harness/schemas/research_handoff.json index 97c56a53..5f05998b 100644 --- a/crates/spark-harness/schemas/research_handoff.json +++ b/crates/spark-harness/schemas/research_handoff.json @@ -27,6 +27,7 @@ "open_questions": { "type": "array", "items": { "type": "string" } - } + }, + "evidence": { "type": "array", "minItems": 1, "items": { "type": "string", "minLength": 2 } } } } diff --git a/crates/spark-harness/src/completion.rs b/crates/spark-harness/src/completion.rs new file mode 100644 index 00000000..e336b485 --- /dev/null +++ b/crates/spark-harness/src/completion.rs @@ -0,0 +1,891 @@ +//! Verified workflow completion (Headstart M1, issue #533). +//! +//! [`HarnessEngine::complete_verified_workflow`] is the only way a workflow +//! reaches [`DONE_STATE`]. The harness itself: +//! +//! 1. refuses to run when workflows.json or evals.json did not load cleanly; +//! 2. checks that the workflow's current state may legally move to `done`; +//! 3. validates the workflow's `required_schema` against the submitted +//! artifact and runs every `required_evals_on_done` entry on it (unknown +//! eval, missing definition, non-deterministic eval kind, missing or +//! invalid schema all count as failures); +//! 4. mints an aien-proof `EvidenceReceiptV1` from its own results (one +//! assertion per gate, artifact digest, source commit, task, workflow and +//! generation bindings) and stores it in its own store; +//! 5. records the consumed (task, generation) pair atomically, and only then +//! moves the workflow to `done`. +//! +//! The caller never supplies a receipt, a verdict or a pass flag: +//! [`CompletionSubmission`] rejects unknown fields, and any extra field in +//! the artifact is judged by the workflow schema like any other content. +//! +//! What `done` means: the completion gates passed on this artifact and a PASS +//! receipt is in the harness store. It does not mean committed. World commit +//! and authorization stay in aien-runtime and are not touched here. +//! +//! Limitations, stated plainly: +//! - EvidenceReceiptV1 is unsigned (aien-proof `evidence.rs`, `Receipt` has no +//! signature field; its ID is a BLAKE3 hash of the canonical encoding). +//! Anyone who can write to the completion store can write a receipt with a +//! matching ID. Authenticity therefore rests on store ownership (filesystem +//! trust) plus recomputation: [`verify_completion`] recomputes the receipt +//! ID and checks every binding, and a verifier holding the artifact can +//! recompute [`artifact_digest`] and rerun the gates. +//! - `source_commit` is the caller-declared revision. The harness checks its +//! format (aien-proof `check_commit`) but does not inspect a source tree, so +//! `dirty` is written as `false` meaning "no tree inspection was made", not +//! "the tree was verified clean". +//! - The tier is `HOST_TEST`: deterministic checks executed on the host, no +//! hardware and no physical qualification. +//! - If writing the consumed record fails (or the process dies) after the +//! receipt is stored, an orphan PASS receipt stays in the store and a +//! resubmission can mint another one for the same generation. The workflow +//! never moves to `done` in that case, and [`verify_completion`] accepts +//! only the receipt the consumed record names, so at most one receipt per +//! task verifies at any time. +//! - One exception to "error means nothing verifies": if the record rename +//! succeeds but the following directory fsync fails, completion returns a +//! `Store` error and the workflow is not moved to `done`, yet the record is +//! already in place and the receipt it names verifies. The rename is not +//! guaranteed durable across a power loss in that case. +//! - The consumed record is keyed by task and holds only the highest +//! completed generation. Completing a newer generation supersedes the older +//! one: its receipt stops verifying. Verification answers "is this the +//! task's current completion", which is what M2 needs. + +use crate::{HarnessEngine, WorkflowState, DONE_STATE}; +use aien_proof::evidence::{self, Assertion, Mutation, Receipt, Tier, Verdict}; +use aien_proof::lock::FileLock; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::fmt; +use std::fs; +use std::io::Write; +use std::path::{Path, PathBuf}; + +/// Receipt `kind` for harness completion receipts. +pub const COMPLETION_KIND: &str = "spark-harness-completion"; +/// Honest tier for harness completions: host-executed deterministic checks. +pub const COMPLETION_TIER: Tier = Tier::HostTest; +/// Subdirectory of the completion store holding consumed completion records. +pub const CONSUMED_DIR: &str = "completions"; +const MAX_TASK_ID_LEN: usize = 256; +const ASSERTION_SOURCE: &str = "spark-harness"; + +/// What a caller submits for completion. There is deliberately no field for +/// a receipt, verdict or pass flag; unknown fields are rejected. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CompletionSubmission { + pub task_id: String, + /// Monotonic generation of the work for this task. A completed + /// generation can never be completed again, and a lower one is stale. + pub generation: u64, + /// Source revision the artifact was produced from: 40 or 64 lowercase hex. + pub source_commit: String, + pub artifact: Value, +} + +/// Result of a successful verified completion. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct CompletionRecord { + pub receipt_id: String, + pub task_id: String, + pub workflow_id: String, + pub workflow_type: String, + pub generation: u64, + pub source_commit: String, + /// BLAKE3 hex of [`canonical_json`] of the artifact. + pub artifact_digest: String, +} + +/// Durable record of the highest completed generation for one task. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct ConsumedRecord { + task_id: String, + generation: u64, + receipt_id: String, + workflow_id: String, + artifact_digest: String, +} + +/// A completion receipt that passed [`verify_completion`]. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct VerifiedCompletion { + pub receipt_id: String, + pub task_id: String, + pub workflow_id: String, + pub generation: u64, + pub source_commit: String, + pub artifact_digest: String, +} + +/// Every way completion or verification can refuse. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CompletionError { + /// workflows.json or evals.json failed to load; nothing can complete. + DefinitionsNotLoaded(Vec), + /// Submission or request arguments are malformed. + InvalidSubmission(String), + UnknownWorkflow(String), + MalformedWorkflow(String), + /// The current state cannot legally move to `done`. + IllegalTransition { + from: String, + allowed: Vec, + }, + /// This task and generation already completed; no new receipt minted. + DuplicateCompletion { + task_id: String, + generation: u64, + receipt_id: String, + }, + /// The submitted generation is lower than the recorded one. + StaleGeneration { + task_id: String, + submitted: u64, + recorded: u64, + }, + /// At least one gate failed. A FAIL receipt was stored; state unchanged. + GatesFailed { + receipt_id: String, + failures: Vec, + }, + /// The completion store could not be read or written. + Store(String), + /// The receipt is missing, malformed or its identity does not recompute. + ReceiptInvalid(String), + /// The receipt does not carry a PASS verdict. + NotPass(String), + /// The receipt is valid but bound to something other than expected. + BindingMismatch { + field: &'static str, + expected: String, + found: String, + }, + /// The receipt is not the task's current completion per the consumed + /// record (orphan receipt, superseded generation, or no record). + NotCurrentCompletion(String), +} + +impl CompletionError { + /// Stable machine-readable name of the refusal. + pub fn kind(&self) -> &'static str { + match self { + CompletionError::DefinitionsNotLoaded(_) => "definitions_not_loaded", + CompletionError::InvalidSubmission(_) => "invalid_submission", + CompletionError::UnknownWorkflow(_) => "unknown_workflow", + CompletionError::MalformedWorkflow(_) => "malformed_workflow", + CompletionError::IllegalTransition { .. } => "illegal_transition", + CompletionError::DuplicateCompletion { .. } => "duplicate_completion", + CompletionError::StaleGeneration { .. } => "stale_generation", + CompletionError::GatesFailed { .. } => "gates_failed", + CompletionError::Store(_) => "store_error", + CompletionError::ReceiptInvalid(_) => "receipt_invalid", + CompletionError::NotPass(_) => "not_pass", + CompletionError::BindingMismatch { .. } => "binding_mismatch", + CompletionError::NotCurrentCompletion(_) => "not_current_completion", + } + } + + /// JSON-RPC error code. Invalid arguments use the standard -32602; every + /// other refusal uses the server-defined range. + pub fn rpc_code(&self) -> i64 { + match self { + CompletionError::InvalidSubmission(_) => -32602, + CompletionError::DefinitionsNotLoaded(_) => -32001, + CompletionError::UnknownWorkflow(_) => -32002, + CompletionError::MalformedWorkflow(_) => -32003, + CompletionError::IllegalTransition { .. } => -32004, + CompletionError::DuplicateCompletion { .. } => -32005, + CompletionError::StaleGeneration { .. } => -32006, + CompletionError::GatesFailed { .. } => -32007, + CompletionError::Store(_) => -32008, + CompletionError::ReceiptInvalid(_) => -32009, + CompletionError::NotPass(_) => -32010, + CompletionError::BindingMismatch { .. } => -32011, + CompletionError::NotCurrentCompletion(_) => -32012, + } + } + + /// JSON-RPC `error` object for an MCP refusal. + pub fn rpc_error(&self) -> Value { + let mut data = json!({ "kind": self.kind() }); + match self { + CompletionError::GatesFailed { + receipt_id, + failures, + } => { + data["receipt_id"] = json!(receipt_id); + data["failures"] = json!(failures); + } + CompletionError::DuplicateCompletion { receipt_id, .. } => { + data["receipt_id"] = json!(receipt_id); + } + _ => {} + } + json!({ "code": self.rpc_code(), "message": self.to_string(), "data": data }) + } +} + +impl fmt::Display for CompletionError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + CompletionError::DefinitionsNotLoaded(errs) => write!( + f, + "workflow/eval definitions did not load, completion refused: {}", + errs.join("; ") + ), + CompletionError::InvalidSubmission(m) => write!(f, "invalid submission: {m}"), + CompletionError::UnknownWorkflow(w) => write!(f, "unknown workflow type '{w}'"), + CompletionError::MalformedWorkflow(m) => write!(f, "malformed workflow: {m}"), + CompletionError::IllegalTransition { from, allowed } => write!( + f, + "state '{from}' cannot move to '{DONE_STATE}'; allowed next states: {allowed:?}" + ), + CompletionError::DuplicateCompletion { + task_id, + generation, + receipt_id, + } => write!( + f, + "task '{task_id}' generation {generation} already completed (receipt {receipt_id})" + ), + CompletionError::StaleGeneration { + task_id, + submitted, + recorded, + } => write!( + f, + "stale generation for task '{task_id}': submitted {submitted}, completed {recorded}" + ), + CompletionError::GatesFailed { + receipt_id, + failures, + } => write!( + f, + "completion gates failed (FAIL receipt {receipt_id}): {}", + failures.join("; ") + ), + CompletionError::Store(m) => write!(f, "completion store error: {m}"), + CompletionError::ReceiptInvalid(m) => write!(f, "receipt invalid: {m}"), + CompletionError::NotPass(m) => write!(f, "receipt is not a PASS: {m}"), + CompletionError::NotCurrentCompletion(m) => { + write!(f, "receipt is not the current completion: {m}") + } + CompletionError::BindingMismatch { + field, + expected, + found, + } => write!( + f, + "receipt binding '{field}' mismatch: expected {expected:?}, found {found:?}" + ), + } + } +} + +impl std::error::Error for CompletionError {} + +/// Canonical JSON encoding used for the artifact digest: object keys sorted +/// by byte order at every level, no whitespace, arrays in order, scalars as +/// serde_json prints them. Keys are sorted here explicitly, so the digest +/// does not depend on whether serde_json's `preserve_order` feature is on. +pub fn canonical_json(v: &Value) -> Vec { + let mut out = Vec::new(); + write_canonical(v, &mut out); + out +} + +fn write_canonical(v: &Value, out: &mut Vec) { + match v { + Value::Array(items) => { + out.push(b'['); + for (i, item) in items.iter().enumerate() { + if i > 0 { + out.push(b','); + } + write_canonical(item, out); + } + out.push(b']'); + } + Value::Object(map) => { + let mut keys: Vec<&String> = map.keys().collect(); + keys.sort(); + out.push(b'{'); + for (i, k) in keys.iter().enumerate() { + if i > 0 { + out.push(b','); + } + // Serializing a string or scalar Value cannot fail. + out.extend_from_slice(serde_json::to_string(k).unwrap_or_default().as_bytes()); + out.push(b':'); + write_canonical(&map[k.as_str()], out); + } + out.push(b'}'); + } + scalar => { + out.extend_from_slice(serde_json::to_string(scalar).unwrap_or_default().as_bytes()) + } + } +} + +/// BLAKE3 hex digest of [`canonical_json`] of the artifact. +pub fn artifact_digest(artifact: &Value) -> String { + blake3::hash(&canonical_json(artifact)).to_hex().to_string() +} + +/// File name key for a task's consumed record (task IDs are free text). +fn task_key(task_id: &str) -> String { + let mut h = blake3::Hasher::new(); + h.update(b"spark-harness-task\0"); + h.update(task_id.as_bytes()); + h.finalize().to_hex().to_string() +} + +fn check_identifier(what: &str, value: &str) -> Result<(), CompletionError> { + if value.is_empty() || value.trim() != value { + return Err(CompletionError::InvalidSubmission(format!( + "{what} must be non-empty with no leading or trailing whitespace" + ))); + } + if value.len() > MAX_TASK_ID_LEN || value.chars().any(char::is_control) { + return Err(CompletionError::InvalidSubmission(format!( + "{what} must be at most {MAX_TASK_ID_LEN} bytes with no control characters" + ))); + } + Ok(()) +} + +fn collect_strings<'a>(v: &'a Value, path: String, out: &mut Vec<(String, &'a str)>) { + match v { + Value::String(s) => out.push((path, s)), + Value::Array(items) => { + for (i, item) in items.iter().enumerate() { + collect_strings(item, format!("{path}/{i}"), out); + } + } + Value::Object(map) => { + for (k, item) in map { + collect_strings(item, format!("{path}/{k}"), out); + } + } + _ => {} + } +} + +fn host_identity() -> String { + let from_proc = fs::read_to_string("/proc/sys/kernel/hostname") + .map(|s| s.trim().to_string()) + .unwrap_or_default(); + if !from_proc.is_empty() { + return from_proc; + } + std::env::var("HOSTNAME") + .ok() + .filter(|s| !s.trim().is_empty()) + .unwrap_or_else(|| "unknown-host".to_string()) +} + +fn read_consumed(path: &Path, task_id: &str) -> Result, CompletionError> { + let bytes = match fs::read(path) { + Ok(b) => b, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => { + return Err(CompletionError::Store(format!( + "cannot read consumed record {}: {e}", + path.display() + ))) + } + }; + let rec: ConsumedRecord = serde_json::from_slice(&bytes).map_err(|e| { + CompletionError::Store(format!( + "consumed record {} is malformed, refusing: {e}", + path.display() + )) + })?; + if rec.task_id != task_id { + return Err(CompletionError::Store(format!( + "consumed record {} belongs to task '{}', not '{task_id}'", + path.display(), + rec.task_id + ))); + } + Ok(Some(rec)) +} + +/// Write temp file, fsync, rename over the target, fsync the directory. +/// +/// Known edge: if the rename succeeds but the directory fsync fails, this +/// returns `Store` and the workflow stays un-done, yet the new record is +/// already in place, so the just-minted receipt verifies (the rename may +/// still be lost on power failure). A resubmission of the same generation +/// is then refused as a duplicate. +fn write_consumed(path: &Path, rec: &ConsumedRecord) -> Result<(), CompletionError> { + let store_err = |e: String| CompletionError::Store(e); + let dir = path + .parent() + .ok_or_else(|| store_err("consumed record has no parent dir".to_string()))?; + let name = path + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let tmp = dir.join(format!( + ".{name}.tmp-{}-{}", + std::process::id(), + uuid::Uuid::new_v4() + )); + let text = serde_json::to_vec_pretty(rec).map_err(|e| store_err(e.to_string()))?; + let result = (|| -> std::io::Result<()> { + let mut f = fs::File::create(&tmp)?; + f.write_all(&text)?; + f.write_all(b"\n")?; + f.sync_all()?; + fs::rename(&tmp, path)?; + fs::File::open(dir)?.sync_all() + })(); + if let Err(e) = result { + let _ = fs::remove_file(&tmp); + return Err(store_err(format!( + "cannot write consumed record {}: {e}", + path.display() + ))); + } + Ok(()) +} + +fn failed_assertion(id: String, expected: &str, observed: String) -> Assertion { + Assertion { + id, + expected: expected.to_string(), + observed, + pass: false, + source: ASSERTION_SOURCE.to_string(), + note: String::new(), + } +} + +impl HarnessEngine { + fn consumed_dir(&self) -> PathBuf { + self.completion_store.join(CONSUMED_DIR) + } + + /// Run the schema gate and every `required_evals_on_done` entry on the + /// artifact. Returns one assertion per gate; never short-circuits. + fn evaluate_gates(&self, wf_def: &Value, artifact: &Value) -> Vec { + let mut out = Vec::new(); + // validate_workflow_def already guaranteed these shapes. + let schema = wf_def["required_schema"].as_str().unwrap_or_default(); + let schema_id = format!("schema:{schema}"); + let expected = "artifact valid against the workflow schema"; + out.push(match self.validate_schema(schema, artifact) { + Ok(()) => Assertion { + id: schema_id, + expected: expected.to_string(), + observed: "valid".to_string(), + pass: true, + source: ASSERTION_SOURCE.to_string(), + note: String::new(), + }, + Err(e) => failed_assertion(schema_id, expected, e), + }); + let evals = wf_def["required_evals_on_done"] + .as_array() + .cloned() + .unwrap_or_default(); + for name in evals.iter().filter_map(Value::as_str) { + out.push(self.completion_eval(name, artifact)); + } + out + } + + /// One eval as a completion gate. Fail closed on a missing definition, + /// a non-deterministic kind, or a name the harness cannot execute. + fn completion_eval(&self, name: &str, artifact: &Value) -> Assertion { + let id = format!("eval:{name}"); + let expected = "eval passes"; + let Some(def) = self.evals.get(name) else { + return failed_assertion(id, expected, "no definition in evals.json".to_string()); + }; + let kind = def.get("kind").and_then(Value::as_str).unwrap_or(""); + if kind != "deterministic" { + return failed_assertion( + id, + expected, + format!("eval kind '{kind}' cannot gate completion; only deterministic evals run in the harness"), + ); + } + let (passed, reason) = if name == "slop_gate" { + // `run_eval("slop_gate")` reads only a top-level `text` field, + // which no completion schema declares, so on its own it would + // pass every artifact. As a completion gate it scans every string + // value in the artifact instead. + let mut strings = Vec::new(); + collect_strings(artifact, String::new(), &mut strings); + match strings + .iter() + .find_map(|(p, s)| crate::slop_violation(s).map(|r| format!("at '{p}': {r}"))) + { + Some(r) => (false, r), + None => (true, format!("{} string value(s) clean", strings.len())), + } + } else { + let r = self.run_eval(name, artifact); + (r.passed, r.reason) + }; + Assertion { + id, + expected: expected.to_string(), + observed: reason, + pass: passed, + source: ASSERTION_SOURCE.to_string(), + note: String::new(), + } + } + + fn mint_receipt( + &self, + wf: &WorkflowState, + wf_def: &Value, + sub: &CompletionSubmission, + digest: &str, + assertions: Vec, + ) -> Result { + let result = if assertions.iter().all(|a| a.pass) { + Verdict::Pass + } else { + Verdict::Fail + }; + let assertion_bytes = + serde_json::to_vec(&assertions).map_err(|e| CompletionError::Store(e.to_string()))?; + let repo = if self.completion_repo.trim().is_empty() { + crate::UNSPECIFIED_REPO.to_string() + } else { + self.completion_repo.clone() + }; + let mut r = Receipt { + schema: evidence::SCHEMA.to_string(), + version: evidence::SCHEMA_VERSION, + id: String::new(), + kind: COMPLETION_KIND.to_string(), + tier: COMPLETION_TIER, + result, + timestamp: (self.completion_clock)(), + repo, + commit: sub.source_commit.clone(), + dirty: false, + toolchain: format!("spark-harness {}", env!("CARGO_PKG_VERSION")), + procedure: format!( + "spark-harness complete_verified_workflow workflow_type={}", + wf.workflow_type + ), + machine: host_identity(), + env_class: COMPLETION_TIER.as_str().to_string(), + // The gate definition that was applied. + input_artifacts: vec![format!("blake3:{}", artifact_digest(wf_def))], + output_artifacts: vec![format!("blake3:{digest}")], + assertions, + dependencies: Vec::new(), + declared_mutation: Mutation::None, + observed_mutation: Mutation::None, + authority: String::new(), + output_digest: blake3::hash(&assertion_bytes).to_hex().to_string(), + external_refs: vec![ + format!("task:{}", sub.task_id), + format!("workflow:{}", wf.id), + format!("generation:{}", sub.generation), + ], + ledger: None, + lease: None, + required_features: Vec::new(), + reserved: String::new(), + }; + r.id = evidence::receipt_id(&r).map_err(CompletionError::Store)?; + Ok(r) + } + + /// The only path into `done`. See the module docs for the full contract. + pub fn complete_verified_workflow( + &self, + wf: &mut WorkflowState, + sub: &CompletionSubmission, + ) -> Result { + if !self.load_errors.is_empty() { + return Err(CompletionError::DefinitionsNotLoaded( + self.load_errors.clone(), + )); + } + check_identifier("task_id", &sub.task_id)?; + check_identifier("workflow id", &wf.id)?; + evidence::check_commit(&sub.source_commit).map_err(CompletionError::InvalidSubmission)?; + + let wf_def = self + .workflows + .get(&wf.workflow_type) + .ok_or_else(|| CompletionError::UnknownWorkflow(wf.workflow_type.clone()))?; + crate::validate_workflow_def(&wf.workflow_type, wf_def) + .map_err(CompletionError::MalformedWorkflow)?; + let allowed: Vec = wf_def["states"] + .get(&wf.current_state) + .and_then(|s| s.get("next")) + .and_then(Value::as_array) + .map(|a| { + a.iter() + .filter_map(Value::as_str) + .map(str::to_string) + .collect() + }) + .unwrap_or_default(); + if !allowed.iter().any(|s| s == DONE_STATE) { + return Err(CompletionError::IllegalTransition { + from: wf.current_state.clone(), + allowed, + }); + } + + let consumed_dir = self.consumed_dir(); + fs::create_dir_all(&consumed_dir).map_err(|e| { + CompletionError::Store(format!("cannot create {}: {e}", consumed_dir.display())) + })?; + // Serializes completions across threads and processes sharing this + // store. flock is released by the kernel if the holder dies. + let _lock = FileLock::acquire(&consumed_dir.join(".lock")) + .map_err(|e| CompletionError::Store(format!("cannot lock completion store: {e}")))?; + let record_path = consumed_dir.join(format!("{}.json", task_key(&sub.task_id))); + if let Some(prev) = read_consumed(&record_path, &sub.task_id)? { + if sub.generation == prev.generation { + return Err(CompletionError::DuplicateCompletion { + task_id: sub.task_id.clone(), + generation: sub.generation, + receipt_id: prev.receipt_id, + }); + } + if sub.generation < prev.generation { + return Err(CompletionError::StaleGeneration { + task_id: sub.task_id.clone(), + submitted: sub.generation, + recorded: prev.generation, + }); + } + } + + let assertions = self.evaluate_gates(wf_def, &sub.artifact); + let failures: Vec = assertions + .iter() + .filter(|a| !a.pass) + .map(|a| format!("{}: {}", a.id, a.observed)) + .collect(); + let digest = artifact_digest(&sub.artifact); + let receipt = self.mint_receipt(wf, wf_def, sub, &digest, assertions)?; + let receipt_id = evidence::store_receipt(&self.completion_store, &receipt) + .map_err(CompletionError::Store)?; + if receipt.result != Verdict::Pass { + return Err(CompletionError::GatesFailed { + receipt_id, + failures, + }); + } + + write_consumed( + &record_path, + &ConsumedRecord { + task_id: sub.task_id.clone(), + generation: sub.generation, + receipt_id: receipt_id.clone(), + workflow_id: wf.id.clone(), + artifact_digest: digest.clone(), + }, + )?; + wf.history.push(wf.current_state.clone()); + wf.current_state = DONE_STATE.to_string(); + Ok(CompletionRecord { + receipt_id, + task_id: sub.task_id.clone(), + workflow_id: wf.id.clone(), + workflow_type: wf.workflow_type.clone(), + generation: sub.generation, + source_commit: sub.source_commit.clone(), + artifact_digest: digest, + }) + } + + /// MCP `harness_complete` adapter. Arguments: + /// `{ "workflow": WorkflowState, "submission": CompletionSubmission }`. + /// The MCP server holds no workflow state, so `workflow.current_state` is + /// caller-declared there; the binding proof is the stored receipt and the + /// consumed record, both written only by the harness. + pub fn handle_complete_request(&self, args: &Value) -> Result { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct CompleteArgs { + workflow: WorkflowState, + submission: CompletionSubmission, + } + let parsed: CompleteArgs = serde_json::from_value(args.clone()).map_err(|e| { + CompletionError::InvalidSubmission(format!("harness_complete arguments: {e}")) + })?; + let mut wf = parsed.workflow; + let record = self.complete_verified_workflow(&mut wf, &parsed.submission)?; + Ok(json!({ "record": record, "workflow": wf })) + } +} + +fn single_ref<'a>(refs: &'a [String], prefix: &str) -> Result<&'a str, CompletionError> { + let found: Vec<&str> = refs.iter().filter_map(|r| r.strip_prefix(prefix)).collect(); + match found.as_slice() { + [one] => Ok(one), + _ => Err(CompletionError::ReceiptInvalid(format!( + "expected exactly one '{prefix}' external ref, found {}", + found.len() + ))), + } +} + +fn require(field: &'static str, expected: &str, found: &str) -> Result<(), CompletionError> { + if expected == found { + Ok(()) + } else { + Err(CompletionError::BindingMismatch { + field, + expected: expected.to_string(), + found: found.to_string(), + }) + } +} + +/// Check that `receipt_id` in `store` is a PASS harness completion receipt +/// bound to exactly this task, generation, source commit and artifact digest +/// (bare BLAKE3 hex or `blake3:`), and that it is the task's current +/// completion: the consumed record must name this receipt, generation and +/// digest. Superseded generations and orphan receipts fail. Identity is +/// recomputed by aien-proof; see the module docs for what that does and does +/// not prove. +pub fn verify_completion( + store: &Path, + receipt_id: &str, + task_id: &str, + generation: u64, + commit: &str, + artifact_digest: &str, +) -> Result { + let receipt = + evidence::load_receipt(store, receipt_id).map_err(CompletionError::ReceiptInvalid)?; + // load_receipt checks identity but discards the consistency report, so + // re-read the same file and take the report from verify_bytes. + let path = store + .join(evidence::RECEIPT_DIR) + .join(format!("{}.json", receipt.id)); + let bytes = fs::read(&path) + .map_err(|e| CompletionError::ReceiptInvalid(format!("{}: {e}", path.display())))?; + let (again, report) = + evidence::verify_bytes(&bytes).map_err(CompletionError::ReceiptInvalid)?; + if again != receipt { + return Err(CompletionError::ReceiptInvalid( + "receipt file changed while being verified".to_string(), + )); + } + if receipt.result != Verdict::Pass || !report.ok() { + return Err(CompletionError::NotPass(format!( + "{} ({})", + receipt.result.as_str(), + report.reasons.join("; ") + ))); + } + require("kind", COMPLETION_KIND, &receipt.kind)?; + require("tier", COMPLETION_TIER.as_str(), receipt.tier.as_str())?; + if !receipt + .assertions + .iter() + .any(|a| a.id.starts_with("schema:")) + { + return Err(CompletionError::ReceiptInvalid( + "completion receipt carries no schema assertion".to_string(), + )); + } + require("commit", commit, &receipt.commit)?; + let want_digest = artifact_digest + .strip_prefix("blake3:") + .unwrap_or(artifact_digest); + let want = format!("blake3:{}", want_digest.to_ascii_lowercase()); + let found = receipt.output_artifacts.join(","); + require("artifact_digest", &want, &found)?; + let found_task = single_ref(&receipt.external_refs, "task:")?; + require("task", task_id, found_task)?; + let found_gen = single_ref(&receipt.external_refs, "generation:")?; + require("generation", &generation.to_string(), found_gen)?; + let workflow_id = single_ref(&receipt.external_refs, "workflow:")?; + // The consumed record is the authority on which receipt is the accepted + // completion. A PASS receipt it does not name (an orphan left by a failed + // record write, or a superseded generation) never verifies. + let digest_hex = want_digest.to_ascii_lowercase(); + let record_path = store + .join(CONSUMED_DIR) + .join(format!("{}.json", task_key(task_id))); + let current = read_consumed(&record_path, task_id)?.ok_or_else(|| { + CompletionError::NotCurrentCompletion(format!( + "no consumed completion record for task '{task_id}'; receipt {} is an orphan", + receipt.id + )) + })?; + if current.receipt_id != receipt.id + || current.generation != generation + || current.artifact_digest != digest_hex + { + return Err(CompletionError::NotCurrentCompletion(format!( + "task '{task_id}' current completion is generation {} receipt {} digest {}; \ + receipt {} generation {generation} digest {digest_hex} is not it", + current.generation, current.receipt_id, current.artifact_digest, receipt.id + ))); + } + Ok(VerifiedCompletion { + receipt_id: receipt.id.clone(), + task_id: task_id.to_string(), + workflow_id: workflow_id.to_string(), + generation, + source_commit: receipt.commit.clone(), + artifact_digest: digest_hex, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn canonical_json_sorts_keys_at_every_level() { + let a = json!({"b": 1, "a": {"y": [1, {"d": true, "c": null}], "x": "s"}}); + assert_eq!( + canonical_json(&a), + br#"{"a":{"x":"s","y":[1,{"c":null,"d":true}]},"b":1}"#.to_vec() + ); + let b: Value = + serde_json::from_str(r#"{"a":{"y":[1,{"c":null,"d":true}],"x":"s"},"b":1}"#).unwrap(); + assert_eq!(artifact_digest(&a), artifact_digest(&b)); + assert_ne!(artifact_digest(&a), artifact_digest(&json!({"b": 2}))); + } + + #[test] + fn task_key_is_stable_and_distinct() { + assert_eq!(task_key("t1"), task_key("t1")); + assert_ne!(task_key("t1"), task_key("t2")); + assert_eq!(task_key("../etc").len(), 64); + } + + #[test] + fn identifiers_are_checked() { + assert!(check_identifier("task_id", "task-1").is_ok()); + assert!(check_identifier("task_id", "").is_err()); + assert!(check_identifier("task_id", " task").is_err()); + assert!(check_identifier("task_id", "a\nb").is_err()); + assert!(check_identifier("task_id", &"x".repeat(MAX_TASK_ID_LEN + 1)).is_err()); + } + + #[test] + fn single_ref_requires_exactly_one() { + let refs = vec!["task:a".to_string(), "task:b".to_string()]; + assert!(single_ref(&refs, "task:").is_err()); + assert!(single_ref(&refs, "generation:").is_err()); + assert_eq!(single_ref(&refs[..1], "task:").unwrap(), "a"); + } +} diff --git a/crates/spark-harness/src/lib.rs b/crates/spark-harness/src/lib.rs index e7e0677f..d187562d 100644 --- a/crates/spark-harness/src/lib.rs +++ b/crates/spark-harness/src/lib.rs @@ -4,6 +4,160 @@ use serde_json::{json, Value}; use std::collections::HashMap; use std::path::{Path, PathBuf}; +pub mod completion; + +/// The terminal workflow state. Since Headstart M1 (#533) it is reachable +/// only through [`HarnessEngine::complete_verified_workflow`], never through +/// [`HarnessEngine::advance_workflow`]. `done` means "the harness ran the +/// workflow's completion gates on the submitted artifact and stored a PASS +/// receipt". It does not mean committed: World commit and authorization stay +/// in aien-runtime and are not touched by this crate. +pub const DONE_STATE: &str = "done"; + +/// Default subdirectory of `base_path` holding the harness-owned completion +/// store (receipts plus consumed completion records). +pub const DEFAULT_COMPLETION_STORE: &str = "completion-store"; + +/// Repo label written into completion receipts when the deployer has not set +/// one. The harness does not know which repository a submitted commit lives +/// in, so it says so instead of guessing. +pub const UNSPECIFIED_REPO: &str = "unspecified"; + +/// Slop scan shared by `run_eval("slop_gate")` and the completion gate. +/// Returns the failure reason, or `None` when the text is clean. +pub(crate) fn slop_violation(text: &str) -> Option { + let lower = text.to_lowercase(); + + // Disallowed phrases + let forbidden = [ + "this is the part where", + "the part everyone's missing", + "the part everyone is missing", + "in today's fast-paced", + "game-changer", + "delve into", + "unlock the power", + "at the end of the day", + "it is important to note", + "in conclusion,", + ]; + + for p in forbidden { + if lower.contains(p) { + return Some(format!("Forbidden AI trope detected: '{}'", p)); + } + } + + // Check antithesis pattern: "not X, it's Y" + let antithesis_re = Regex::new(r"(?i)\bnot\s+([a-z0-9_\-\s]+),\s*(it's|it\s+is)\s+").unwrap(); + if antithesis_re.is_match(&lower) { + return Some("Formulaic antithesis trope detected ('not X, it's Y')".to_string()); + } + None +} + +fn read_definition_file(path: &Path) -> Result, String> { + let content = std::fs::read_to_string(path) + .map_err(|e| format!("cannot read {}: {}", path.display(), e))?; + serde_json::from_str::>(&content) + .map_err(|e| format!("invalid JSON object in {}: {}", path.display(), e)) +} + +/// Structural check of one workflow definition. Used at load time and again +/// at completion time, because `workflows` is a public map callers can edit. +pub fn validate_workflow_def(name: &str, def: &Value) -> Result<(), String> { + let states = def + .get("states") + .and_then(|v| v.as_object()) + .ok_or_else(|| format!("workflow '{}': 'states' must be an object", name))?; + for (state, sdef) in states { + let next = sdef.get("next").and_then(|v| v.as_array()).ok_or_else(|| { + format!( + "workflow '{}': state '{}' needs a 'next' array", + name, state + ) + })?; + for n in next { + let n = n.as_str().ok_or_else(|| { + format!( + "workflow '{}': state '{}' has a non-string next entry", + name, state + ) + })?; + if !states.contains_key(n) { + return Err(format!( + "workflow '{}': state '{}' points to undeclared state '{}'", + name, state, n + )); + } + } + } + if let Some(initial) = def.get("initial") { + let initial = initial + .as_str() + .ok_or_else(|| format!("workflow '{}': 'initial' must be a string", name))?; + if !states.contains_key(initial) { + return Err(format!( + "workflow '{}': initial state '{}' is not declared", + name, initial + )); + } + } + def.get("required_schema") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + .ok_or_else(|| { + format!( + "workflow '{}': 'required_schema' must be a non-empty string", + name + ) + })?; + let evals = def + .get("required_evals_on_done") + .and_then(|v| v.as_array()) + .ok_or_else(|| { + format!( + "workflow '{}': 'required_evals_on_done' must be an array", + name + ) + })?; + let mut seen = std::collections::BTreeSet::new(); + for e in evals { + let e = e + .as_str() + .filter(|s| !s.is_empty()) + .ok_or_else(|| format!("workflow '{}': eval names must be non-empty strings", name))?; + if !seen.insert(e) { + return Err(format!("workflow '{}': eval '{}' listed twice", name, e)); + } + } + Ok(()) +} + +fn validate_eval_def(name: &str, def: &Value) -> Result<(), String> { + def.get("kind") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + .map(|_| ()) + .ok_or_else(|| format!("eval '{}': 'kind' must be a non-empty string", name)) +} + +fn load_evals(base: &Path) -> Result, String> { + let m = read_definition_file(&base.join("evals.json"))?; + for (k, v) in &m { + validate_eval_def(k, v)?; + } + Ok(m) +} + +fn load_workflows(base: &Path) -> Result, String> { + let m = read_definition_file(&base.join("workflows.json"))?; + for (k, v) in &m { + validate_workflow_def(k, v)?; + } + Ok(m) +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct EvalResult { pub name: String, @@ -25,33 +179,70 @@ pub struct HarnessEngine { pub base_path: PathBuf, pub evals: HashMap, pub workflows: HashMap, + /// Errors from the last definition load. The verified completion API + /// refuses to run while this is non-empty, so a missing or broken + /// workflows.json or evals.json can never let a completion through. + pub load_errors: Vec, + /// Harness-owned evidence store for completion receipts and consumed + /// completion records. Defaults to `/completion-store`. + pub completion_store: PathBuf, + /// Repo identity recorded in completion receipts. + pub completion_repo: String, + /// Unix-seconds clock for receipt timestamps. Defaults to the system + /// clock; tests swap it to make receipt IDs deterministic. + pub completion_clock: fn() -> u64, +} + +/// System clock in Unix seconds (0 if the clock is before the epoch). +pub fn system_clock_secs() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) } impl HarnessEngine { + /// Compatibility constructor. Loads what it can, as before, but records + /// every load error in `load_errors` so the verified completion API + /// refuses to run on missing or broken definitions. pub fn new>(base_path: P) -> Self { let base = base_path.as_ref().to_path_buf(); let mut engine = Self { + completion_store: base.join(DEFAULT_COMPLETION_STORE), base_path: base, evals: HashMap::new(), workflows: HashMap::new(), + load_errors: Vec::new(), + completion_repo: UNSPECIFIED_REPO.to_string(), + completion_clock: system_clock_secs, }; engine.reload(); engine } - pub fn reload(&mut self) { - let evals_path = self.base_path.join("evals.json"); - if let Ok(content) = std::fs::read_to_string(&evals_path) { - if let Ok(val) = serde_json::from_str::>(&content) { - self.evals = val; - } + /// Fail-closed constructor: errors when workflows.json or evals.json is + /// missing, is not a JSON object, or holds a malformed definition. + pub fn load>(base_path: P) -> Result { + let engine = Self::new(base_path); + if engine.load_errors.is_empty() { + Ok(engine) + } else { + Err(engine.load_errors.join("; ")) } + } - let wf_path = self.base_path.join("workflows.json"); - if let Ok(content) = std::fs::read_to_string(&wf_path) { - if let Ok(val) = serde_json::from_str::>(&content) { - self.workflows = val; - } + /// Re-read both definition files. A file that fails to load keeps the + /// previous in-memory map (the old behavior) and adds an entry to + /// `load_errors`, which blocks verified completion until a clean reload. + pub fn reload(&mut self) { + self.load_errors.clear(); + match load_evals(&self.base_path) { + Ok(m) => self.evals = m, + Err(e) => self.load_errors.push(e), + } + match load_workflows(&self.base_path) { + Ok(m) => self.workflows = m, + Err(e) => self.load_errors.push(e), } } @@ -89,47 +280,17 @@ impl HarnessEngine { match eval_name { "slop_gate" => { let text = payload.get("text").and_then(|v| v.as_str()).unwrap_or(""); - let lower = text.to_lowercase(); - - // Disallowed phrases - let forbidden = [ - "this is the part where", - "the part everyone's missing", - "the part everyone is missing", - "in today's fast-paced", - "game-changer", - "delve into", - "unlock the power", - "at the end of the day", - "it is important to note", - "in conclusion,", - ]; - - for p in forbidden { - if lower.contains(p) { - return EvalResult { - name: eval_name.to_string(), - passed: false, - reason: format!("Forbidden AI trope detected: '{}'", p), - }; - } - } - - // Check antithesis pattern: "not X, it's Y" - let antithesis_re = - Regex::new(r"(?i)\bnot\s+([a-z0-9_\-\s]+),\s*(it's|it\s+is)\s+").unwrap(); - if antithesis_re.is_match(&lower) { - return EvalResult { + match slop_violation(text) { + Some(reason) => EvalResult { name: eval_name.to_string(), passed: false, - reason: "Formulaic antithesis trope detected ('not X, it's Y')".to_string(), - }; - } - - EvalResult { - name: eval_name.to_string(), - passed: true, - reason: "Slop gate passed clean.".to_string(), + reason, + }, + None => EvalResult { + name: eval_name.to_string(), + passed: true, + reason: "Slop gate passed clean.".to_string(), + }, } } @@ -179,7 +340,20 @@ impl HarnessEngine { } /// Layer 4: State Machine Workflow Engine + /// + /// Checks transition legality only. A transition into [`DONE_STATE`] is + /// always refused here: a legal transition by itself is not proof of + /// completion. Use [`HarnessEngine::complete_verified_workflow`], which + /// runs the workflow's completion gates on the real artifact and stores a + /// harness-minted receipt before moving to `done`. pub fn advance_workflow(&self, wf: &mut WorkflowState, next_state: &str) -> Result<(), String> { + if next_state == DONE_STATE { + return Err(format!( + "Refusing transition from '{}' to '{}': '{}' is reachable only through \ + verified completion (complete_verified_workflow / MCP harness_complete).", + wf.current_state, DONE_STATE, DONE_STATE + )); + } let wf_def = self .workflows .get(&wf.workflow_type) @@ -309,11 +483,30 @@ mod tests { assert!(engine.advance_workflow(&mut wf, "in_progress").is_ok()); assert_eq!(wf.current_state, "in_progress"); - assert!(engine.advance_workflow(&mut wf, "done").is_ok()); - assert_eq!(wf.current_state, "done"); + // `done` is legal per the state table but only reachable through + // verified completion, so advance_workflow refuses it and leaves the + // state and history untouched. + let err = engine.advance_workflow(&mut wf, "done").unwrap_err(); + assert!(err.contains("complete_verified_workflow"), "{err}"); + assert_eq!(wf.current_state, "in_progress"); + assert_eq!(wf.history, vec!["start".to_string()]); assert!(engine.advance_workflow(&mut wf, "start").is_err()); } + #[test] + fn test_shipped_definitions_load_clean() { + let engine = HarnessEngine::load(env!("CARGO_MANIFEST_DIR")).unwrap(); + assert!(engine.load_errors.is_empty()); + for wf in [ + "engineering_fix", + "research_handoff", + "harness_change", + "python_pipeline", + ] { + assert!(engine.workflows.contains_key(wf), "{wf}"); + } + } + #[test] fn test_schema_validation() { let engine = HarnessEngine::new(std::path::Path::new(env!("CARGO_MANIFEST_DIR"))); diff --git a/crates/spark-harness/src/main.rs b/crates/spark-harness/src/main.rs index 29284b16..77c912b8 100644 --- a/crates/spark-harness/src/main.rs +++ b/crates/spark-harness/src/main.rs @@ -10,6 +10,7 @@ fn default_harness_path() -> PathBuf { use clap::{Parser, Subcommand}; use serde_json::{json, Value}; +use spark_harness::completion::CompletionSubmission; use spark_harness::{HarnessEngine, WorkflowState}; use std::io::{self, BufRead, Write}; use std::path::PathBuf; @@ -97,8 +98,39 @@ async fn main() -> Result<(), Box> { engine.advance_workflow(&mut wf, "done").is_err(), "Cannot jump directly to done" ); + assert!(engine.advance_workflow(&mut wf, "retest").is_ok()); + assert!(engine.advance_workflow(&mut wf, "review").is_ok()); + assert!( + engine.advance_workflow(&mut wf, "done").is_err(), + "done is reachable only through verified completion" + ); + assert_eq!(wf.current_state, "review"); println!("Layer 4 (Deterministic Workflows): PASSED"); + // 3b. Verified completion into a throwaway store. + let mut gated = engine.clone(); + gated.completion_store = std::env::temp_dir() + .join(format!("spark-harness-selftest-{}", uuid::Uuid::new_v4())); + let sub = CompletionSubmission { + task_id: "selftest-task".to_string(), + generation: 1, + source_commit: "0".repeat(40), + artifact: json!({ + "bug": "Parser rejects valid token sequence", + "reproduction_steps": ["Run parser test"], + "failure_evidence": "thread panicked at line 42", + "regression_test": "tests::test_parser", + "diff_summary": "Fixed token parser logic", + "retest_evidence": "All tests passing cleanly" + }), + }; + let outcome = gated.complete_verified_workflow(&mut wf, &sub); + let _ = std::fs::remove_dir_all(&gated.completion_store); + let record = outcome?; + assert_eq!(wf.current_state, "done"); + assert_eq!(record.receipt_id.len(), 64); + println!("Layer 4b (Verified Completion Gate): PASSED"); + // 4. Failure Replay Record Test let log_path = engine.record_failure( "test-task-1", @@ -203,6 +235,39 @@ async fn run_mcp_stdio_loop(engine: HarnessEngine) -> io::Result<()> { }, "required": ["schema", "data"] } + }, + { + "name": "harness_complete", + "description": "Verified completion: runs the workflow's required schema and completion evals on the artifact, stores a harness-minted EvidenceReceiptV1, and only then moves the workflow to done. Refusals are JSON-RPC errors. done does not mean committed.", + "inputSchema": { + "type": "object", + "properties": { + "workflow": { + "type": "object", + "properties": { + "id": { "type": "string" }, + "workflow_type": { "type": "string" }, + "current_state": { "type": "string" }, + "history": { "type": "array", "items": { "type": "string" } }, + "created_at": { "type": "string" } + }, + "required": ["id", "workflow_type", "current_state", "history", "created_at"] + }, + "submission": { + "type": "object", + "properties": { + "task_id": { "type": "string" }, + "generation": { "type": "integer", "minimum": 0 }, + "source_commit": { "type": "string" }, + "artifact": { "type": "object" } + }, + "required": ["task_id", "generation", "source_commit", "artifact"], + "additionalProperties": false + } + }, + "required": ["workflow", "submission"], + "additionalProperties": false + } } ] } @@ -251,6 +316,23 @@ async fn run_mcp_stdio_loop(engine: HarnessEngine) -> io::Result<()> { } } + "harness_complete" => match engine.handle_complete_request(&args) { + Ok(done) => json!({ + "jsonrpc": "2.0", + "id": req_id, + "result": { + "content": [ + { "type": "text", "text": done.to_string() } + ] + } + }), + Err(e) => json!({ + "jsonrpc": "2.0", + "id": req_id, + "error": e.rpc_error() + }), + }, + _ => json!({ "jsonrpc": "2.0", "id": req_id, diff --git a/crates/spark-harness/tests/workflow_gates.rs b/crates/spark-harness/tests/workflow_gates.rs new file mode 100644 index 00000000..2d354a60 --- /dev/null +++ b/crates/spark-harness/tests/workflow_gates.rs @@ -0,0 +1,1041 @@ +//! Headstart M1 (#533): completion gates are enforced, fail closed, and +//! bound to a harness-minted aien-proof receipt. + +use aien_proof::evidence::{self, Verdict}; +use serde_json::{json, Value}; +use spark_harness::completion::{ + artifact_digest, verify_completion, CompletionError, CompletionSubmission, +}; +use spark_harness::{HarnessEngine, WorkflowState, DONE_STATE}; +use std::fs; +use std::path::{Path, PathBuf}; + +const COMMIT: &str = "1111111111111111111111111111111111111111"; +const OTHER_COMMIT: &str = "2222222222222222222222222222222222222222"; + +/// Temp copy of the shipped definitions, removed on drop. +struct Fixture { + dir: PathBuf, +} + +impl Fixture { + fn new() -> Self { + let dir = + std::env::temp_dir().join(format!("spark-harness-gates-{}", uuid::Uuid::new_v4())); + let src = Path::new(env!("CARGO_MANIFEST_DIR")); + fs::create_dir_all(dir.join("schemas")).unwrap(); + for f in ["workflows.json", "evals.json"] { + fs::copy(src.join(f), dir.join(f)).unwrap(); + } + for entry in fs::read_dir(src.join("schemas")).unwrap() { + let entry = entry.unwrap(); + fs::copy(entry.path(), dir.join("schemas").join(entry.file_name())).unwrap(); + } + Fixture { dir } + } + + fn engine(&self) -> HarnessEngine { + HarnessEngine::load(&self.dir).expect("shipped definitions load") + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.dir); + } +} + +fn wf_at(workflow_type: &str, state: &str) -> WorkflowState { + WorkflowState { + id: format!("wf-{workflow_type}"), + workflow_type: workflow_type.to_string(), + current_state: state.to_string(), + history: Vec::new(), + created_at: "2026-10-15T00:00:00Z".to_string(), + } +} + +fn sub(task: &str, generation: u64, artifact: Value) -> CompletionSubmission { + CompletionSubmission { + task_id: task.to_string(), + generation, + source_commit: COMMIT.to_string(), + artifact, + } +} + +fn engineering_fix_artifact() -> Value { + json!({ + "bug": "Parser rejects valid token sequence", + "reproduction_steps": ["Run parser test"], + "failure_evidence": "thread panicked at line 42", + "regression_test": "tests::test_parser", + "diff_summary": "Fixed token parser logic", + "retest_evidence": "All tests passing cleanly" + }) +} + +fn research_handoff_artifact() -> Value { + json!({ + "question": "Which serde_json feature changes map ordering?", + "claims": [{ + "claim": "preserve_order switches Map to an insertion ordered map", + "source_url": "https://docs.rs/serde_json", + "excerpt": "preserve_order: use IndexMap instead of BTreeMap" + }], + "sources": ["https://docs.rs/serde_json"], + "open_questions": [], + "evidence": ["Cargo.lock serde_json entry lists no indexmap"] + }) +} + +fn harness_change_artifact() -> Value { + json!({ + "change": "Tighten the slop gate phrase list", + "why": "Replay showed two missed tropes", + "replay_report": "12 of 12 replayed failures now caught", + "eval_results": ["slop_gate: pass"], + "rollback": "Revert the evals.json commit", + "evidence": ["replay log 2026-10-15"] + }) +} + +fn python_result_artifact() -> Value { + json!({ + "goal": "Sum a column", + "code": "print(sum([1, 2, 3]))", + "stdout": "6\n", + "ok": "yes", + "evidence": ["stdout matched expected 6"] + }) +} + +fn receipt_count(engine: &HarnessEngine) -> usize { + evidence::list_receipts(&engine.completion_store).len() +} + +fn gate_failures(err: CompletionError) -> (String, Vec) { + match err { + CompletionError::GatesFailed { + receipt_id, + failures, + } => (receipt_id, failures), + other => panic!("expected GatesFailed, got {other:?}"), + } +} + +// ---------- success for all four shipped workflows ---------- + +fn assert_completes(workflow_type: &str, pre_done: &str, artifact: Value) { + let fx = Fixture::new(); + let engine = fx.engine(); + let mut wf = wf_at(workflow_type, pre_done); + let s = sub(&format!("task-{workflow_type}"), 1, artifact.clone()); + let rec = engine.complete_verified_workflow(&mut wf, &s).unwrap(); + assert_eq!(wf.current_state, DONE_STATE); + assert_eq!(wf.history, vec![pre_done.to_string()]); + assert_eq!(rec.artifact_digest, artifact_digest(&artifact)); + assert_eq!(receipt_count(&engine), 1); + + let receipt = evidence::load_receipt(&engine.completion_store, &rec.receipt_id).unwrap(); + assert_eq!(receipt.result, Verdict::Pass); + assert_eq!(receipt.commit, COMMIT); + assert_eq!( + receipt.output_artifacts, + vec![format!("blake3:{}", rec.artifact_digest)] + ); + let ids: Vec<&str> = receipt.assertions.iter().map(|a| a.id.as_str()).collect(); + let def = &engine.workflows[workflow_type]; + assert!(ids.contains(&format!("schema:{}", def["required_schema"].as_str().unwrap()).as_str())); + for e in def["required_evals_on_done"].as_array().unwrap() { + assert!(ids.contains(&format!("eval:{}", e.as_str().unwrap()).as_str())); + } + + let v = verify_completion( + &engine.completion_store, + &rec.receipt_id, + &s.task_id, + 1, + COMMIT, + &rec.artifact_digest, + ) + .unwrap(); + assert_eq!(v.workflow_id, wf.id); + assert_eq!(v.generation, 1); +} + +#[test] +fn engineering_fix_completes() { + assert_completes("engineering_fix", "review", engineering_fix_artifact()); +} + +#[test] +fn research_handoff_completes() { + assert_completes("research_handoff", "deliver", research_handoff_artifact()); +} + +#[test] +fn harness_change_completes() { + assert_completes("harness_change", "verify", harness_change_artifact()); +} + +#[test] +fn python_pipeline_completes() { + assert_completes("python_pipeline", "deliver", python_result_artifact()); +} + +// ---------- gate failures ---------- + +fn assert_fails_gate( + engine: &HarnessEngine, + workflow_type: &str, + pre_done: &str, + artifact: Value, + failing: &str, +) { + let mut wf = wf_at(workflow_type, pre_done); + let before = receipt_count(engine); + let err = engine + .complete_verified_workflow(&mut wf, &sub("task-fail", 1, artifact.clone())) + .unwrap_err(); + let (receipt_id, failures) = gate_failures(err); + assert!( + failures.iter().any(|f| f.starts_with(failing)), + "expected {failing} in {failures:?}" + ); + assert_eq!(wf.current_state, pre_done, "state must not move on failure"); + assert!(wf.history.is_empty()); + // The failure is recorded as a FAIL receipt, which never verifies. + assert_eq!(receipt_count(engine), before + 1); + let r = evidence::load_receipt(&engine.completion_store, &receipt_id).unwrap(); + assert_eq!(r.result, Verdict::Fail); + let v = verify_completion( + &engine.completion_store, + &receipt_id, + "task-fail", + 1, + COMMIT, + &artifact_digest(&artifact), + ); + assert!(matches!(v, Err(CompletionError::NotPass(_))), "{v:?}"); + // A failure does not consume the generation: a fixed artifact may follow. +} + +#[test] +fn schema_failure_blocks_done() { + let fx = Fixture::new(); + let engine = fx.engine(); + let mut art = engineering_fix_artifact(); + art.as_object_mut().unwrap().remove("retest_evidence"); + assert_fails_gate( + &engine, + "engineering_fix", + "review", + art, + "schema:engineering_fix", + ); +} + +#[test] +fn reproduction_present_failure_blocks_done() { + let fx = Fixture::new(); + let engine = fx.engine(); + let mut art = engineering_fix_artifact(); + // Passes the schema (minLength 8) but is blank to the eval. + art["failure_evidence"] = json!(" "); + assert!(engine.validate_schema("engineering_fix", &art).is_ok()); + assert_fails_gate( + &engine, + "engineering_fix", + "review", + art, + "eval:reproduction_present", + ); +} + +#[test] +fn required_evidence_failure_blocks_done() { + let fx = Fixture::new(); + let engine = fx.engine(); + let mut art = harness_change_artifact(); + art.as_object_mut().unwrap().remove("evidence"); + assert!(engine.validate_schema("harness_change", &art).is_ok()); + assert_fails_gate( + &engine, + "harness_change", + "verify", + art, + "eval:required_evidence", + ); +} + +#[test] +fn slop_gate_failure_blocks_done() { + let fx = Fixture::new(); + let engine = fx.engine(); + let mut art = research_handoff_artifact(); + art["claims"][0]["claim"] = json!("This finding is a game-changer for ordering"); + assert!(engine.validate_schema("research_handoff", &art).is_ok()); + assert_fails_gate( + &engine, + "research_handoff", + "deliver", + art, + "eval:slop_gate", + ); +} + +#[test] +fn unknown_eval_rule_fails_closed() { + let fx = Fixture::new(); + let mut engine = fx.engine(); + engine.workflows.get_mut("python_pipeline").unwrap()["required_evals_on_done"] = + json!(["required_evidence", "no_such_eval"]); + assert_fails_gate( + &engine, + "python_pipeline", + "deliver", + python_result_artifact(), + "eval:no_such_eval", + ); +} + +#[test] +fn judgment_eval_cannot_gate_completion() { + let fx = Fixture::new(); + let mut engine = fx.engine(); + engine.workflows.get_mut("python_pipeline").unwrap()["required_evals_on_done"] = + json!(["source_supports_claim"]); + assert_fails_gate( + &engine, + "python_pipeline", + "deliver", + python_result_artifact(), + "eval:source_supports_claim", + ); +} + +#[test] +fn eval_without_definition_fails_closed() { + let fx = Fixture::new(); + let mut engine = fx.engine(); + engine.evals.remove("required_evidence"); + assert_fails_gate( + &engine, + "python_pipeline", + "deliver", + python_result_artifact(), + "eval:required_evidence", + ); +} + +#[test] +fn missing_schema_file_fails_closed() { + let fx = Fixture::new(); + fs::remove_file(fx.dir.join("schemas/engineering_fix.json")).unwrap(); + let engine = fx.engine(); + assert_fails_gate( + &engine, + "engineering_fix", + "review", + engineering_fix_artifact(), + "schema:engineering_fix", + ); +} + +#[test] +fn invalid_schema_file_fails_closed() { + let fx = Fixture::new(); + fs::write(fx.dir.join("schemas/python_result.json"), "{ not json").unwrap(); + let engine = fx.engine(); + assert_fails_gate( + &engine, + "python_pipeline", + "deliver", + python_result_artifact(), + "schema:python_result", + ); + fs::write(fx.dir.join("schemas/python_result.json"), r#"{"type": 12}"#).unwrap(); + assert_fails_gate( + &engine, + "python_pipeline", + "deliver", + python_result_artifact(), + "schema:python_result", + ); +} + +// ---------- fail-closed loading ---------- + +#[test] +fn malformed_workflows_json_blocks_completion() { + let fx = Fixture::new(); + fs::write(fx.dir.join("workflows.json"), "{ \"engineering_fix\": ").unwrap(); + assert!(HarnessEngine::load(&fx.dir).is_err()); + let engine = HarnessEngine::new(&fx.dir); + assert!(!engine.load_errors.is_empty()); + let mut wf = wf_at("engineering_fix", "review"); + let err = engine + .complete_verified_workflow(&mut wf, &sub("t", 1, engineering_fix_artifact())) + .unwrap_err(); + assert!( + matches!(err, CompletionError::DefinitionsNotLoaded(_)), + "{err:?}" + ); + assert_eq!(wf.current_state, "review"); + assert_eq!(receipt_count(&engine), 0); +} + +#[test] +fn structurally_bad_workflow_rejected_at_load() { + let fx = Fixture::new(); + let mut defs: Value = + serde_json::from_str(&fs::read_to_string(fx.dir.join("workflows.json")).unwrap()).unwrap(); + defs["engineering_fix"] + .as_object_mut() + .unwrap() + .remove("required_schema"); + fs::write(fx.dir.join("workflows.json"), defs.to_string()).unwrap(); + let err = HarnessEngine::load(&fx.dir).unwrap_err(); + assert!(err.contains("required_schema"), "{err}"); +} + +#[test] +fn missing_evals_json_blocks_completion() { + let fx = Fixture::new(); + fs::remove_file(fx.dir.join("evals.json")).unwrap(); + assert!(HarnessEngine::load(&fx.dir).is_err()); + let engine = HarnessEngine::new(&fx.dir); + let mut wf = wf_at("python_pipeline", "deliver"); + let err = engine + .complete_verified_workflow(&mut wf, &sub("t", 1, python_result_artifact())) + .unwrap_err(); + assert!( + matches!(err, CompletionError::DefinitionsNotLoaded(_)), + "{err:?}" + ); +} + +// ---------- forged success flags ---------- + +#[test] +fn forged_success_flag_in_artifact_is_not_proof() { + let fx = Fixture::new(); + let engine = fx.engine(); + let mut art = python_result_artifact(); + art["evidence"] = json!([]); + art["passed"] = json!(true); + art["verified"] = json!(true); + art["receipt"] = json!({"result": "PASS"}); + assert_fails_gate( + &engine, + "python_pipeline", + "deliver", + art, + "schema:python_result", + ); +} + +#[test] +fn forged_fields_in_submission_are_rejected() { + for extra in ["passed", "receipt", "verdict"] { + let mut raw = json!({ + "task_id": "t", + "generation": 1, + "source_commit": COMMIT, + "artifact": python_result_artifact() + }); + raw[extra] = json!(true); + assert!( + serde_json::from_value::(raw).is_err(), + "{extra}" + ); + } + // Same through the MCP adapter, which must answer with an explicit error. + let fx = Fixture::new(); + let engine = fx.engine(); + let args = json!({ + "workflow": wf_at("python_pipeline", "deliver"), + "submission": { + "task_id": "t", "generation": 1, "source_commit": COMMIT, + "artifact": python_result_artifact(), "passed": true + } + }); + let err = engine.handle_complete_request(&args).unwrap_err(); + assert!(matches!(err, CompletionError::InvalidSubmission(_))); + assert_eq!(err.rpc_error()["code"], json!(-32602)); + assert_eq!(receipt_count(&engine), 0); +} + +#[test] +fn bad_commit_is_rejected_before_evaluation() { + let fx = Fixture::new(); + let engine = fx.engine(); + let mut wf = wf_at("python_pipeline", "deliver"); + let mut s = sub("t", 1, python_result_artifact()); + s.source_commit = "HEAD".to_string(); + let err = engine.complete_verified_workflow(&mut wf, &s).unwrap_err(); + assert!( + matches!(err, CompletionError::InvalidSubmission(_)), + "{err:?}" + ); + assert_eq!(receipt_count(&engine), 0); +} + +// ---------- state progression ---------- + +#[test] +fn advance_workflow_to_done_is_refused() { + let fx = Fixture::new(); + let engine = fx.engine(); + let mut wf = wf_at("engineering_fix", "review"); + let err = engine.advance_workflow(&mut wf, DONE_STATE).unwrap_err(); + assert!(err.contains("complete_verified_workflow"), "{err}"); + assert_eq!(wf.current_state, "review"); + assert!(wf.history.is_empty()); + // Other legal transitions still work. + engine.advance_workflow(&mut wf, "implement").unwrap(); + assert_eq!(wf.current_state, "implement"); +} + +#[test] +fn completion_from_state_that_cannot_reach_done() { + let fx = Fixture::new(); + let engine = fx.engine(); + for state in ["implement", "nonexistent_state"] { + let mut wf = wf_at("engineering_fix", state); + let err = engine + .complete_verified_workflow(&mut wf, &sub("t", 1, engineering_fix_artifact())) + .unwrap_err(); + assert!( + matches!(err, CompletionError::IllegalTransition { .. }), + "{err:?}" + ); + assert_eq!(wf.current_state, state); + } + assert_eq!(receipt_count(&engine), 0); +} + +#[test] +fn unknown_workflow_type_is_refused() { + let fx = Fixture::new(); + let engine = fx.engine(); + let mut wf = wf_at("no_such_flow", "review"); + let err = engine + .complete_verified_workflow(&mut wf, &sub("t", 1, engineering_fix_artifact())) + .unwrap_err(); + assert!( + matches!(err, CompletionError::UnknownWorkflow(_)), + "{err:?}" + ); +} + +// ---------- duplicates, replay, generations ---------- + +#[test] +fn duplicate_completion_on_done_workflow_is_refused() { + let fx = Fixture::new(); + let engine = fx.engine(); + let mut wf = wf_at("engineering_fix", "review"); + let s = sub("dup", 1, engineering_fix_artifact()); + engine.complete_verified_workflow(&mut wf, &s).unwrap(); + let err = engine.complete_verified_workflow(&mut wf, &s).unwrap_err(); + assert!( + matches!(err, CompletionError::IllegalTransition { .. }), + "{err:?}" + ); + assert_eq!(receipt_count(&engine), 1); +} + +#[test] +fn replayed_submission_mints_no_second_receipt() { + let fx = Fixture::new(); + let engine = fx.engine(); + let snapshot = wf_at("engineering_fix", "review"); + let s = sub("replay", 1, engineering_fix_artifact()); + let mut first = snapshot.clone(); + let rec = engine.complete_verified_workflow(&mut first, &s).unwrap(); + + // Replay with a stale copy of the workflow that still says "review". + let mut replay = snapshot.clone(); + let err = engine + .complete_verified_workflow(&mut replay, &s) + .unwrap_err(); + match err { + CompletionError::DuplicateCompletion { + receipt_id, + generation, + .. + } => { + assert_eq!(receipt_id, rec.receipt_id); + assert_eq!(generation, 1); + } + other => panic!("expected DuplicateCompletion, got {other:?}"), + } + assert_eq!(replay.current_state, "review"); + assert_eq!( + evidence::list_receipts(&engine.completion_store), + vec![rec.receipt_id.clone()] + ); + + // A fresh engine on the same store sees the durable record too. + let engine2 = fx.engine(); + let mut replay2 = snapshot.clone(); + let err = engine2 + .complete_verified_workflow(&mut replay2, &s) + .unwrap_err(); + assert!( + matches!(err, CompletionError::DuplicateCompletion { .. }), + "{err:?}" + ); + assert_eq!(receipt_count(&engine2), 1); + + // Through MCP the replay is an explicit JSON-RPC error. + let args = json!({ "workflow": snapshot, "submission": s }); + let rpc = engine2 + .handle_complete_request(&args) + .unwrap_err() + .rpc_error(); + assert_eq!(rpc["code"], json!(-32005)); + assert_eq!(rpc["data"]["kind"], json!("duplicate_completion")); +} + +#[test] +fn stale_and_newer_generations() { + let fx = Fixture::new(); + let engine = fx.engine(); + let mut wf = wf_at("engineering_fix", "review"); + engine + .complete_verified_workflow(&mut wf, &sub("gen", 5, engineering_fix_artifact())) + .unwrap(); + + let mut lower = wf_at("engineering_fix", "review"); + let err = engine + .complete_verified_workflow(&mut lower, &sub("gen", 3, engineering_fix_artifact())) + .unwrap_err(); + assert_eq!( + err, + CompletionError::StaleGeneration { + task_id: "gen".to_string(), + submitted: 3, + recorded: 5 + } + ); + assert_eq!(receipt_count(&engine), 1); + + // A newer generation (reworked task) is a new completion. + let mut newer = wf_at("engineering_fix", "review"); + let rec = engine + .complete_verified_workflow(&mut newer, &sub("gen", 6, engineering_fix_artifact())) + .unwrap(); + assert_eq!(receipt_count(&engine), 2); + let mut back = wf_at("engineering_fix", "review"); + assert!(matches!( + engine.complete_verified_workflow(&mut back, &sub("gen", 5, engineering_fix_artifact())), + Err(CompletionError::StaleGeneration { recorded: 6, .. }) + )); + // The receipt for generation 6 does not verify as generation 5. + assert!(matches!( + verify_completion( + &engine.completion_store, + &rec.receipt_id, + "gen", + 5, + COMMIT, + &rec.artifact_digest + ), + Err(CompletionError::BindingMismatch { + field: "generation", + .. + }) + )); +} + +#[test] +fn corrupt_consumed_record_fails_closed() { + let fx = Fixture::new(); + let engine = fx.engine(); + let mut wf = wf_at("engineering_fix", "review"); + engine + .complete_verified_workflow(&mut wf, &sub("corrupt", 1, engineering_fix_artifact())) + .unwrap(); + let dir = engine.completion_store.join("completions"); + for entry in fs::read_dir(&dir).unwrap() { + let p = entry.unwrap().path(); + if p.extension().is_some_and(|e| e == "json") { + fs::write(&p, "garbage").unwrap(); + } + } + let mut again = wf_at("engineering_fix", "review"); + let err = engine + .complete_verified_workflow(&mut again, &sub("corrupt", 2, engineering_fix_artifact())) + .unwrap_err(); + assert!(matches!(err, CompletionError::Store(_)), "{err:?}"); + assert_eq!(again.current_state, "review"); +} + +// ---------- verify_completion bindings ---------- + +fn completed() -> (Fixture, HarnessEngine, String, String) { + let fx = Fixture::new(); + let engine = fx.engine(); + let mut wf = wf_at("python_pipeline", "deliver"); + let rec = engine + .complete_verified_workflow(&mut wf, &sub("verify-me", 7, python_result_artifact())) + .unwrap(); + (fx, engine, rec.receipt_id, rec.artifact_digest) +} + +#[test] +fn verify_completion_accepts_exact_bindings() { + let (_fx, engine, id, digest) = completed(); + let v = verify_completion( + &engine.completion_store, + &id, + "verify-me", + 7, + COMMIT, + &digest, + ) + .unwrap(); + assert_eq!(v.receipt_id, id); + let prefixed = format!("blake3:{digest}"); + assert!(verify_completion( + &engine.completion_store, + &id, + "verify-me", + 7, + COMMIT, + &prefixed + ) + .is_ok()); +} + +#[test] +fn verify_completion_wrong_digest() { + let (_fx, engine, id, _) = completed(); + let mut other = python_result_artifact(); + other["stdout"] = json!("7\n"); + let err = verify_completion( + &engine.completion_store, + &id, + "verify-me", + 7, + COMMIT, + &artifact_digest(&other), + ) + .unwrap_err(); + assert!( + matches!( + err, + CompletionError::BindingMismatch { + field: "artifact_digest", + .. + } + ), + "{err:?}" + ); +} + +#[test] +fn verify_completion_wrong_commit() { + let (_fx, engine, id, digest) = completed(); + let err = verify_completion( + &engine.completion_store, + &id, + "verify-me", + 7, + OTHER_COMMIT, + &digest, + ) + .unwrap_err(); + assert!( + matches!( + err, + CompletionError::BindingMismatch { + field: "commit", + .. + } + ), + "{err:?}" + ); +} + +#[test] +fn verify_completion_wrong_task() { + let (_fx, engine, id, digest) = completed(); + let err = verify_completion( + &engine.completion_store, + &id, + "someone-else", + 7, + COMMIT, + &digest, + ) + .unwrap_err(); + assert!( + matches!(err, CompletionError::BindingMismatch { field: "task", .. }), + "{err:?}" + ); +} + +#[test] +fn verify_completion_missing_receipt() { + let (_fx, engine, _, digest) = completed(); + let err = verify_completion( + &engine.completion_store, + &"a".repeat(64), + "verify-me", + 7, + COMMIT, + &digest, + ) + .unwrap_err(); + assert!(matches!(err, CompletionError::ReceiptInvalid(_)), "{err:?}"); +} + +#[test] +fn verify_completion_tampered_receipt_file() { + let (_fx, engine, id, digest) = completed(); + let path = engine + .completion_store + .join(evidence::RECEIPT_DIR) + .join(format!("{id}.json")); + let mut r: Value = serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap(); + // Rebind the receipt to another task without re-minting it. + r["external_refs"] = json!([ + "task:someone-else", + "workflow:wf-python_pipeline", + "generation:7" + ]); + fs::write(&path, serde_json::to_string_pretty(&r).unwrap()).unwrap(); + let err = verify_completion( + &engine.completion_store, + &id, + "someone-else", + 7, + COMMIT, + &digest, + ) + .unwrap_err(); + assert!(matches!(err, CompletionError::ReceiptInvalid(_)), "{err:?}"); +} + +#[test] +fn mcp_success_returns_record_and_done_state() { + let fx = Fixture::new(); + let engine = fx.engine(); + let args = json!({ + "workflow": wf_at("harness_change", "verify"), + "submission": sub("mcp-task", 1, harness_change_artifact()) + }); + let out = engine.handle_complete_request(&args).unwrap(); + assert_eq!(out["workflow"]["current_state"], json!(DONE_STATE)); + let id = out["record"]["receipt_id"].as_str().unwrap(); + let digest = out["record"]["artifact_digest"].as_str().unwrap(); + assert!(verify_completion(&engine.completion_store, id, "mcp-task", 1, COMMIT, digest).is_ok()); +} + +// ---------- consumed record is the authority (inspector finding 1) ---------- + +fn consumed_records(engine: &HarnessEngine) -> Vec { + let dir = engine.completion_store.join("completions"); + fs::read_dir(&dir) + .map(|it| { + it.flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|e| e == "json")) + .collect() + }) + .unwrap_or_default() +} + +fn assert_not_current(r: Result) { + match r { + Err(CompletionError::NotCurrentCompletion(_)) => {} + other => panic!("expected NotCurrentCompletion, got {other:?}"), + } +} + +/// Real write failure: the consumed-record directory is read-only, so +/// write_consumed fails after store_receipt succeeded. +#[test] +fn orphan_receipt_from_failed_record_write_never_verifies() { + use std::os::unix::fs::PermissionsExt; + let fx = Fixture::new(); + let mut engine = fx.engine(); + engine.completion_clock = || 1_000; + let dir = engine.completion_store.join("completions"); + fs::create_dir_all(&dir).unwrap(); + fs::File::create(dir.join(".lock")).unwrap(); + fs::set_permissions(&dir, fs::Permissions::from_mode(0o555)).unwrap(); + let probe = dir.join("probe"); + if fs::File::create(&probe).is_ok() { + // Running with permission override (root): the injection cannot work. + let _ = fs::remove_file(&probe); + fs::set_permissions(&dir, fs::Permissions::from_mode(0o755)).unwrap(); + eprintln!("skipping permission injection: directory stayed writable"); + return; + } + + let art_a = python_result_artifact(); + let mut wf = wf_at("python_pipeline", "deliver"); + let err = engine + .complete_verified_workflow(&mut wf, &sub("orphan", 1, art_a.clone())) + .unwrap_err(); + fs::set_permissions(&dir, fs::Permissions::from_mode(0o755)).unwrap(); + assert!(matches!(err, CompletionError::Store(_)), "{err:?}"); + assert_eq!( + wf.current_state, "deliver", + "no done without a consumed record" + ); + let ids = evidence::list_receipts(&engine.completion_store); + assert_eq!(ids.len(), 1); + let orphan = ids[0].clone(); + let r = evidence::load_receipt(&engine.completion_store, &orphan).unwrap(); + assert_eq!( + r.result, + Verdict::Pass, + "the orphan is a well-formed PASS receipt" + ); + assert_not_current(verify_completion( + &engine.completion_store, + &orphan, + "orphan", + 1, + COMMIT, + &artifact_digest(&art_a), + )); + + // Retry: the SAME task, generation, commit and artifact, one second + // later. Every binding the verifier checks is identical for both + // receipts; only the timestamp (and therefore the ID) differs. + engine.completion_clock = || 1_001; + let mut wf2 = wf_at("python_pipeline", "deliver"); + let rec = engine + .complete_verified_workflow(&mut wf2, &sub("orphan", 1, art_a.clone())) + .unwrap(); + assert_eq!(wf2.current_state, "done"); + assert_ne!(rec.receipt_id, orphan, "retry must mint a distinct receipt"); + assert_eq!(receipt_count(&engine), 2); + // Exactly one of the two PASS receipts verifies: the receipt-id match + // against the consumed record is the only thing that separates them. + assert_not_current(verify_completion( + &engine.completion_store, + &orphan, + "orphan", + 1, + COMMIT, + &artifact_digest(&art_a), + )); + assert!(verify_completion( + &engine.completion_store, + &rec.receipt_id, + "orphan", + 1, + COMMIT, + &artifact_digest(&art_a) + ) + .is_ok()); +} + +/// Simulated write failure: the consumed record vanishes after a completion. +#[test] +fn receipt_without_consumed_record_never_verifies() { + let (_fx, engine, id, digest) = completed(); + for p in consumed_records(&engine) { + fs::remove_file(p).unwrap(); + } + assert_not_current(verify_completion( + &engine.completion_store, + &id, + "verify-me", + 7, + COMMIT, + &digest, + )); +} + +#[test] +fn corrupt_consumed_record_blocks_verification() { + let (_fx, engine, id, digest) = completed(); + for p in consumed_records(&engine) { + fs::write(p, "garbage").unwrap(); + } + let err = verify_completion( + &engine.completion_store, + &id, + "verify-me", + 7, + COMMIT, + &digest, + ) + .unwrap_err(); + assert!(matches!(err, CompletionError::Store(_)), "{err:?}"); +} + +#[test] +fn superseded_generation_stops_verifying() { + let fx = Fixture::new(); + let engine = fx.engine(); + let art = engineering_fix_artifact(); + let mut wf1 = wf_at("engineering_fix", "review"); + let r1 = engine + .complete_verified_workflow(&mut wf1, &sub("super", 1, art.clone())) + .unwrap(); + assert!(verify_completion( + &engine.completion_store, + &r1.receipt_id, + "super", + 1, + COMMIT, + &r1.artifact_digest + ) + .is_ok()); + let mut wf2 = wf_at("engineering_fix", "review"); + let r2 = engine + .complete_verified_workflow(&mut wf2, &sub("super", 2, art)) + .unwrap(); + assert_not_current(verify_completion( + &engine.completion_store, + &r1.receipt_id, + "super", + 1, + COMMIT, + &r1.artifact_digest, + )); + assert!(verify_completion( + &engine.completion_store, + &r2.receipt_id, + "super", + 2, + COMMIT, + &r2.artifact_digest + ) + .is_ok()); +} + +// ---------- deterministic-kind guard (inspector finding 3) ---------- + +#[test] +fn executable_eval_marked_judgment_is_refused() { + let fx = Fixture::new(); + let mut engine = fx.engine(); + // run_eval can execute required_evidence and would pass this artifact; + // only the kind guard can refuse it. + let art = python_result_artifact(); + assert!(engine.run_eval("required_evidence", &art).passed); + engine.evals.get_mut("required_evidence").unwrap()["kind"] = json!("judgment"); + let mut wf = wf_at("python_pipeline", "deliver"); + let err = engine + .complete_verified_workflow(&mut wf, &sub("kind", 1, art)) + .unwrap_err(); + let (_, failures) = gate_failures(err); + assert!( + failures + .iter() + .any(|f| f.starts_with("eval:required_evidence") && f.contains("judgment")), + "{failures:?}" + ); + assert_eq!(wf.current_state, "deliver"); +} diff --git a/scripts/.crumb b/scripts/.crumb index 2c341dc6..9bbde84b 100644 --- a/scripts/.crumb +++ b/scripts/.crumb @@ -4,14 +4,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-15T12:41:41Z", + "compiled_at": "2026-10-15T19:05:36Z", "compiler": "crumb-compile/1", - "digest": "sha256:4696ee460c13e9a19a44104036e26407ddefd300f9d2221b4308208ba249980e", + "digest": "sha256:5f09d70a65f15a35b71b895eca7a3b1f0ce9e457906efdac9faba79a39c0d757", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 48, - "generated_at_commit": "c8e55074720ff4354695373e5bb59f3e7a65a765", - "source_tree": "sha256:8c62281e81b80bdb68a162ed38606cc39956672c6b678aafaee41267553de77f" + "generated_at_commit": "99914e0e651c0af4620fa2743f5e05f2d87b9faa", + "source_tree": "sha256:f98aa3275c648028b84ca063957df6a806c90c46baa137ece40c5acfbceb0c38" } }, "parent": { diff --git a/scripts/sync-standalone-repos.sh b/scripts/sync-standalone-repos.sh index e8ce4cf6..a8d528cb 100755 --- a/scripts/sync-standalone-repos.sh +++ b/scripts/sync-standalone-repos.sh @@ -21,6 +21,20 @@ SOVEREIGN_CORE="$(cd "$SCRIPT_DIR/.." && pwd)" # Parent directory holding the checkouts. Override for a CI # runner or a scratch directory; defaults to the monorepo's parent. WORKSPACE="${AIEN_MIRROR_WORKSPACE:-$(cd "$SOVEREIGN_CORE/.." && pwd)}" +# Git source used for monorepo path dependencies in mirrored manifests. +MONOREPO_GIT_URL="https://github.com/aien-spark/aien-sovereign-core" + +# Source [dependencies] that sync_manifest may APPEND to a mirror manifest that +# lacks them, per repo (space-separated dep names). Repos not listed get no +# appended deps. Keep this list explicit: appending a dep changes what the +# mirror builds, so each entry must be a reviewed decision. +# spark-harness: aien-proof and blake3 back the verified completion gate (#533). +manifest_append_deps() { + case "$1" in + spark-harness) echo "aien-proof blake3" ;; + *) echo "" ;; + esac +} # Repository mapping: :: REPOS=( @@ -136,11 +150,14 @@ pkg_field() { # Bring the destination [package] table in line with the source: license from the # workspace root (single source of truth), version and edition from the source crate. +# Also: in-repo path deps become pinned git deps, and deps named by +# manifest_append_deps for this repo are added when missing (see below). # Pure awk, no Python. Exit 0 parity or synced, 2 disparity in check mode, 1 error. sync_manifest() { local src_manifest="$1" local dest_manifest="$2" local is_check="$3" + local repo_name="$4" local ws_manifest="$SOVEREIGN_CORE/Cargo.toml" local license_id @@ -174,6 +191,61 @@ sync_manifest() { END { flush_license() } ' "$dest_manifest" > "$tmp" + # [dependencies]: a source dep of the form `name = { path = "../" ... }` + # cannot build outside the monorepo, and Cargo refuses `path` and `git` on one + # dependency ("Only one of `git` or `path` is allowed", cargo 1.98.1). So it is + # rewritten to a git dep on this monorepo pinned to `rev = ` and replaces the mirror's entry of the same name. The pin lives + # in the manifest itself: the aien-harness mirror ships no Cargo.lock, so a + # floating branch would build whatever main is at build time. Consequences: + # sync from a commit that is pushed to the monorepo (cargo fetches it), and + # `--check` reports disparity for a mirror with path deps after every + # monorepo commit until it is re-synced. Only deps named by + # manifest_append_deps are appended when missing; every other mirror line, + # and every mirror with no path deps and no list entry, is left byte-identical. + local mono_rev append_deps + mono_rev=$(git -C "$SOVEREIGN_CORE" rev-parse HEAD) || { + echo "[ERROR] Cannot resolve monorepo HEAD in $SOVEREIGN_CORE" + return 1 + } + append_deps=$(manifest_append_deps "$repo_name") + local tmp_deps + tmp_deps=$(mktemp) + awk -v url="$MONOREPO_GIT_URL" -v rev="$mono_rev" -v allow="$append_deps" ' + function key_of(line, k) { k = line; sub(/[[:space:]]*=.*/, "", k); gsub(/^[[:space:]]+/, "", k); return k } + function emit_missing( i) { for (i = 1; i <= n; i++) if (!(keys[i] in seen)) print lines[i]; emitted = 1 } + function missing_count( i, c) { c = 0; for (i = 1; i <= n; i++) if (!(keys[i] in seen)) c++; return c } + BEGIN { na = split(allow, al, " "); for (i = 1; i <= na; i++) allowed[al[i]] = 1 } + FNR == NR { + if ($0 ~ /^[[:space:]]*\[/) { in_src = ($0 ~ /^[[:space:]]*\[dependencies\][[:space:]]*$/); next } + if (in_src && $0 ~ /^[[:space:]]*[A-Za-z0-9_-]+[[:space:]]*=/) { + line = $0 + if (line ~ /path[[:space:]]*=[[:space:]]*"\.\.\//) { + gsub(/path[[:space:]]*=[[:space:]]*"\.\.\/[^"]*"/, "git = \"" url "\", rev = \"" rev "\"", line) + rewritten[key_of(line)] = line + } + if (key_of(line) in allowed) { n++; keys[n] = key_of(line); lines[n] = line } + } + next + } + /^[[:space:]]*\[/ { + if (in_dst && !emitted) emit_missing() + in_dst = ($0 ~ /^[[:space:]]*\[dependencies\][[:space:]]*$/) + if (in_dst) has_dst = 1 + print; next + } + in_dst && /^[[:space:]]*[A-Za-z0-9_-]+[[:space:]]*=/ { + k = key_of($0); seen[k] = 1 + if (k in rewritten) { print rewritten[k]; next } + } + { print } + END { + if (in_dst && !emitted) emit_missing() + else if (!has_dst && missing_count() > 0) { print ""; print "[dependencies]"; emit_missing() } + } + ' "$src_manifest" "$tmp" > "$tmp_deps" + mv "$tmp_deps" "$tmp" + if cmp -s "$tmp" "$dest_manifest"; then rm -f "$tmp" echo "[PARITY OK] Manifest $dest_manifest in parity (license = $license_id)" @@ -181,7 +253,7 @@ sync_manifest() { fi if [[ "$is_check" == "true" ]]; then rm -f "$tmp" - echo "[DISPARITY] $dest_manifest requires manifest update (license $license_id or version/edition)" + echo "[DISPARITY] $dest_manifest requires manifest update (license $license_id, version/edition or dependencies)" return 2 fi mv "$tmp" "$dest_manifest" @@ -308,7 +380,7 @@ process_repo() { # Step 4: Selective manifest synchronization if [[ -f "$src_dir/Cargo.toml" && -f "$dest_dir/Cargo.toml" ]]; then local manifest_code=0 - if sync_manifest "$src_dir/Cargo.toml" "$dest_dir/Cargo.toml" "$CHECK_MODE"; then + if sync_manifest "$src_dir/Cargo.toml" "$dest_dir/Cargo.toml" "$CHECK_MODE" "$cli_name"; then manifest_code=0 else manifest_code=$? ```