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
aien-sovereign-core-mv / crates / spark-harness / src / completion.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! Verified workflow completion (Headstart M1, issue #533). |
| 17 | //! |
| 18 | //! [`HarnessEngine::complete_verified_workflow`] is the only way a workflow |
| 19 | //! reaches [`DONE_STATE`]. The harness itself: |
| 20 | //! |
| 21 | //! 1. refuses to run when workflows.json or evals.json did not load cleanly; |
| 22 | //! 2. checks that the workflow's current state may legally move to `done`; |
| 23 | //! 3. validates the workflow's `required_schema` against the submitted |
| 24 | //! artifact and runs every `required_evals_on_done` entry on it (unknown |
| 25 | //! eval, missing definition, non-deterministic eval kind, missing or |
| 26 | //! invalid schema all count as failures); |
| 27 | //! 4. mints an aien-proof `EvidenceReceiptV1` from its own results (one |
| 28 | //! assertion per gate, artifact digest, source commit, task, workflow and |
| 29 | //! generation bindings) and stores it in its own store; |
| 30 | //! 5. records the consumed (task, generation) pair atomically, and only then |
| 31 | //! moves the workflow to `done`. |
| 32 | //! |
| 33 | //! The caller never supplies a receipt, a verdict or a pass flag: |
| 34 | //! [`CompletionSubmission`] rejects unknown fields, and any extra field in |
| 35 | //! the artifact is judged by the workflow schema like any other content. |
| 36 | //! |
| 37 | //! What `done` means: the completion gates passed on this artifact and a PASS |
| 38 | //! receipt is in the harness store. It does not mean committed. World commit |
| 39 | //! and authorization stay in aien-runtime and are not touched here. |
| 40 | //! |
| 41 | //! Limitations, stated plainly: |
| 42 | //! - EvidenceReceiptV1 is unsigned (aien-proof `evidence.rs`, `Receipt` has no |
| 43 | //! signature field; its ID is a BLAKE3 hash of the canonical encoding). |
| 44 | //! Anyone who can write to the completion store can write a receipt with a |
| 45 | //! matching ID. Authenticity therefore rests on store ownership (filesystem |
| 46 | //! trust) plus recomputation: [`verify_completion`] recomputes the receipt |
| 47 | //! ID and checks every binding, and a verifier holding the artifact can |
| 48 | //! recompute [`artifact_digest`] and rerun the gates. |
| 49 | //! - `source_commit` is the caller-declared revision. The harness checks its |
| 50 | //! format (aien-proof `check_commit`) but does not inspect a source tree, so |
| 51 | //! `dirty` is written as `false` meaning "no tree inspection was made", not |
| 52 | //! "the tree was verified clean". |
| 53 | //! - The tier is `HOST_TEST`: deterministic checks executed on the host, no |
| 54 | //! hardware and no physical qualification. |
| 55 | //! - If writing the consumed record fails (or the process dies) after the |
| 56 | //! receipt is stored, an orphan PASS receipt stays in the store and a |
| 57 | //! resubmission can mint another one for the same generation. The workflow |
| 58 | //! never moves to `done` in that case, and [`verify_completion`] accepts |
| 59 | //! only the receipt the consumed record names, so at most one receipt per |
| 60 | //! task verifies at any time. |
| 61 | //! - One exception to "error means nothing verifies": if the record rename |
| 62 | //! succeeds but the following directory fsync fails, completion returns a |
| 63 | //! `Store` error and the workflow is not moved to `done`, yet the record is |
| 64 | //! already in place and the receipt it names verifies. The rename is not |
| 65 | //! guaranteed durable across a power loss in that case. |
| 66 | //! - The consumed record is keyed by task and holds only the highest |
| 67 | //! completed generation. Completing a newer generation supersedes the older |
| 68 | //! one: its receipt stops verifying. Verification answers "is this the |
| 69 | //! task's current completion", which is what M2 needs. |
| 70 | |
| 71 | use crate::{HarnessEngine, WorkflowState, DONE_STATE}; |
| 72 | use aien_proof::evidence::{self, Assertion, Mutation, Receipt, Tier, Verdict}; |
| 73 | use aien_proof::lock::FileLock; |
| 74 | use serde::{Deserialize, Serialize}; |
| 75 | use serde_json::{json, Value}; |
| 76 | use std::fmt; |
| 77 | use std::fs; |
| 78 | use std::io::Write; |
| 79 | use std::path::{Path, PathBuf}; |
| 80 | |
| 81 | /// Receipt `kind` for harness completion receipts. |
| 82 | pub const COMPLETION_KIND: &str = "spark-harness-completion"; |
| 83 | /// Honest tier for harness completions: host-executed deterministic checks. |
| 84 | pub const COMPLETION_TIER: Tier = Tier::HostTest; |
| 85 | /// Subdirectory of the completion store holding consumed completion records. |
| 86 | pub const CONSUMED_DIR: &str = "completions"; |
| 87 | const MAX_TASK_ID_LEN: usize = 256; |
| 88 | const ASSERTION_SOURCE: &str = "spark-harness"; |
| 89 | |
| 90 | /// What a caller submits for completion. There is deliberately no field for |
| 91 | /// a receipt, verdict or pass flag; unknown fields are rejected. |
| 92 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 93 | #[serde(deny_unknown_fields)] |
| 94 | pub struct CompletionSubmission { |
| 95 | pub task_id: String, |
| 96 | /// Monotonic generation of the work for this task. A completed |
| 97 | /// generation can never be completed again, and a lower one is stale. |
| 98 | pub generation: u64, |
| 99 | /// Source revision the artifact was produced from: 40 or 64 lowercase hex. |
| 100 | pub source_commit: String, |
| 101 | pub artifact: Value, |
| 102 | } |
| 103 | |
| 104 | /// Result of a successful verified completion. |
| 105 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 106 | pub struct CompletionRecord { |
| 107 | pub receipt_id: String, |
| 108 | pub task_id: String, |
| 109 | pub workflow_id: String, |
| 110 | pub workflow_type: String, |
| 111 | pub generation: u64, |
| 112 | pub source_commit: String, |
| 113 | /// BLAKE3 hex of [`canonical_json`] of the artifact. |
| 114 | pub artifact_digest: String, |
| 115 | } |
| 116 | |
| 117 | /// Durable record of the highest completed generation for one task. |
| 118 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 119 | #[serde(deny_unknown_fields)] |
| 120 | struct ConsumedRecord { |
| 121 | task_id: String, |
| 122 | generation: u64, |
| 123 | receipt_id: String, |
| 124 | workflow_id: String, |
| 125 | artifact_digest: String, |
| 126 | } |
| 127 | |
| 128 | /// A completion receipt that passed [`verify_completion`]. |
| 129 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 130 | pub struct VerifiedCompletion { |
| 131 | pub receipt_id: String, |
| 132 | pub task_id: String, |
| 133 | pub workflow_id: String, |
| 134 | pub generation: u64, |
| 135 | pub source_commit: String, |
| 136 | pub artifact_digest: String, |
| 137 | } |
| 138 | |
| 139 | /// Every way completion or verification can refuse. |
| 140 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 141 | pub enum CompletionError { |
| 142 | /// workflows.json or evals.json failed to load; nothing can complete. |
| 143 | DefinitionsNotLoaded(Vec<String>), |
| 144 | /// Submission or request arguments are malformed. |
| 145 | InvalidSubmission(String), |
| 146 | UnknownWorkflow(String), |
| 147 | MalformedWorkflow(String), |
| 148 | /// The current state cannot legally move to `done`. |
| 149 | IllegalTransition { |
| 150 | from: String, |
| 151 | allowed: Vec<String>, |
| 152 | }, |
| 153 | /// This task and generation already completed; no new receipt minted. |
| 154 | DuplicateCompletion { |
| 155 | task_id: String, |
| 156 | generation: u64, |
| 157 | receipt_id: String, |
| 158 | }, |
| 159 | /// The submitted generation is lower than the recorded one. |
| 160 | StaleGeneration { |
| 161 | task_id: String, |
| 162 | submitted: u64, |
| 163 | recorded: u64, |
| 164 | }, |
| 165 | /// At least one gate failed. A FAIL receipt was stored; state unchanged. |
| 166 | GatesFailed { |
| 167 | receipt_id: String, |
| 168 | failures: Vec<String>, |
| 169 | }, |
| 170 | /// The completion store could not be read or written. |
| 171 | Store(String), |
| 172 | /// The receipt is missing, malformed or its identity does not recompute. |
| 173 | ReceiptInvalid(String), |
| 174 | /// The receipt does not carry a PASS verdict. |
| 175 | NotPass(String), |
| 176 | /// The receipt is valid but bound to something other than expected. |
| 177 | BindingMismatch { |
| 178 | field: &'static str, |
| 179 | expected: String, |
| 180 | found: String, |
| 181 | }, |
| 182 | /// The receipt is not the task's current completion per the consumed |
| 183 | /// record (orphan receipt, superseded generation, or no record). |
| 184 | NotCurrentCompletion(String), |
| 185 | } |
| 186 | |
| 187 | impl CompletionError { |
| 188 | /// Stable machine-readable name of the refusal. |
| 189 | pub fn kind(&self) -> &'static str { |
| 190 | match self { |
| 191 | CompletionError::DefinitionsNotLoaded(_) => "definitions_not_loaded", |
| 192 | CompletionError::InvalidSubmission(_) => "invalid_submission", |
| 193 | CompletionError::UnknownWorkflow(_) => "unknown_workflow", |
| 194 | CompletionError::MalformedWorkflow(_) => "malformed_workflow", |
| 195 | CompletionError::IllegalTransition { .. } => "illegal_transition", |
| 196 | CompletionError::DuplicateCompletion { .. } => "duplicate_completion", |
| 197 | CompletionError::StaleGeneration { .. } => "stale_generation", |
| 198 | CompletionError::GatesFailed { .. } => "gates_failed", |
| 199 | CompletionError::Store(_) => "store_error", |
| 200 | CompletionError::ReceiptInvalid(_) => "receipt_invalid", |
| 201 | CompletionError::NotPass(_) => "not_pass", |
| 202 | CompletionError::BindingMismatch { .. } => "binding_mismatch", |
| 203 | CompletionError::NotCurrentCompletion(_) => "not_current_completion", |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | /// JSON-RPC error code. Invalid arguments use the standard -32602; every |
| 208 | /// other refusal uses the server-defined range. |
| 209 | pub fn rpc_code(&self) -> i64 { |
| 210 | match self { |
| 211 | CompletionError::InvalidSubmission(_) => -32602, |
| 212 | CompletionError::DefinitionsNotLoaded(_) => -32001, |
| 213 | CompletionError::UnknownWorkflow(_) => -32002, |
| 214 | CompletionError::MalformedWorkflow(_) => -32003, |
| 215 | CompletionError::IllegalTransition { .. } => -32004, |
| 216 | CompletionError::DuplicateCompletion { .. } => -32005, |
| 217 | CompletionError::StaleGeneration { .. } => -32006, |
| 218 | CompletionError::GatesFailed { .. } => -32007, |
| 219 | CompletionError::Store(_) => -32008, |
| 220 | CompletionError::ReceiptInvalid(_) => -32009, |
| 221 | CompletionError::NotPass(_) => -32010, |
| 222 | CompletionError::BindingMismatch { .. } => -32011, |
| 223 | CompletionError::NotCurrentCompletion(_) => -32012, |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | /// JSON-RPC `error` object for an MCP refusal. |
| 228 | pub fn rpc_error(&self) -> Value { |
| 229 | let mut data = json!({ "kind": self.kind() }); |
| 230 | match self { |
| 231 | CompletionError::GatesFailed { |
| 232 | receipt_id, |
| 233 | failures, |
| 234 | } => { |
| 235 | data["receipt_id"] = json!(receipt_id); |
| 236 | data["failures"] = json!(failures); |
| 237 | } |
| 238 | CompletionError::DuplicateCompletion { receipt_id, .. } => { |
| 239 | data["receipt_id"] = json!(receipt_id); |
| 240 | } |
| 241 | _ => {} |
| 242 | } |
| 243 | json!({ "code": self.rpc_code(), "message": self.to_string(), "data": data }) |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | impl fmt::Display for CompletionError { |
| 248 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 249 | match self { |
| 250 | CompletionError::DefinitionsNotLoaded(errs) => write!( |
| 251 | f, |
| 252 | "workflow/eval definitions did not load, completion refused: {}", |
| 253 | errs.join("; ") |
| 254 | ), |
| 255 | CompletionError::InvalidSubmission(m) => write!(f, "invalid submission: {m}"), |
| 256 | CompletionError::UnknownWorkflow(w) => write!(f, "unknown workflow type '{w}'"), |
| 257 | CompletionError::MalformedWorkflow(m) => write!(f, "malformed workflow: {m}"), |
| 258 | CompletionError::IllegalTransition { from, allowed } => write!( |
| 259 | f, |
| 260 | "state '{from}' cannot move to '{DONE_STATE}'; allowed next states: {allowed:?}" |
| 261 | ), |
| 262 | CompletionError::DuplicateCompletion { |
| 263 | task_id, |
| 264 | generation, |
| 265 | receipt_id, |
| 266 | } => write!( |
| 267 | f, |
| 268 | "task '{task_id}' generation {generation} already completed (receipt {receipt_id})" |
| 269 | ), |
| 270 | CompletionError::StaleGeneration { |
| 271 | task_id, |
| 272 | submitted, |
| 273 | recorded, |
| 274 | } => write!( |
| 275 | f, |
| 276 | "stale generation for task '{task_id}': submitted {submitted}, completed {recorded}" |
| 277 | ), |
| 278 | CompletionError::GatesFailed { |
| 279 | receipt_id, |
| 280 | failures, |
| 281 | } => write!( |
| 282 | f, |
| 283 | "completion gates failed (FAIL receipt {receipt_id}): {}", |
| 284 | failures.join("; ") |
| 285 | ), |
| 286 | CompletionError::Store(m) => write!(f, "completion store error: {m}"), |
| 287 | CompletionError::ReceiptInvalid(m) => write!(f, "receipt invalid: {m}"), |
| 288 | CompletionError::NotPass(m) => write!(f, "receipt is not a PASS: {m}"), |
| 289 | CompletionError::NotCurrentCompletion(m) => { |
| 290 | write!(f, "receipt is not the current completion: {m}") |
| 291 | } |
| 292 | CompletionError::BindingMismatch { |
| 293 | field, |
| 294 | expected, |
| 295 | found, |
| 296 | } => write!( |
| 297 | f, |
| 298 | "receipt binding '{field}' mismatch: expected {expected:?}, found {found:?}" |
| 299 | ), |
| 300 | } |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | impl std::error::Error for CompletionError {} |
| 305 | |
| 306 | /// Canonical JSON encoding used for the artifact digest: object keys sorted |
| 307 | /// by byte order at every level, no whitespace, arrays in order, scalars as |
| 308 | /// serde_json prints them. Keys are sorted here explicitly, so the digest |
| 309 | /// does not depend on whether serde_json's `preserve_order` feature is on. |
| 310 | pub fn canonical_json(v: &Value) -> Vec<u8> { |
| 311 | let mut out = Vec::new(); |
| 312 | write_canonical(v, &mut out); |
| 313 | out |
| 314 | } |
| 315 | |
| 316 | fn write_canonical(v: &Value, out: &mut Vec<u8>) { |
| 317 | match v { |
| 318 | Value::Array(items) => { |
| 319 | out.push(b'['); |
| 320 | for (i, item) in items.iter().enumerate() { |
| 321 | if i > 0 { |
| 322 | out.push(b','); |
| 323 | } |
| 324 | write_canonical(item, out); |
| 325 | } |
| 326 | out.push(b']'); |
| 327 | } |
| 328 | Value::Object(map) => { |
| 329 | let mut keys: Vec<&String> = map.keys().collect(); |
| 330 | keys.sort(); |
| 331 | out.push(b'{'); |
| 332 | for (i, k) in keys.iter().enumerate() { |
| 333 | if i > 0 { |
| 334 | out.push(b','); |
| 335 | } |
| 336 | // Serializing a string or scalar Value cannot fail. |
| 337 | out.extend_from_slice(serde_json::to_string(k).unwrap_or_default().as_bytes()); |
| 338 | out.push(b':'); |
| 339 | write_canonical(&map[k.as_str()], out); |
| 340 | } |
| 341 | out.push(b'}'); |
| 342 | } |
| 343 | scalar => { |
| 344 | out.extend_from_slice(serde_json::to_string(scalar).unwrap_or_default().as_bytes()) |
| 345 | } |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | /// BLAKE3 hex digest of [`canonical_json`] of the artifact. |
| 350 | pub fn artifact_digest(artifact: &Value) -> String { |
| 351 | blake3::hash(&canonical_json(artifact)).to_hex().to_string() |
| 352 | } |
| 353 | |
| 354 | /// File name key for a task's consumed record (task IDs are free text). |
| 355 | pub(crate) fn task_key(task_id: &str) -> String { |
| 356 | let mut h = blake3::Hasher::new(); |
| 357 | h.update(b"spark-harness-task\0"); |
| 358 | h.update(task_id.as_bytes()); |
| 359 | h.finalize().to_hex().to_string() |
| 360 | } |
| 361 | |
| 362 | pub(crate) fn check_identifier(what: &str, value: &str) -> Result<(), CompletionError> { |
| 363 | if value.is_empty() || value.trim() != value { |
| 364 | return Err(CompletionError::InvalidSubmission(format!( |
| 365 | "{what} must be non-empty with no leading or trailing whitespace" |
| 366 | ))); |
| 367 | } |
| 368 | if value.len() > MAX_TASK_ID_LEN || value.chars().any(char::is_control) { |
| 369 | return Err(CompletionError::InvalidSubmission(format!( |
| 370 | "{what} must be at most {MAX_TASK_ID_LEN} bytes with no control characters" |
| 371 | ))); |
| 372 | } |
| 373 | Ok(()) |
| 374 | } |
| 375 | |
| 376 | fn collect_strings<'a>(v: &'a Value, path: String, out: &mut Vec<(String, &'a str)>) { |
| 377 | match v { |
| 378 | Value::String(s) => out.push((path, s)), |
| 379 | Value::Array(items) => { |
| 380 | for (i, item) in items.iter().enumerate() { |
| 381 | collect_strings(item, format!("{path}/{i}"), out); |
| 382 | } |
| 383 | } |
| 384 | Value::Object(map) => { |
| 385 | for (k, item) in map { |
| 386 | collect_strings(item, format!("{path}/{k}"), out); |
| 387 | } |
| 388 | } |
| 389 | _ => {} |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | pub(crate) fn host_identity() -> String { |
| 394 | let from_proc = fs::read_to_string("/proc/sys/kernel/hostname") |
| 395 | .map(|s| s.trim().to_string()) |
| 396 | .unwrap_or_default(); |
| 397 | if !from_proc.is_empty() { |
| 398 | return from_proc; |
| 399 | } |
| 400 | std::env::var("HOSTNAME") |
| 401 | .ok() |
| 402 | .filter(|s| !s.trim().is_empty()) |
| 403 | .unwrap_or_else(|| "unknown-host".to_string()) |
| 404 | } |
| 405 | |
| 406 | fn read_consumed(path: &Path, task_id: &str) -> Result<Option<ConsumedRecord>, CompletionError> { |
| 407 | let bytes = match fs::read(path) { |
| 408 | Ok(b) => b, |
| 409 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), |
| 410 | Err(e) => { |
| 411 | return Err(CompletionError::Store(format!( |
| 412 | "cannot read consumed record {}: {e}", |
| 413 | path.display() |
| 414 | ))) |
| 415 | } |
| 416 | }; |
| 417 | let rec: ConsumedRecord = serde_json::from_slice(&bytes).map_err(|e| { |
| 418 | CompletionError::Store(format!( |
| 419 | "consumed record {} is malformed, refusing: {e}", |
| 420 | path.display() |
| 421 | )) |
| 422 | })?; |
| 423 | if rec.task_id != task_id { |
| 424 | return Err(CompletionError::Store(format!( |
| 425 | "consumed record {} belongs to task '{}', not '{task_id}'", |
| 426 | path.display(), |
| 427 | rec.task_id |
| 428 | ))); |
| 429 | } |
| 430 | Ok(Some(rec)) |
| 431 | } |
| 432 | |
| 433 | /// Write temp file, fsync, rename over the target, fsync the directory. |
| 434 | /// |
| 435 | /// Known edge: if the rename succeeds but the directory fsync fails, this |
| 436 | /// returns `Store` and the workflow stays un-done, yet the new record is |
| 437 | /// already in place, so the just-minted receipt verifies (the rename may |
| 438 | /// still be lost on power failure). A resubmission of the same generation |
| 439 | /// is then refused as a duplicate. |
| 440 | fn write_consumed(path: &Path, rec: &ConsumedRecord) -> Result<(), CompletionError> { |
| 441 | let text = serde_json::to_vec_pretty(rec).map_err(|e| CompletionError::Store(e.to_string()))?; |
| 442 | write_atomic(path, &text).map_err(|e| { |
| 443 | CompletionError::Store(format!( |
| 444 | "cannot write consumed record {}: {e}", |
| 445 | path.display() |
| 446 | )) |
| 447 | }) |
| 448 | } |
| 449 | |
| 450 | /// Atomic replace used by the consumed and interface records: write a temp |
| 451 | /// file in the same directory, append a newline, fsync it, rename it over |
| 452 | /// `path`, fsync the directory. The temp file is removed on failure. |
| 453 | pub(crate) fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> { |
| 454 | let dir = path.parent().ok_or_else(|| { |
| 455 | std::io::Error::new(std::io::ErrorKind::InvalidInput, "record has no parent dir") |
| 456 | })?; |
| 457 | let name = path |
| 458 | .file_name() |
| 459 | .map(|n| n.to_string_lossy().into_owned()) |
| 460 | .unwrap_or_default(); |
| 461 | let tmp = dir.join(format!( |
| 462 | ".{name}.tmp-{}-{}", |
| 463 | std::process::id(), |
| 464 | uuid::Uuid::new_v4() |
| 465 | )); |
| 466 | let result = (|| -> std::io::Result<()> { |
| 467 | let mut f = fs::File::create(&tmp)?; |
| 468 | f.write_all(bytes)?; |
| 469 | f.write_all(b"\n")?; |
| 470 | f.sync_all()?; |
| 471 | fs::rename(&tmp, path)?; |
| 472 | fs::File::open(dir)?.sync_all() |
| 473 | })(); |
| 474 | if result.is_err() { |
| 475 | let _ = fs::remove_file(&tmp); |
| 476 | } |
| 477 | result |
| 478 | } |
| 479 | |
| 480 | fn failed_assertion(id: String, expected: &str, observed: String) -> Assertion { |
| 481 | Assertion { |
| 482 | id, |
| 483 | expected: expected.to_string(), |
| 484 | observed, |
| 485 | pass: false, |
| 486 | source: ASSERTION_SOURCE.to_string(), |
| 487 | note: String::new(), |
| 488 | } |
| 489 | } |
| 490 | |
| 491 | impl HarnessEngine { |
| 492 | fn consumed_dir(&self) -> PathBuf { |
| 493 | self.completion_store.join(CONSUMED_DIR) |
| 494 | } |
| 495 | |
| 496 | /// Run the schema gate and every `required_evals_on_done` entry on the |
| 497 | /// artifact. Returns one assertion per gate; never short-circuits. |
| 498 | fn evaluate_gates(&self, wf_def: &Value, artifact: &Value) -> Vec<Assertion> { |
| 499 | let mut out = Vec::new(); |
| 500 | // validate_workflow_def already guaranteed these shapes. |
| 501 | let schema = wf_def["required_schema"].as_str().unwrap_or_default(); |
| 502 | let schema_id = format!("schema:{schema}"); |
| 503 | let expected = "artifact valid against the workflow schema"; |
| 504 | out.push(match self.validate_schema(schema, artifact) { |
| 505 | Ok(()) => Assertion { |
| 506 | id: schema_id, |
| 507 | expected: expected.to_string(), |
| 508 | observed: "valid".to_string(), |
| 509 | pass: true, |
| 510 | source: ASSERTION_SOURCE.to_string(), |
| 511 | note: String::new(), |
| 512 | }, |
| 513 | Err(e) => failed_assertion(schema_id, expected, e), |
| 514 | }); |
| 515 | let evals = wf_def["required_evals_on_done"] |
| 516 | .as_array() |
| 517 | .cloned() |
| 518 | .unwrap_or_default(); |
| 519 | for name in evals.iter().filter_map(Value::as_str) { |
| 520 | out.push(self.completion_eval(name, artifact)); |
| 521 | } |
| 522 | out |
| 523 | } |
| 524 | |
| 525 | /// One eval as a completion gate. Fail closed on a missing definition, |
| 526 | /// a non-deterministic kind, or a name the harness cannot execute. |
| 527 | fn completion_eval(&self, name: &str, artifact: &Value) -> Assertion { |
| 528 | let id = format!("eval:{name}"); |
| 529 | let expected = "eval passes"; |
| 530 | let Some(def) = self.evals.get(name) else { |
| 531 | return failed_assertion(id, expected, "no definition in evals.json".to_string()); |
| 532 | }; |
| 533 | let kind = def.get("kind").and_then(Value::as_str).unwrap_or(""); |
| 534 | if kind != "deterministic" { |
| 535 | return failed_assertion( |
| 536 | id, |
| 537 | expected, |
| 538 | format!("eval kind '{kind}' cannot gate completion; only deterministic evals run in the harness"), |
| 539 | ); |
| 540 | } |
| 541 | let (passed, reason) = if name == "slop_gate" { |
| 542 | // `run_eval("slop_gate")` reads only a top-level `text` field, |
| 543 | // which no completion schema declares, so on its own it would |
| 544 | // pass every artifact. As a completion gate it scans every string |
| 545 | // value in the artifact instead. |
| 546 | let mut strings = Vec::new(); |
| 547 | collect_strings(artifact, String::new(), &mut strings); |
| 548 | match strings |
| 549 | .iter() |
| 550 | .find_map(|(p, s)| crate::slop_violation(s).map(|r| format!("at '{p}': {r}"))) |
| 551 | { |
| 552 | Some(r) => (false, r), |
| 553 | None => (true, format!("{} string value(s) clean", strings.len())), |
| 554 | } |
| 555 | } else { |
| 556 | let r = self.run_eval(name, artifact); |
| 557 | (r.passed, r.reason) |
| 558 | }; |
| 559 | Assertion { |
| 560 | id, |
| 561 | expected: expected.to_string(), |
| 562 | observed: reason, |
| 563 | pass: passed, |
| 564 | source: ASSERTION_SOURCE.to_string(), |
| 565 | note: String::new(), |
| 566 | } |
| 567 | } |
| 568 | |
| 569 | fn mint_receipt( |
| 570 | &self, |
| 571 | wf: &WorkflowState, |
| 572 | wf_def: &Value, |
| 573 | sub: &CompletionSubmission, |
| 574 | digest: &str, |
| 575 | assertions: Vec<Assertion>, |
| 576 | ) -> Result<Receipt, CompletionError> { |
| 577 | let result = if assertions.iter().all(|a| a.pass) { |
| 578 | Verdict::Pass |
| 579 | } else { |
| 580 | Verdict::Fail |
| 581 | }; |
| 582 | let assertion_bytes = |
| 583 | serde_json::to_vec(&assertions).map_err(|e| CompletionError::Store(e.to_string()))?; |
| 584 | let repo = if self.completion_repo.trim().is_empty() { |
| 585 | crate::UNSPECIFIED_REPO.to_string() |
| 586 | } else { |
| 587 | self.completion_repo.clone() |
| 588 | }; |
| 589 | let mut r = Receipt { |
| 590 | schema: evidence::SCHEMA.to_string(), |
| 591 | version: evidence::SCHEMA_VERSION, |
| 592 | id: String::new(), |
| 593 | kind: COMPLETION_KIND.to_string(), |
| 594 | tier: COMPLETION_TIER, |
| 595 | result, |
| 596 | timestamp: (self.completion_clock)(), |
| 597 | repo, |
| 598 | commit: sub.source_commit.clone(), |
| 599 | dirty: false, |
| 600 | toolchain: format!("spark-harness {}", env!("CARGO_PKG_VERSION")), |
| 601 | procedure: format!( |
| 602 | "spark-harness complete_verified_workflow workflow_type={}", |
| 603 | wf.workflow_type |
| 604 | ), |
| 605 | machine: host_identity(), |
| 606 | env_class: COMPLETION_TIER.as_str().to_string(), |
| 607 | // The gate definition that was applied. |
| 608 | input_artifacts: vec![format!("blake3:{}", artifact_digest(wf_def))], |
| 609 | output_artifacts: vec![format!("blake3:{digest}")], |
| 610 | assertions, |
| 611 | dependencies: Vec::new(), |
| 612 | declared_mutation: Mutation::None, |
| 613 | observed_mutation: Mutation::None, |
| 614 | authority: String::new(), |
| 615 | output_digest: blake3::hash(&assertion_bytes).to_hex().to_string(), |
| 616 | external_refs: vec![ |
| 617 | format!("task:{}", sub.task_id), |
| 618 | format!("workflow:{}", wf.id), |
| 619 | format!("generation:{}", sub.generation), |
| 620 | ], |
| 621 | ledger: None, |
| 622 | lease: None, |
| 623 | required_features: Vec::new(), |
| 624 | reserved: String::new(), |
| 625 | }; |
| 626 | r.id = evidence::receipt_id(&r).map_err(CompletionError::Store)?; |
| 627 | Ok(r) |
| 628 | } |
| 629 | |
| 630 | /// The only path into `done`. See the module docs for the full contract. |
| 631 | pub fn complete_verified_workflow( |
| 632 | &self, |
| 633 | wf: &mut WorkflowState, |
| 634 | sub: &CompletionSubmission, |
| 635 | ) -> Result<CompletionRecord, CompletionError> { |
| 636 | if !self.load_errors.is_empty() { |
| 637 | return Err(CompletionError::DefinitionsNotLoaded( |
| 638 | self.load_errors.clone(), |
| 639 | )); |
| 640 | } |
| 641 | check_identifier("task_id", &sub.task_id)?; |
| 642 | check_identifier("workflow id", &wf.id)?; |
| 643 | evidence::check_commit(&sub.source_commit).map_err(CompletionError::InvalidSubmission)?; |
| 644 | |
| 645 | let wf_def = self |
| 646 | .workflows |
| 647 | .get(&wf.workflow_type) |
| 648 | .ok_or_else(|| CompletionError::UnknownWorkflow(wf.workflow_type.clone()))?; |
| 649 | crate::validate_workflow_def(&wf.workflow_type, wf_def) |
| 650 | .map_err(CompletionError::MalformedWorkflow)?; |
| 651 | let allowed: Vec<String> = wf_def["states"] |
| 652 | .get(&wf.current_state) |
| 653 | .and_then(|s| s.get("next")) |
| 654 | .and_then(Value::as_array) |
| 655 | .map(|a| { |
| 656 | a.iter() |
| 657 | .filter_map(Value::as_str) |
| 658 | .map(str::to_string) |
| 659 | .collect() |
| 660 | }) |
| 661 | .unwrap_or_default(); |
| 662 | if !allowed.iter().any(|s| s == DONE_STATE) { |
| 663 | return Err(CompletionError::IllegalTransition { |
| 664 | from: wf.current_state.clone(), |
| 665 | allowed, |
| 666 | }); |
| 667 | } |
| 668 | |
| 669 | let consumed_dir = self.consumed_dir(); |
| 670 | fs::create_dir_all(&consumed_dir).map_err(|e| { |
| 671 | CompletionError::Store(format!("cannot create {}: {e}", consumed_dir.display())) |
| 672 | })?; |
| 673 | // Serializes completions across threads and processes sharing this |
| 674 | // store. flock is released by the kernel if the holder dies. |
| 675 | let _lock = FileLock::acquire(&consumed_dir.join(".lock")) |
| 676 | .map_err(|e| CompletionError::Store(format!("cannot lock completion store: {e}")))?; |
| 677 | let record_path = consumed_dir.join(format!("{}.json", task_key(&sub.task_id))); |
| 678 | if let Some(prev) = read_consumed(&record_path, &sub.task_id)? { |
| 679 | if sub.generation == prev.generation { |
| 680 | return Err(CompletionError::DuplicateCompletion { |
| 681 | task_id: sub.task_id.clone(), |
| 682 | generation: sub.generation, |
| 683 | receipt_id: prev.receipt_id, |
| 684 | }); |
| 685 | } |
| 686 | if sub.generation < prev.generation { |
| 687 | return Err(CompletionError::StaleGeneration { |
| 688 | task_id: sub.task_id.clone(), |
| 689 | submitted: sub.generation, |
| 690 | recorded: prev.generation, |
| 691 | }); |
| 692 | } |
| 693 | } |
| 694 | |
| 695 | let assertions = self.evaluate_gates(wf_def, &sub.artifact); |
| 696 | let failures: Vec<String> = assertions |
| 697 | .iter() |
| 698 | .filter(|a| !a.pass) |
| 699 | .map(|a| format!("{}: {}", a.id, a.observed)) |
| 700 | .collect(); |
| 701 | let digest = artifact_digest(&sub.artifact); |
| 702 | let receipt = self.mint_receipt(wf, wf_def, sub, &digest, assertions)?; |
| 703 | let receipt_id = evidence::store_receipt(&self.completion_store, &receipt) |
| 704 | .map_err(CompletionError::Store)?; |
| 705 | if receipt.result != Verdict::Pass { |
| 706 | return Err(CompletionError::GatesFailed { |
| 707 | receipt_id, |
| 708 | failures, |
| 709 | }); |
| 710 | } |
| 711 | |
| 712 | write_consumed( |
| 713 | &record_path, |
| 714 | &ConsumedRecord { |
| 715 | task_id: sub.task_id.clone(), |
| 716 | generation: sub.generation, |
| 717 | receipt_id: receipt_id.clone(), |
| 718 | workflow_id: wf.id.clone(), |
| 719 | artifact_digest: digest.clone(), |
| 720 | }, |
| 721 | )?; |
| 722 | wf.history.push(wf.current_state.clone()); |
| 723 | wf.current_state = DONE_STATE.to_string(); |
| 724 | Ok(CompletionRecord { |
| 725 | receipt_id, |
| 726 | task_id: sub.task_id.clone(), |
| 727 | workflow_id: wf.id.clone(), |
| 728 | workflow_type: wf.workflow_type.clone(), |
| 729 | generation: sub.generation, |
| 730 | source_commit: sub.source_commit.clone(), |
| 731 | artifact_digest: digest, |
| 732 | }) |
| 733 | } |
| 734 | |
| 735 | /// MCP `harness_complete` adapter. Arguments: |
| 736 | /// `{ "workflow": WorkflowState, "submission": CompletionSubmission }`. |
| 737 | /// The MCP server holds no workflow state, so `workflow.current_state` is |
| 738 | /// caller-declared there; the binding proof is the stored receipt and the |
| 739 | /// consumed record, both written only by the harness. |
| 740 | pub fn handle_complete_request(&self, args: &Value) -> Result<Value, CompletionError> { |
| 741 | #[derive(Deserialize)] |
| 742 | #[serde(deny_unknown_fields)] |
| 743 | struct CompleteArgs { |
| 744 | workflow: WorkflowState, |
| 745 | submission: CompletionSubmission, |
| 746 | } |
| 747 | let parsed: CompleteArgs = serde_json::from_value(args.clone()).map_err(|e| { |
| 748 | CompletionError::InvalidSubmission(format!("harness_complete arguments: {e}")) |
| 749 | })?; |
| 750 | let mut wf = parsed.workflow; |
| 751 | let record = self.complete_verified_workflow(&mut wf, &parsed.submission)?; |
| 752 | Ok(json!({ "record": record, "workflow": wf })) |
| 753 | } |
| 754 | } |
| 755 | |
| 756 | pub(crate) fn single_ref<'a>(refs: &'a [String], prefix: &str) -> Result<&'a str, CompletionError> { |
| 757 | let found: Vec<&str> = refs.iter().filter_map(|r| r.strip_prefix(prefix)).collect(); |
| 758 | match found.as_slice() { |
| 759 | [one] => Ok(one), |
| 760 | _ => Err(CompletionError::ReceiptInvalid(format!( |
| 761 | "expected exactly one '{prefix}' external ref, found {}", |
| 762 | found.len() |
| 763 | ))), |
| 764 | } |
| 765 | } |
| 766 | |
| 767 | pub(crate) fn require( |
| 768 | field: &'static str, |
| 769 | expected: &str, |
| 770 | found: &str, |
| 771 | ) -> Result<(), CompletionError> { |
| 772 | if expected == found { |
| 773 | Ok(()) |
| 774 | } else { |
| 775 | Err(CompletionError::BindingMismatch { |
| 776 | field, |
| 777 | expected: expected.to_string(), |
| 778 | found: found.to_string(), |
| 779 | }) |
| 780 | } |
| 781 | } |
| 782 | |
| 783 | /// Check that `receipt_id` in `store` is a PASS harness completion receipt |
| 784 | /// bound to exactly this task, generation, source commit and artifact digest |
| 785 | /// (bare BLAKE3 hex or `blake3:<hex>`), and that it is the task's current |
| 786 | /// completion: the consumed record must name this receipt, generation and |
| 787 | /// digest. Superseded generations and orphan receipts fail. Identity is |
| 788 | /// recomputed by aien-proof; see the module docs for what that does and does |
| 789 | /// not prove. |
| 790 | pub fn verify_completion( |
| 791 | store: &Path, |
| 792 | receipt_id: &str, |
| 793 | task_id: &str, |
| 794 | generation: u64, |
| 795 | commit: &str, |
| 796 | artifact_digest: &str, |
| 797 | ) -> Result<VerifiedCompletion, CompletionError> { |
| 798 | let receipt = |
| 799 | evidence::load_receipt(store, receipt_id).map_err(CompletionError::ReceiptInvalid)?; |
| 800 | // load_receipt checks identity but discards the consistency report, so |
| 801 | // re-read the same file and take the report from verify_bytes. |
| 802 | let path = store |
| 803 | .join(evidence::RECEIPT_DIR) |
| 804 | .join(format!("{}.json", receipt.id)); |
| 805 | let bytes = fs::read(&path) |
| 806 | .map_err(|e| CompletionError::ReceiptInvalid(format!("{}: {e}", path.display())))?; |
| 807 | let (again, report) = |
| 808 | evidence::verify_bytes(&bytes).map_err(CompletionError::ReceiptInvalid)?; |
| 809 | if again != receipt { |
| 810 | return Err(CompletionError::ReceiptInvalid( |
| 811 | "receipt file changed while being verified".to_string(), |
| 812 | )); |
| 813 | } |
| 814 | if receipt.result != Verdict::Pass || !report.ok() { |
| 815 | return Err(CompletionError::NotPass(format!( |
| 816 | "{} ({})", |
| 817 | receipt.result.as_str(), |
| 818 | report.reasons.join("; ") |
| 819 | ))); |
| 820 | } |
| 821 | require("kind", COMPLETION_KIND, &receipt.kind)?; |
| 822 | require("tier", COMPLETION_TIER.as_str(), receipt.tier.as_str())?; |
| 823 | if !receipt |
| 824 | .assertions |
| 825 | .iter() |
| 826 | .any(|a| a.id.starts_with("schema:")) |
| 827 | { |
| 828 | return Err(CompletionError::ReceiptInvalid( |
| 829 | "completion receipt carries no schema assertion".to_string(), |
| 830 | )); |
| 831 | } |
| 832 | require("commit", commit, &receipt.commit)?; |
| 833 | let want_digest = artifact_digest |
| 834 | .strip_prefix("blake3:") |
| 835 | .unwrap_or(artifact_digest); |
| 836 | let want = format!("blake3:{}", want_digest.to_ascii_lowercase()); |
| 837 | let found = receipt.output_artifacts.join(","); |
| 838 | require("artifact_digest", &want, &found)?; |
| 839 | let found_task = single_ref(&receipt.external_refs, "task:")?; |
| 840 | require("task", task_id, found_task)?; |
| 841 | let found_gen = single_ref(&receipt.external_refs, "generation:")?; |
| 842 | require("generation", &generation.to_string(), found_gen)?; |
| 843 | let workflow_id = single_ref(&receipt.external_refs, "workflow:")?; |
| 844 | // The consumed record is the authority on which receipt is the accepted |
| 845 | // completion. A PASS receipt it does not name (an orphan left by a failed |
| 846 | // record write, or a superseded generation) never verifies. |
| 847 | let digest_hex = want_digest.to_ascii_lowercase(); |
| 848 | let record_path = store |
| 849 | .join(CONSUMED_DIR) |
| 850 | .join(format!("{}.json", task_key(task_id))); |
| 851 | let current = read_consumed(&record_path, task_id)?.ok_or_else(|| { |
| 852 | CompletionError::NotCurrentCompletion(format!( |
| 853 | "no consumed completion record for task '{task_id}'; receipt {} is an orphan", |
| 854 | receipt.id |
| 855 | )) |
| 856 | })?; |
| 857 | if current.receipt_id != receipt.id |
| 858 | || current.generation != generation |
| 859 | || current.artifact_digest != digest_hex |
| 860 | { |
| 861 | return Err(CompletionError::NotCurrentCompletion(format!( |
| 862 | "task '{task_id}' current completion is generation {} receipt {} digest {}; \ |
| 863 | receipt {} generation {generation} digest {digest_hex} is not it", |
| 864 | current.generation, current.receipt_id, current.artifact_digest, receipt.id |
| 865 | ))); |
| 866 | } |
| 867 | Ok(VerifiedCompletion { |
| 868 | receipt_id: receipt.id.clone(), |
| 869 | task_id: task_id.to_string(), |
| 870 | workflow_id: workflow_id.to_string(), |
| 871 | generation, |
| 872 | source_commit: receipt.commit.clone(), |
| 873 | artifact_digest: digest_hex, |
| 874 | }) |
| 875 | } |
| 876 | |
| 877 | #[cfg(test)] |
| 878 | mod tests { |
| 879 | use super::*; |
| 880 | |
| 881 | #[test] |
| 882 | fn canonical_json_sorts_keys_at_every_level() { |
| 883 | let a = json!({"b": 1, "a": {"y": [1, {"d": true, "c": null}], "x": "s"}}); |
| 884 | assert_eq!( |
| 885 | canonical_json(&a), |
| 886 | br#"{"a":{"x":"s","y":[1,{"c":null,"d":true}]},"b":1}"#.to_vec() |
| 887 | ); |
| 888 | let b: Value = |
| 889 | serde_json::from_str(r#"{"a":{"y":[1,{"c":null,"d":true}],"x":"s"},"b":1}"#).unwrap(); |
| 890 | assert_eq!(artifact_digest(&a), artifact_digest(&b)); |
| 891 | assert_ne!(artifact_digest(&a), artifact_digest(&json!({"b": 2}))); |
| 892 | } |
| 893 | |
| 894 | #[test] |
| 895 | fn task_key_is_stable_and_distinct() { |
| 896 | assert_eq!(task_key("t1"), task_key("t1")); |
| 897 | assert_ne!(task_key("t1"), task_key("t2")); |
| 898 | assert_eq!(task_key("../etc").len(), 64); |
| 899 | } |
| 900 | |
| 901 | #[test] |
| 902 | fn identifiers_are_checked() { |
| 903 | assert!(check_identifier("task_id", "task-1").is_ok()); |
| 904 | assert!(check_identifier("task_id", "").is_err()); |
| 905 | assert!(check_identifier("task_id", " task").is_err()); |
| 906 | assert!(check_identifier("task_id", "a\nb").is_err()); |
| 907 | assert!(check_identifier("task_id", &"x".repeat(MAX_TASK_ID_LEN + 1)).is_err()); |
| 908 | } |
| 909 | |
| 910 | #[test] |
| 911 | fn single_ref_requires_exactly_one() { |
| 912 | let refs = vec!["task:a".to_string(), "task:b".to_string()]; |
| 913 | assert!(single_ref(&refs, "task:").is_err()); |
| 914 | assert!(single_ref(&refs, "generation:").is_err()); |
| 915 | assert_eq!(single_ref(&refs[..1], "task:").unwrap(), "a"); |
| 916 | } |
| 917 | } |