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
aien-sovereign-core-mv / crates / spark-adapters / src / bin / spark_distill.rs
| 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 chrono::Utc; |
| 17 | use clap::{Parser, Subcommand}; |
| 18 | use spark_adapters::curriculum::{CurriculumEngine, CurriculumTrack}; |
| 19 | use spark_adapters::models::{DistillTask, DistillationRecord, TaskType, VerificationStrategy}; |
| 20 | use spark_adapters::vault::sanitize_outbound_prompt; |
| 21 | use spark_adapters::verifier::Verifier; |
| 22 | use spark_adapters::{AdapterRouter, DistillationEngine}; |
| 23 | use std::io::{self, BufRead, IsTerminal, Write}; |
| 24 | use std::net::{SocketAddr, TcpStream}; |
| 25 | use std::path::PathBuf; |
| 26 | use std::time::Duration; |
| 27 | use uuid::Uuid; |
| 28 | |
| 29 | #[derive(Parser, Debug)] |
| 30 | #[command(name = "spark-distill")] |
| 31 | #[command(author = "AIEN <aien@aienos.com>")] |
| 32 | #[command(version = "0.2.0")] |
| 33 | #[command( |
| 34 | about = "Sovereign Teacher Distillation, Multi-Track Curriculum Crawler, and Training Pair Generator" |
| 35 | )] |
| 36 | struct Cli { |
| 37 | #[command(subcommand)] |
| 38 | command: Option<Commands>, |
| 39 | |
| 40 | // Flat arguments for backwards compatibility when no subcommand is given |
| 41 | #[arg(short, long, help = "Task prompt or reasoning challenge to evaluate")] |
| 42 | prompt: Option<String>, |
| 43 | |
| 44 | #[arg( |
| 45 | short, |
| 46 | long, |
| 47 | default_value = "anthropic/claude-3-7-sonnet", |
| 48 | help = "Teacher model identifier" |
| 49 | )] |
| 50 | teacher: String, |
| 51 | |
| 52 | #[arg( |
| 53 | short, |
| 54 | long, |
| 55 | default_value = "atlas-lightning-omni", |
| 56 | help = "Student open-weight model seat" |
| 57 | )] |
| 58 | student: String, |
| 59 | |
| 60 | #[arg( |
| 61 | long, |
| 62 | default_value = "code", |
| 63 | help = "Task type: code, arch, reasoning, refactor, harness" |
| 64 | )] |
| 65 | task_type: String, |
| 66 | |
| 67 | #[arg( |
| 68 | long, |
| 69 | default_value = "compiler", |
| 70 | help = "Verification strategy: compiler, unslop, json, consensus" |
| 71 | )] |
| 72 | verify: String, |
| 73 | |
| 74 | #[arg(long, help = "Commit high-scoring verified solution to Cortex memory")] |
| 75 | commit_cortex: bool, |
| 76 | |
| 77 | #[arg(long, help = "Custom dataset directory for SFT/DPO output")] |
| 78 | dataset_dir: Option<PathBuf>, |
| 79 | } |
| 80 | |
| 81 | #[derive(Subcommand, Debug)] |
| 82 | enum Commands { |
| 83 | /// Launch the interactive terminal distillation workbench |
| 84 | Cli { |
| 85 | #[arg( |
| 86 | short, |
| 87 | long, |
| 88 | default_value = "anthropic/claude-3-7-sonnet", |
| 89 | help = "Default teacher model identifier" |
| 90 | )] |
| 91 | teacher: String, |
| 92 | |
| 93 | #[arg( |
| 94 | short, |
| 95 | long, |
| 96 | default_value = "atlas-lightning-omni", |
| 97 | help = "Default student open-weight model seat" |
| 98 | )] |
| 99 | student: String, |
| 100 | |
| 101 | #[arg( |
| 102 | short = 'k', |
| 103 | long, |
| 104 | help = "Optional initial curriculum track: systems, agent, science, frontier, dynamic" |
| 105 | )] |
| 106 | track: Option<String>, |
| 107 | |
| 108 | #[arg( |
| 109 | long, |
| 110 | alias = "commit-cortex", |
| 111 | help = "Auto-commit verified high-scoring solutions to Cortex without interactive confirmation" |
| 112 | )] |
| 113 | auto_commit: bool, |
| 114 | |
| 115 | #[arg(long, help = "Custom dataset directory for SFT/DPO output")] |
| 116 | dataset_dir: Option<PathBuf>, |
| 117 | }, |
| 118 | |
| 119 | /// Execute a single prompt distillation task |
| 120 | Single { |
| 121 | #[arg(short, long, help = "Task prompt or reasoning challenge to evaluate")] |
| 122 | prompt: String, |
| 123 | |
| 124 | #[arg( |
| 125 | short, |
| 126 | long, |
| 127 | default_value = "anthropic/claude-3-7-sonnet", |
| 128 | help = "Teacher model identifier" |
| 129 | )] |
| 130 | teacher: String, |
| 131 | |
| 132 | #[arg( |
| 133 | short, |
| 134 | long, |
| 135 | default_value = "atlas-lightning-omni", |
| 136 | help = "Student open-weight model seat" |
| 137 | )] |
| 138 | student: String, |
| 139 | |
| 140 | #[arg( |
| 141 | long, |
| 142 | default_value = "code", |
| 143 | help = "Task type: code, arch, reasoning, refactor, harness" |
| 144 | )] |
| 145 | task_type: String, |
| 146 | |
| 147 | #[arg( |
| 148 | long, |
| 149 | default_value = "compiler", |
| 150 | help = "Verification strategy: compiler, unslop, json, consensus" |
| 151 | )] |
| 152 | verify: String, |
| 153 | |
| 154 | #[arg(long, help = "Commit high-scoring verified solution to Cortex memory")] |
| 155 | commit_cortex: bool, |
| 156 | |
| 157 | #[arg(long, help = "Custom dataset directory for SFT/DPO output")] |
| 158 | dataset_dir: Option<PathBuf>, |
| 159 | }, |
| 160 | |
| 161 | /// Run an autonomous batch distillation crawler across a curriculum track |
| 162 | Crawl { |
| 163 | #[arg( |
| 164 | short = 'k', |
| 165 | long, |
| 166 | default_value = "systems", |
| 167 | help = "Curriculum track: systems, agent, science, frontier, dynamic" |
| 168 | )] |
| 169 | track: String, |
| 170 | |
| 171 | #[arg(short, long, default_value_t = 5, help = "Number of tasks to execute")] |
| 172 | limit: usize, |
| 173 | |
| 174 | #[arg( |
| 175 | short, |
| 176 | long, |
| 177 | default_value = "anthropic/claude-3-7-sonnet", |
| 178 | help = "Teacher model identifier" |
| 179 | )] |
| 180 | teacher: String, |
| 181 | |
| 182 | #[arg( |
| 183 | short, |
| 184 | long, |
| 185 | default_value = "atlas-lightning-omni", |
| 186 | help = "Student open-weight model seat" |
| 187 | )] |
| 188 | student: String, |
| 189 | |
| 190 | #[arg(long, help = "Commit high-scoring verified solution to Cortex memory")] |
| 191 | commit_cortex: bool, |
| 192 | |
| 193 | #[arg(long, help = "Custom dataset directory for SFT/DPO output")] |
| 194 | dataset_dir: Option<PathBuf>, |
| 195 | }, |
| 196 | |
| 197 | /// Audit and verify all configured cloud subscriptions and hardware TPM vault keys |
| 198 | VerifyKeys, |
| 199 | } |
| 200 | |
| 201 | #[tokio::main] |
| 202 | async fn main() { |
| 203 | let cli = Cli::parse(); |
| 204 | |
| 205 | match cli.command { |
| 206 | Some(Commands::Cli { |
| 207 | teacher, |
| 208 | student, |
| 209 | track, |
| 210 | auto_commit, |
| 211 | dataset_dir, |
| 212 | }) => { |
| 213 | run_cli(teacher, student, track, auto_commit, dataset_dir).await; |
| 214 | } |
| 215 | |
| 216 | Some(Commands::Single { |
| 217 | prompt, |
| 218 | teacher, |
| 219 | student, |
| 220 | task_type, |
| 221 | verify, |
| 222 | commit_cortex, |
| 223 | dataset_dir, |
| 224 | }) => { |
| 225 | run_single( |
| 226 | prompt, |
| 227 | teacher, |
| 228 | student, |
| 229 | task_type, |
| 230 | verify, |
| 231 | commit_cortex, |
| 232 | dataset_dir, |
| 233 | ) |
| 234 | .await; |
| 235 | } |
| 236 | |
| 237 | Some(Commands::Crawl { |
| 238 | track, |
| 239 | limit, |
| 240 | teacher, |
| 241 | student, |
| 242 | commit_cortex, |
| 243 | dataset_dir, |
| 244 | }) => { |
| 245 | run_crawl( |
| 246 | &track, |
| 247 | limit, |
| 248 | &teacher, |
| 249 | &student, |
| 250 | commit_cortex, |
| 251 | dataset_dir, |
| 252 | ) |
| 253 | .await; |
| 254 | } |
| 255 | |
| 256 | Some(Commands::VerifyKeys) => { |
| 257 | run_verify_keys(); |
| 258 | } |
| 259 | |
| 260 | None => { |
| 261 | if let Some(prompt) = cli.prompt { |
| 262 | run_single( |
| 263 | prompt, |
| 264 | cli.teacher, |
| 265 | cli.student, |
| 266 | cli.task_type, |
| 267 | cli.verify, |
| 268 | cli.commit_cortex, |
| 269 | cli.dataset_dir, |
| 270 | ) |
| 271 | .await; |
| 272 | } else { |
| 273 | eprintln!("Error: Missing prompt. Use `spark-distill single --prompt ...` or `spark-distill crawl --track systems`."); |
| 274 | std::process::exit(1); |
| 275 | } |
| 276 | } |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | async fn run_cli( |
| 281 | mut teacher: String, |
| 282 | mut student: String, |
| 283 | initial_track: Option<String>, |
| 284 | auto_commit: bool, |
| 285 | dataset_dir: Option<PathBuf>, |
| 286 | ) { |
| 287 | let mut task_type = TaskType::CodeSynthesis; |
| 288 | let mut strategy = VerificationStrategy::CompilerCheck; |
| 289 | let is_interactive = io::stdin().is_terminal(); |
| 290 | |
| 291 | println!("========================================================================"); |
| 292 | println!(" AIEN Sovereign Distillation Workshop - Interactive Terminal Workbench"); |
| 293 | println!(" NVIDIA DGX Spark (Grace Blackwell GB10 LPDDR5X)"); |
| 294 | println!("========================================================================"); |
| 295 | println!("Type 'help' for command reference, or enter a prompt directly to distill."); |
| 296 | println!("Commands: models, teacher <id>, student <id>, track <name>, strategy <name>, status, quit\n"); |
| 297 | |
| 298 | let mut engine = DistillationEngine::new().with_timeout(Duration::from_secs(180)); |
| 299 | if let Some(ref dir) = dataset_dir { |
| 300 | engine = engine.with_dataset_dir(dir.clone()); |
| 301 | } |
| 302 | |
| 303 | if let Some(ref track_str) = initial_track { |
| 304 | if let Some(track) = CurriculumTrack::parse(track_str) { |
| 305 | println!("Loaded curriculum track: {}", track.display_name()); |
| 306 | let tasks = |
| 307 | CurriculumEngine::generate_tasks(track, 5, &teacher, Some(&student), auto_commit); |
| 308 | println!("\nTrack prompts:"); |
| 309 | for (i, t) in tasks.iter().enumerate() { |
| 310 | println!(" [{}] {}", i + 1, t.prompt); |
| 311 | } |
| 312 | } else { |
| 313 | eprintln!("Warning: Unknown curriculum track '{}'", track_str); |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | let stdin = io::stdin(); |
| 318 | let mut reader = stdin.lock(); |
| 319 | |
| 320 | loop { |
| 321 | if is_interactive { |
| 322 | print!("spark-distill> "); |
| 323 | let _ = io::stdout().flush(); |
| 324 | } |
| 325 | |
| 326 | let mut input = String::new(); |
| 327 | match reader.read_line(&mut input) { |
| 328 | Ok(0) => { |
| 329 | if is_interactive { |
| 330 | println!("\nExiting interactive workbench."); |
| 331 | } |
| 332 | break; |
| 333 | } |
| 334 | Ok(_) => { |
| 335 | let trimmed = input.trim(); |
| 336 | if trimmed.is_empty() { |
| 337 | continue; |
| 338 | } |
| 339 | |
| 340 | let parts: Vec<&str> = trimmed.split_whitespace().collect(); |
| 341 | match parts[0].to_lowercase().as_str() { |
| 342 | "help" | "?" => { |
| 343 | print_cli_help(); |
| 344 | } |
| 345 | "status" => { |
| 346 | println!("Current Configuration:"); |
| 347 | println!(" Teacher Model: {}", teacher); |
| 348 | println!(" Student Model: {}", student); |
| 349 | println!(" Task Type: {:?}", task_type); |
| 350 | println!(" Strategy: {:?}", strategy); |
| 351 | println!(" Dataset Dir: {}", engine.dataset_dir.display()); |
| 352 | println!(" Auto Commit: {}", auto_commit); |
| 353 | println!(" Interactive TTY: {}", is_interactive); |
| 354 | } |
| 355 | "models" => { |
| 356 | run_verify_keys(); |
| 357 | } |
| 358 | "teacher" => { |
| 359 | if parts.len() > 1 { |
| 360 | teacher = parts[1].to_string(); |
| 361 | println!("Teacher model set to: {}", teacher); |
| 362 | } else { |
| 363 | println!("Usage: teacher <model_id>"); |
| 364 | } |
| 365 | } |
| 366 | "student" => { |
| 367 | if parts.len() > 1 { |
| 368 | student = parts[1].to_string(); |
| 369 | println!("Student model seat set to: {}", student); |
| 370 | } else { |
| 371 | println!("Usage: student <model_id>"); |
| 372 | } |
| 373 | } |
| 374 | "strategy" => { |
| 375 | if parts.len() > 1 { |
| 376 | strategy = parse_strategy(parts[1]); |
| 377 | println!("Verification strategy set to: {:?}", strategy); |
| 378 | } else { |
| 379 | println!("Usage: strategy <compiler|unslop|json|consensus>"); |
| 380 | } |
| 381 | } |
| 382 | "type" => { |
| 383 | if parts.len() > 1 { |
| 384 | task_type = parse_task_type(parts[1]); |
| 385 | println!("Task type set to: {:?}", task_type); |
| 386 | } else { |
| 387 | println!("Usage: type <code|arch|reasoning|refactor|harness>"); |
| 388 | } |
| 389 | } |
| 390 | "track" => { |
| 391 | let track_name = if parts.len() > 1 { parts[1] } else { "systems" }; |
| 392 | if let Some(track) = CurriculumTrack::parse(track_name) { |
| 393 | println!("Track: {}", track.display_name()); |
| 394 | let tasks = CurriculumEngine::generate_tasks( |
| 395 | track, |
| 396 | 5, |
| 397 | &teacher, |
| 398 | Some(&student), |
| 399 | auto_commit, |
| 400 | ); |
| 401 | for (i, t) in tasks.iter().enumerate() { |
| 402 | println!(" [{}] {}", i + 1, t.prompt); |
| 403 | } |
| 404 | if is_interactive { |
| 405 | print!("Select task [1-5] or [c]ancel: "); |
| 406 | let _ = io::stdout().flush(); |
| 407 | let mut choice = String::new(); |
| 408 | if reader.read_line(&mut choice).is_ok() { |
| 409 | let choice_trim = choice.trim(); |
| 410 | if let Ok(num) = choice_trim.parse::<usize>() { |
| 411 | if num >= 1 && num <= tasks.len() { |
| 412 | let selected_task = tasks[num - 1].clone(); |
| 413 | execute_cli_distill( |
| 414 | &engine, |
| 415 | selected_task.prompt, |
| 416 | &teacher, |
| 417 | &student, |
| 418 | selected_task.task_type, |
| 419 | selected_task.verification_strategy, |
| 420 | auto_commit, |
| 421 | is_interactive, |
| 422 | &mut reader, |
| 423 | ) |
| 424 | .await; |
| 425 | } |
| 426 | } |
| 427 | } |
| 428 | } |
| 429 | } else { |
| 430 | println!( |
| 431 | "Unknown track '{}'. Available: systems, agent, science, frontier, dynamic", |
| 432 | track_name |
| 433 | ); |
| 434 | } |
| 435 | } |
| 436 | "exit" | "quit" | "q" => { |
| 437 | println!("Exiting interactive workbench."); |
| 438 | break; |
| 439 | } |
| 440 | _ => { |
| 441 | execute_cli_distill( |
| 442 | &engine, |
| 443 | trimmed.to_string(), |
| 444 | &teacher, |
| 445 | &student, |
| 446 | task_type, |
| 447 | strategy, |
| 448 | auto_commit, |
| 449 | is_interactive, |
| 450 | &mut reader, |
| 451 | ) |
| 452 | .await; |
| 453 | } |
| 454 | } |
| 455 | } |
| 456 | Err(e) => { |
| 457 | eprintln!("Error reading input: {}", e); |
| 458 | break; |
| 459 | } |
| 460 | } |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | #[allow(clippy::too_many_arguments)] |
| 465 | async fn execute_cli_distill<R: BufRead>( |
| 466 | engine: &DistillationEngine, |
| 467 | prompt: String, |
| 468 | teacher: &str, |
| 469 | student: &str, |
| 470 | task_type: TaskType, |
| 471 | strategy: VerificationStrategy, |
| 472 | auto_commit: bool, |
| 473 | is_interactive: bool, |
| 474 | reader: &mut R, |
| 475 | ) { |
| 476 | let sanitized_prompt = sanitize_outbound_prompt(&prompt); |
| 477 | if sanitized_prompt != prompt { |
| 478 | println!(" [Vault Sanitizer] Outbound prompt scrubbed: local paths, private IPs, and secrets redacted."); |
| 479 | } |
| 480 | |
| 481 | let task_id = Uuid::new_v4().to_string(); |
| 482 | let task = DistillTask { |
| 483 | id: task_id.clone(), |
| 484 | task_type, |
| 485 | prompt: sanitized_prompt.clone(), |
| 486 | system_prompt: Some( |
| 487 | "You are a verified sovereign systems specialist. Output clear, compilable native code with zero unslop." |
| 488 | .to_string(), |
| 489 | ), |
| 490 | teacher_model: teacher.to_string(), |
| 491 | student_model: Some(student.to_string()), |
| 492 | verification_strategy: strategy, |
| 493 | commit_to_cortex: false, |
| 494 | }; |
| 495 | |
| 496 | println!("\n=== Distillation Rollout Dispatched ==="); |
| 497 | println!("Task ID: {}", task.id); |
| 498 | println!("Teacher Oracle: {}", teacher); |
| 499 | println!("Student Seat: {}", student); |
| 500 | println!("Task Type: {:?}", task_type); |
| 501 | println!("Strategy: {:?}", strategy); |
| 502 | println!("Prompt: {}", sanitized_prompt); |
| 503 | |
| 504 | match engine.distill(task).await { |
| 505 | Ok(record) => { |
| 506 | display_rollout_comparison(&record); |
| 507 | |
| 508 | let t_pass = record.teacher_rollout.verification.passed; |
| 509 | let t_score = record.teacher_rollout.verification.score; |
| 510 | let s_pass = record |
| 511 | .student_rollout |
| 512 | .as_ref() |
| 513 | .map(|s| s.verification.passed) |
| 514 | .unwrap_or(false); |
| 515 | let s_score = record |
| 516 | .student_rollout |
| 517 | .as_ref() |
| 518 | .map(|s| s.verification.score) |
| 519 | .unwrap_or(0.0); |
| 520 | |
| 521 | let winning_score = t_score.max(s_score); |
| 522 | let winning_passed = if t_score >= s_score { t_pass } else { s_pass }; |
| 523 | let qualifies = winning_passed && winning_score >= 0.85; |
| 524 | |
| 525 | if qualifies { |
| 526 | if auto_commit { |
| 527 | commit_cli_cortex(engine, &record).await; |
| 528 | } else if is_interactive { |
| 529 | print!( |
| 530 | "\nCommit verified winning heuristic to Cortex memory (atlas-memory on port 18080)? [y/N]: " |
| 531 | ); |
| 532 | let _ = io::stdout().flush(); |
| 533 | let mut ans = String::new(); |
| 534 | if reader.read_line(&mut ans).is_ok() { |
| 535 | let a = ans.trim().to_lowercase(); |
| 536 | if a == "y" || a == "yes" { |
| 537 | commit_cli_cortex(engine, &record).await; |
| 538 | } else { |
| 539 | println!(" [Cortex Commit] Skipped by operator."); |
| 540 | } |
| 541 | } |
| 542 | } else { |
| 543 | println!( |
| 544 | " [Cortex Commit] Non-interactive mode: commit skipped (use --auto-commit to persist)." |
| 545 | ); |
| 546 | } |
| 547 | } else { |
| 548 | println!( |
| 549 | "\n [Cortex Gate] Solution score ({:.2}) did not meet qualification threshold (score >= 0.85 and passed).", |
| 550 | winning_score |
| 551 | ); |
| 552 | } |
| 553 | |
| 554 | if record.has_dpo_pair() { |
| 555 | println!( |
| 556 | " Datasets Appended: {}/sft.jsonl, {}/dpo.jsonl", |
| 557 | engine.dataset_dir.display(), |
| 558 | engine.dataset_dir.display() |
| 559 | ); |
| 560 | } else { |
| 561 | println!( |
| 562 | " Datasets Appended: {}/sft.jsonl", |
| 563 | engine.dataset_dir.display() |
| 564 | ); |
| 565 | } |
| 566 | } |
| 567 | Err(e) => { |
| 568 | eprintln!("\nDistillation error: {}", e); |
| 569 | } |
| 570 | } |
| 571 | } |
| 572 | |
| 573 | fn display_rollout_comparison(record: &DistillationRecord) { |
| 574 | let teacher_content = &record.teacher_rollout.content; |
| 575 | let student_content = record |
| 576 | .student_rollout |
| 577 | .as_ref() |
| 578 | .map(|s| s.content.as_str()) |
| 579 | .unwrap_or(""); |
| 580 | |
| 581 | println!( |
| 582 | "\n--- Teacher Oracle Rollout ({} ms, {} tokens) ---", |
| 583 | record.teacher_rollout.duration_ms, record.teacher_rollout.token_count |
| 584 | ); |
| 585 | let preview_len = 300.min(teacher_content.len()); |
| 586 | println!( |
| 587 | "{}{}", |
| 588 | &teacher_content[..preview_len], |
| 589 | if teacher_content.len() > preview_len { |
| 590 | "..." |
| 591 | } else { |
| 592 | "" |
| 593 | } |
| 594 | ); |
| 595 | |
| 596 | if let Some(ref s_roll) = record.student_rollout { |
| 597 | println!( |
| 598 | "\n--- Student Seat Rollout ({} ms, {} tokens) ---", |
| 599 | s_roll.duration_ms, s_roll.token_count |
| 600 | ); |
| 601 | let s_preview_len = 300.min(student_content.len()); |
| 602 | println!( |
| 603 | "{}{}", |
| 604 | &student_content[..s_preview_len], |
| 605 | if student_content.len() > s_preview_len { |
| 606 | "..." |
| 607 | } else { |
| 608 | "" |
| 609 | } |
| 610 | ); |
| 611 | } |
| 612 | |
| 613 | let lev = Verifier::normalized_levenshtein(teacher_content, student_content); |
| 614 | let lcs = Verifier::normalized_lcs(teacher_content, student_content); |
| 615 | let jac = Verifier::token_jaccard(teacher_content, student_content); |
| 616 | let consensus = Verifier::hybrid_consensus(teacher_content, student_content); |
| 617 | |
| 618 | let (s_dur, s_tok, s_pass, s_score, s_viol, s_comp) = match record.student_rollout.as_ref() { |
| 619 | Some(s) => ( |
| 620 | format!("{}", s.duration_ms), |
| 621 | format!("{}", s.token_count), |
| 622 | if s.verification.passed { |
| 623 | "PASSED" |
| 624 | } else { |
| 625 | "FAILED" |
| 626 | }, |
| 627 | format!("{:.2}", s.verification.score), |
| 628 | format!("{}", s.verification.rule_violations.len()), |
| 629 | if s.verification.compiler_output.is_some() { |
| 630 | "CHECKED" |
| 631 | } else { |
| 632 | "CLEAN" |
| 633 | }, |
| 634 | ), |
| 635 | None => ( |
| 636 | "N/A".to_string(), |
| 637 | "N/A".to_string(), |
| 638 | "N/A", |
| 639 | "N/A".to_string(), |
| 640 | "N/A".to_string(), |
| 641 | "N/A", |
| 642 | ), |
| 643 | }; |
| 644 | |
| 645 | let t_comp = if record |
| 646 | .teacher_rollout |
| 647 | .verification |
| 648 | .compiler_output |
| 649 | .is_some() |
| 650 | { |
| 651 | "CHECKED" |
| 652 | } else { |
| 653 | "CLEAN" |
| 654 | }; |
| 655 | |
| 656 | println!("\n+------------------------------------------------------------------------+"); |
| 657 | println!("| SCORECARD & VERIFICATION |"); |
| 658 | println!("+------------------------------------+-----------------+-----------------+"); |
| 659 | println!("| Metric | Teacher Oracle | Student Seat |"); |
| 660 | println!("+------------------------------------+-----------------+-----------------+"); |
| 661 | println!( |
| 662 | "| Latency | {:>13} ms | {:>13} ms |", |
| 663 | record.teacher_rollout.duration_ms, s_dur |
| 664 | ); |
| 665 | println!( |
| 666 | "| Tokens | {:>15} | {:>15} |", |
| 667 | record.teacher_rollout.token_count, s_tok |
| 668 | ); |
| 669 | println!( |
| 670 | "| Verification | {:>15} | {:>15} |", |
| 671 | if record.teacher_rollout.verification.passed { |
| 672 | "PASSED" |
| 673 | } else { |
| 674 | "FAILED" |
| 675 | }, |
| 676 | s_pass |
| 677 | ); |
| 678 | println!( |
| 679 | "| Quality Score | {:>15.2} | {:>15} |", |
| 680 | record.teacher_rollout.verification.score, s_score |
| 681 | ); |
| 682 | println!( |
| 683 | "| Rule Violations | {:>15} | {:>15} |", |
| 684 | record.teacher_rollout.verification.rule_violations.len(), |
| 685 | s_viol |
| 686 | ); |
| 687 | println!( |
| 688 | "| Rustc Syntax Check | {:>15} | {:>15} |", |
| 689 | t_comp, s_comp |
| 690 | ); |
| 691 | println!("+------------------------------------+-----------------+-----------------+"); |
| 692 | println!("| DUAL-CONSENSUS ALIGNMENT |"); |
| 693 | println!("+------------------------------------+-----------------------------------+"); |
| 694 | println!("| Token Jaccard Similarity | {:>33.4} |", jac); |
| 695 | println!("| Normalized Levenshtein | {:>33.4} |", lev); |
| 696 | println!("| Normalized LCS | {:>33.4} |", lcs); |
| 697 | println!( |
| 698 | "| Hybrid Consensus Score | {:>33.4} |", |
| 699 | consensus |
| 700 | ); |
| 701 | println!( |
| 702 | "| Preference Delta | {:>33.4} |", |
| 703 | record.preference_delta |
| 704 | ); |
| 705 | println!( |
| 706 | "| Selected Solution | {:>33} |", |
| 707 | if record.chosen == *teacher_content { |
| 708 | "Teacher Oracle" |
| 709 | } else { |
| 710 | "Student Seat" |
| 711 | } |
| 712 | ); |
| 713 | println!("+------------------------------------+-----------------------------------+"); |
| 714 | } |
| 715 | |
| 716 | async fn commit_cli_cortex(engine: &DistillationEngine, record: &DistillationRecord) { |
| 717 | let canonical = format!("distill_{}", record.task_id.replace('-', "_")); |
| 718 | let entity_name = format!( |
| 719 | "distill_lesson:{}_{}", |
| 720 | record.task_id, |
| 721 | Utc::now().timestamp() |
| 722 | ); |
| 723 | let summary = format!( |
| 724 | "Interactive distillation. Prompt: {}. Reasoning: {}. Verified Solution: {}", |
| 725 | record.prompt, |
| 726 | record.chosen_reasoning.as_deref().unwrap_or("<direct>"), |
| 727 | record.chosen |
| 728 | ); |
| 729 | let confidence = (record.teacher_rollout.verification.score.max( |
| 730 | record |
| 731 | .student_rollout |
| 732 | .as_ref() |
| 733 | .map(|s| s.verification.score) |
| 734 | .unwrap_or(0.0), |
| 735 | )) as f64; |
| 736 | |
| 737 | match engine |
| 738 | .commit_to_cortex( |
| 739 | &entity_name, |
| 740 | &canonical, |
| 741 | &summary, |
| 742 | &record.task_id, |
| 743 | confidence, |
| 744 | ) |
| 745 | .await |
| 746 | { |
| 747 | Ok(id) => { |
| 748 | println!( |
| 749 | " [Cortex Commit] Entity registered successfully: {} (Target ID: {})", |
| 750 | canonical, id |
| 751 | ); |
| 752 | } |
| 753 | Err(e) => { |
| 754 | eprintln!(" [Cortex Commit Error] Failed to persist to Cortex: {}", e); |
| 755 | } |
| 756 | } |
| 757 | } |
| 758 | |
| 759 | fn print_cli_help() { |
| 760 | println!("\nSovereign Distillation Workbench Command Reference:"); |
| 761 | println!(" help, ? Show this help reference"); |
| 762 | println!(" status Display active models, strategy, and options"); |
| 763 | println!(" models List all catalog model adapters and key status"); |
| 764 | println!(" teacher <model_id> Set teacher model (e.g. anthropic/claude-3-7-sonnet, openai/gpt-4o)"); |
| 765 | println!(" student <model_id> Set student model seat (e.g. atlas-lightning-omni, ollama/qwen2.5-coder)"); |
| 766 | println!(" strategy <name> Set strategy: compiler, unslop, json, consensus"); |
| 767 | println!( |
| 768 | " type <name> Set task type: code, arch, reasoning, refactor, harness" |
| 769 | ); |
| 770 | println!(" track [name] List tasks in curriculum track (systems, agent, science, frontier, dynamic)"); |
| 771 | println!(" exit, quit, q Exit interactive workbench"); |
| 772 | println!(" <prompt text> Evaluate prompt immediately through dual rollouts\n"); |
| 773 | } |
| 774 | |
| 775 | async fn run_single( |
| 776 | prompt: String, |
| 777 | teacher: String, |
| 778 | student: String, |
| 779 | task_type_str: String, |
| 780 | verify_str: String, |
| 781 | commit_cortex: bool, |
| 782 | dataset_dir: Option<PathBuf>, |
| 783 | ) { |
| 784 | let task_type = parse_task_type(&task_type_str); |
| 785 | let strategy = parse_strategy(&verify_str); |
| 786 | |
| 787 | let sanitized_prompt = sanitize_outbound_prompt(&prompt); |
| 788 | if sanitized_prompt != prompt { |
| 789 | println!(" [Vault Sanitizer] Outbound prompt scrubbed: local paths, private IPs, and secrets redacted."); |
| 790 | } |
| 791 | |
| 792 | let task = DistillTask { |
| 793 | id: Uuid::new_v4().to_string(), |
| 794 | task_type, |
| 795 | prompt: sanitized_prompt.clone(), |
| 796 | system_prompt: Some( |
| 797 | "You are a verified sovereign systems specialist. Output clear, compilable native code with zero unslop." |
| 798 | .to_string(), |
| 799 | ), |
| 800 | teacher_model: teacher.clone(), |
| 801 | student_model: Some(student.clone()), |
| 802 | verification_strategy: strategy, |
| 803 | commit_to_cortex: commit_cortex, |
| 804 | }; |
| 805 | |
| 806 | println!("=== Sovereign Knowledge Distillation ==="); |
| 807 | println!("Task ID: {}", task.id); |
| 808 | println!("Teacher: {}", task.teacher_model); |
| 809 | println!( |
| 810 | "Student: {}", |
| 811 | task.student_model.as_deref().unwrap_or("<none>") |
| 812 | ); |
| 813 | println!("Prompt: {}", task.prompt); |
| 814 | |
| 815 | let mut engine = DistillationEngine::new().with_timeout(Duration::from_secs(180)); |
| 816 | if let Some(dir) = dataset_dir { |
| 817 | engine = engine.with_dataset_dir(dir); |
| 818 | } |
| 819 | |
| 820 | match engine.distill(task).await { |
| 821 | Ok(record) => { |
| 822 | println!("\n=== Distillation Complete ==="); |
| 823 | println!( |
| 824 | "Teacher Verification: Passed: {}, Score: {:.2}", |
| 825 | record.teacher_rollout.verification.passed, |
| 826 | record.teacher_rollout.verification.score |
| 827 | ); |
| 828 | if let Some(ref s_roll) = record.student_rollout { |
| 829 | println!( |
| 830 | "Student Verification: Passed: {}, Score: {:.2}", |
| 831 | s_roll.verification.passed, s_roll.verification.score |
| 832 | ); |
| 833 | println!("Preference Delta: {:.2}", record.preference_delta); |
| 834 | } |
| 835 | if record.durable_memory_committed { |
| 836 | println!( |
| 837 | "Cortex Entity: {}", |
| 838 | record.cortex_entity_id.as_deref().unwrap_or("<committed>") |
| 839 | ); |
| 840 | } |
| 841 | if record.has_dpo_pair() { |
| 842 | println!( |
| 843 | "Datasets Appended: {}/sft.jsonl, {}/dpo.jsonl", |
| 844 | engine.dataset_dir.display(), |
| 845 | engine.dataset_dir.display() |
| 846 | ); |
| 847 | } else { |
| 848 | println!( |
| 849 | "Datasets Appended: {}/sft.jsonl", |
| 850 | engine.dataset_dir.display() |
| 851 | ); |
| 852 | } |
| 853 | } |
| 854 | Err(e) => { |
| 855 | eprintln!("Distillation error: {}", e); |
| 856 | std::process::exit(1); |
| 857 | } |
| 858 | } |
| 859 | } |
| 860 | |
| 861 | async fn run_crawl( |
| 862 | track_str: &str, |
| 863 | limit: usize, |
| 864 | teacher: &str, |
| 865 | student: &str, |
| 866 | commit_cortex: bool, |
| 867 | dataset_dir: Option<PathBuf>, |
| 868 | ) { |
| 869 | let track = CurriculumTrack::parse(track_str).unwrap_or(CurriculumTrack::NativeSystemsAndGpu); |
| 870 | println!("=== Sovereign Batch Curriculum Crawler ==="); |
| 871 | println!("Curriculum Track: {}", track.display_name()); |
| 872 | println!("Task Limit: {}", limit); |
| 873 | println!("Teacher Model: {}", teacher); |
| 874 | println!("Student Seat: {}", student); |
| 875 | println!("Cortex Commit: {}", commit_cortex); |
| 876 | |
| 877 | let tasks = |
| 878 | CurriculumEngine::generate_tasks(track, limit, teacher, Some(student), commit_cortex); |
| 879 | |
| 880 | let mut engine = DistillationEngine::new().with_timeout(Duration::from_secs(180)); |
| 881 | if let Some(dir) = dataset_dir { |
| 882 | engine = engine.with_dataset_dir(dir); |
| 883 | } |
| 884 | |
| 885 | let mut passed_count = 0; |
| 886 | let mut total_delta = 0.0; |
| 887 | let mut cortex_count = 0; |
| 888 | |
| 889 | for (idx, task) in tasks.into_iter().enumerate() { |
| 890 | println!("\n[{}/{}] Distilling: {}", idx + 1, limit, task.prompt); |
| 891 | match engine.distill(task).await { |
| 892 | Ok(record) => { |
| 893 | let t_pass = record.teacher_rollout.verification.passed; |
| 894 | let s_pass = record |
| 895 | .student_rollout |
| 896 | .as_ref() |
| 897 | .map(|s| s.verification.passed) |
| 898 | .unwrap_or(false); |
| 899 | if t_pass || s_pass { |
| 900 | passed_count += 1; |
| 901 | } |
| 902 | total_delta += record.preference_delta; |
| 903 | if record.durable_memory_committed { |
| 904 | cortex_count += 1; |
| 905 | println!( |
| 906 | " [+] Committed to Cortex: {}", |
| 907 | record.cortex_entity_id.as_deref().unwrap_or("<id>") |
| 908 | ); |
| 909 | } |
| 910 | println!( |
| 911 | " [+] Score: Teacher: {:.2}, Delta: {:.2}", |
| 912 | record.teacher_rollout.verification.score, record.preference_delta |
| 913 | ); |
| 914 | } |
| 915 | Err(e) => { |
| 916 | eprintln!(" [-] Task failed: {}", e); |
| 917 | } |
| 918 | } |
| 919 | } |
| 920 | |
| 921 | println!("\n=== Curriculum Crawl Summary ==="); |
| 922 | println!("Total Tasks Evaluated: {}", limit); |
| 923 | println!("Passing Candidates: {}/{}", passed_count, limit); |
| 924 | println!("Cortex Entities Added: {}", cortex_count); |
| 925 | println!( |
| 926 | "Average Preference Delta: {:.2}", |
| 927 | total_delta / limit.max(1) as f32 |
| 928 | ); |
| 929 | println!("Datasets Directory: {}", engine.dataset_dir.display()); |
| 930 | } |
| 931 | |
| 932 | fn is_port_open(port: u16) -> bool { |
| 933 | let addr = SocketAddr::from(([127, 0, 0, 1], port)); |
| 934 | TcpStream::connect_timeout(&addr, Duration::from_millis(50)).is_ok() |
| 935 | } |
| 936 | |
| 937 | fn run_verify_keys() { |
| 938 | let router = AdapterRouter::new(); |
| 939 | let adapters = router.discover_adapters(); |
| 940 | |
| 941 | println!("=== Sovereign Model & Subscription Key Audit ==="); |
| 942 | println!( |
| 943 | "{:<28} {:<15} {:<20} {:<10}", |
| 944 | "ADAPTER ID", "PROVIDER", "STATUS", "RESIDENT" |
| 945 | ); |
| 946 | println!("{}", "-".repeat(76)); |
| 947 | |
| 948 | for a in adapters { |
| 949 | let status = if a.is_resident { |
| 950 | "LOCAL_SILICON" |
| 951 | } else if a.provider == spark_adapters::models::ProviderType::Ollama { |
| 952 | if is_port_open(11434) { |
| 953 | "PORT_OPEN" |
| 954 | } else { |
| 955 | "UNCONFIGURED" |
| 956 | } |
| 957 | } else if a.is_available { |
| 958 | "OK" |
| 959 | } else { |
| 960 | "UNCONFIGURED" |
| 961 | }; |
| 962 | let resident = if a.is_resident { "YES" } else { "NO" }; |
| 963 | println!( |
| 964 | "{:<28} {:<15} {:<20} {:<10}", |
| 965 | a.id, |
| 966 | a.provider.slug(), |
| 967 | status, |
| 968 | resident |
| 969 | ); |
| 970 | } |
| 971 | |
| 972 | println!("\n=== Sovereign Infrastructure & Daemons ==="); |
| 973 | println!( |
| 974 | "{:<28} {:<24} {:<15} {:<20}", |
| 975 | "SERVICE", "ENDPOINT", "STATUS", "AUTH" |
| 976 | ); |
| 977 | println!("{}", "-".repeat(84)); |
| 978 | |
| 979 | let seat_port = is_port_open(18006); |
| 980 | let seat_status = if seat_port { "PORT_OPEN" } else { "OFFLINE" }; |
| 981 | println!( |
| 982 | "{:<28} {:<24} {:<15} {:<20}", |
| 983 | "Local Model Seat", "http://127.0.0.1:18006", seat_status, "LOCAL_SILICON" |
| 984 | ); |
| 985 | |
| 986 | let cortex_port = is_port_open(18080); |
| 987 | let cortex_key = spark_adapters::vault::is_secret_present("CORTEX_TOKEN"); |
| 988 | let cortex_status = if cortex_port { "PORT_OPEN" } else { "OFFLINE" }; |
| 989 | let cortex_auth = if cortex_key { |
| 990 | "OK (CORTEX_TOKEN)" |
| 991 | } else { |
| 992 | "UNCONFIGURED" |
| 993 | }; |
| 994 | println!( |
| 995 | "{:<28} {:<24} {:<15} {:<20}", |
| 996 | "Cortex Memory Daemon", "http://127.0.0.1:18080", cortex_status, cortex_auth |
| 997 | ); |
| 998 | } |
| 999 | |
| 1000 | fn parse_task_type(s: &str) -> TaskType { |
| 1001 | match s.to_lowercase().as_str() { |
| 1002 | "arch" => TaskType::SystemArchitecture, |
| 1003 | "reasoning" => TaskType::ReasoningTrace, |
| 1004 | "refactor" => TaskType::RefactorLogic, |
| 1005 | "harness" => TaskType::VerificationHarness, |
| 1006 | _ => TaskType::CodeSynthesis, |
| 1007 | } |
| 1008 | } |
| 1009 | |
| 1010 | fn parse_strategy(s: &str) -> VerificationStrategy { |
| 1011 | match s.to_lowercase().as_str() { |
| 1012 | "unslop" => VerificationStrategy::UnslopStrict, |
| 1013 | "json" => VerificationStrategy::JsonSchema, |
| 1014 | "consensus" => VerificationStrategy::DualConsensus, |
| 1015 | _ => VerificationStrategy::CompilerCheck, |
| 1016 | } |
| 1017 | } |