interplane.Get Omega
Read in your language

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

branch main Branches Tags History

aien-sovereign-core-mv / crates / spark-harness / src / lib.rs

546 lines · 20386 bytes Raw Blame History
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
16use regex::Regex;
17use serde::{Deserialize, Serialize};
18use serde_json::{json, Value};
19use std::collections::HashMap;
20use std::path::{Path, PathBuf};
21
22pub mod completion;
23pub mod dependency;
24pub mod execution;
25pub mod journal;
26pub mod readiness;
27pub mod scheduler;
28
29/// The terminal workflow state. Since Headstart M1 (#533) it is reachable
30/// only through [`HarnessEngine::complete_verified_workflow`], never through
31/// [`HarnessEngine::advance_workflow`]. `done` means "the harness ran the
32/// workflow's completion gates on the submitted artifact and stored a PASS
33/// receipt". It does not mean committed: World commit and authorization stay
34/// in aien-runtime and are not touched by this crate.
35pub const DONE_STATE: &str = "done";
36
37/// Default subdirectory of `base_path` holding the harness-owned completion
38/// store (receipts plus consumed completion records).
39pub const DEFAULT_COMPLETION_STORE: &str = "completion-store";
40
41/// Repo label written into completion receipts when the deployer has not set
42/// one. The harness does not know which repository a submitted commit lives
43/// in, so it says so instead of guessing.
44pub const UNSPECIFIED_REPO: &str = "unspecified";
45
46/// Slop scan shared by `run_eval("slop_gate")` and the completion gate.
47/// Returns the failure reason, or `None` when the text is clean.
48pub(crate) fn slop_violation(text: &str) -> Option<String> {
49 let lower = text.to_lowercase();
50
51 // Disallowed phrases
52 let forbidden = [
53 "this is the part where",
54 "the part everyone's missing",
55 "the part everyone is missing",
56 "in today's fast-paced",
57 "game-changer",
58 "delve into",
59 "unlock the power",
60 "at the end of the day",
61 "it is important to note",
62 "in conclusion,",
63 ];
64
65 for p in forbidden {
66 if lower.contains(p) {
67 return Some(format!("Forbidden AI trope detected: '{}'", p));
68 }
69 }
70
71 // Check antithesis pattern: "not X, it's Y"
72 let antithesis_re = Regex::new(r"(?i)\bnot\s+([a-z0-9_\-\s]+),\s*(it's|it\s+is)\s+").unwrap();
73 if antithesis_re.is_match(&lower) {
74 return Some("Formulaic antithesis trope detected ('not X, it's Y')".to_string());
75 }
76 None
77}
78
79fn read_definition_file(path: &Path) -> Result<HashMap<String, Value>, String> {
80 let content = std::fs::read_to_string(path)
81 .map_err(|e| format!("cannot read {}: {}", path.display(), e))?;
82 serde_json::from_str::<HashMap<String, Value>>(&content)
83 .map_err(|e| format!("invalid JSON object in {}: {}", path.display(), e))
84}
85
86/// Structural check of one workflow definition. Used at load time and again
87/// at completion time, because `workflows` is a public map callers can edit.
88pub fn validate_workflow_def(name: &str, def: &Value) -> Result<(), String> {
89 let states = def
90 .get("states")
91 .and_then(|v| v.as_object())
92 .ok_or_else(|| format!("workflow '{}': 'states' must be an object", name))?;
93 for (state, sdef) in states {
94 let next = sdef.get("next").and_then(|v| v.as_array()).ok_or_else(|| {
95 format!(
96 "workflow '{}': state '{}' needs a 'next' array",
97 name, state
98 )
99 })?;
100 for n in next {
101 let n = n.as_str().ok_or_else(|| {
102 format!(
103 "workflow '{}': state '{}' has a non-string next entry",
104 name, state
105 )
106 })?;
107 if !states.contains_key(n) {
108 return Err(format!(
109 "workflow '{}': state '{}' points to undeclared state '{}'",
110 name, state, n
111 ));
112 }
113 }
114 }
115 if let Some(initial) = def.get("initial") {
116 let initial = initial
117 .as_str()
118 .ok_or_else(|| format!("workflow '{}': 'initial' must be a string", name))?;
119 if !states.contains_key(initial) {
120 return Err(format!(
121 "workflow '{}': initial state '{}' is not declared",
122 name, initial
123 ));
124 }
125 }
126 def.get("required_schema")
127 .and_then(|v| v.as_str())
128 .filter(|s| !s.is_empty())
129 .ok_or_else(|| {
130 format!(
131 "workflow '{}': 'required_schema' must be a non-empty string",
132 name
133 )
134 })?;
135 let evals = def
136 .get("required_evals_on_done")
137 .and_then(|v| v.as_array())
138 .ok_or_else(|| {
139 format!(
140 "workflow '{}': 'required_evals_on_done' must be an array",
141 name
142 )
143 })?;
144 let mut seen = std::collections::BTreeSet::new();
145 for e in evals {
146 let e = e
147 .as_str()
148 .filter(|s| !s.is_empty())
149 .ok_or_else(|| format!("workflow '{}': eval names must be non-empty strings", name))?;
150 if !seen.insert(e) {
151 return Err(format!("workflow '{}': eval '{}' listed twice", name, e));
152 }
153 }
154 Ok(())
155}
156
157fn validate_eval_def(name: &str, def: &Value) -> Result<(), String> {
158 def.get("kind")
159 .and_then(|v| v.as_str())
160 .filter(|s| !s.is_empty())
161 .map(|_| ())
162 .ok_or_else(|| format!("eval '{}': 'kind' must be a non-empty string", name))
163}
164
165fn load_evals(base: &Path) -> Result<HashMap<String, Value>, String> {
166 let m = read_definition_file(&base.join("evals.json"))?;
167 for (k, v) in &m {
168 validate_eval_def(k, v)?;
169 }
170 Ok(m)
171}
172
173fn load_workflows(base: &Path) -> Result<HashMap<String, Value>, String> {
174 let m = read_definition_file(&base.join("workflows.json"))?;
175 for (k, v) in &m {
176 validate_workflow_def(k, v)?;
177 }
178 Ok(m)
179}
180
181#[derive(Debug, Clone, Serialize, Deserialize)]
182pub struct EvalResult {
183 pub name: String,
184 pub passed: bool,
185 pub reason: String,
186}
187
188#[derive(Debug, Clone, Serialize, Deserialize)]
189pub struct WorkflowState {
190 pub id: String,
191 pub workflow_type: String,
192 pub current_state: String,
193 pub history: Vec<String>,
194 pub created_at: String,
195}
196
197#[derive(Debug, Clone)]
198pub struct HarnessEngine {
199 pub base_path: PathBuf,
200 pub evals: HashMap<String, Value>,
201 pub workflows: HashMap<String, Value>,
202 /// Errors from the last definition load. The verified completion API
203 /// refuses to run while this is non-empty, so a missing or broken
204 /// workflows.json or evals.json can never let a completion through.
205 pub load_errors: Vec<String>,
206 /// Harness-owned evidence store for completion receipts and consumed
207 /// completion records. Defaults to `<base_path>/completion-store`.
208 pub completion_store: PathBuf,
209 /// Repo identity recorded in completion receipts.
210 pub completion_repo: String,
211 /// Unix-seconds clock for receipt timestamps. Defaults to the system
212 /// clock; tests swap it to make receipt IDs deterministic.
213 pub completion_clock: fn() -> u64,
214}
215
216/// System clock in Unix seconds (0 if the clock is before the epoch).
217pub fn system_clock_secs() -> u64 {
218 std::time::SystemTime::now()
219 .duration_since(std::time::UNIX_EPOCH)
220 .map(|d| d.as_secs())
221 .unwrap_or(0)
222}
223
224impl HarnessEngine {
225 /// Compatibility constructor. Loads what it can, as before, but records
226 /// every load error in `load_errors` so the verified completion API
227 /// refuses to run on missing or broken definitions.
228 pub fn new<P: AsRef<Path>>(base_path: P) -> Self {
229 let base = base_path.as_ref().to_path_buf();
230 let mut engine = Self {
231 completion_store: base.join(DEFAULT_COMPLETION_STORE),
232 base_path: base,
233 evals: HashMap::new(),
234 workflows: HashMap::new(),
235 load_errors: Vec::new(),
236 completion_repo: UNSPECIFIED_REPO.to_string(),
237 completion_clock: system_clock_secs,
238 };
239 engine.reload();
240 engine
241 }
242
243 /// Fail-closed constructor: errors when workflows.json or evals.json is
244 /// missing, is not a JSON object, or holds a malformed definition.
245 pub fn load<P: AsRef<Path>>(base_path: P) -> Result<Self, String> {
246 let engine = Self::new(base_path);
247 if engine.load_errors.is_empty() {
248 Ok(engine)
249 } else {
250 Err(engine.load_errors.join("; "))
251 }
252 }
253
254 /// Re-read both definition files. A file that fails to load keeps the
255 /// previous in-memory map (the old behavior) and adds an entry to
256 /// `load_errors`, which blocks verified completion until a clean reload.
257 pub fn reload(&mut self) {
258 self.load_errors.clear();
259 match load_evals(&self.base_path) {
260 Ok(m) => self.evals = m,
261 Err(e) => self.load_errors.push(e),
262 }
263 match load_workflows(&self.base_path) {
264 Ok(m) => self.workflows = m,
265 Err(e) => self.load_errors.push(e),
266 }
267 }
268
269 /// Layer 1: Schema Validation
270 pub fn validate_schema(&self, schema_name: &str, data: &Value) -> Result<(), String> {
271 let schema_path = self
272 .base_path
273 .join("schemas")
274 .join(format!("{}.json", schema_name));
275 if !schema_path.exists() {
276 return Err(format!(
277 "Schema '{}' not found at {:?}",
278 schema_name, schema_path
279 ));
280 }
281
282 let content = std::fs::read_to_string(&schema_path)
283 .map_err(|e| format!("Failed to read schema {}: {}", schema_name, e))?;
284 let schema_json: Value = serde_json::from_str(&content)
285 .map_err(|e| format!("Invalid JSON in schema {}: {}", schema_name, e))?;
286
287 let compiled = jsonschema::JSONSchema::compile(&schema_json)
288 .map_err(|e| format!("Schema compilation failed: {}", e))?;
289
290 if let Err(errors) = compiled.validate(data) {
291 let err_msgs: Vec<String> = errors.map(|e| e.to_string()).collect();
292 return Err(format!("Schema validation failed: {}", err_msgs.join("; ")));
293 }
294
295 Ok(())
296 }
297
298 /// Layer 2: Deterministic Evals & Guardrails
299 pub fn run_eval(&self, eval_name: &str, payload: &Value) -> EvalResult {
300 match eval_name {
301 "slop_gate" => {
302 let text = payload.get("text").and_then(|v| v.as_str()).unwrap_or("");
303 match slop_violation(text) {
304 Some(reason) => EvalResult {
305 name: eval_name.to_string(),
306 passed: false,
307 reason,
308 },
309 None => EvalResult {
310 name: eval_name.to_string(),
311 passed: true,
312 reason: "Slop gate passed clean.".to_string(),
313 },
314 }
315 }
316
317 "required_evidence" => {
318 let evidence = payload.get("evidence").and_then(|v| v.as_array());
319 match evidence {
320 Some(arr) if !arr.is_empty() => EvalResult {
321 name: eval_name.to_string(),
322 passed: true,
323 reason: format!("Evidence present ({} item(s)).", arr.len()),
324 },
325 _ => EvalResult {
326 name: eval_name.to_string(),
327 passed: false,
328 reason: "Required evidence array is missing or empty.".to_string(),
329 },
330 }
331 }
332
333 "reproduction_present" => {
334 let repro = payload.get("reproduction_steps").and_then(|v| v.as_array());
335 let failure = payload.get("failure_evidence").and_then(|v| v.as_str());
336 if repro.map(|a| !a.is_empty()).unwrap_or(false)
337 && failure.map(|s| !s.trim().is_empty()).unwrap_or(false)
338 {
339 EvalResult {
340 name: eval_name.to_string(),
341 passed: true,
342 reason: "Reproduction steps and failure evidence verified.".to_string(),
343 }
344 } else {
345 EvalResult {
346 name: eval_name.to_string(),
347 passed: false,
348 reason: "Reproduction steps and failure evidence must be non-empty."
349 .to_string(),
350 }
351 }
352 }
353
354 _ => EvalResult {
355 name: eval_name.to_string(),
356 passed: false,
357 reason: format!("Unknown eval rule: '{}'", eval_name),
358 },
359 }
360 }
361
362 /// Layer 4: State Machine Workflow Engine
363 ///
364 /// Checks transition legality only. A transition into [`DONE_STATE`] is
365 /// always refused here: a legal transition by itself is not proof of
366 /// completion. Use [`HarnessEngine::complete_verified_workflow`], which
367 /// runs the workflow's completion gates on the real artifact and stores a
368 /// harness-minted receipt before moving to `done`.
369 pub fn advance_workflow(&self, wf: &mut WorkflowState, next_state: &str) -> Result<(), String> {
370 if next_state == DONE_STATE {
371 return Err(format!(
372 "Refusing transition from '{}' to '{}': '{}' is reachable only through \
373 verified completion (complete_verified_workflow / MCP harness_complete).",
374 wf.current_state, DONE_STATE, DONE_STATE
375 ));
376 }
377 let wf_def = self
378 .workflows
379 .get(&wf.workflow_type)
380 .ok_or_else(|| format!("Unknown workflow type: '{}'", wf.workflow_type))?;
381
382 let states = wf_def
383 .get("states")
384 .and_then(|v| v.as_object())
385 .ok_or_else(|| "Malformed workflow states definition".to_string())?;
386
387 let current_def = states
388 .get(&wf.current_state)
389 .ok_or_else(|| format!("Current state '{}' not found in workflow", wf.current_state))?;
390
391 let allowed_next: Vec<&str> = current_def
392 .get("next")
393 .and_then(|v| v.as_array())
394 .map(|arr| arr.iter().filter_map(|s| s.as_str()).collect())
395 .unwrap_or_default();
396
397 if !allowed_next.contains(&next_state) {
398 return Err(format!(
399 "Invalid transition from '{}' to '{}'. Allowed: {:?}",
400 wf.current_state, next_state, allowed_next
401 ));
402 }
403
404 wf.history.push(wf.current_state.clone());
405 wf.current_state = next_state.to_string();
406 Ok(())
407 }
408
409 /// Layer 5: Failure Replay Verification
410 pub fn record_failure(
411 &self,
412 task_id: &str,
413 failure_type: &str,
414 details: &Value,
415 ) -> Result<PathBuf, String> {
416 let failures_dir = self.base_path.join("failures");
417 std::fs::create_dir_all(&failures_dir)
418 .map_err(|e| format!("Failed to create failures dir: {}", e))?;
419
420 let file_name = format!(
421 "failure_{}_{}.json",
422 task_id,
423 chrono::Utc::now().timestamp()
424 );
425 let file_path = failures_dir.join(file_name);
426
427 let record = json!({
428 "task_id": task_id,
429 "failure_type": failure_type,
430 "timestamp": chrono::Utc::now().to_rfc3339(),
431 "details": details,
432 });
433
434 std::fs::write(&file_path, serde_json::to_string_pretty(&record).unwrap())
435 .map_err(|e| format!("Failed to write failure log: {}", e))?;
436
437 Ok(file_path)
438 }
439}
440
441#[cfg(test)]
442mod tests {
443 use super::*;
444 use serde_json::json;
445
446 #[test]
447 fn test_slop_gate() {
448 let engine = HarnessEngine::new(std::path::Path::new(env!("CARGO_MANIFEST_DIR")));
449 let clean = json!({ "text": "Direct execution of native Rust binary on DGX Spark." });
450 let slopped =
451 json!({ "text": "In today's fast-paced world, this is a game-changer to delve into." });
452 let antithesis = json!({ "text": "It is not speed, it's quality." });
453
454 assert!(engine.run_eval("slop_gate", &clean).passed);
455 assert!(!engine.run_eval("slop_gate", &slopped).passed);
456 assert!(!engine.run_eval("slop_gate", &antithesis).passed);
457 }
458
459 #[test]
460 fn test_required_evidence() {
461 let engine = HarnessEngine::new(std::path::Path::new(env!("CARGO_MANIFEST_DIR")));
462 let no_evidence = json!({ "text": "Sample" });
463 let has_evidence = json!({ "text": "Sample", "evidence": ["commit c9db3e2"] });
464
465 assert!(!engine.run_eval("required_evidence", &no_evidence).passed);
466 assert!(engine.run_eval("required_evidence", &has_evidence).passed);
467 }
468
469 #[test]
470 fn test_reproduction_present() {
471 let engine = HarnessEngine::new(std::path::Path::new(env!("CARGO_MANIFEST_DIR")));
472 let invalid = json!({ "reproduction_steps": [] });
473 let valid = json!({
474 "reproduction_steps": ["step 1"],
475 "failure_evidence": "panic log"
476 });
477
478 assert!(!engine.run_eval("reproduction_present", &invalid).passed);
479 assert!(engine.run_eval("reproduction_present", &valid).passed);
480 }
481
482 #[test]
483 fn test_workflow_transitions() {
484 let mut engine = HarnessEngine::new(std::path::Path::new(env!("CARGO_MANIFEST_DIR")));
485 engine.workflows.insert(
486 "test_flow".to_string(),
487 json!({
488 "states": {
489 "start": { "next": ["in_progress"] },
490 "in_progress": { "next": ["done"] },
491 "done": { "next": [] }
492 }
493 }),
494 );
495
496 let mut wf = WorkflowState {
497 id: "wf-1".to_string(),
498 workflow_type: "test_flow".to_string(),
499 current_state: "start".to_string(),
500 history: Vec::new(),
501 created_at: chrono::Utc::now().to_rfc3339(),
502 };
503
504 assert!(engine.advance_workflow(&mut wf, "in_progress").is_ok());
505 assert_eq!(wf.current_state, "in_progress");
506 // `done` is legal per the state table but only reachable through
507 // verified completion, so advance_workflow refuses it and leaves the
508 // state and history untouched.
509 let err = engine.advance_workflow(&mut wf, "done").unwrap_err();
510 assert!(err.contains("complete_verified_workflow"), "{err}");
511 assert_eq!(wf.current_state, "in_progress");
512 assert_eq!(wf.history, vec!["start".to_string()]);
513 assert!(engine.advance_workflow(&mut wf, "start").is_err());
514 }
515
516 #[test]
517 fn test_shipped_definitions_load_clean() {
518 let engine = HarnessEngine::load(env!("CARGO_MANIFEST_DIR")).unwrap();
519 assert!(engine.load_errors.is_empty());
520 for wf in [
521 "engineering_fix",
522 "research_handoff",
523 "harness_change",
524 "python_pipeline",
525 ] {
526 assert!(engine.workflows.contains_key(wf), "{wf}");
527 }
528 }
529
530 #[test]
531 fn test_schema_validation() {
532 let engine = HarnessEngine::new(std::path::Path::new(env!("CARGO_MANIFEST_DIR")));
533 let valid_payload = json!({
534 "bug": "Parser rejects valid token sequence",
535 "reproduction_steps": ["Run parser test"],
536 "failure_evidence": "thread panicked at line 42",
537 "regression_test": "tests::test_parser",
538 "diff_summary": "Fixed token parser logic",
539 "retest_evidence": "All tests passing cleanly"
540 });
541
542 assert!(engine
543 .validate_schema("engineering_fix", &valid_payload)
544 .is_ok());
545 }
546}