aien-harness
Autonomous agent verification and benchmark test harness
Brought by drakestapleton
aien-harness / src / lib.rs
| 1 | use regex::Regex; |
| 2 | use serde::{Deserialize, Serialize}; |
| 3 | use serde_json::{json, Value}; |
| 4 | use std::collections::HashMap; |
| 5 | use std::path::{Path, PathBuf}; |
| 6 | |
| 7 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 8 | pub struct EvalResult { |
| 9 | pub name: String, |
| 10 | pub passed: bool, |
| 11 | pub reason: String, |
| 12 | } |
| 13 | |
| 14 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 15 | pub struct WorkflowState { |
| 16 | pub id: String, |
| 17 | pub workflow_type: String, |
| 18 | pub current_state: String, |
| 19 | pub history: Vec<String>, |
| 20 | pub created_at: String, |
| 21 | } |
| 22 | |
| 23 | #[derive(Debug, Clone)] |
| 24 | pub struct HarnessEngine { |
| 25 | pub base_path: PathBuf, |
| 26 | pub evals: HashMap<String, Value>, |
| 27 | pub workflows: HashMap<String, Value>, |
| 28 | } |
| 29 | |
| 30 | impl HarnessEngine { |
| 31 | pub fn new<P: AsRef<Path>>(base_path: P) -> Self { |
| 32 | let base = base_path.as_ref().to_path_buf(); |
| 33 | let mut engine = Self { |
| 34 | base_path: base, |
| 35 | evals: HashMap::new(), |
| 36 | workflows: HashMap::new(), |
| 37 | }; |
| 38 | engine.reload(); |
| 39 | engine |
| 40 | } |
| 41 | |
| 42 | pub fn reload(&mut self) { |
| 43 | let evals_path = self.base_path.join("evals.json"); |
| 44 | if let Ok(content) = std::fs::read_to_string(&evals_path) { |
| 45 | if let Ok(val) = serde_json::from_str::<HashMap<String, Value>>(&content) { |
| 46 | self.evals = val; |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | let wf_path = self.base_path.join("workflows.json"); |
| 51 | if let Ok(content) = std::fs::read_to_string(&wf_path) { |
| 52 | if let Ok(val) = serde_json::from_str::<HashMap<String, Value>>(&content) { |
| 53 | self.workflows = val; |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | /// Layer 1: Schema Validation |
| 59 | pub fn validate_schema(&self, schema_name: &str, data: &Value) -> Result<(), String> { |
| 60 | let schema_path = self.base_path.join("schemas").join(format!("{}.json", schema_name)); |
| 61 | if !schema_path.exists() { |
| 62 | return Err(format!("Schema '{}' not found at {:?}", schema_name, schema_path)); |
| 63 | } |
| 64 | |
| 65 | let content = std::fs::read_to_string(&schema_path) |
| 66 | .map_err(|e| format!("Failed to read schema {}: {}", schema_name, e))?; |
| 67 | let schema_json: Value = serde_json::from_str(&content) |
| 68 | .map_err(|e| format!("Invalid JSON in schema {}: {}", schema_name, e))?; |
| 69 | |
| 70 | let compiled = jsonschema::JSONSchema::compile(&schema_json) |
| 71 | .map_err(|e| format!("Schema compilation failed: {}", e))?; |
| 72 | |
| 73 | if let Err(errors) = compiled.validate(data) { |
| 74 | let err_msgs: Vec<String> = errors.map(|e| e.to_string()).collect(); |
| 75 | return Err(format!("Schema validation failed: {}", err_msgs.join("; "))); |
| 76 | } |
| 77 | |
| 78 | Ok(()) |
| 79 | } |
| 80 | |
| 81 | /// Layer 2: Deterministic Evals & Guardrails |
| 82 | pub fn run_eval(&self, eval_name: &str, payload: &Value) -> EvalResult { |
| 83 | match eval_name { |
| 84 | "slop_gate" => { |
| 85 | let text = payload.get("text").and_then(|v| v.as_str()).unwrap_or(""); |
| 86 | let lower = text.to_lowercase(); |
| 87 | |
| 88 | // Disallowed phrases |
| 89 | let forbidden = [ |
| 90 | "this is the part where", |
| 91 | "the part everyone's missing", |
| 92 | "the part everyone is missing", |
| 93 | "in today's fast-paced", |
| 94 | "game-changer", |
| 95 | "delve into", |
| 96 | "unlock the power", |
| 97 | "at the end of the day", |
| 98 | "it is important to note", |
| 99 | "in conclusion,", |
| 100 | ]; |
| 101 | |
| 102 | for p in forbidden { |
| 103 | if lower.contains(p) { |
| 104 | return EvalResult { |
| 105 | name: eval_name.to_string(), |
| 106 | passed: false, |
| 107 | reason: format!("Forbidden AI trope detected: '{}'", p), |
| 108 | }; |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | // Check antithesis pattern: "not X, it's Y" |
| 113 | let antithesis_re = Regex::new(r"(?i)\bnot\s+([a-z0-9_\-\s]+),\s*(it's|it\s+is)\s+").unwrap(); |
| 114 | if antithesis_re.is_match(&lower) { |
| 115 | return EvalResult { |
| 116 | name: eval_name.to_string(), |
| 117 | passed: false, |
| 118 | reason: "Formulaic antithesis trope detected ('not X, it's Y')".to_string(), |
| 119 | }; |
| 120 | } |
| 121 | |
| 122 | EvalResult { |
| 123 | name: eval_name.to_string(), |
| 124 | passed: true, |
| 125 | reason: "Slop gate passed clean.".to_string(), |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | "required_evidence" => { |
| 130 | let evidence = payload.get("evidence").and_then(|v| v.as_array()); |
| 131 | match evidence { |
| 132 | Some(arr) if !arr.is_empty() => EvalResult { |
| 133 | name: eval_name.to_string(), |
| 134 | passed: true, |
| 135 | reason: format!("Evidence present ({} item(s)).", arr.len()), |
| 136 | }, |
| 137 | _ => EvalResult { |
| 138 | name: eval_name.to_string(), |
| 139 | passed: false, |
| 140 | reason: "Required evidence array is missing or empty.".to_string(), |
| 141 | }, |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | "reproduction_present" => { |
| 146 | let repro = payload.get("reproduction_steps").and_then(|v| v.as_array()); |
| 147 | let failure = payload.get("failure_evidence").and_then(|v| v.as_str()); |
| 148 | if repro.map(|a| !a.is_empty()).unwrap_or(false) && failure.map(|s| !s.trim().is_empty()).unwrap_or(false) { |
| 149 | EvalResult { |
| 150 | name: eval_name.to_string(), |
| 151 | passed: true, |
| 152 | reason: "Reproduction steps and failure evidence verified.".to_string(), |
| 153 | } |
| 154 | } else { |
| 155 | EvalResult { |
| 156 | name: eval_name.to_string(), |
| 157 | passed: false, |
| 158 | reason: "Reproduction steps and failure evidence must be non-empty.".to_string(), |
| 159 | } |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | _ => EvalResult { |
| 164 | name: eval_name.to_string(), |
| 165 | passed: false, |
| 166 | reason: format!("Unknown eval rule: '{}'", eval_name), |
| 167 | }, |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | /// Layer 4: State Machine Workflow Engine |
| 172 | pub fn advance_workflow(&self, wf: &mut WorkflowState, next_state: &str) -> Result<(), String> { |
| 173 | let wf_def = self.workflows.get(&wf.workflow_type) |
| 174 | .ok_or_else(|| format!("Unknown workflow type: '{}'", wf.workflow_type))?; |
| 175 | |
| 176 | let states = wf_def.get("states").and_then(|v| v.as_object()) |
| 177 | .ok_or_else(|| "Malformed workflow states definition".to_string())?; |
| 178 | |
| 179 | let current_def = states.get(&wf.current_state) |
| 180 | .ok_or_else(|| format!("Current state '{}' not found in workflow", wf.current_state))?; |
| 181 | |
| 182 | let allowed_next: Vec<&str> = current_def.get("next") |
| 183 | .and_then(|v| v.as_array()) |
| 184 | .map(|arr| arr.iter().filter_map(|s| s.as_str()).collect()) |
| 185 | .unwrap_or_default(); |
| 186 | |
| 187 | if !allowed_next.contains(&next_state) { |
| 188 | return Err(format!( |
| 189 | "Invalid transition from '{}' to '{}'. Allowed: {:?}", |
| 190 | wf.current_state, next_state, allowed_next |
| 191 | )); |
| 192 | } |
| 193 | |
| 194 | wf.history.push(wf.current_state.clone()); |
| 195 | wf.current_state = next_state.to_string(); |
| 196 | Ok(()) |
| 197 | } |
| 198 | |
| 199 | /// Layer 5: Failure Replay Verification |
| 200 | pub fn record_failure(&self, task_id: &str, failure_type: &str, details: &Value) -> Result<PathBuf, String> { |
| 201 | let failures_dir = self.base_path.join("failures"); |
| 202 | std::fs::create_dir_all(&failures_dir) |
| 203 | .map_err(|e| format!("Failed to create failures dir: {}", e))?; |
| 204 | |
| 205 | let file_name = format!("failure_{}_{}.json", task_id, chrono::Utc::now().timestamp()); |
| 206 | let file_path = failures_dir.join(file_name); |
| 207 | |
| 208 | let record = json!({ |
| 209 | "task_id": task_id, |
| 210 | "failure_type": failure_type, |
| 211 | "timestamp": chrono::Utc::now().to_rfc3339(), |
| 212 | "details": details, |
| 213 | }); |
| 214 | |
| 215 | std::fs::write(&file_path, serde_json::to_string_pretty(&record).unwrap()) |
| 216 | .map_err(|e| format!("Failed to write failure log: {}", e))?; |
| 217 | |
| 218 | Ok(file_path) |
| 219 | } |
| 220 | } |