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/blob/main/crates/spark-adapters/src/verifier.rs # 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 branch `main` Branches Tags History `aien-sovereign-core-mv / crates / spark-adapters / src / verifier.rs` 456 lines · 15535 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 16 use crate::models::{VerificationOutcome, VerificationStrategy}; 17 use std::collections::HashSet; 18 use std::io::Write; 19 use std::process::{Command, Stdio}; 20 21 pub struct Verifier; 22 23 impl Verifier { 24 pub fn verify(content: &str, strategy: VerificationStrategy) -> VerificationOutcome { 25 if content.trim().is_empty() { 26 return VerificationOutcome { 27 passed: false, 28 score: 0.0, 29 rule_violations: vec!["Empty completion received".to_string()], 30 compiler_output: None, 31 }; 32 } 33 34 let mut violations = Vec::new(); 35 let mut score: f32 = 1.0; 36 37 // 1. Unslop and Tone Invariants 38 if content.contains('\u{2014}') { 39 violations.push("Contains forbidden em dash (\\u{2014})".to_string()); 40 score -= 0.25; 41 } 42 if content.contains('\u{2013}') { 43 violations.push("Contains forbidden en dash (\\u{2013})".to_string()); 44 score -= 0.15; 45 } 46 47 let banned_words = [ 48 "delve", 49 "tapestry", 50 "crucial", 51 "beacon", 52 "game-changer", 53 "unleash", 54 "seamlessly", 55 "elevate", 56 "pivotal", 57 ]; 58 let lower = content.to_lowercase(); 59 for word in banned_words { 60 if lower.contains(word) { 61 violations.push(format!("Contains banned AI cliché: '{}'", word)); 62 score -= 0.15; 63 } 64 } 65 66 let sycophancy_phrases = [ 67 "certainly!", 68 "great question!", 69 "sure thing!", 70 "i would be happy to help", 71 "as an ai language model", 72 ]; 73 for phrase in sycophancy_phrases { 74 if lower.contains(phrase) { 75 violations.push(format!("Contains sycophantic phrase: '{}'", phrase)); 76 score -= 0.2; 77 } 78 } 79 80 // 2. Zero-Secret Leak Invariant 81 let secret_signatures = [ 82 "-----BEGIN PRIVATE KEY-----", 83 "-----BEGIN OPENSSH PRIVATE KEY-----", 84 "sk-proj-", 85 "sk-ant-", 86 "ghp_", 87 "gho_", 88 ]; 89 for sig in secret_signatures { 90 if content.contains(sig) { 91 violations.push(format!("Critical: Contains secret signature: {}", sig)); 92 score = 0.0; 93 } 94 } 95 96 // 3. Strategy-specific validation 97 let mut compiler_output = None; 98 match strategy { 99 VerificationStrategy::CompilerCheck => { 100 let code_blocks = Self::extract_code_blocks(content); 101 let rust_code = code_blocks 102 .into_iter() 103 .find(|b| b.contains("fn ") || b.contains("struct ") || b.contains("impl ")); 104 105 if let Some(code) = rust_code { 106 match Self::verify_with_rustc(&code) { 107 Ok(msg) => { 108 compiler_output = Some(msg); 109 } 110 Err(err) => { 111 violations.push(format!("Compiler error: {}", err)); 112 score -= 0.35; 113 compiler_output = Some(err); 114 } 115 } 116 } else if let Some(err) = Self::check_balanced_delimiters(content) { 117 violations.push(format!("Code structure syntax error: {}", err)); 118 score -= 0.3; 119 compiler_output = Some(err); 120 } else { 121 compiler_output = 122 Some("Balanced delimiters and structure syntax verified.".to_string()); 123 } 124 } 125 VerificationStrategy::JsonSchema => { 126 if let Some(json_start) = content.find('{') { 127 if let Some(json_end) = content.rfind('}') { 128 let slice = &content[json_start..=json_end]; 129 if serde_json::from_str::(slice).is_err() { 130 violations.push("Embedded JSON payload is malformed".to_string()); 131 score -= 0.3; 132 } 133 } else { 134 violations.push("Incomplete JSON object brackets".to_string()); 135 score -= 0.3; 136 } 137 } 138 } 139 VerificationStrategy::UnslopStrict => { 140 if !violations.is_empty() { 141 score = score.min(0.5); 142 } 143 } 144 VerificationStrategy::DualConsensus => { 145 // Handled during multi-candidate evaluation 146 } 147 } 148 149 score = score.clamp(0.0, 1.0); 150 let passed = violations.is_empty() 151 || (score >= 0.70 && !violations.iter().any(|v| v.starts_with("Critical"))); 152 153 VerificationOutcome { 154 passed, 155 score, 156 rule_violations: violations, 157 compiler_output, 158 } 159 } 160 161 /// Extract code blocks delimited by triple backticks. 162 pub fn extract_code_blocks(content: &str) -> Vec { 163 let mut blocks = Vec::new(); 164 let mut in_block = false; 165 let mut current_block = String::new(); 166 167 for line in content.lines() { 168 if line.trim_start().starts_with("```") { 169 if in_block { 170 blocks.push(current_block.clone()); 171 current_block.clear(); 172 in_block = false; 173 } else { 174 in_block = true; 175 } 176 } else if in_block { 177 current_block.push_str(line); 178 current_block.push('\n'); 179 } 180 } 181 182 if blocks.is_empty() && (content.contains("fn ") || content.contains("struct ")) { 183 blocks.push(content.to_string()); 184 } 185 186 blocks 187 } 188 189 /// Verify a code snippet by invoking `rustc --crate-type lib --emit=metadata -`. 190 pub fn verify_with_rustc(code: &str) -> Result { 191 let temp_dir = std::env::temp_dir(); 192 let mut child = Command::new("rustc") 193 .args([ 194 "--crate-type", 195 "lib", 196 "--emit=metadata", 197 "--crate-name", 198 "spark_verifier_eval", 199 "--out-dir", 200 temp_dir.to_str().unwrap_or("/tmp"), 201 "-", 202 ]) 203 .stdin(Stdio::piped()) 204 .stdout(Stdio::piped()) 205 .stderr(Stdio::piped()) 206 .spawn() 207 .map_err(|e| format!("Failed to spawn rustc: {}", e))?; 208 209 if let Some(mut stdin) = child.stdin.take() { 210 let _ = stdin.write_all(code.as_bytes()); 211 } 212 213 let output = child 214 .wait_with_output() 215 .map_err(|e| format!("Failed to wait for rustc: {}", e))?; 216 217 if output.status.success() { 218 Ok("Sandboxed rustc compilation check verified.".to_string()) 219 } else { 220 let stderr = String::from_utf8_lossy(&output.stderr); 221 let first_error = stderr 222 .lines() 223 .find(|l| l.contains("error[E") || l.starts_with("error:")) 224 .unwrap_or("syntax compilation error") 225 .to_string(); 226 Err(first_error) 227 } 228 } 229 230 /// Compute Word-level Token Jaccard Similarity between two completions. 231 pub fn token_jaccard(a: &str, b: &str) -> f32 { 232 let words_a: HashSet<&str> = a.split_whitespace().collect(); 233 let words_b: HashSet<&str> = b.split_whitespace().collect(); 234 235 if words_a.is_empty() && words_b.is_empty() { 236 return 1.0; 237 } 238 239 let intersection = words_a.intersection(&words_b).count(); 240 let union = words_a.union(&words_b).count(); 241 242 if union == 0 { 243 0.0 244 } else { 245 intersection as f32 / union as f32 246 } 247 } 248 249 /// Compute Normalized Levenshtein similarity (1.0 = identical, 0.0 = completely different). 250 pub fn normalized_levenshtein(a: &str, b: &str) -> f32 { 251 let len_a = a.chars().count(); 252 let len_b = b.chars().count(); 253 254 if len_a == 0 && len_b == 0 { 255 return 1.0; 256 } 257 let max_len = len_a.max(len_b); 258 if max_len == 0 { 259 return 1.0; 260 } 261 262 let distance = Self::levenshtein_distance(a, b); 263 1.0 - (distance as f32 / max_len as f32) 264 } 265 266 fn levenshtein_distance(a: &str, b: &str) -> usize { 267 let b_chars: Vec = b.chars().collect(); 268 let mut prev: Vec = (0..=b_chars.len()).collect(); 269 let mut curr = vec![0; b_chars.len() + 1]; 270 271 for (i, ca) in a.chars().enumerate() { 272 curr[0] = i + 1; 273 for (j, &cb) in b_chars.iter().enumerate() { 274 let cost = if ca == cb { 0 } else { 1 }; 275 curr[j + 1] = (prev[j + 1] + 1).min(curr[j] + 1).min(prev[j] + cost); 276 } 277 std::mem::swap(&mut prev, &mut curr); 278 } 279 280 prev[b_chars.len()] 281 } 282 283 /// Compute Normalized Longest Common Subsequence similarity. 284 pub fn normalized_lcs(a: &str, b: &str) -> f32 { 285 let a_chars: Vec = a.chars().collect(); 286 let b_chars: Vec = b.chars().collect(); 287 288 if a_chars.is_empty() && b_chars.is_empty() { 289 return 1.0; 290 } 291 let max_len = a_chars.len().max(b_chars.len()); 292 if max_len == 0 { 293 return 1.0; 294 } 295 296 let mut prev = vec![0; b_chars.len() + 1]; 297 let mut curr = vec![0; b_chars.len() + 1]; 298 299 for ca in &a_chars { 300 for (j, cb) in b_chars.iter().enumerate() { 301 if ca == cb { 302 curr[j + 1] = prev[j] + 1; 303 } else { 304 curr[j + 1] = prev[j + 1].max(curr[j]); 305 } 306 } 307 std::mem::swap(&mut prev, &mut curr); 308 } 309 310 prev[b_chars.len()] as f32 / max_len as f32 311 } 312 313 /// Compute Hybrid Consensus Score: 314 /// 40% Normalized Levenshtein + 30% Normalized LCS + 30% Token Jaccard. 315 pub fn hybrid_consensus(a: &str, b: &str) -> f32 { 316 let lev = Self::normalized_levenshtein(a, b); 317 let lcs = Self::normalized_lcs(a, b); 318 let jac = Self::token_jaccard(a, b); 319 320 (0.40 * lev) + (0.30 * lcs) + (0.30 * jac) 321 } 322 323 fn check_balanced_delimiters(content: &str) -> Option { 324 let mut stack = Vec::new(); 325 let mut in_string = false; 326 let mut escape = false; 327 328 for (i, c) in content.chars().enumerate() { 329 if escape { 330 escape = false; 331 continue; 332 } 333 if c == '\\' { 334 escape = true; 335 continue; 336 } 337 if c == '"' { 338 in_string = !in_string; 339 continue; 340 } 341 if in_string { 342 continue; 343 } 344 345 match c { 346 '(' | '[' | '{' => stack.push((c, i)), 347 ')' => { 348 if let Some(('(', _)) = stack.last() { 349 stack.pop(); 350 } else { 351 return Some(format!("Unmatched ')' at position {}", i)); 352 } 353 } 354 ']' => { 355 if let Some(('[', _)) = stack.last() { 356 stack.pop(); 357 } else { 358 return Some(format!("Unmatched ']' at position {}", i)); 359 } 360 } 361 '}' => { 362 if let Some(('{', _)) = stack.last() { 363 stack.pop(); 364 } else { 365 return Some(format!("Unmatched '}}' at position {}", i)); 366 } 367 } 368 _ => {} 369 } 370 } 371 372 if let Some((unmatched, pos)) = stack.pop() { 373 Some(format!( 374 "Unclosed delimiter '{}' opened at position {}", 375 unmatched, pos 376 )) 377 } else { 378 None 379 } 380 } 381 } 382 383 #[cfg(test)] 384 mod tests { 385 use super::*; 386 387 #[test] 388 fn test_clean_response_passes() { 389 let text = "Here is the pure Rust ring buffer implementation with zero allocations."; 390 let out = Verifier::verify(text, VerificationStrategy::UnslopStrict); 391 assert!(out.passed); 392 assert_eq!(out.score, 1.0); 393 assert!(out.rule_violations.is_empty()); 394 } 395 396 #[test] 397 fn test_em_dash_detected() { 398 let text = "This module is fast \u{2014} and very reliable."; 399 let out = Verifier::verify(text, VerificationStrategy::UnslopStrict); 400 assert!(!out.passed); 401 assert!(out.rule_violations.iter().any(|v| v.contains("em dash"))); 402 } 403 404 #[test] 405 fn test_banned_cliche_detected() { 406 let text = "Let us delve into the architecture."; 407 let out = Verifier::verify(text, VerificationStrategy::UnslopStrict); 408 assert!(out.rule_violations.iter().any(|v| v.contains("delve"))); 409 } 410 411 #[test] 412 fn test_rustc_compilation_verification() { 413 let valid_code = "```rust\npub fn add(a: i32, b: i32) -> i32 { a + b }\n```"; 414 let out = Verifier::verify(valid_code, VerificationStrategy::CompilerCheck); 415 assert!(out.passed); 416 assert_eq!(out.score, 1.0); 417 418 let invalid_code = "```rust\npub fn add(a: i32, b: i32) -> i32 { a + \"broken\" }\n```"; 419 let out_inv = Verifier::verify(invalid_code, VerificationStrategy::CompilerCheck); 420 assert!(!out_inv.passed); 421 assert!(out_inv 422 .rule_violations 423 .iter() 424 .any(|v| v.contains("Compiler error"))); 425 } 426 427 #[test] 428 fn test_hybrid_consensus_scoring() { 429 let a = "fn reverse(s: &mut [i32]) { s.reverse(); }"; 430 let b = "fn reverse(s: &mut [i32]) { s.reverse(); }"; 431 let c = "pub fn sort(s: &mut [i32]) { s.sort(); }"; 432 433 assert_eq!(Verifier::hybrid_consensus(a, b), 1.0); 434 let sim = Verifier::hybrid_consensus(a, c); 435 assert!(sim > 0.0 && sim < 1.0); 436 } 437 438 #[test] 439 fn test_empty_completion_rejected() { 440 let empty_out = Verifier::verify("", VerificationStrategy::CompilerCheck); 441 assert!(!empty_out.passed); 442 assert_eq!(empty_out.score, 0.0); 443 assert!(empty_out 444 .rule_violations 445 .iter() 446 .any(|v| v.contains("Empty completion"))); 447 448 let whitespace_out = Verifier::verify( 449 " 450 ", 451 VerificationStrategy::UnslopStrict, 452 ); 453 assert!(!whitespace_out.passed); 454 assert_eq!(whitespace_out.score, 0.0); 455 } 456 }