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-adapters / tests / tier2_boundary.rs

1239 lines · 41776 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 std::path::{Path, PathBuf};
17
18fn 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 // Fallback: this file lives at <root>/crates/spark-adapters/tests.
28 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..")
29}
30
31fn spark_distill_bin() -> PathBuf {
32 PathBuf::from(env!("CARGO_BIN_EXE_spark-distill"))
33}
34// Tier 2: Boundary, Corner, Negative, and Stress Tests
35// Strictly adheres to sovereign unslop invariants: zero em dashes, zero en dashes.
36
37use spark_adapters::curriculum::{CurriculumEngine, CurriculumTrack};
38use spark_adapters::models::{ChatMessage, DistillTask, TaskType, VerificationStrategy};
39use spark_adapters::providers::format_openai_payload;
40use spark_adapters::router::AdapterRouter;
41use spark_adapters::vault::{is_secret_present, resolve_secret, sanitize_outbound_prompt};
42use spark_adapters::verifier::Verifier;
43use std::fs;
44use std::process::Command;
45
46// ============================================================================
47// Feature 1: Vault Boundary
48// ============================================================================
49
50#[test]
51fn test_t2_f01_vault_nonexistent_key_returns_none() {
52 let res = resolve_secret("NONEXISTENT_ATLAS_KEY_9999");
53 assert_eq!(res, None);
54}
55
56#[test]
57fn test_t2_f02_vault_empty_env_var_treated_as_absent() {
58 std::env::set_var("EMPTY_ATLAS_TEST_VAR", "");
59 assert_eq!(resolve_secret("EMPTY_ATLAS_TEST_VAR"), None);
60 std::env::remove_var("EMPTY_ATLAS_TEST_VAR");
61}
62
63#[test]
64fn test_t2_f03_vault_whitespace_secret_rejected() {
65 std::env::set_var("WS_ATLAS_TEST_VAR", " \t \n ");
66 assert_eq!(resolve_secret("WS_ATLAS_TEST_VAR"), None);
67 std::env::remove_var("WS_ATLAS_TEST_VAR");
68}
69
70#[test]
71fn test_t2_f04_vault_key_case_sensitivity() {
72 std::env::set_var("SOVEREIGN_LOWERCASE_VAR", "value123");
73 assert_ne!(
74 resolve_secret("sovereign_lowercase_var"),
75 Some("value123".to_string())
76 );
77 std::env::remove_var("SOVEREIGN_LOWERCASE_VAR");
78}
79
80#[test]
81fn test_t2_f05_vault_missing_daemon_handled_gracefully() {
82 let res = is_secret_present("SOME_DEFINITELY_MISSING_SECRET_KEY");
83 assert!(!res);
84}
85
86// ============================================================================
87// Feature 2: Outbound Prompt Sanitizer Boundary
88// ============================================================================
89
90#[test]
91fn test_t2_f06_sanitizer_empty_prompt() {
92 let res = sanitize_outbound_prompt("");
93 assert_eq!(res, "");
94}
95
96#[test]
97fn test_t2_f07_sanitizer_prompt_only_paths() {
98 let input = "/home/alice/dir/file.rs";
99 let output = sanitize_outbound_prompt(input);
100 assert_eq!(output, "<WORKSPACE_PATH>");
101}
102
103#[test]
104fn test_t2_f08_sanitizer_prompt_only_ips() {
105 let input = "127.0.0.1 192.168.0.1 10.0.0.1";
106 let output = sanitize_outbound_prompt(input);
107 assert!(!output.contains("127.0.0.1"));
108 assert!(!output.contains("192.168.0.1"));
109 assert!(!output.contains("10.0.0.1"));
110 assert!(output.contains("<LOCAL_HOST>"));
111}
112
113#[test]
114fn test_t2_f09_sanitizer_multiple_mixed_secrets() {
115 let input = "sk-proj-abc12345678901234567890 and ghp_xyz12345678901234567890";
116 let output = sanitize_outbound_prompt(input);
117 assert!(!output.contains("sk-proj-"));
118 assert!(!output.contains("ghp_"));
119 assert!(output.contains("[REDACTED_BY_ATLAS_VAULT]"));
120}
121
122#[test]
123fn test_t2_f10_sanitizer_system_prompt_scrubbing() {
124 let sys = "You are running on /home/alice for aien@aienos.com";
125 let cleaned = sanitize_outbound_prompt(sys);
126 assert!(!cleaned.contains("/home/alice"));
127 assert!(!cleaned.contains("aien@aienos.com"));
128}
129
130// ============================================================================
131// Feature 3: Cortex Auth Boundary
132// ============================================================================
133
134#[test]
135fn test_t2_f11_cortex_commit_without_token_fails_gracefully() {
136 let default_endpoint = "http://127.0.0.1:18080";
137 let url = format!("{}/api/cortex/write", default_endpoint);
138 assert!(url.contains("/api/cortex/write"));
139}
140
141#[test]
142fn test_t2_f12_cortex_unreachable_endpoint_handled() {
143 let bad_endpoint = "http://127.0.0.1:19999/api/cortex/write";
144 let res = Command::new("curl")
145 .args([
146 "-s",
147 "-o",
148 "/dev/null",
149 "-w",
150 "%{http_code}",
151 "--connect-timeout",
152 "1",
153 bad_endpoint,
154 ])
155 .output();
156 assert!(res.is_ok());
157 let out = res.expect("curl");
158 let code = String::from_utf8_lossy(&out.stdout);
159 assert_eq!(code.trim(), "000");
160}
161
162#[test]
163fn test_t2_f13_cortex_http_401_unauthorized_handled() {
164 if std::env::var("CI").is_ok() {
165 return;
166 }
167 let output = Command::new("curl")
168 .args([
169 "-s",
170 "-o",
171 "/dev/null",
172 "-w",
173 "%{http_code}",
174 "-H",
175 "Authorization: Bearer invalid_test_token",
176 "http://127.0.0.1:18080/api/status",
177 ])
178 .output()
179 .expect("curl cortex status");
180 let code = String::from_utf8_lossy(&output.stdout);
181 assert_eq!(code.trim(), "401");
182}
183
184#[test]
185fn test_t2_f14_cortex_malformed_json_response_handled() {
186 let invalid_json = "{ invalid_payload: ";
187 let parsed: Result<serde_json::Value, _> = serde_json::from_str(invalid_json);
188 assert!(parsed.is_err());
189}
190
191#[test]
192fn test_t2_f15_cortex_missing_target_id_fallback() {
193 let body = serde_json::json!({
194 "status": "ok"
195 });
196 let canonical_name = "distill_fallback_test";
197 let entity_id = body
198 .pointer("/receipt/targetId")
199 .and_then(|v| v.as_str())
200 .unwrap_or(canonical_name);
201 assert_eq!(entity_id, "distill_fallback_test");
202}
203
204// ============================================================================
205// Feature 4: Resident Generation Bounds Boundary
206// ============================================================================
207
208#[test]
209fn test_t2_f16_resident_zero_or_negative_temperature_handling() {
210 let msgs = vec![ChatMessage {
211 role: "user".to_string(),
212 content: "Test".to_string(),
213 reasoning: None,
214 }];
215 let payload = format_openai_payload("atlas-lightning-omni", &msgs, Some(0.0), false);
216 let temp = payload["temperature"].as_f64().unwrap();
217 assert_eq!(temp, 0.0);
218}
219
220#[test]
221fn test_t2_f17_resident_context_length_exceeded_handling() {
222 let max_len = 32768;
223 let request_len = 35000;
224 assert!(request_len > max_len);
225}
226
227#[test]
228fn test_t2_f18_resident_large_prompt_payload_safety() {
229 let large_prompt = "a".repeat(100_000);
230 let msgs = vec![ChatMessage {
231 role: "user".to_string(),
232 content: large_prompt,
233 reasoning: None,
234 }];
235 let payload = format_openai_payload("atlas-lightning-omni", &msgs, None, false);
236 assert_eq!(payload["messages"].as_array().unwrap().len(), 1);
237}
238
239#[test]
240fn test_t2_f19_resident_empty_messages_payload_safety() {
241 let msgs: Vec<ChatMessage> = Vec::new();
242 let payload = format_openai_payload("atlas-lightning-omni", &msgs, None, false);
243 assert_eq!(payload["messages"].as_array().unwrap().len(), 0);
244}
245
246#[test]
247fn test_t2_f20_resident_unicode_preservation() {
248 let math_prompt = "Prove α + β = γ with ∀x ∈ ℝ";
249 let msgs = vec![ChatMessage {
250 role: "user".to_string(),
251 content: math_prompt.to_string(),
252 reasoning: None,
253 }];
254 let payload = format_openai_payload("atlas-lightning-omni", &msgs, None, false);
255 let content = payload["messages"][0]["content"].as_str().unwrap();
256 assert_eq!(content, math_prompt);
257}
258
259// ============================================================================
260// Feature 5: Crawler Flag Collision Boundary
261// ============================================================================
262
263#[test]
264fn test_t2_f21_crawler_short_flag_t_collision_rejection() {
265 let bin_path = spark_distill_bin();
266 let output = Command::new(bin_path)
267 .args(["crawl", "--help"])
268 .output()
269 .expect("crawl help");
270 let stderr = String::from_utf8_lossy(&output.stderr);
271 assert!(
272 !stderr.contains("Short option names must be unique"),
273 "Clap short flag collision detected"
274 );
275}
276
277#[test]
278fn test_t2_f22_crawler_unknown_track_returns_none() {
279 let track = CurriculumTrack::parse("unknown_track_xyz");
280 assert_eq!(track, None);
281}
282
283#[test]
284fn test_t2_f23_crawler_zero_task_limit_returns_empty() {
285 let tasks = CurriculumEngine::generate_tasks(
286 CurriculumTrack::NativeSystemsAndGpu,
287 0,
288 "anthropic/claude-3-7-sonnet",
289 None,
290 false,
291 );
292 assert_eq!(tasks.len(), 0);
293}
294
295#[test]
296fn test_t2_f24_crawler_large_limit_safe_bounded_tasks() {
297 let tasks = CurriculumEngine::generate_tasks(
298 CurriculumTrack::NativeSystemsAndGpu,
299 100,
300 "anthropic/claude-3-7-sonnet",
301 None,
302 false,
303 );
304 assert!(!tasks.is_empty());
305 assert!(tasks.len() <= 100);
306}
307
308#[test]
309fn test_t2_f25_crawler_dynamic_track_fallback_without_git() {
310 let tasks = CurriculumEngine::generate_tasks(
311 CurriculumTrack::DynamicMining,
312 2,
313 "anthropic/claude-3-7-sonnet",
314 None,
315 false,
316 );
317 assert!(!tasks.is_empty());
318}
319
320// ============================================================================
321// Feature 6: CLI Workbench Boundary
322// ============================================================================
323
324#[test]
325fn test_t2_f26_cli_empty_args_shows_error() {
326 let bin_path = spark_distill_bin();
327 let output = Command::new(bin_path).output().expect("distill invocation");
328 assert!(!output.status.success());
329}
330
331#[test]
332fn test_t2_f27_cli_unknown_subcommand_exits_nonzero() {
333 let bin_path = spark_distill_bin();
334 let output = Command::new(bin_path)
335 .arg("invalid_subcommand_xyz")
336 .output()
337 .expect("invalid subcmd");
338 assert!(!output.status.success());
339}
340
341#[test]
342fn test_t2_f28_cli_invalid_strategy_defaults_to_compiler() {
343 let parsed = match "unknown_strategy".to_lowercase().as_str() {
344 "unslop" => VerificationStrategy::UnslopStrict,
345 "json" => VerificationStrategy::JsonSchema,
346 "consensus" => VerificationStrategy::DualConsensus,
347 _ => VerificationStrategy::CompilerCheck,
348 };
349 assert_eq!(parsed, VerificationStrategy::CompilerCheck);
350}
351
352#[test]
353fn test_t2_f29_cli_invalid_task_type_defaults_to_code() {
354 let parsed = match "unknown_task".to_lowercase().as_str() {
355 "arch" => TaskType::SystemArchitecture,
356 "reasoning" => TaskType::ReasoningTrace,
357 "refactor" => TaskType::RefactorLogic,
358 "harness" => TaskType::VerificationHarness,
359 _ => TaskType::CodeSynthesis,
360 };
361 assert_eq!(parsed, TaskType::CodeSynthesis);
362}
363
364#[test]
365fn test_t2_f30_cli_dataset_dir_auto_created() {
366 let temp_dir = std::env::temp_dir().join(format!("test_auto_create_{}", uuid::Uuid::new_v4()));
367 assert!(!temp_dir.exists());
368 fs::create_dir_all(&temp_dir).unwrap();
369 assert!(temp_dir.exists());
370 fs::remove_dir_all(&temp_dir).unwrap();
371}
372
373// ============================================================================
374// Feature 7: Key Verification Boundary
375// ============================================================================
376
377#[test]
378fn test_t2_f31_verify_keys_zero_keys_handling() {
379 let router = AdapterRouter::new();
380 let adapters = router.discover_adapters();
381 assert!(!adapters.is_empty());
382}
383
384#[test]
385fn test_t2_f32_verify_keys_catalog_no_duplicate_ids() {
386 let router = AdapterRouter::new();
387 let adapters = router.discover_adapters();
388 let mut seen = std::collections::HashSet::new();
389 for a in adapters {
390 assert!(seen.insert(a.id), "Duplicate adapter ID detected");
391 }
392}
393
394#[test]
395fn test_t2_f33_verify_keys_all_endpoints_valid_urls() {
396 let router = AdapterRouter::new();
397 let adapters = router.discover_adapters();
398 for a in adapters {
399 assert!(
400 a.endpoint.starts_with("http://")
401 || a.endpoint.starts_with("https://")
402 || a.endpoint.starts_with("in-process://"),
403 "Invalid endpoint scheme"
404 );
405 }
406}
407
408#[test]
409fn test_t2_f34_verify_keys_all_context_lengths_positive() {
410 let router = AdapterRouter::new();
411 let adapters = router.discover_adapters();
412 for a in adapters {
413 assert!(
414 a.context_length > 0,
415 "Context length must be strictly positive"
416 );
417 }
418}
419
420#[test]
421fn test_t2_f35_verify_keys_adapter_status_string_representation() {
422 let status_ready = "READY";
423 let status_missing = "KEY MISSING";
424 let status_local = "LOCAL";
425 assert_ne!(status_ready, status_missing);
426 assert_ne!(status_ready, status_local);
427}
428
429// ============================================================================
430// Feature 8: Axum Routes Boundary
431// ============================================================================
432
433#[test]
434fn test_t2_f36_axum_nonexistent_route_404() {
435 if std::env::var("CI").is_ok() {
436 return;
437 }
438 let output = Command::new("curl")
439 .args([
440 "-s",
441 "-o",
442 "/dev/null",
443 "-w",
444 "%{http_code}",
445 "http://127.0.0.1:18095/nonexistent_route_xyz",
446 ])
447 .output()
448 .expect("curl cockpit");
449 let code = String::from_utf8_lossy(&output.stdout);
450 // An unknown route never serves content. Without a session the cockpit access
451 // gate (spark-cockpit-rs/src/access.rs) answers 401 before routing, so an
452 // anonymous probe learns nothing about which routes exist; a gate-less build
453 // answers 404.
454 assert!(
455 code.trim() == "404" || code.trim() == "401",
456 "unknown route returned {} (expected 404, or 401 from the access gate)",
457 code.trim()
458 );
459}
460
461#[test]
462fn test_t2_f37_axum_distill_empty_json_error() {
463 let empty_payload = "{}";
464 let res: Result<DistillTask, _> = serde_json::from_str(empty_payload);
465 assert!(res.is_err(), "Empty payload must fail deserialization");
466}
467
468#[test]
469fn test_t2_f38_axum_distill_missing_teacher_error() {
470 let missing_teacher = r#"{
471 "id": "task-01",
472 "task_type": "code_synthesis",
473 "prompt": "ping",
474 "verification_strategy": "compiler_check",
475 "commit_to_cortex": false
476 }"#;
477 let res: Result<DistillTask, _> = serde_json::from_str(missing_teacher);
478 assert!(res.is_err());
479}
480
481#[test]
482fn test_t2_f39_axum_commit_empty_json_error() {
483 let empty_json = "{}";
484 let val: serde_json::Value = serde_json::from_str(empty_json).unwrap();
485 assert!(val.get("solution").is_none());
486}
487
488#[test]
489fn test_t2_f40_axum_distill_invalid_track_caught() {
490 let parsed = CurriculumTrack::parse("invalid_track_string");
491 assert!(parsed.is_none());
492}
493
494// ============================================================================
495// Feature 9: Cortex Closed-Loop Storage Boundary
496// ============================================================================
497
498#[test]
499fn test_t2_f41_cortex_sub_threshold_score_rejected() {
500 let score: f32 = 0.84;
501 let passed = true;
502 let commit_to_cortex = true;
503 let should_commit = commit_to_cortex && passed && score >= 0.85;
504 assert!(
505 !should_commit,
506 "Score 0.84 must not qualify for Cortex commit"
507 );
508}
509
510#[test]
511fn test_t2_f42_cortex_failed_verification_rejected() {
512 let score: f32 = 0.95;
513 let passed = false;
514 let commit_to_cortex = true;
515 let should_commit = commit_to_cortex && passed && score >= 0.85;
516 assert!(
517 !should_commit,
518 "Failed verification must not qualify for Cortex commit"
519 );
520}
521
522#[test]
523fn test_t2_f43_cortex_commit_false_flag_respected() {
524 use spark_adapters::distill::DistillationEngine;
525
526 let qualifies = DistillationEngine::qualifies_for_cortex(false, true, 1.0);
527 assert!(!qualifies, "commit_to_cortex=false must prevent commit");
528}
529
530#[test]
531fn test_t2_f44_cortex_canonical_name_hyphen_sanitization() {
532 let raw = "task-uuid-123-abc";
533 let canonical = format!("distill_{}", raw.replace('-', "_"));
534 assert!(
535 !canonical.contains('-'),
536 "Canonical name must not contain hyphens"
537 );
538}
539
540#[test]
541fn test_t2_f45_cortex_content_summary_includes_verified_solution() {
542 let solution = "pub fn add() {}";
543 let summary = format!("Verified Solution: {}", solution);
544 assert!(summary.contains("Verified Solution:"));
545}
546
547// ============================================================================
548// Feature 10: SFT & DPO Dataset Boundary
549// ============================================================================
550
551#[test]
552fn test_t2_f46_dpo_zero_delta_rejected() {
553 use spark_adapters::distill::DistillationEngine;
554 use spark_adapters::models::{DistillTask, TaskType, VerificationStrategy};
555 use std::fs;
556
557 let temp_dir =
558 std::env::temp_dir().join(format!("spark_distill_t2_f46_{}", uuid::Uuid::new_v4()));
559 let engine = DistillationEngine::new().with_dataset_dir(&temp_dir);
560
561 let task = DistillTask {
562 id: "task-zero-delta-01".to_string(),
563 task_type: TaskType::CodeSynthesis,
564 prompt: "Implement vector push".to_string(),
565 system_prompt: None,
566 teacher_model: "anthropic/claude-3-7-sonnet".to_string(),
567 student_model: Some("atlas-lightning-omni".to_string()),
568 verification_strategy: VerificationStrategy::UnslopStrict,
569 commit_to_cortex: false,
570 };
571
572 let chosen = "fn push(v: &mut Vec<i32>, val: i32) { v.push(val); }";
573 let rejected = "fn push(v: &mut Vec<i32>, val: i32) { v.push(val); }";
574 let preference_delta = 0.0f32;
575
576 let valid_rej =
577 DistillationEngine::filter_dpo_candidate(chosen, Some(rejected), preference_delta);
578 assert_eq!(
579 valid_rej, None,
580 "Zero preference delta must be rejected for DPO pair"
581 );
582
583 let dpo_persisted = engine
584 .persist_training_pair(&task, chosen, None, valid_rej)
585 .expect("persist training pair");
586 assert!(
587 !dpo_persisted,
588 "DPO pair must NOT be persisted when delta is zero"
589 );
590
591 assert!(
592 temp_dir.join("sft.jsonl").exists(),
593 "SFT dataset must still be written"
594 );
595 assert!(
596 !temp_dir.join("dpo.jsonl").exists(),
597 "DPO dataset must NOT be written when delta is zero"
598 );
599
600 let _ = fs::remove_dir_all(&temp_dir);
601}
602
603#[test]
604fn test_t2_f47_dpo_negative_delta_rejected() {
605 use spark_adapters::distill::DistillationEngine;
606 use spark_adapters::models::{DistillTask, TaskType, VerificationStrategy};
607 use std::fs;
608
609 let temp_dir =
610 std::env::temp_dir().join(format!("spark_distill_t2_f47_{}", uuid::Uuid::new_v4()));
611 let engine = DistillationEngine::new().with_dataset_dir(&temp_dir);
612
613 let task = DistillTask {
614 id: "task-negative-delta-01".to_string(),
615 task_type: TaskType::CodeSynthesis,
616 prompt: "Calculate factorial".to_string(),
617 system_prompt: None,
618 teacher_model: "anthropic/claude-3-7-sonnet".to_string(),
619 student_model: Some("atlas-lightning-omni".to_string()),
620 verification_strategy: VerificationStrategy::CompilerCheck,
621 commit_to_cortex: false,
622 };
623
624 let chosen = "fn fact(n: u64) -> u64 { (1..=n).product() }";
625 let rejected = "fn fact(n: u64) -> u64 { 1 }";
626 let negative_delta = -0.15f32;
627
628 let valid_rej =
629 DistillationEngine::filter_dpo_candidate(chosen, Some(rejected), negative_delta);
630 assert_eq!(
631 valid_rej, None,
632 "Negative preference delta must be rejected for DPO pair"
633 );
634
635 let dpo_persisted = engine
636 .persist_training_pair(&task, chosen, None, valid_rej)
637 .expect("persist training pair");
638 assert!(
639 !dpo_persisted,
640 "DPO pair must NOT be persisted when delta is negative"
641 );
642 assert!(
643 !temp_dir.join("dpo.jsonl").exists(),
644 "DPO dataset must NOT exist for negative delta"
645 );
646
647 let _ = fs::remove_dir_all(&temp_dir);
648}
649
650#[test]
651fn test_t2_f48_dpo_identical_outputs_rejected() {
652 use spark_adapters::distill::DistillationEngine;
653 use spark_adapters::models::{DistillTask, TaskType, VerificationStrategy};
654 use std::fs;
655
656 let temp_dir =
657 std::env::temp_dir().join(format!("spark_distill_t2_f48_{}", uuid::Uuid::new_v4()));
658 let engine = DistillationEngine::new().with_dataset_dir(&temp_dir);
659
660 let task = DistillTask {
661 id: "task-identical-dpo-01".to_string(),
662 task_type: TaskType::CodeSynthesis,
663 prompt: "Write empty entry point".to_string(),
664 system_prompt: None,
665 teacher_model: "anthropic/claude-3-7-sonnet".to_string(),
666 student_model: Some("atlas-lightning-omni".to_string()),
667 verification_strategy: VerificationStrategy::CompilerCheck,
668 commit_to_cortex: false,
669 };
670
671 let chosen = "fn main() {}";
672 let identical_rejected = "fn main() {}";
673 let positive_delta = 0.30f32;
674
675 let valid_rej =
676 DistillationEngine::filter_dpo_candidate(chosen, Some(identical_rejected), positive_delta);
677 assert_eq!(
678 valid_rej, None,
679 "Identical chosen and rejected completions must be rejected for DPO pair"
680 );
681
682 let dpo_persisted = engine
683 .persist_training_pair(&task, chosen, None, valid_rej)
684 .expect("persist training pair");
685 assert!(
686 !dpo_persisted,
687 "DPO pair must NOT be persisted for identical completions"
688 );
689 assert!(
690 !temp_dir.join("dpo.jsonl").exists(),
691 "DPO dataset must NOT exist for identical completions"
692 );
693
694 let _ = fs::remove_dir_all(&temp_dir);
695}
696
697#[test]
698fn test_t2_f49_dpo_missing_student_rollout_no_dpo_file() {
699 use spark_adapters::distill::DistillationEngine;
700 use spark_adapters::models::{DistillTask, TaskType, VerificationStrategy};
701 use std::fs;
702
703 let temp_dir =
704 std::env::temp_dir().join(format!("spark_distill_t2_f49_{}", uuid::Uuid::new_v4()));
705 let engine = DistillationEngine::new().with_dataset_dir(&temp_dir);
706
707 let task = DistillTask {
708 id: "task-missing-student-01".to_string(),
709 task_type: TaskType::CodeSynthesis,
710 prompt: "Write unit test".to_string(),
711 system_prompt: None,
712 teacher_model: "anthropic/claude-3-7-sonnet".to_string(),
713 student_model: None,
714 verification_strategy: VerificationStrategy::UnslopStrict,
715 commit_to_cortex: false,
716 };
717
718 let chosen = "#[test] fn test() {}";
719 let valid_rej = DistillationEngine::filter_dpo_candidate(chosen, None, 0.0);
720 assert_eq!(
721 valid_rej, None,
722 "Missing student rollout must yield None for DPO candidate"
723 );
724
725 let dpo_persisted = engine
726 .persist_training_pair(&task, chosen, None, valid_rej)
727 .expect("persist training pair");
728 assert!(
729 !dpo_persisted,
730 "DPO pair must NOT be persisted when student rollout is missing"
731 );
732 assert!(
733 !temp_dir.join("dpo.jsonl").exists(),
734 "DPO dataset must NOT exist when student rollout is missing"
735 );
736
737 let _ = fs::remove_dir_all(&temp_dir);
738}
739
740#[test]
741fn test_t2_f50_dataset_permission_denied_handled_gracefully() {
742 let bad_path = std::path::Path::new("/root/nonexistent_forbidden_dir/sft.jsonl");
743 let res = fs::OpenOptions::new()
744 .create(true)
745 .write(true)
746 .truncate(true)
747 .open(bad_path);
748 assert!(res.is_err());
749}
750
751// ============================================================================
752// Feature 11: Verification Gates Boundary
753// ============================================================================
754
755#[test]
756fn test_t2_f51_verifier_rustc_compilation_failure_deducts_score() {
757 let broken_code = "pub fn broken() { let x: i32 = \"not an int\"; }";
758 let res = Verifier::verify_with_rustc(broken_code);
759 assert!(res.is_err(), "rustc must fail on type mismatch");
760}
761
762#[test]
763fn test_t2_f52_verifier_em_dash_detected_and_penalized() {
764 let bad_text = "Fast \u{2014} and reliable.";
765 let outcome = Verifier::verify(bad_text, VerificationStrategy::UnslopStrict);
766 assert!(!outcome.passed);
767 assert!(outcome
768 .rule_violations
769 .iter()
770 .any(|v| v.contains("em dash")));
771 assert!(outcome.score <= 0.75);
772}
773
774#[test]
775fn test_t2_f53_verifier_en_dash_detected_and_penalized() {
776 let bad_text = "Pages 1\u{2013}5.";
777 let outcome = Verifier::verify(bad_text, VerificationStrategy::UnslopStrict);
778 assert!(outcome
779 .rule_violations
780 .iter()
781 .any(|v| v.contains("en dash")));
782 assert!(outcome.score <= 0.85);
783}
784
785#[test]
786fn test_t2_f54_verifier_banned_cliche_detected_and_penalized() {
787 let text = "We must delve into the tapestry of the problem.";
788 let outcome = Verifier::verify(text, VerificationStrategy::UnslopStrict);
789 assert!(outcome.rule_violations.iter().any(|v| v.contains("delve")));
790 assert!(outcome
791 .rule_violations
792 .iter()
793 .any(|v| v.contains("tapestry")));
794}
795
796#[test]
797fn test_t2_f55_verifier_secret_signature_resets_score_to_zero() {
798 let text = "Here is my secret sk-proj-123456789012345678901234";
799 let outcome = Verifier::verify(text, VerificationStrategy::CompilerCheck);
800 assert_eq!(outcome.score, 0.0);
801 assert!(!outcome.passed);
802 assert!(outcome
803 .rule_violations
804 .iter()
805 .any(|v| v.contains("Critical: Contains secret signature")));
806}
807
808// ============================================================================
809// Feature 12: Test Suite Boundary
810// ============================================================================
811
812#[test]
813fn test_t2_f56_verifier_unclosed_delimiter_detected() {
814 let unclosed = "fn test() { let x = (1 + 2;";
815 let outcome = Verifier::verify(unclosed, VerificationStrategy::CompilerCheck);
816 eprintln!("VIOLATIONS: {:?}", outcome.rule_violations);
817 assert!(outcome
818 .rule_violations
819 .iter()
820 .any(|v| v.to_lowercase().contains("unclosed delimiter")));
821}
822
823#[test]
824fn test_t2_f57_verifier_mismatched_delimiter_detected() {
825 let mismatched = "fn test() { let x = [1, 2); }";
826 let outcome = Verifier::verify(mismatched, VerificationStrategy::CompilerCheck);
827 assert!(outcome
828 .rule_violations
829 .iter()
830 .any(|v| v.to_lowercase().contains("delimiter")));
831}
832
833#[test]
834fn test_t2_f58_verifier_string_literal_delimiters_ignored() {
835 let code_with_string = "pub fn greet() -> &'static str { \"([{\"}";
836 let outcome = Verifier::verify(code_with_string, VerificationStrategy::CompilerCheck);
837 assert!(!outcome
838 .rule_violations
839 .iter()
840 .any(|v| v.to_lowercase().contains("unclosed delimiter")));
841}
842
843#[test]
844fn test_t2_f59_verifier_malformed_json_schema_detected() {
845 let bad_json = "Here is JSON: { \"invalid_json\": ";
846 let outcome = Verifier::verify(bad_json, VerificationStrategy::JsonSchema);
847 assert!(outcome
848 .rule_violations
849 .iter()
850 .any(|v| v.contains("malformed") || v.contains("Incomplete")));
851}
852
853#[test]
854fn test_t2_f60_verifier_incomplete_json_brackets_detected() {
855 let incomplete_json = "Payload: { \"key\": \"value\"";
856 let outcome = Verifier::verify(incomplete_json, VerificationStrategy::JsonSchema);
857 assert!(outcome
858 .rule_violations
859 .iter()
860 .any(|v| v.contains("Incomplete JSON")));
861}
862
863// ============================================================================
864// Feature 13: Remote Git Parity Boundary
865// ============================================================================
866
867#[test]
868fn test_t2_f61_git_no_uncommitted_env_secrets() {
869 let output = Command::new("git")
870 .args(["status", "--porcelain"])
871 .current_dir(workspace_root())
872 .output()
873 .expect("git status");
874 let status = String::from_utf8_lossy(&output.stdout);
875 assert!(
876 !status.contains(".env"),
877 "No .env files allowed in git status"
878 );
879}
880
881/// Scan of commit messages a branch introduces over a base revision.
882#[derive(Debug)]
883enum CommitMessageScan {
884 /// `AIEN_COMMIT_LINT_BASE` is unset or empty. This is the only skip.
885 NoBase,
886 Clean,
887 Forbidden {
888 em: bool,
889 en: bool,
890 },
891 /// The base was set, but it cannot be resolved or `git log` failed.
892 Failed(String),
893}
894
895/// What the workspace test does with a scan. `Fail` panics.
896#[derive(Debug)]
897enum CommitLintAction {
898 Skip(String),
899 Pass,
900 Fail(String),
901}
902
903fn git_in(repo: &Path, args: &[&str]) -> std::process::Output {
904 Command::new("git")
905 .arg("-c")
906 .arg("safe.directory=*")
907 .args(args)
908 .current_dir(repo)
909 .env("GIT_CONFIG_GLOBAL", "/dev/null")
910 .env("GIT_CONFIG_SYSTEM", "/dev/null")
911 .env("GIT_AUTHOR_NAME", "t2f62")
912 .env("GIT_AUTHOR_EMAIL", "t2f62@example.com")
913 .env("GIT_COMMITTER_NAME", "t2f62")
914 .env("GIT_COMMITTER_EMAIL", "t2f62@example.com")
915 .output()
916 .unwrap_or_else(|err| panic!("spawn git {args:?}: {err}"))
917}
918
919fn git_ok(repo: &Path, args: &[&str]) -> std::process::Output {
920 let output = git_in(repo, args);
921 assert!(
922 output.status.success(),
923 "git {args:?} exited {}: {}",
924 output.status,
925 String::from_utf8_lossy(&output.stderr)
926 );
927 output
928}
929
930/// `git log <base>..HEAD` in `repo`.
931///
932/// `base` is `AIEN_COMMIT_LINT_BASE` (the PR base, or the previous push SHA).
933/// Unset or empty is the only skip. A set base that cannot be resolved, or a
934/// failed `git log`, is `Failed`. This does not fall back to `git log -n` or
935/// any other scan of history already on the base.
936fn scan_commits_introduced_over_base(repo: &Path, base: Option<&str>) -> CommitMessageScan {
937 let Some(base) = base.map(str::trim).filter(|b| !b.is_empty()) else {
938 return CommitMessageScan::NoBase;
939 };
940 if base.starts_with('-') || base.chars().any(|c| c.is_whitespace()) {
941 return CommitMessageScan::Failed(format!("base {base:?} is not a usable revision"));
942 }
943 let peeled = format!("{base}^{{commit}}");
944 let resolved = git_in(repo, &["rev-parse", "--verify", "--quiet", &peeled]);
945 if !resolved.status.success() {
946 return CommitMessageScan::Failed(format!(
947 "base {base} cannot be resolved (shallow checkout or missing ref)"
948 ));
949 }
950 let range = format!("{base}..HEAD");
951 let output = git_in(repo, &["log", &range, "--format=%B"]);
952 if !output.status.success() {
953 return CommitMessageScan::Failed(format!(
954 "git log {range} failed: {}",
955 String::from_utf8_lossy(&output.stderr).trim()
956 ));
957 }
958 let log = String::from_utf8_lossy(&output.stdout);
959 let em = log.contains('\u{2014}');
960 let en = log.contains('\u{2013}');
961 if em || en {
962 CommitMessageScan::Forbidden { em, en }
963 } else {
964 CommitMessageScan::Clean
965 }
966}
967
968fn commit_lint_action(scan: CommitMessageScan, ci: bool) -> CommitLintAction {
969 match scan {
970 CommitMessageScan::NoBase => CommitLintAction::Skip(
971 "AIEN_SKIP test_t2_f62: AIEN_COMMIT_LINT_BASE is unset or empty".to_string(),
972 ),
973 CommitMessageScan::Clean => CommitLintAction::Pass,
974 CommitMessageScan::Forbidden { em, en } => CommitLintAction::Fail(format!(
975 "commits introduced over AIEN_COMMIT_LINT_BASE contain em dash ({em}) or en dash ({en})"
976 )),
977 CommitMessageScan::Failed(reason) => CommitLintAction::Fail(format!(
978 "commit lint failed{}: {reason}",
979 if ci { " in CI" } else { "" }
980 )),
981 }
982}
983
984fn apply_commit_lint(action: CommitLintAction) {
985 match action {
986 CommitLintAction::Skip(line) => eprintln!("{line}"),
987 CommitLintAction::Pass => {}
988 CommitLintAction::Fail(msg) => panic!("{msg}"),
989 }
990}
991
992fn assert_ci_hard_failure(scan: CommitMessageScan) {
993 let reason = match &scan {
994 CommitMessageScan::Failed(reason) => reason.clone(),
995 other => panic!("a set base that cannot be used must not skip, got {other:?}"),
996 };
997 let action = commit_lint_action(scan, true);
998 let msg = match action {
999 CommitLintAction::Fail(msg) => msg,
1000 other => panic!("CI must fail the commit lint, got {other:?}"),
1001 };
1002 assert!(
1003 msg.contains("in CI"),
1004 "CI failure must be marked as CI: {msg}"
1005 );
1006 assert!(
1007 msg.contains(&reason),
1008 "CI failure must keep the scan reason: {msg}"
1009 );
1010 let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1011 apply_commit_lint(CommitLintAction::Fail(msg));
1012 }));
1013 assert!(panicked.is_err(), "the test must panic when the lint fails");
1014}
1015
1016fn commit_in(repo: &Path, file: &str, message: &str) {
1017 fs::write(repo.join(file), file).expect("write commit file");
1018 git_ok(repo, &["add", "--", file]);
1019 git_ok(
1020 repo,
1021 &["-c", "commit.gpgsign=false", "commit", "-m", message],
1022 );
1023}
1024
1025fn head_commit(repo: &Path) -> String {
1026 let output = git_ok(repo, &["rev-parse", "HEAD"]);
1027 String::from_utf8(output.stdout)
1028 .expect("utf8 sha")
1029 .trim()
1030 .to_string()
1031}
1032
1033struct RemoveOnDrop(PathBuf);
1034
1035impl Drop for RemoveOnDrop {
1036 fn drop(&mut self) {
1037 let _ = fs::remove_dir_all(&self.0);
1038 }
1039}
1040
1041fn temp_repo(label: &str) -> (PathBuf, RemoveOnDrop) {
1042 let dir = std::env::temp_dir().join(format!("t2_f62_{label}_{}", uuid::Uuid::new_v4()));
1043 fs::create_dir_all(&dir).expect("temp repo dir");
1044 let guard = RemoveOnDrop(dir.clone());
1045 git_ok(&dir, &["init", "-b", "main"]);
1046 (dir, guard)
1047}
1048
1049#[test]
1050fn test_t2_f62_git_log_zero_em_or_en_dashes() {
1051 let base = std::env::var("AIEN_COMMIT_LINT_BASE").ok();
1052 let ci = std::env::var("CI").is_ok();
1053 let scan = scan_commits_introduced_over_base(&workspace_root(), base.as_deref());
1054 apply_commit_lint(commit_lint_action(scan, ci));
1055}
1056
1057#[test]
1058fn test_t2_f62_new_commit_with_em_or_en_dash_fails() {
1059 let (repo, _guard) = temp_repo("dash");
1060 commit_in(&repo, "old.txt", "history \u{2014} before the base");
1061 commit_in(&repo, "base.txt", "base commit");
1062 let base = head_commit(&repo);
1063 commit_in(&repo, "clean.txt", "plain ascii addition");
1064 assert!(
1065 matches!(
1066 scan_commits_introduced_over_base(&repo, Some(&base)),
1067 CommitMessageScan::Clean
1068 ),
1069 "a clean commit over the base must pass, and a dash before the base must not be scanned"
1070 );
1071 commit_in(&repo, "en.txt", "range \u{2013} in a new commit");
1072 match scan_commits_introduced_over_base(&repo, Some(&base)) {
1073 CommitMessageScan::Forbidden { em, en } => {
1074 assert!(
1075 !em,
1076 "an em dash that sits before the base must not fail the new range"
1077 );
1078 assert!(en, "a new commit containing U+2013 must fail");
1079 }
1080 other => panic!("expected the new en dash to fail the lint, got {other:?}"),
1081 }
1082 commit_in(&repo, "em.txt", "clause \u{2014} in a new commit");
1083 match scan_commits_introduced_over_base(&repo, Some(&base)) {
1084 CommitMessageScan::Forbidden { em, en } => {
1085 assert!(em, "a new commit containing U+2014 must fail");
1086 assert!(en, "a new commit containing U+2013 must fail");
1087 }
1088 other => panic!("expected the new em dash to fail the lint, got {other:?}"),
1089 }
1090}
1091
1092#[test]
1093fn test_t2_f62_missing_base_skips_instead_of_scanning_history() {
1094 let (repo, _guard) = temp_repo("skip");
1095 commit_in(&repo, "bad.txt", "whole history \u{2014} and \u{2013}");
1096 for base in [None, Some(" "), Some("")] {
1097 let scan = scan_commits_introduced_over_base(&repo, base);
1098 match &scan {
1099 CommitMessageScan::NoBase => {}
1100 other => panic!(
1101 "unset or empty base must skip even when history contains dashes, got {other:?}"
1102 ),
1103 }
1104 // CI being set does not turn an empty base into a failure.
1105 match commit_lint_action(scan, true) {
1106 CommitLintAction::Skip(line) => {
1107 assert_eq!(
1108 line,
1109 "AIEN_SKIP test_t2_f62: AIEN_COMMIT_LINT_BASE is unset or empty"
1110 );
1111 eprintln!("{line}");
1112 }
1113 other => panic!("unset or empty base must skip under CI, got {other:?}"),
1114 }
1115 }
1116}
1117
1118#[test]
1119fn test_t2_f62_unresolved_base_fails_when_ci_set() {
1120 let (repo, _guard) = temp_repo("missing");
1121 commit_in(&repo, "bad.txt", "whole history \u{2014} and \u{2013}");
1122 let scan =
1123 scan_commits_introduced_over_base(&repo, Some("0123456789abcdef0123456789abcdef01234567"));
1124 match &scan {
1125 CommitMessageScan::Failed(reason) => {
1126 assert!(
1127 reason.contains("cannot be resolved"),
1128 "failure must name the unresolved base, not the history: {reason}"
1129 );
1130 }
1131 other => panic!("unresolved base must fail, got {other:?}"),
1132 }
1133 assert_ci_hard_failure(scan);
1134}
1135
1136#[test]
1137fn test_t2_f62_shallow_checkout_unresolved_base_fails_when_ci_set() {
1138 let (full, _full_guard) = temp_repo("full");
1139 commit_in(&full, "a.txt", "base");
1140 let base = head_commit(&full);
1141 commit_in(&full, "b.txt", "tip \u{2014} only on the branch");
1142 let parent =
1143 std::env::temp_dir().join(format!("t2_f62_shallow_parent_{}", uuid::Uuid::new_v4()));
1144 fs::create_dir_all(&parent).expect("shallow parent");
1145 let _parent_guard = RemoveOnDrop(parent.clone());
1146 let url = format!("file://{}", full.display());
1147 git_ok(
1148 &parent,
1149 &[
1150 "-c",
1151 "protocol.file.allow=always",
1152 "clone",
1153 "--depth",
1154 "1",
1155 &url,
1156 "shallow",
1157 ],
1158 );
1159 let shallow = parent.join("shallow");
1160 let scan = scan_commits_introduced_over_base(&shallow, Some(&base));
1161 match &scan {
1162 CommitMessageScan::Failed(reason) => assert!(
1163 reason.contains("cannot be resolved"),
1164 "shallow checkout must fail because the base is missing, not because of a dash: {reason}"
1165 ),
1166 other => panic!("shallow unresolved base must fail, got {other:?}"),
1167 }
1168 assert_ci_hard_failure(scan);
1169}
1170
1171#[test]
1172fn test_t2_f62_git_log_failure_fails_when_ci_set() {
1173 let (repo, _guard) = temp_repo("walk");
1174 commit_in(&repo, "a.txt", "base");
1175 let base = head_commit(&repo);
1176 commit_in(&repo, "b.txt", "middle");
1177 let middle = head_commit(&repo);
1178 commit_in(&repo, "c.txt", "tip");
1179 let object = repo
1180 .join(".git")
1181 .join("objects")
1182 .join(&middle[..2])
1183 .join(&middle[2..]);
1184 fs::remove_file(&object).unwrap_or_else(|err| panic!("remove {object:?}: {err}"));
1185 let scan = scan_commits_introduced_over_base(&repo, Some(&base));
1186 match &scan {
1187 CommitMessageScan::Failed(reason) => assert!(
1188 reason.contains("git log"),
1189 "a failed git log must fail the lint: {reason}"
1190 ),
1191 other => panic!("git log failure must fail the lint, got {other:?}"),
1192 }
1193 assert_ci_hard_failure(scan);
1194}
1195
1196#[test]
1197fn test_t2_f63_git_covenant_is_nonbinding_values_statement() {
1198 let covenant_path = workspace_root().join("COVENANT.md");
1199 let content = fs::read_to_string(covenant_path).expect("read COVENANT");
1200 assert!(content.contains("Keep foundational advances open"));
1201 assert!(content.contains("grants no legal rights"));
1202}
1203
1204#[test]
1205fn test_t2_f64_git_readme_contains_apache_badge() {
1206 let readme_path = workspace_root().join("README.md");
1207 let content = fs::read_to_string(readme_path).expect("read README");
1208 assert!(content.contains("License-Apache--2.0"));
1209 assert!(!content.contains("AGPL--3.0") && !content.contains("AGPL-3.0"));
1210}
1211
1212#[test]
1213fn test_t2_f65_git_worktree_clean_no_confidential_files() {
1214 // target/ is build output and holds the pinned dependency checkouts written by
1215 // scripts/pins.sh, whose vendored crates ship PEM test fixtures; the scan is
1216 // about files a person or agent committed or dropped into the worktree.
1217 let root = workspace_root();
1218 let target = root.join("target");
1219 let output = Command::new("find")
1220 .args([
1221 root.to_str().unwrap(),
1222 "-path",
1223 target.to_str().unwrap(),
1224 "-prune",
1225 "-o",
1226 "(",
1227 "-name",
1228 "*.pem",
1229 "-o",
1230 "-name",
1231 "*.id_rsa",
1232 ")",
1233 "-print",
1234 ])
1235 .output()
1236 .expect("find keys");
1237 let stdout = String::from_utf8_lossy(&output.stdout);
1238 assert!(stdout.trim().is_empty(), "No private key files on disk");
1239}