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/tests/tier1_features.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 / tests / tier1_features.rs` 1080 lines ยท 36654 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 std::path::PathBuf; 17 18 fn workspace_root() -> PathBuf { 19 if let Ok(manifest_dir) = std::env::var("CARGO_MANIFEST_DIR") { 20 let p = PathBuf::from(manifest_dir); 21 if let Some(parent) = p.parent() { 22 if let Some(root) = parent.parent() { 23 return root.to_path_buf(); 24 } 25 } 26 } 27 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..") 28 } 29 30 fn workshop_html_path() -> PathBuf { 31 workspace_root().join("crates/spark-cockpit-rs/static/workshop.html") 32 } 33 34 fn spark_distill_bin() -> PathBuf { 35 PathBuf::from(env!("CARGO_BIN_EXE_spark-distill")) 36 } 37 // Tier 1: Feature Coverage Tests for Sovereign Distillation Workshop 38 // Strictly adheres to sovereign unslop invariants: zero em dashes, zero en dashes. 39 40 use spark_adapters::curriculum::{CurriculumEngine, CurriculumTrack}; 41 use spark_adapters::models::{ 42 ChatMessage, DistillTask, ProviderType, TaskType, VerificationOutcome, VerificationStrategy, 43 }; 44 use spark_adapters::providers::format_openai_payload; 45 use spark_adapters::router::AdapterRouter; 46 use spark_adapters::vault::{ 47 is_secret_present, list_vault_keys, resolve_secret, sanitize_outbound_prompt, 48 }; 49 use spark_adapters::verifier::Verifier; 50 use std::fs; 51 use std::process::Command; 52 53 // ============================================================================ 54 // Feature 1: In-Memory Vault Secret Resolution 55 // ============================================================================ 56 57 #[test] 58 fn test_t1_f01_vault_keys_listing() { 59 let keys = list_vault_keys(); 60 // list_vault_keys must return a vector without crashing or hanging 61 assert!(keys.iter().all(|k| !k.trim().is_empty())); 62 } 63 64 #[test] 65 fn test_t1_f02_vault_secret_presence_check() { 66 std::env::set_var("TEST_KEY_PRESENCE", "present_value"); 67 assert!(is_secret_present("TEST_KEY_PRESENCE")); 68 std::env::remove_var("TEST_KEY_PRESENCE"); 69 } 70 71 #[test] 72 fn test_t1_f03_vault_secret_resolution_non_empty() { 73 std::env::set_var("TEST_KEY_RESOLUTION", "sovereign_secret_123"); 74 let resolved = resolve_secret("TEST_KEY_RESOLUTION"); 75 assert_eq!(resolved, Some("sovereign_secret_123".to_string())); 76 std::env::remove_var("TEST_KEY_RESOLUTION"); 77 } 78 79 #[test] 80 fn test_t1_f04_vault_env_variable_resolution() { 81 std::env::set_var("ATLAS_TEST_VAR", "in_memory_val"); 82 assert_eq!( 83 resolve_secret("ATLAS_TEST_VAR"), 84 Some("in_memory_val".to_string()) 85 ); 86 std::env::remove_var("ATLAS_TEST_VAR"); 87 } 88 89 #[test] 90 fn test_t1_f05_vault_keys_caching_invariant() { 91 let t0_keys = list_vault_keys(); 92 let t1_keys = list_vault_keys(); 93 assert_eq!(t0_keys, t1_keys); 94 } 95 96 // ============================================================================ 97 // Feature 2: Outbound Prompt Sanitizer Hardening 98 // ============================================================================ 99 100 #[test] 101 fn test_t1_f06_sanitizer_scrubs_workspace_paths() { 102 let input = "Inspect file at /home/alice/workspace/secret.rs and /Users/alice/audit.md"; 103 let output = sanitize_outbound_prompt(input); 104 assert!(!output.contains("/home/alice")); 105 assert!(!output.contains("/Users/alice")); 106 assert!(output.contains("")); 107 } 108 109 #[test] 110 fn test_t1_f07_sanitizer_scrubs_private_ips() { 111 let input = "Connect to 127.0.0.1 and 100.100.1.2 and 192.168.0.10 and 10.0.0.5"; 112 let output = sanitize_outbound_prompt(input); 113 assert!(!output.contains("127.0.0.1")); 114 assert!(!output.contains("100.100.1.2")); 115 assert!(!output.contains("192.168.0.10")); 116 assert!(!output.contains("10.0.0.5")); 117 assert!(output.contains("")); 118 } 119 120 #[test] 121 fn test_t1_f08_sanitizer_scrubs_local_hostnames() { 122 let input = "Run job on spark and spark-1a2b and localhost directly"; 123 let output = sanitize_outbound_prompt(input); 124 // Hardening requirement: hostnames scrubbed per PROJECT.md interface contract 125 assert!(!output.contains("spark-1a2b")); 126 assert!(output.contains("")); 127 } 128 129 #[test] 130 fn test_t1_f09_sanitizer_scrubs_operator_names() { 131 let input = "Operator drakestapleton and Drake Stapleton with email aien@aienos.com"; 132 let output = sanitize_outbound_prompt(input); 133 assert!(!output.contains("drakestapleton")); 134 assert!(!output.contains("aien@aienos.com")); 135 assert!(output.contains("")); 136 } 137 138 #[test] 139 fn test_t1_f10_sanitizer_scrubs_vault_secret_signatures() { 140 let input = "Keys: sk-proj-`123456789012345678901234` and ghp_`12345678901234567890`"; 141 let output = sanitize_outbound_prompt(input); 142 assert!(!output.contains("sk-proj-")); 143 assert!(!output.contains("ghp_")); 144 assert!(output.contains("[REDACTED_BY_ATLAS_VAULT]")); 145 } 146 147 #[test] 148 fn test_t1_f10b_sanitizer_persisted_dataset_contains_no_raw_paths_or_ips() { 149 use spark_adapters::distill::DistillationEngine; 150 use spark_adapters::models::{DistillTask, TaskType, VerificationStrategy}; 151 use spark_adapters::vault::sanitize_outbound_prompt; 152 use std::fs; 153 154 let temp_dir = 155 std::env::temp_dir().join(format!("spark_distill_t1_f10b_{}", uuid::Uuid::new_v4())); 156 let engine = DistillationEngine::new().with_dataset_dir(&temp_dir); 157 158 let raw_prompt = "Write code for /home/alice/audit_secret.rs at 10.0.0.15"; 159 let sanitized_prompt = sanitize_outbound_prompt(raw_prompt); 160 161 let task = DistillTask { 162 id: "task-sanitizer-persist-01".to_string(), 163 task_type: TaskType::CodeSynthesis, 164 prompt: sanitized_prompt, 165 system_prompt: Some("You are AIEN Sovereign Architect.".to_string()), 166 teacher_model: "anthropic/claude-3-7-sonnet".to_string(), 167 student_model: Some("atlas-lightning-omni".to_string()), 168 verification_strategy: VerificationStrategy::CompilerCheck, 169 commit_to_cortex: false, 170 }; 171 172 let chosen = "pub fn secret_fn() {}"; 173 engine 174 .persist_training_pair(&task, chosen, None, None) 175 .expect("persist training pair"); 176 177 let sft_path = temp_dir.join("sft.jsonl"); 178 assert!(sft_path.exists(), "sft.jsonl must exist on disk"); 179 180 let content = fs::read_to_string(&sft_path).expect("read sft.jsonl"); 181 assert!( 182 !content.contains("/home/alice"), 183 "sft.jsonl must not contain raw home path" 184 ); 185 assert!( 186 !content.contains("10.0.0.15"), 187 "sft.jsonl must not contain private IP" 188 ); 189 assert!( 190 content.contains(""), 191 "sft.jsonl must contain " 192 ); 193 assert!( 194 content.contains(""), 195 "sft.jsonl must contain " 196 ); 197 198 let _ = fs::remove_dir_all(&temp_dir); 199 } 200 201 // ============================================================================ 202 // Feature 3: Cortex Token Dynamic Auth 203 // ============================================================================ 204 205 #[test] 206 fn test_t1_f11_cortex_token_resolves_from_vault() { 207 if std::env::var("CI").is_ok() { 208 return; 209 } 210 // Either CORTEX_TOKEN is in atlas-vault or environment 211 let is_present = is_secret_present("CORTEX_TOKEN"); 212 assert!( 213 is_present, 214 "CORTEX_TOKEN must be registered in vault or environment" 215 ); 216 let resolved = resolve_secret("CORTEX_TOKEN"); 217 assert!(resolved.is_some()); 218 assert!(!resolved.unwrap().trim().is_empty()); 219 } 220 221 #[test] 222 fn test_t1_f12_cortex_token_presence_without_disk_file() { 223 if std::env::var("CI").is_ok() { 224 return; 225 } 226 // Presence check must function purely in memory without disk dependency 227 assert!(is_secret_present("CORTEX_TOKEN")); 228 } 229 230 #[test] 231 fn test_t1_f13_cortex_bearer_header_format() { 232 let token = "test_token_cortex"; 233 let header_val = format!("Bearer {}", token); 234 assert_eq!(header_val, "Bearer test_token_cortex"); 235 } 236 237 #[test] 238 fn test_t1_f14_cortex_endpoint_resolution_default() { 239 let default_endpoint = "http://127.0.0.1:18080"; 240 assert_eq!(default_endpoint, "http://127.0.0.1:18080"); 241 } 242 243 #[test] 244 fn test_t1_f15_cortex_live_service_connectivity() { 245 // Live Cortex service on 18080 must be listening (returns 200, 401, or 404, but responds) 246 let output = Command::new("curl") 247 .args([ 248 "-s", 249 "-o", 250 "/dev/null", 251 "-w", 252 "%{http_code}", 253 "http://127.0.0.1:18080/api/status", 254 ]) 255 .output() 256 .expect("curl cortex"); 257 let code = String::from_utf8_lossy(&output.stdout); 258 assert!(!code.trim().is_empty()); 259 } 260 261 // ============================================================================ 262 // Feature 4: Resident Generation Bounds 263 // ============================================================================ 264 265 #[test] 266 fn test_t1_f16_resident_adapter_catalog_spec() { 267 let router = AdapterRouter::new(); 268 let adapters = router.discover_adapters(); 269 let resident = adapters.iter().find(|a| a.id == "atlas-lightning-omni"); 270 assert!(resident.is_some()); 271 let spec = resident.unwrap(); 272 assert!(spec.is_resident); 273 assert!(!spec.requires_key); 274 } 275 276 #[test] 277 fn test_t1_f17_resident_context_length_bounds() { 278 let router = AdapterRouter::new(); 279 let adapters = router.discover_adapters(); 280 let resident = adapters 281 .iter() 282 .find(|a| a.id == "atlas-lightning-omni") 283 .unwrap(); 284 assert_eq!(spec_context_len(resident), 32768); 285 } 286 287 fn spec_context_len(spec: &spark_adapters::models::AdapterSpec) -> usize { 288 spec.context_length 289 } 290 291 #[test] 292 fn test_t1_f18_resident_model_endpoint_resolution() { 293 let router = AdapterRouter::new(); 294 let (prov, endpoint, model, key) = router.resolve_route("atlas-lightning-omni"); 295 assert_eq!(prov, ProviderType::LocalSeat); 296 assert_eq!(endpoint, "http://127.0.0.1:18006/v1/chat/completions"); 297 assert_eq!(model, "atlas-lightning-omni"); 298 assert!(key.is_none()); 299 } 300 301 #[test] 302 fn test_t1_f19_resident_format_openai_payload() { 303 let msgs = vec![ChatMessage { 304 role: "user".to_string(), 305 content: "Ping".to_string(), 306 reasoning: None, 307 }]; 308 let payload = format_openai_payload("atlas-lightning-omni", &msgs, Some(0.7), false); 309 assert_eq!(payload["model"], "atlas-lightning-omni"); 310 let temp = payload["temperature"].as_f64().unwrap(); 311 assert!((temp - 0.7).abs() < 1e-4); 312 assert_eq!(payload["stream"], false); 313 } 314 315 #[test] 316 fn test_t1_f20_resident_live_model_availability() { 317 let output = Command::new("curl") 318 .args([ 319 "-fsS", 320 "--max-time", 321 "3", 322 "http://127.0.0.1:18006/v1/models", 323 ]) 324 .output() 325 .expect("curl max"); 326 if !output.status.success() { 327 // This is a live integration check. The local model service is optional 328 // for the ordinary workspace test suite. 329 return; 330 } 331 let body = String::from_utf8_lossy(&output.stdout); 332 assert!(body.contains("atlas-lightning-omni")); 333 } 334 335 // ============================================================================ 336 // Feature 5: Crawler Flag Collision Fix 337 // ============================================================================ 338 339 #[test] 340 fn test_t1_f21_crawler_track_flag_parsing_long() { 341 let track = CurriculumTrack::parse("systems"); 342 assert_eq!(track, Some(CurriculumTrack::NativeSystemsAndGpu)); 343 } 344 345 #[test] 346 fn test_t1_f22_crawler_teacher_flag_parsing_long() { 347 let router = AdapterRouter::new(); 348 let (prov, _, model, _) = router.resolve_route("anthropic/claude-3-7-sonnet"); 349 assert_eq!(prov, ProviderType::Anthropic); 350 assert_eq!(model, "claude-3-7-sonnet-`20250219`"); 351 } 352 353 #[test] 354 fn test_t1_f23_crawler_track_short_flag_distinct_from_teacher() { 355 // spark-distill crawl --help must not panic with clap duplicate short option '-t' 356 let bin_path = spark_distill_bin(); 357 let output = Command::new(bin_path).args(["crawl", "--help"]).output(); 358 assert!(output.is_ok()); 359 let res = output.unwrap(); 360 assert_eq!( 361 res.status.code(), 362 Some(0), 363 "spark-distill crawl --help must exit with 0" 364 ); 365 } 366 367 #[test] 368 fn test_t1_f24_crawler_curriculum_tracks_enumeration() { 369 assert!(CurriculumTrack::parse("systems").is_some()); 370 assert!(CurriculumTrack::parse("agent").is_some()); 371 assert!(CurriculumTrack::parse("science").is_some()); 372 assert!(CurriculumTrack::parse("frontier").is_some()); 373 assert!(CurriculumTrack::parse("dynamic").is_some()); 374 } 375 376 #[test] 377 fn test_t1_f24b_crawler_curriculum_tracks_aliases() { 378 assert_eq!( 379 CurriculumTrack::parse("cuda"), 380 Some(CurriculumTrack::NativeSystemsAndGpu) 381 ); 382 assert_eq!( 383 CurriculumTrack::parse("git"), 384 Some(CurriculumTrack::DynamicMining) 385 ); 386 assert_eq!( 387 CurriculumTrack::parse("git_mining"), 388 Some(CurriculumTrack::DynamicMining) 389 ); 390 assert_eq!( 391 CurriculumTrack::parse("git-mining"), 392 Some(CurriculumTrack::DynamicMining) 393 ); 394 assert_eq!( 395 CurriculumTrack::parse("refactor"), 396 Some(CurriculumTrack::DynamicMining) 397 ); 398 } 399 400 #[test] 401 fn test_t1_f25_crawler_task_generation_limit_respect() { 402 let tasks = CurriculumEngine::generate_tasks( 403 CurriculumTrack::NativeSystemsAndGpu, 404 3, 405 "anthropic/claude-3-7-sonnet", 406 Some("atlas-lightning-omni"), 407 false, 408 ); 409 assert_eq!(tasks.len(), 3); 410 } 411 412 // ============================================================================ 413 // Feature 6: Interactive CLI Workbench 414 // ============================================================================ 415 416 #[test] 417 fn test_t1_f26_cli_help_invocation() { 418 let bin_path = spark_distill_bin(); 419 let output = Command::new(bin_path) 420 .arg("--help") 421 .output() 422 .expect("help invocation"); 423 let stdout = String::from_utf8_lossy(&output.stdout); 424 assert!(stdout.contains("spark-distill")); 425 } 426 427 #[test] 428 fn test_t1_f26b_cli_interactive_subcommand_schema() { 429 let bin_path = spark_distill_bin(); 430 let output = Command::new(bin_path) 431 .args(["cli", "--help"]) 432 .output() 433 .expect("cli help"); 434 let stdout = String::from_utf8_lossy(&output.stdout); 435 assert!(output.status.success()); 436 assert!(stdout.contains("--teacher")); 437 assert!(stdout.contains("--student")); 438 } 439 440 #[test] 441 fn test_t1_f27_cli_single_subcommand_schema() { 442 let bin_path = spark_distill_bin(); 443 let output = Command::new(bin_path) 444 .args(["single", "--help"]) 445 .output() 446 .expect("single help"); 447 let stdout = String::from_utf8_lossy(&output.stdout); 448 assert!(stdout.contains("--prompt")); 449 } 450 451 #[test] 452 fn test_t1_f28_cli_crawl_subcommand_schema() { 453 let bin_path = spark_distill_bin(); 454 let output = Command::new(bin_path) 455 .args(["crawl", "--help"]) 456 .output() 457 .expect("crawl help"); 458 let stdout = String::from_utf8_lossy(&output.stdout); 459 assert!(stdout.contains("--track") || stdout.contains("-k") || stdout.contains("-t")); 460 } 461 462 #[test] 463 fn test_t1_f29_cli_verify_keys_subcommand_schema() { 464 let bin_path = spark_distill_bin(); 465 let output = Command::new(bin_path) 466 .args(["verify-keys", "--help"]) 467 .output(); 468 assert!(output.is_ok()); 469 let res = output.unwrap(); 470 assert_eq!(res.status.code(), Some(0)); 471 } 472 473 #[test] 474 fn test_t1_f30_cli_task_type_parsing_coverage() { 475 let json_code = serde_json::to_string(&TaskType::CodeSynthesis).unwrap(); 476 assert_eq!(json_code, "\"code_synthesis\""); 477 let json_arch = serde_json::to_string(&TaskType::SystemArchitecture).unwrap(); 478 assert_eq!(json_arch, "\"system_architecture\""); 479 let json_reasoning = serde_json::to_string(&TaskType::ReasoningTrace).unwrap(); 480 assert_eq!(json_reasoning, "\"reasoning_trace\""); 481 } 482 483 // ============================================================================ 484 // Feature 7: Key Verification Command 485 // ============================================================================ 486 487 #[test] 488 fn test_t1_f31_verify_keys_discovers_all_catalog_adapters() { 489 let router = AdapterRouter::new(); 490 let adapters = router.discover_adapters(); 491 assert!(adapters.len() >= 11); 492 } 493 494 #[test] 495 fn test_t1_f32_verify_keys_resident_models_ready_without_key() { 496 let router = AdapterRouter::new(); 497 let adapters = router.discover_adapters(); 498 let resident = adapters 499 .iter() 500 .find(|a| a.id == "atlas-lightning-omni") 501 .unwrap(); 502 assert!(!resident.requires_key); 503 assert!(resident.is_available); 504 } 505 506 #[test] 507 fn test_t1_f33_verify_keys_local_engine_ready_without_key() { 508 let router = AdapterRouter::new(); 509 let adapters = router.discover_adapters(); 510 let ollama = adapters 511 .iter() 512 .find(|a| a.id == "ollama/qwen2.5-coder") 513 .unwrap(); 514 assert!(!ollama.requires_key); 515 assert!(ollama.is_available); 516 } 517 518 #[test] 519 fn test_t1_f34_verify_keys_cloud_models_require_key() { 520 let router = AdapterRouter::new(); 521 let adapters = router.discover_adapters(); 522 let openai = adapters.iter().find(|a| a.id == "openai/gpt-4o").unwrap(); 523 assert!(openai.requires_key); 524 let anthropic = adapters 525 .iter() 526 .find(|a| a.id == "anthropic/claude-3-7-sonnet") 527 .unwrap(); 528 assert!(anthropic.requires_key); 529 } 530 531 #[test] 532 fn test_t1_f35_verify_keys_web_sessions_require_key() { 533 let router = AdapterRouter::new(); 534 let adapters = router.discover_adapters(); 535 let chatgpt_web = adapters 536 .iter() 537 .find(|a| a.id == "chatgpt/web-plus") 538 .unwrap(); 539 assert!(chatgpt_web.requires_key); 540 let claude_web = adapters.iter().find(|a| a.id == "claude/web-pro").unwrap(); 541 assert!(claude_web.requires_key); 542 } 543 544 #[test] 545 fn test_t1_f35b_web_session_token_aliases() { 546 let chatgpt = spark_adapters::models::ProviderType::ChatGPTWeb; 547 assert!(chatgpt.key_aliases().contains(&"CHATGPT_SESSION_TOKEN")); 548 assert!(chatgpt.key_aliases().contains(&"OPENAI_WEB_TOKEN")); 549 550 let claude = spark_adapters::models::ProviderType::ClaudeWeb; 551 assert!(claude.key_aliases().contains(&"CLAUDE_SESSION_KEY")); 552 assert!(claude.key_aliases().contains(&"CLAUDE_WEB_SESSION_KEY")); 553 } 554 555 // ============================================================================ 556 // Feature 8: Axum Web Workshop Service 557 // ============================================================================ 558 559 #[test] 560 fn test_t1_f36_axum_workshop_static_html_content() { 561 let html_path = workshop_html_path(); 562 let content = fs::read_to_string(html_path).expect("read workshop.html"); 563 assert!(content.contains("")); 564 assert!(content.contains("Knowledge Distillation Workshop")); 565 } 566 567 #[test] 568 fn test_t1_f37_axum_workshop_html_contains_model_options() { 569 let html_path = workshop_html_path(); 570 let content = fs::read_to_string(html_path).expect("read workshop.html"); 571 assert!(content.contains("atlas-lightning-omni")); 572 assert!(content.contains("claude-3-7-sonnet")); 573 } 574 575 #[test] 576 fn test_t1_f38_axum_workshop_html_unslop_compliance() { 577 let html_path = workshop_html_path(); 578 let content = fs::read_to_string(html_path).expect("read workshop.html"); 579 assert!( 580 !content.contains('\u{2014}'), 581 "workshop.html must not contain em dashes" 582 ); 583 assert!( 584 !content.contains('\u{2013}'), 585 "workshop.html must not contain en dashes" 586 ); 587 } 588 589 #[test] 590 fn test_t1_f39_axum_workshop_distill_task_deserialization() { 591 let raw_json = r#"{ 592 "id": "task-test-01", 593 "task_type": "code_synthesis", 594 "prompt": "Write ring buffer in Rust", 595 "system_prompt": "You are AIEN Sovereign Architect", 596 "teacher_model": "anthropic/claude-3-7-sonnet", 597 "student_model": "atlas-lightning-omni", 598 "verification_strategy": "compiler_check", 599 "commit_to_cortex": false 600 }"#; 601 let parsed: Result = serde_json::from_str(raw_json); 602 assert!(parsed.is_ok()); 603 let task = parsed.unwrap(); 604 assert_eq!(task.id, "task-test-01"); 605 } 606 607 #[test] 608 fn test_t1_f40_axum_workshop_response_json_serialization() { 609 let outcome = VerificationOutcome { 610 passed: true, 611 score: 1.0, 612 rule_violations: Vec::new(), 613 compiler_output: Some("Verified".to_string()), 614 }; 615 let serialized = serde_json::to_string(&outcome).unwrap(); 616 assert!(serialized.contains("\"passed\":true")); 617 assert!(serialized.contains("\"score\":1.0")); 618 } 619 620 // ============================================================================ 621 // Feature 9: Closed-Loop Cortex Storage 622 // ============================================================================ 623 624 #[test] 625 fn test_t1_f41_cortex_payload_entity_kind() { 626 let payload = serde_json::json!({ 627 "kind": "entity", 628 "value": { 629 "canonicalName": "distill_task_123", 630 "entityType": "learned_procedure", 631 "content": "Verified heuristic content", 632 "confidence": 0.95 633 } 634 }); 635 assert_eq!(payload["kind"], "entity"); 636 assert_eq!(payload["value"]["entityType"], "learned_procedure"); 637 } 638 639 #[test] 640 fn test_t1_f42_cortex_payload_canonical_name_format() { 641 let task_id = "task-uuid-456"; 642 let canonical = format!("distill_{}", task_id.replace('-', "_")); 643 assert_eq!(canonical, "distill_task_uuid_456"); 644 } 645 646 #[test] 647 fn test_t1_f43_cortex_payload_metadata_contains_task_id() { 648 use spark_adapters::distill::DistillationEngine; 649 650 let payload = DistillationEngine::build_cortex_payload( 651 "lesson_alias", 652 "distill_task_789", 653 "Verified compiler solution", 654 "task-uuid-789", 655 0.95, 656 ); 657 658 assert_eq!(payload["kind"], "entity"); 659 assert_eq!(payload["value"]["space"], "atlas-memory"); 660 assert_eq!(payload["value"]["entityType"], "learned_procedure"); 661 assert_eq!(payload["value"]["canonicalName"], "distill_task_789"); 662 assert_eq!(payload["value"]["metadata"]["source"], "spark-distill"); 663 assert_eq!(payload["value"]["metadata"]["taskId"], "task-uuid-789"); 664 } 665 666 #[test] 667 fn test_t1_f44_cortex_receipt_target_id_extraction() { 668 use spark_adapters::distill::DistillationEngine; 669 670 // Test standard camelCase targetId variant 671 let body_target_id = serde_json::json!({ 672 "receipt": { "targetId": "cortex-entity-999" } 673 }); 674 let id1 = DistillationEngine::parse_cortex_receipt(&body_target_id, "fallback"); 675 assert_eq!(id1, "cortex-entity-999"); 676 677 // Test snake_case target_id variant 678 let body_snake = serde_json::json!({ 679 "receipt": { "target_id": "cortex-entity-888" } 680 }); 681 let id2 = DistillationEngine::parse_cortex_receipt(&body_snake, "fallback"); 682 assert_eq!(id2, "cortex-entity-888"); 683 684 // Test simple id variant 685 let body_simple = serde_json::json!({ 686 "receipt": { "id": "cortex-entity-777" } 687 }); 688 let id3 = DistillationEngine::parse_cortex_receipt(&body_simple, "fallback"); 689 assert_eq!(id3, "cortex-entity-777"); 690 691 // Test fallback behavior when receipt lacks explicit target identifier 692 let body_empty = serde_json::json!({ "receipt": {} }); 693 let id4 = DistillationEngine::parse_cortex_receipt(&body_empty, "default_canonical"); 694 assert_eq!(id4, "default_canonical"); 695 } 696 697 #[test] 698 fn test_t1_f45_cortex_qualification_gate_score_threshold() { 699 use spark_adapters::distill::DistillationEngine; 700 701 assert_eq!(DistillationEngine::CORTEX_QUALIFICATION_THRESHOLD, 0.85); 702 703 // Exactly at threshold and passed: qualifies 704 assert!( 705 DistillationEngine::qualifies_for_cortex(true, true, 0.85), 706 "Score of 0.85 with passed verification must qualify for Cortex commit" 707 ); 708 709 // Well above threshold and passed: qualifies 710 assert!( 711 DistillationEngine::qualifies_for_cortex(true, true, 1.0), 712 "Score of 1.0 with passed verification must qualify for Cortex commit" 713 ); 714 715 // Below threshold (0.84): must NOT qualify 716 assert!( 717 !DistillationEngine::qualifies_for_cortex(true, true, 0.84), 718 "Score below 0.85 must be rejected by Cortex qualification gate" 719 ); 720 721 // High score but verification failed: must NOT qualify 722 assert!( 723 !DistillationEngine::qualifies_for_cortex(true, false, 0.95), 724 "Failed verification must prevent Cortex commit regardless of score" 725 ); 726 727 // High score and passed, but commit_to_cortex is disabled: must NOT qualify 728 assert!( 729 !DistillationEngine::qualifies_for_cortex(false, true, 0.95), 730 "commit_to_cortex=false flag must prevent Cortex commit" 731 ); 732 } 733 734 // ============================================================================ 735 // Feature 10: SFT and DPO Dataset Emission 736 // ============================================================================ 737 738 #[test] 739 fn test_t1_f46_sft_dataset_chatml_structure() { 740 let sft_entry = serde_json::json!({ 741 "task_id": "test-sft-01", 742 "timestamp": "2026-09-20T21:00:00Z", 743 "messages": [ 744 { "role": "system", "content": "You are AIEN." }, 745 { "role": "user", "content": "Write hello world in Rust" }, 746 { "role": "assistant", "content": "fn main() { println!(\"Hello\"); }" } 747 ] 748 }); 749 let msgs = sft_entry["messages"].as_array().unwrap(); 750 assert_eq!(msgs.len(), 3); 751 assert_eq!(msgs[0]["role"], "system"); 752 assert_eq!(msgs[1]["role"], "user"); 753 assert_eq!(msgs[2]["role"], "assistant"); 754 } 755 756 #[test] 757 fn test_t1_f47_sft_dataset_contains_iso_timestamp() { 758 let now_rfc3339 = chrono::Utc::now().to_rfc3339(); 759 let parsed = chrono::DateTime::parse_from_rfc3339(&now_rfc3339); 760 assert!(parsed.is_ok()); 761 } 762 763 #[test] 764 fn test_t1_f48_sft_dataset_assistant_reasoning_field() { 765 let assistant_obj = serde_json::json!({ 766 "role": "assistant", 767 "content": "Solution", 768 "reasoning": "Step-by-step trace" 769 }); 770 assert_eq!(assistant_obj["reasoning"], "Step-by-step trace"); 771 } 772 773 #[test] 774 fn test_t1_f49_dpo_dataset_pair_structure() { 775 let dpo_entry = serde_json::json!({ 776 "task_id": "dpo-01", 777 "prompt": "Optimize channel in Rust", 778 "chosen": "pub struct Channel;", 779 "rejected": "pub struct BrokenChannel;", 780 "timestamp": "2026-09-20T21:00:00Z" 781 }); 782 assert_eq!(dpo_entry["chosen"], "pub struct Channel;"); 783 assert_ne!(dpo_entry["chosen"], dpo_entry["rejected"]); 784 } 785 786 #[test] 787 fn test_t1_f50_dpo_dataset_preference_delta_strictly_positive() { 788 use spark_adapters::distill::DistillationEngine; 789 use spark_adapters::models::{DistillTask, TaskType, VerificationStrategy}; 790 use std::fs; 791 792 let temp_dir = 793 std::env::temp_dir().join(format!("spark_distill_t1_f50_{}", uuid::Uuid::new_v4())); 794 let engine = DistillationEngine::new().with_dataset_dir(&temp_dir); 795 796 let task = DistillTask { 797 id: "task-dpo-positive-01".to_string(), 798 task_type: TaskType::CodeSynthesis, 799 prompt: "Write a thread-safe counter in Rust".to_string(), 800 system_prompt: Some("You are AIEN Sovereign Architect.".to_string()), 801 teacher_model: "anthropic/claude-3-7-sonnet".to_string(), 802 student_model: Some("atlas-lightning-omni".to_string()), 803 verification_strategy: VerificationStrategy::CompilerCheck, 804 commit_to_cortex: false, 805 }; 806 807 let chosen = "pub struct Counter(std::sync::atomic::AtomicUsize);"; 808 let rejected = "pub struct Counter(usize);"; 809 let preference_delta = 0.25f32; 810 811 let valid_rej = 812 DistillationEngine::filter_dpo_candidate(chosen, Some(rejected), preference_delta); 813 assert_eq!( 814 valid_rej, 815 Some(rejected), 816 "Positive preference delta must qualify rejected candidate" 817 ); 818 819 let dpo_persisted = engine 820 .persist_training_pair( 821 &task, 822 chosen, 823 Some("Atomic counter is thread-safe"), 824 valid_rej, 825 ) 826 .expect("persist training pair"); 827 assert!( 828 dpo_persisted, 829 "DPO pair must be recorded when preference delta > 0.0" 830 ); 831 832 let dpo_path = temp_dir.join("dpo.jsonl"); 833 assert!(dpo_path.exists(), "dpo.jsonl must exist on disk"); 834 835 let content = fs::read_to_string(&dpo_path).expect("read dpo.jsonl"); 836 let entry: serde_json::Value = serde_json::from_str(content.trim()).expect("parse dpo entry"); 837 assert_eq!(entry["task_id"], "task-dpo-positive-01"); 838 assert_eq!(entry["chosen"], chosen); 839 assert_eq!(entry["rejected"], rejected); 840 assert_eq!(entry["prompt"], "Write a thread-safe counter in Rust"); 841 842 let _ = fs::remove_dir_all(&temp_dir); 843 } 844 845 // ============================================================================ 846 // Feature 11: Four-Tier Verification Gates 847 // ============================================================================ 848 849 #[test] 850 fn test_t1_f51_verifier_rustc_compiles_clean_code() { 851 let valid_code = "pub fn add_two(x: i32) -> i32 { x + 2 }"; 852 let res = Verifier::verify_with_rustc(valid_code); 853 assert!(res.is_ok(), "rustc must compile clean valid Rust code"); 854 } 855 856 #[test] 857 fn test_t1_f52_verifier_unslop_passes_clean_response() { 858 let text = "Pure native Rust implementation with zero allocations and zero unslop."; 859 let outcome = Verifier::verify(text, VerificationStrategy::UnslopStrict); 860 assert!(outcome.passed); 861 assert_eq!(outcome.score, 1.0); 862 } 863 864 #[test] 865 fn test_t1_f53_verifier_token_jaccard_identical() { 866 let a = "fn reverse_slice(s: &mut [u8]) { s.reverse(); }"; 867 let score = Verifier::token_jaccard(a, a); 868 assert_eq!(score, 1.0); 869 } 870 871 #[test] 872 fn test_t1_f54_verifier_normalized_levenshtein_identical() { 873 let text = "Sovereign AIEN Inference Stack"; 874 let score = Verifier::normalized_levenshtein(text, text); 875 assert_eq!(score, 1.0); 876 } 877 878 #[test] 879 fn test_t1_f55_verifier_hybrid_consensus_weighting() { 880 let a = "pub struct FastMap { inner: std::collections::HashMap }"; 881 let score = Verifier::hybrid_consensus(a, a); 882 assert_eq!(score, 1.0); 883 } 884 885 // ============================================================================ 886 // Feature 12: E2E Opaque-Box Test Suite 887 // ============================================================================ 888 889 #[test] 890 fn test_t1_f56_e2e_harness_test_count_verification() { 891 // Verifies all 13 features are indexed 892 let features = [ 893 "vault_resolution", 894 "prompt_sanitizer", 895 "cortex_auth", 896 "resident_bounds", 897 "crawler_flags", 898 "cli_workbench", 899 "key_verification", 900 "axum_routes", 901 "cortex_storage", 902 "dataset_emission", 903 "verification_gates", 904 "test_harness", 905 "git_parity", 906 ]; 907 assert_eq!(features.len(), 13); 908 } 909 910 #[test] 911 fn test_t1_f57_e2e_harness_cargo_test_invocation() { 912 if std::env::var("CI").is_ok() { 913 return; 914 } 915 let status = Command::new("cargo") 916 .args(["check", "-p", "spark-adapters"]) 917 .current_dir(workspace_root()) 918 .status(); 919 assert!(status.is_ok()); 920 assert!(status.unwrap().success()); 921 } 922 923 #[test] 924 fn test_t1_f58_e2e_harness_isolated_temp_directories() { 925 let temp_dir = std::env::temp_dir().join(format!("spark_test_{}", uuid::Uuid::new_v4())); 926 fs::create_dir_all(&temp_dir).unwrap(); 927 assert!(temp_dir.exists()); 928 fs::remove_dir_all(&temp_dir).unwrap(); 929 } 930 931 #[test] 932 fn test_t1_f59_e2e_harness_zero_disk_secrets_invariant() { 933 let output = Command::new("find") 934 .args([ 935 workspace_root().to_str().unwrap(), 936 "-name", 937 ".env*", 938 "-not", 939 "-path", 940 "*/.*", 941 ]) 942 .output() 943 .expect("find .env"); 944 let stdout = String::from_utf8_lossy(&output.stdout); 945 assert!( 946 stdout.trim().is_empty(), 947 "No .env files allowed in workspace" 948 ); 949 } 950 951 #[test] 952 fn test_t1_f60_e2e_harness_unslop_output_formatting() { 953 use std::fs; 954 use std::process::Command; 955 956 // 1. Inspect the real E2E test suite runner script 957 let script_path = workspace_root().join("scripts/e2e_distill_test.sh"); 958 assert!( 959 script_path.exists(), 960 "scripts/e2e_distill_test.sh must exist" 961 ); 962 let script_content = fs::read_to_string(&script_path).expect("read e2e_distill_test.sh"); 963 assert!( 964 !script_content.contains('\u{2014}'), 965 "e2e_distill_test.sh contains forbidden em dash" 966 ); 967 assert!( 968 !script_content.contains('\u{2013}'), 969 "e2e_distill_test.sh contains forbidden en dash" 970 ); 971 972 // 2. Execute spark-distill --help and verify CLI output formatting 973 let bin = spark_distill_bin(); 974 let output = Command::new(bin) 975 .arg("--help") 976 .output() 977 .expect("run spark-distill --help"); 978 assert!(output.status.success()); 979 let stdout = String::from_utf8_lossy(&output.stdout); 980 assert!( 981 !stdout.contains('\u{2014}'), 982 "spark-distill CLI help contains forbidden em dash" 983 ); 984 assert!( 985 !stdout.contains('\u{2013}'), 986 "spark-distill CLI help contains forbidden en dash" 987 ); 988 } 989 990 // ============================================================================ 991 // Feature 13: Remote Git Parity & PR Lifecycle 992 // ============================================================================ 993 994 #[test] 995 fn test_t1_f61_git_current_branch_is_feature_branch() { 996 if std::env::var("CI").is_ok() { 997 return; 998 } 999 let output = Command::new("git") 1000 .args(["branch", "--show-current"]) 1001 .current_dir(workspace_root()) 1002 .output() 1003 .expect("git branch"); 1004 let branch = String::from_utf8_lossy(&output.stdout).trim().to_string(); 1005 assert!( 1006 branch.starts_with("feat/") 1007 || branch == "main" 1008 || branch == "master" 1009 || branch.starts_with("fix/") 1010 || branch.starts_with("perf/") 1011 || branch.starts_with("refactor/") 1012 || branch.starts_with("release/") 1013 || branch.is_empty(), 1014 "Branch must be a valid lifecycle branch (feat/*, fix/*, perf/*, refactor/*, release/*) or main/master, found: {}", 1015 branch 1016 ); 1017 } 1018 1019 #[test] 1020 fn test_t1_f62_git_origin_remote_configured() { 1021 let output = Command::new("git") 1022 .args(["remote", "get-url", "origin"]) 1023 .current_dir(workspace_root()) 1024 .output() 1025 .expect("git remote origin"); 1026 let url = String::from_utf8_lossy(&output.stdout); 1027 // Canon is Radicle while GitHub is held (Drake, 2026-11-07); GitHub stays accepted for when it returns. 1028 assert!( 1029 url.contains("github.com") 1030 || url.trim_start().starts_with("rad:") 1031 || url.contains("/.radicle/storage/z") 1032 || url.contains("aienos.com/rad/z"), 1033 "origin must be the GitHub or Radicle canonical repository, found: {}", 1034 url.trim() 1035 ); 1036 } 1037 1038 #[test] 1039 fn test_t1_f63_git_forgejo_remote_configured() { 1040 if std::env::var("CI").is_ok() { 1041 return; 1042 } 1043 let output = Command::new("git") 1044 .args(["remote", "get-url", "forgejo"]) 1045 .current_dir(workspace_root()) 1046 .output() 1047 .expect("git remote forgejo"); 1048 assert!( 1049 output.status.success(), 1050 "forgejo remote must be configured for dual-push" 1051 ); 1052 } 1053 1054 #[test] 1055 fn test_t1_f64_git_commit_messages_unslop_compliant() { 1056 let output = Command::new("git") 1057 .args(["log", "-n", "10", "--format=%s"]) 1058 .current_dir(workspace_root()) 1059 .output() 1060 .expect("git log"); 1061 let log = String::from_utf8_lossy(&output.stdout); 1062 assert!( 1063 !log.contains('\u{2014}'), 1064 "Commit messages must not contain em dashes" 1065 ); 1066 assert!( 1067 !log.contains('\u{2013}'), 1068 "Commit messages must not contain en dashes" 1069 ); 1070 } 1071 1072 #[test] 1073 fn test_t1_f65_git_license_file_declares_apache() { 1074 let license_path = workspace_root().join("LICENSE"); 1075 let content = fs::read_to_string(license_path).expect("read LICENSE"); 1076 assert!(content.contains("Apache License")); 1077 assert!(content.contains("Version 2.0, January 2004")); 1078 assert!(!content.contains("GNU AFFERO GENERAL PUBLIC LICENSE")); 1079 assert!(!content.contains("SRCL-1.0")); 1080 }