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 / aien-cli / src / commands.rs

3199 lines · 127626 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
16pub fn parse_quoted_args(input: &str) -> Vec<String> {
17 let mut tokens = Vec::new();
18 let mut current = String::new();
19 let mut in_quotes = false;
20 for ch in input.chars() {
21 if ch == '"' {
22 in_quotes = !in_quotes;
23 } else if ch.is_whitespace() && !in_quotes {
24 if !current.is_empty() {
25 tokens.push(current.clone());
26 current.clear();
27 }
28 } else {
29 current.push(ch);
30 }
31 }
32 if !current.is_empty() {
33 tokens.push(current);
34 }
35 tokens
36}
37use crate::crumbs::{format_dir_crumb_tui, whisper_as_self};
38use crate::hive::{hive_kill, hive_roster, hive_spawn};
39use crate::nesting::perform_nesting_ritual;
40use crate::telemetry::get_gpu_telemetry;
41use colored::*;
42use reqwest::Client;
43use serde_json::json;
44use std::fs::{self, OpenOptions};
45use std::io::Write;
46use std::path::Path;
47use std::process::Command;
48
49pub async fn handle_slash_command(cmd: &str) -> bool {
50 let parts: Vec<&str> = cmd.split_whitespace().collect();
51 if parts.is_empty() {
52 return false;
53 }
54
55 match parts[0] {
56 "/exit" | "/quit" => {
57 println!("{}", "Exiting AIEN. The Spark desk remains ours.".cyan());
58 std::process::exit(0);
59 }
60 "/rollback" => {
61 // sc#667: undo the agent's own file writes from a turn on; the
62 // operator's edits are never touched.
63 let home = crate::platform::PlatformContext::detect().home_dir;
64 let turn = parts.get(1).and_then(|t| t.parse::<u64>().ok());
65 let session = parts.get(if turn.is_some() { 2 } else { 1 }).copied();
66 match crate::checkpoint::rollback(&home, turn, session) {
67 Ok(r) => {
68 println!(
69 "{}",
70 format!("Rolled back from turn {}", r.from_turn)
71 .cyan()
72 .bold()
73 );
74 for (label, paths) in [
75 ("restored", &r.restored),
76 ("removed (the agent created it)", &r.removed),
77 ("already as it was", &r.unchanged),
78 ("KEPT: changed after the agent wrote it", &r.conflicts),
79 ("spared: your own edits, not touched", &r.spared),
80 ] {
81 for p in paths {
82 println!(" {}: {}", label, p);
83 }
84 }
85 }
86 Err(e) => println!("{}", format!("Rollback refused: {}", e).red()),
87 }
88 true
89 }
90 "/checkpoints" => {
91 let home = crate::platform::PlatformContext::detect().home_dir;
92 match crate::checkpoint::list_turns(&home, parts.get(1).copied()) {
93 Ok(turns) if turns.is_empty() => {
94 println!("No agent file writes recorded in that session.")
95 }
96 Ok(turns) => {
97 println!("{}", "Agent writes by turn".cyan());
98 for (t, n) in turns {
99 println!(" turn {}: {} file(s)", t, n);
100 }
101 }
102 Err(e) => println!("{}", e.red()),
103 }
104 true
105 }
106 "/approval" => {
107 let ctx = crate::approval::GateContext::from_env();
108 println!("{}", "Approval gate (sc#667)".cyan().bold());
109 println!(
110 " mode: {:?} person present: {}",
111 ctx.mode,
112 ctx.presence == crate::approval::Presence::Person
113 );
114 println!(
115 " policy file: {}",
116 crate::approval::policy_path(&crate::platform::PlatformContext::detect().home_dir)
117 .display()
118 );
119 if let Some(why) = ctx.policy.broken() {
120 println!(
121 " {}",
122 format!("EVERY REQUEST IS DENIED: {}", why).red().bold()
123 );
124 }
125 for w in &ctx.policy.warnings {
126 println!(" {}", w.yellow());
127 }
128 println!(" floors (every mode): hardline commands, runtime files, sudo password on stdin, your deny patterns");
129 true
130 }
131 "/clear" => {
132 print!("{esc}[2J{esc}[1;1H", esc = 27 as char);
133 let _ = std::io::stdout().flush();
134 true
135 }
136 "/help" => {
137 println!("{}", "\nAvailable Slash Commands:".cyan().bold());
138 println!(
139 " /skill [list|preview|search|full|optimize] CPU-filtered skill access
140 /context7 resolve <library> [query] | /context7 query <library_id> <query>
141 context7-sync Refresh Rust, Tokio, Axum, and Serde docs into Cortex
142 /sandbox [init|status|test|promote|clean] Isolated Git worktree sandbox
143 /browser [test|mentor|screenshot|eval] Headless Chrome CDP mirror (Rust, aien-browser-mirror)
144 /subagents [list|view|run] Recursive contextual subagents hierarchy
145 /goal [list|new|done] Manage project goals & milestone lattices"
146 );
147 println!(" /rollback [turn] [session] Undo the agent's own file writes from a turn on (your edits are kept)");
148 println!(" /checkpoints [session] List turns with agent file writes");
149 println!(
150 " /approval Show approval mode, presence and the policy file"
151 );
152 println!(" /rules Inspect active repository & directory rules (AGENTS.md, GEMINI.md)");
153 println!(" /walkthrough [save] Display live architecture map & roadmap (or save to WALKTHROUGH.md)");
154 println!(" /nest Execute the Agent Nesting Ritual (grounding, threat check, peer wind, scent)");
155 println!(" /crumb [path] Inspect directory crumb (above, below, and local agent history)");
156 println!(" /crumb whisper <message> Leave a directory whisper for peer agents");
157 println!(" /vault Inspect hardware TPM key vault and secret hygiene audit");
158 println!(" /doctor Probe GB10 GPU, Model (18006), Judge (18082), Cortex (18080), Vault, Dream (18085)");
159 println!(" /dream [now|status] Inspect or trigger JSpace Dynamic Dream Cycle");
160 println!(" /hive Manage swarm & inspect lattice (/hive roster | /hive wall | /hive spawn <role> <task>)");
161 println!(" /adapter [list|emit|pr] Autonomous open-source model adapters & PR pipeline for consumer hardware");
162 println!(" /socratic <question> Trigger Socratic inquiry and emit comb onto hexagonal lattice");
163 println!(" /mask List or inspect active persona mask");
164 println!(" /park <text> Park high-volume input or interruption to park/ directory");
165 println!(" /cortex <query> Query permanent memory in Spark Cortex");
166 println!(
167 " /sync Run Radicle sovereign identity key synchronization"
168 );
169 println!(" /clear Clear terminal screen");
170 println!(" /exit Exit AIEN session\n");
171 true
172 }
173 "/walkthrough" | "/roadmap" | "/map" => {
174 if parts.len() > 1 && parts[1] == "save" {
175 let platform = crate::platform::PlatformContext::detect();
176 let dest = platform.home_dir.join("basecamp/WALKTHROUGH.md");
177 match crate::walkthrough::generate_and_save_walkthrough_md(&dest) {
178 Ok(msg) => println!("{}", msg.green()),
179 Err(e) => println!("{}", format!("Failed to save walkthrough: {}", e).red()),
180 }
181 } else {
182 let card = crate::walkthrough::render_walkthrough_tui();
183 println!("{}", card);
184 }
185 true
186 }
187 "/nest" => {
188 let session_id = format!("manual-nest-{}", chrono::Utc::now().timestamp());
189 perform_nesting_ritual(&session_id, true).await;
190 true
191 }
192 "/crumb" => {
193 if parts.len() > 1 && parts[1] == "whisper" {
194 if parts.len() < 3 {
195 println!("Usage: /crumb whisper <message>");
196 } else {
197 let msg = parts[2..].join(" ");
198 let cwd =
199 std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
200 match whisper_as_self(&cwd, None, &msg) {
201 Ok(()) => println!(
202 "{}",
203 format!(
204 "✓ Whisper left in {}/.crumb.local: \"{}\"",
205 cwd.display(),
206 msg
207 )
208 .green()
209 ),
210 Err(err) => println!(
211 "{}",
212 format!("✗ Whisper not recorded in {}: {}", cwd.display(), err).red()
213 ),
214 }
215 }
216 } else {
217 let target_str = if parts.len() > 1 { parts[1] } else { "." };
218 let p = Path::new(target_str);
219 println!("{}", format_dir_crumb_tui(p));
220 }
221 true
222 }
223 "/vault" => {
224 println!(
225 "{}",
226 "\n=== Hardware TPM Key Vault (atlas-vault) ==="
227 .cyan()
228 .bold()
229 );
230 if !crate::vault::is_vault_available() {
231 let platform = crate::platform::PlatformContext::detect();
232 println!(
233 "{}",
234 format!(
235 "❌ atlas-vault not found at {}",
236 platform.home_dir.join(".local/bin/atlas-vault").display()
237 )
238 .red()
239 );
240 } else {
241 let keys = crate::vault::list_keys();
242 println!(
243 "• Hardware Vault: {}",
244 "TPM-bound atlas-vault (Active)".green()
245 );
246 println!(
247 "• Registered Keys: {}",
248 keys.len().to_string().cyan().bold()
249 );
250 for k in &keys {
251 println!(" - {}", k.green());
252 }
253 let findings = crate::vault::audit_workspace_secrets();
254 if findings.is_empty() {
255 println!("{}", "✓ Secret Hygiene: Clean (0 stray .env or plaintext credential files on disk).".green());
256 } else {
257 println!(
258 "{}",
259 format!(
260 "⚠ Warning: {} stray .env files detected on disk:",
261 findings.len()
262 )
263 .yellow()
264 .bold()
265 );
266 for f in &findings {
267 println!(" - {}", f.red());
268 }
269 }
270 println!("{}", "• Storage Policy: Direct value retrieval is in-memory only; plaintext .env strictly forbidden.\n".dimmed());
271 }
272 true
273 }
274 "/doctor" => {
275 run_doctor().await;
276 true
277 }
278 "/dream" => {
279 // The former dream engine was a Python script outside this repository
280 // (basecamp/aien-dream/dream_engine.py). AIEN carries no Python, so the
281 // command says so instead of shelling out. Native dream telemetry lives
282 // in the spark-dream crate (binary `spark-dream`).
283 println!(
284 "{}",
285 "The /dream cycle is not part of the sovereign build: its old engine was a Python script outside this repo. Use the native `spark-dream` binary for dream telemetry."
286 .yellow()
287 );
288 true
289 }
290 "/adapter" | "/adapters" => {
291 handle_adapter_command(&parts[1..]);
292 true
293 }
294 "/hive" => {
295 if parts.len() >= 2 && parts[1] == "wall" {
296 match spark_hive::CombStore::open_default() {
297 Ok(store) => match store.get_cells() {
298 Ok((combs, bounds)) => {
299 println!("{}", format!("\n=== Sovereign Hexagonal Honeycomb Wall ({} combs, radius {}) ===", bounds.count, bounds.radius).yellow().bold());
300 for comb in combs.iter().take(12) {
301 println!(
302 " [{:3}, {:3}] {:<18} {:<12} {}",
303 comb.q,
304 comb.r,
305 comb.author.cyan(),
306 comb.role.dimmed(),
307 comb.content
308 );
309 }
310 if combs.len() > 12 {
311 println!(
312 " ... and {} more combs on hexagonal lattice.",
313 combs.len() - 12
314 );
315 }
316 }
317 Err(e) => {
318 println!("{}", format!("Failed to query hive cells: {}", e).red())
319 }
320 },
321 Err(e) => println!("{}", format!("Failed to open hive db: {}", e).red()),
322 }
323 } else if parts.len() < 2 || parts[1] == "roster" {
324 println!("{}", "=== aien-hive Active Swarm Roster ===".cyan().bold());
325 println!("{}", hive_roster());
326 } else if parts[1] == "spawn" && parts.len() >= 4 {
327 let role = parts[2];
328 let task = parts[3..].join(" ");
329 println!("{}", format!("Spawning hive cell [{}]...", role).yellow());
330 let res = hive_spawn(role, &task);
331 println!("{}", res.green());
332 } else if parts[1] == "kill" && parts.len() >= 3 {
333 let name = parts[2];
334 println!("{}", hive_kill(name));
335 } else {
336 println!("Usage: /hive [roster | wall | spawn <role> <task> | kill <name>]");
337 }
338 true
339 }
340 "/socratic" => {
341 if parts.len() < 2 {
342 println!("Usage: /socratic <philosophical question or inquiry>");
343 } else {
344 let question = parts[1..].join(" ");
345 println!(
346 "{}",
347 format!("Emitting Socratic inquiry: \"{}\"...", question).cyan()
348 );
349 match spark_hive::CombStore::open_default() {
350 Ok(store) => {
351 match spark_hive::emit_socratic_comb(&store, &question, None) {
352 Ok(comb) => {
353 println!("{}", format!("✓ Socratic Comb placed at axial coordinate ({}, {}) [id: {}]", comb.q, comb.r, comb.id).green());
354 }
355 Err(e) => {
356 println!("{}", format!("Failed to emit socratic comb: {}", e).red())
357 }
358 }
359 }
360 Err(e) => println!("{}", format!("Failed to open hive db: {}", e).red()),
361 }
362 }
363 true
364 }
365 "/mask" => {
366 run_mask_command(&parts[1..]);
367 true
368 }
369 "/park" => {
370 if parts.len() < 2 {
371 println!("Usage: /park <notes/text to park>");
372 } else {
373 let text = parts[1..].join(" ");
374 park_input(&text);
375 }
376 true
377 }
378 "/sync" => {
379 println!("{}", "Synchronizing Radicle identity keys...".yellow());
380 let out = Command::new("basecamp/rad-id-sync/target/debug/rad-id-sync")
381 .arg("sync")
382 .current_dir(&crate::platform::PlatformContext::detect().home_dir)
383 .output();
384 match out {
385 Ok(o) => println!("{}", String::from_utf8_lossy(&o.stdout).green()),
386 Err(e) => println!("{}", format!("Failed to sync keys: {}", e).red()),
387 }
388 true
389 }
390 "/goal" | "/goals" => {
391 if parts.len() < 2 || parts[1] == "list" {
392 println!("{}", crate::goals::format_goals_tui());
393 } else if parts[1] == "new" || parts[1] == "add" {
394 if parts.len() < 3 {
395 println!("Usage: /goal new <title> [| milestone 1, milestone 2]");
396 } else {
397 let rest = parts[2..].join(" ");
398 let split: Vec<&str> = rest.split('|').collect();
399 let title = split[0].trim();
400 let milestones: Vec<String> = if split.len() > 1 {
401 split[1]
402 .split(',')
403 .map(|s| s.trim().to_string())
404 .filter(|s| !s.is_empty())
405 .collect()
406 } else {
407 Vec::new()
408 };
409 let g = crate::goals::add_goal(title, "", milestones);
410 println!(
411 "{}",
412 format!("✓ Initialized goal: {} ({})", g.title, g.id)
413 .green()
414 .bold()
415 );
416 }
417 } else if parts[1] == "auto" {
418 if parts.len() < 3 {
419 println!("Usage: /goal auto <id or title>");
420 } else {
421 let target_id = parts[2..].join(" ");
422 crate::run_autonomous_goal(&target_id).await;
423 }
424 } else if parts[1] == "done" || parts[1] == "complete" {
425 if parts.len() < 3 {
426 println!("Usage: /goal done <id or title>");
427 } else {
428 let id = parts[2..].join(" ");
429 match crate::goals::complete_goal(&id) {
430 Ok(msg) => println!("{}", msg.green().bold()),
431 Err(e) => println!("{}", e.red()),
432 }
433 }
434 } else {
435 println!("Usage: /goal [list | new <title> [| m1, m2] | done <id>]");
436 }
437 true
438 }
439 "/rule" | "/rules" => {
440 let cwd = std::env::current_dir()
441 .unwrap_or_else(|_| crate::platform::PlatformContext::detect().home_dir);
442 println!("{}", crate::rules::format_rules_tui(&cwd));
443 true
444 }
445 "/context7" => {
446 let result = if parts.len() < 3 {
447 json!({"status": "error", "error": "Usage: /context7 resolve <library> [query] | /context7 query <library_id> <query>"})
448 } else if parts[1] == "resolve" {
449 let library = parts[2];
450 let query = if parts.len() > 3 {
451 parts[3..].join(" ")
452 } else {
453 library.to_string()
454 };
455 crate::context7::context7_dispatch(&json!({
456 "action": "resolve",
457 "library": library,
458 "query": query
459 }))
460 .await
461 } else if parts[1] == "query" && parts.len() >= 4 {
462 crate::context7::context7_dispatch(&json!({
463 "action": "query",
464 "library_id": parts[2],
465 "query": parts[3..].join(" ")
466 }))
467 .await
468 } else {
469 json!({"status": "error", "error": "Usage: /context7 resolve <library> [query] | /context7 query <library_id> <query>"})
470 };
471 println!(
472 "{}",
473 serde_json::to_string_pretty(&result).unwrap_or_default()
474 );
475 true
476 }
477 "/skill" | "/skills" => {
478 if parts.len() > 1 && parts[1] == "optimize" {
479 let name = if parts.len() > 2 {
480 parts[2..].join(" ")
481 } else {
482 "atlas-skillopt".to_string()
483 };
484 crate::skills::run_optimize_cli(&name);
485 } else if parts.len() < 2 || parts[1] == "list" {
486 println!("{}", crate::skills::format_skills_tui());
487 } else if parts[1] == "full" {
488 let name = parts[2..].join(" ");
489 match crate::skills::read_skill_content(&name) {
490 Ok(content) => println!("{}", content),
491 Err(e) => println!("{}", e.red()),
492 }
493 } else if parts[1] == "search" && parts.len() >= 4 {
494 let name = parts[2];
495 let query = parts[3..].join(" ");
496 match crate::skills::search_skill(name, &query, 3) {
497 Ok(result) => println!(
498 "{}",
499 serde_json::to_string_pretty(&result).unwrap_or_default()
500 ),
501 Err(e) => println!("{}", e.red()),
502 }
503 } else {
504 let name = if parts[1] == "preview" {
505 parts[2..].join(" ")
506 } else {
507 parts[1..].join(" ")
508 };
509 match crate::skills::preview_skill(&name, 96) {
510 Ok(preview) => println!(
511 "{}",
512 serde_json::to_string_pretty(&preview).unwrap_or_default()
513 ),
514 Err(e) => println!("{}", e.red()),
515 }
516 }
517 true
518 }
519 "/sandbox" => {
520 crate::sandbox::handle_sandbox_command(&parts[1..]);
521 true
522 }
523 "/browser" | "/mirror" => {
524 crate::sandbox::handle_browser_command(&parts[1..]);
525 true
526 }
527 "/subagent" | "/subagents" => {
528 let tokens = parse_quoted_args(cmd);
529 if tokens.len() > 1 && tokens[1] == "view" {
530 let id = if tokens.len() > 2 { &tokens[2] } else { "" };
531 let res = crate::subagents::view_subagent(id);
532 println!("{}", serde_json::to_string_pretty(&res).unwrap_or_default());
533 } else if tokens.len() > 1 && tokens[1] == "run" {
534 let role = if tokens.len() > 2 {
535 &tokens[2]
536 } else {
537 "Researcher"
538 };
539 let prompt = if tokens.len() > 3 {
540 tokens[3..].join(" ")
541 } else {
542 "Investigate active workspace".to_string()
543 };
544 println!(
545 "{}",
546 format!("Spawning subagent '{}'...", role).cyan().bold()
547 );
548 let res = tokio::task::block_in_place(|| {
549 tokio::runtime::Handle::current()
550 .block_on(crate::subagents::invoke_subagent_from_root(role, &prompt))
551 });
552 println!("{}", serde_json::to_string_pretty(&res).unwrap_or_default());
553 } else {
554 println!("{}", crate::subagents::format_subagents_tui());
555 }
556 true
557 }
558 "/cortex" => {
559 crate::cortex::handle_cortex_command(&parts[1..]).await;
560 true
561 }
562 _ => false,
563 }
564}
565
566pub async fn run_doctor() {
567 println!("{}", "=== AIEN Comprehensive Diagnostics ===".cyan().bold());
568 let client = Client::new();
569
570 // 1. GPU
571 let gpu = get_gpu_telemetry();
572 if gpu.available {
573 let name = gpu.display_name();
574 let temp = gpu.display_temp();
575 let vram = gpu.display_vram();
576 println!(
577 "✓ GPU Hardware: {} ({}, VRAM: {})",
578 name.green(),
579 temp,
580 vram
581 );
582 } else {
583 println!(
584 "{}",
585 "ℹ GPU Hardware: Unavailable / Sensor Offline".yellow()
586 );
587 }
588
589 // 2. Model Seat 18006
590 match client.get("http://127.0.0.1:18006/v1/models").send().await {
591 Ok(r) if r.status().is_success() => println!(
592 "{}",
593 "✓ Model Seat (Port 18006): Online (Nemotron-3.5-Lightning-30B-A3B BF16)".green()
594 ),
595 _ => println!(
596 "{}",
597 "⚠ Model Seat (Port 18006): OFFLINE or unreachable".yellow()
598 ),
599 }
600
601 // 3. JSpace Judge 18082
602 match client.get("http://127.0.0.1:18082/v1/models").send().await {
603 Ok(r) if r.status().is_success() => println!(
604 "{}",
605 "✓ JSpace Truth Judge (Port 18082): Online (Llama-3.2-1B on CPU)".green()
606 ),
607 _ => println!("{}", "⚠ JSpace Truth Judge (Port 18082): Offline".yellow()),
608 }
609
610 // 4. Cortex Memory 18080
611 match client.get("http://127.0.0.1:18080/").send().await {
612 Ok(_) => println!(
613 "{}",
614 "✓ Spark Cortex Memory (Port 18080): Online (Postgres socket 15433)".green()
615 ),
616 _ => println!("{}", "⚠ Spark Cortex Memory (Port 18080): Offline".yellow()),
617 }
618
619 // 5. ONNX Encoder 18081
620 match client.get("http://127.0.0.1:18081/health").send().await {
621 Ok(r) if r.status().is_success() => println!(
622 "{}",
623 "✓ Cortex ONNX Encoder (Port 18081): Online (bge-base embeddings/salience)".green()
624 ),
625 _ => println!("{}", "⚠ Cortex ONNX Encoder (Port 18081): Offline".yellow()),
626 }
627
628 // 6. Dream Daemon 18085
629 match client.get("http://127.0.0.1:18085/health").send().await {
630 Ok(r) if r.status().is_success() => println!(
631 "{}",
632 "✓ JSpace Dream Engine (Port 18085): Online (Idle watcher daemon)".green()
633 ),
634 _ => println!("{}", "⚠ JSpace Dream Engine (Port 18085): Offline".yellow()),
635 }
636
637 // 7. Radicle Anchor
638 println!(
639 "{}",
640 "✓ Radicle Identity: did:rad:aien:spark-master (Active)".green()
641 );
642
643 // 8. Hardware TPM Vault & Secret Hygiene
644 if crate::vault::is_vault_available() {
645 let keys = crate::vault::list_keys();
646 let findings = crate::vault::audit_workspace_secrets();
647 if findings.is_empty() {
648 println!("{}", format!("✓ TPM Key Vault: Online ({} keys registered; 0 plaintext .env files on disk)", keys.len()).green());
649 } else {
650 println!(
651 "{}",
652 format!(
653 "⚠ TPM Key Vault: Online ({} keys), but {} stray .env files found!",
654 keys.len(),
655 findings.len()
656 )
657 .yellow()
658 );
659 }
660 } else {
661 println!(
662 "{}",
663 "⚠ TPM Key Vault: Offline (atlas-vault binary missing)".yellow()
664 );
665 }
666
667 println!();
668}
669
670fn run_mask_command(_args: &[&str]) {
671 let out = Command::new("aien-mask")
672 .current_dir(&crate::platform::PlatformContext::detect().home_dir)
673 .output();
674
675 if out.is_ok() {
676 println!("{}", "Active Mask: AIEN (Sovereign Operator)".cyan().bold());
677 } else {
678 println!("Active Mask: AIEN (default)");
679 }
680}
681
682fn park_input(text: &str) {
683 let platform = crate::platform::PlatformContext::detect();
684 let park_dir = platform.home_dir.join("atlas-prime-workspace/park");
685 let _ = fs::create_dir_all(&park_dir);
686 let stamp = chrono::Utc::now().timestamp();
687 let filename = format!("overload-{}.md", stamp);
688 let path = park_dir.join(&filename);
689
690 match OpenOptions::new()
691 .create(true)
692 .write(true)
693 .truncate(true)
694 .open(&path)
695 {
696 Ok(mut f) => {
697 let _ = writeln!(f, "# Overload Parked: {}", chrono::Utc::now().to_rfc3339());
698 let _ = writeln!(f, "{}", text);
699 println!(
700 "{}",
701 format!("✓ Input safely parked to: {}", path.display())
702 .green()
703 .bold()
704 );
705 println!("Continuing active thread without derailment.");
706 }
707 Err(e) => println!("{}", format!("Failed to park input: {}", e).red()),
708 }
709}
710
711#[allow(dead_code)]
712async fn query_cortex(query: &str) {
713 let client = Client::new();
714 let platform = crate::platform::PlatformContext::detect();
715 let token_path = platform.home_dir.join(".config/cortex/token");
716 let token = fs::read_to_string(token_path)
717 .unwrap_or_default()
718 .trim()
719 .to_string();
720
721 let url = format!(
722 "http://127.0.0.1:18080/api/cortex/search?q={}&space=atlas-memory&limit=5",
723 urlencoding_simple(query)
724 );
725 let mut req = client.get(&url).header("Accept", "application/json");
726 if !token.is_empty() {
727 req = req.header("Authorization", format!("Bearer {}", token));
728 }
729
730 match req.send().await {
731 Ok(r) => {
732 if let Ok(data) = r.json::<serde_json::Value>().await {
733 let results = data.get("results").and_then(|v| v.as_array());
734 match results {
735 Some(items) if !items.is_empty() => {
736 println!(
737 "{}",
738 format!(
739 "\nCortex Knowledge Recall for '{}' ({} found):",
740 query,
741 items.len()
742 )
743 .cyan()
744 .bold()
745 );
746 for (idx, item) in items.iter().enumerate() {
747 let title = item
748 .get("canonicalName")
749 .and_then(|v| v.as_str())
750 .unwrap_or("Untitled");
751 let score = item.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0);
752 let content =
753 item.get("content").and_then(|v| v.as_str()).unwrap_or("");
754 let snippet = if content.len() > 180 {
755 &content[..180]
756 } else {
757 content
758 };
759 println!("{}. {} ({:.2})", idx + 1, title.bold().yellow(), score);
760 println!(" {}\n", snippet.dimmed());
761 }
762 }
763 _ => println!("{}", "No matching entities found in atlas-memory.".dimmed()),
764 }
765 } else {
766 println!("{}", "Could not parse JSON response from Cortex.".red());
767 }
768 }
769 Err(e) => println!("{}", format!("Cortex query failed: {}", e).red()),
770 }
771}
772
773#[allow(dead_code)]
774fn urlencoding_simple(s: &str) -> String {
775 s.replace(" ", "%20")
776}
777
778fn handle_adapter_command(args: &[&str]) {
779 use spark_hive::{
780 emit_adapter_pipeline_combs, evaluate_socratic_reflex, generate_pr_plan,
781 get_catalog_adapters, list_adapter_pipeline_chains, BenchmarkTelemetry, CombStore,
782 };
783
784 if args.is_empty() || args[0] == "list" {
785 println!(
786 "{}",
787 "\n=== AIEN Autonomous Model Adapters Catalogue (Democratizing Consumer Compute) ==="
788 .yellow()
789 .bold()
790 );
791 let adapters = get_catalog_adapters();
792 for (i, a) in adapters.iter().enumerate() {
793 println!(
794 " {}. [{}] {} ({})\n Target: {} | Upstream: {} ({})\n Impact: {}",
795 i + 1,
796 a.id.cyan().bold(),
797 a.model.display_name(),
798 a.model.slug(),
799 a.model.hardware_profile().description().green(),
800 a.engine.repo().yellow(),
801 a.engine.primary_language(),
802 a.summary.dimmed()
803 );
804 }
805 println!("\nUsage: /adapter emit <adapter-id> Emit 4-stage pipeline onto Honeycomb Wall");
806 println!(" /adapter pr <adapter-id> Preview PR body and gh submission commands");
807 println!(
808 " /adapter lattice Inspect adapter chains on the Honeycomb Wall\n"
809 );
810 } else if args[0] == "lattice" || args[0] == "chains" {
811 match CombStore::open_default() {
812 Ok(store) => {
813 match list_adapter_pipeline_chains(&store) {
814 Ok(chains) => {
815 println!("{}", format!("\n=== Honeycomb Wall: Autonomous Adapter Chains ({} pipelines) ===", chains.len()).yellow().bold());
816 if chains.is_empty() {
817 println!(" No adapter pipelines on lattice yet. Run `/adapter emit <id>` to place one.");
818 }
819 for chain in chains {
820 println!(
821 " • Origin [{}, {}] id={}: {}",
822 chain.origin.q,
823 chain.origin.r,
824 chain.origin.id.cyan(),
825 chain.origin.content
826 );
827 if let Some(soc) = chain.socratic {
828 println!(
829 " ↳ Socratic [{}, {}]: {}",
830 soc.q,
831 soc.r,
832 soc.content.lines().next().unwrap_or("")
833 );
834 }
835 if let Some(ver) = chain.verifier {
836 println!(
837 " ↳ Verifier [{}, {}]: {}",
838 ver.q,
839 ver.r,
840 ver.content.lines().next().unwrap_or("")
841 );
842 }
843 if let Some(pr) = chain.pr {
844 println!(
845 " ↳ PR [{}, {}]: {}",
846 pr.q,
847 pr.r,
848 pr.content.lines().next().unwrap_or("")
849 );
850 }
851 }
852 }
853 Err(e) => {
854 println!("{}", format!("Failed to query adapter chains: {}", e).red())
855 }
856 }
857 }
858 Err(e) => println!("{}", format!("Failed to open hive database: {}", e).red()),
859 }
860 } else if args[0] == "emit" {
861 if args.len() < 2 {
862 println!("Usage: /adapter emit <adapter-id | model-slug> [engine]");
863 return;
864 }
865 let target = args[1].trim().to_lowercase();
866 let engine_override = if args.len() > 2 {
867 spark_hive::UpstreamEngine::from_name(args[2])
868 } else {
869 None
870 };
871 let spec = spark_hive::find_or_create_adapter(&target, engine_override);
872 let Some(spec) = spec else {
873 println!(
874 "{}",
875 format!(
876 "Adapter or model '{}' not found. Run `/adapter list` to view catalog.",
877 target
878 )
879 .red()
880 );
881 return;
882 };
883
884 println!(
885 "{}",
886 format!(
887 "Initiating autonomous adapter pipeline for '{}'...",
888 spec.id
889 )
890 .cyan()
891 .bold()
892 );
893 let socratic = evaluate_socratic_reflex(&spec.model, &spec.engine);
894 println!(
895 "{}",
896 format!(
897 "✓ Socratic Reflex: Approved (freedom score: {:.2}, consumer impact: {:.2})",
898 socratic.freedom_alignment_score, socratic.consumer_impact_score
899 )
900 .green()
901 );
902
903 let telem = BenchmarkTelemetry::estimate_for_model(
904 &spec.model,
905 &spec.engine,
906 &crate::platform::PlatformContext::detect()
907 .home_dir
908 .join("workspace/aien-sandbox")
909 .to_string_lossy(),
910 None,
911 );
912 println!(
913 "{}",
914 format!("✓ Sandbox Telemetry: {}", telem.summary_line()).green()
915 );
916
917 let plan = generate_pr_plan(&spec, telem, socratic);
918 match CombStore::open_default() {
919 Ok(store) => match emit_adapter_pipeline_combs(&store, &plan, None) {
920 Ok(receipt) => {
921 println!(
922 "{}",
923 "\n✓ Successfully emitted 4-stage pipeline onto Honeycomb Wall:"
924 .green()
925 .bold()
926 );
927 println!(
928 " 1. Origin Comb: id={} [role: adapter-engine]",
929 receipt.origin_comb_id.cyan()
930 );
931 println!(
932 " 2. Socratic Comb: id={} [role: socratic]",
933 receipt.socratic_comb_id.cyan()
934 );
935 println!(
936 " 3. Verifier Comb: id={} [role: verifier]",
937 receipt.sandbox_comb_id.cyan()
938 );
939 println!(
940 " 4. PR Comb: id={} [role: pr-pipeline]",
941 receipt.pr_comb_id.cyan()
942 );
943 println!(
944 "\nUpstream PR Target: {} (branch: {})",
945 plan.target_repo.yellow(),
946 plan.branch.yellow()
947 );
948 println!("Commit Title: {}", plan.commit_message.bold());
949 println!(
950 "Run `/adapter pr {}` to view full PR markdown and gh commands.\n",
951 spec.id
952 );
953 }
954 Err(e) => println!(
955 "{}",
956 format!("Failed to emit combs to honeycomb lattice: {}", e).red()
957 ),
958 },
959 Err(e) => println!("{}", format!("Failed to open hive database: {}", e).red()),
960 }
961 } else if args[0] == "pr" {
962 if args.len() < 2 {
963 println!("Usage: /adapter pr <adapter-id | model-slug> [engine]");
964 return;
965 }
966 let target = args[1].trim().to_lowercase();
967 let engine_override = if args.len() > 2 {
968 spark_hive::UpstreamEngine::from_name(args[2])
969 } else {
970 None
971 };
972 let spec = spark_hive::find_or_create_adapter(&target, engine_override);
973 let Some(spec) = spec else {
974 println!(
975 "{}",
976 format!(
977 "Adapter or model '{}' not found. Run `/adapter list` to view catalog.",
978 target
979 )
980 .red()
981 );
982 return;
983 };
984
985 let socratic = evaluate_socratic_reflex(&spec.model, &spec.engine);
986 let telem = BenchmarkTelemetry::estimate_for_model(
987 &spec.model,
988 &spec.engine,
989 &crate::platform::PlatformContext::detect()
990 .home_dir
991 .join("workspace/aien-sandbox")
992 .to_string_lossy(),
993 None,
994 );
995 let plan = generate_pr_plan(&spec, telem, socratic);
996
997 println!(
998 "{}",
999 format!("\n=== Sovereign Pull Request Plan: {} ===", plan.pr_title)
1000 .yellow()
1001 .bold()
1002 );
1003 println!("Author: {}", plan.author.green());
1004 println!("Target Repository: {}", plan.target_repo.cyan());
1005 println!("Branch: {}", plan.branch.cyan());
1006 println!("\n--- Pull Request Body (Sovereign Voice / Anti-Slop Compliant) ---\n");
1007 println!("{}", plan.pr_body);
1008 println!("\n--- Automated gh CLI Commands ---");
1009 for cmd in plan.gh_commands {
1010 println!(" $ {}", cmd.yellow());
1011 }
1012 println!("\n--- Autonomous PR Execution Script ---");
1013 println!("{}", plan.pr_script);
1014 println!();
1015 } else {
1016 println!("Usage: /adapter [list | emit <id> | pr <id> | lattice]");
1017 }
1018}
1019
1020// --------------------------------------------------------------------------
1021// SOVEREIGN ORCHESTRATION & DEVELOPER EXPERIENCE
1022// --------------------------------------------------------------------------
1023
1024/// Explicit model manifest for daemon boot. No silent developer-machine paths.
1025/// After loading, it records the SHA-256 (hex) of the model and tokenizer files
1026/// so a later run receipt can name exactly which bytes were served.
1027struct DaemonModelManifest {
1028 model_id: String,
1029 label: String,
1030 checkpoint_path: Option<std::path::PathBuf>,
1031 tokenizer_path: Option<std::path::PathBuf>,
1032 /// Why no checkpoint file was resolved (None when one was found).
1033 fallback_reason: Option<String>,
1034 /// Hex SHA-256 of what was loaded (set only when its weights loaded): the file's own
1035 /// digest for a single file, the manifest digest over the index and every shard for a
1036 /// sharded checkpoint (see [`checkpoint_digest`]).
1037 model_sha256: Option<String>,
1038 /// Which form `model_sha256` has: `file` or `index+shards` (set with it).
1039 model_digest_kind: Option<&'static str>,
1040 /// Hex SHA-256 of the loaded tokenizer file (set only when it parsed).
1041 tokenizer_sha256: Option<String>,
1042}
1043
1044/// Checkpoint selection inputs, read once from the environment.
1045/// `AIEN_MODEL_PATH` (a safetensors file) and `AIEN_TOKENIZER_PATH` (tokenizer.json,
1046/// default: `tokenizer.json` beside the model file) take precedence over any directory
1047/// scan. `AIEN_MODEL_DIR` is scanned first for a `*.safetensors` file (directly or one level
1048/// down). The model is described by `config.json` beside the checkpoint when present (any
1049/// `LlamaForCausalLM`, e.g. Llama 3.x), else by the built-in TinyLlama-1.1B config.
1050/// `AIEN_REQUIRE_CHECKPOINT=1` makes every fallback to reference weights fatal.
1051#[derive(Debug, Clone, Default)]
1052struct CheckpointPolicy {
1053 model_path: Option<std::path::PathBuf>,
1054 tokenizer_path: Option<std::path::PathBuf>,
1055 scan_dirs: Vec<std::path::PathBuf>,
1056 require_checkpoint: bool,
1057}
1058
1059impl CheckpointPolicy {
1060 fn from_lookup(get: impl Fn(&str) -> Option<String>) -> Self {
1061 let non_empty = |key: &str| {
1062 get(key)
1063 .map(|value| value.trim().to_string())
1064 .filter(|value| !value.is_empty())
1065 };
1066 let mut scan_dirs = Vec::new();
1067 if let Some(dir) = non_empty("AIEN_MODEL_DIR") {
1068 scan_dirs.push(std::path::PathBuf::from(dir));
1069 }
1070 scan_dirs.push(std::path::PathBuf::from("models"));
1071 if let Some(home) = non_empty("HOME") {
1072 scan_dirs.push(std::path::PathBuf::from(home).join("models"));
1073 }
1074 Self {
1075 model_path: non_empty("AIEN_MODEL_PATH").map(std::path::PathBuf::from),
1076 tokenizer_path: non_empty("AIEN_TOKENIZER_PATH")
1077 .or_else(|| non_empty("AIEN_TOKENIZER"))
1078 .map(std::path::PathBuf::from),
1079 scan_dirs,
1080 require_checkpoint: non_empty("AIEN_REQUIRE_CHECKPOINT")
1081 .map(|value| value == "1" || value.eq_ignore_ascii_case("true"))
1082 .unwrap_or(aien_inference_abi::strict::production_strict()),
1083 }
1084 }
1085
1086 fn from_env() -> Self {
1087 Self::from_lookup(|key| std::env::var(key).ok())
1088 }
1089}
1090
1091/// The daemon's start line (sc#337): whether this process fails closed, whether
1092/// the binary was built with `dev-fallback`, the effective `require_checkpoint`
1093/// and the tensor backend's name, so a run's log shows the protections were on
1094/// instead of only the absence of a crash.
1095fn strict_start_line(
1096 strict: bool,
1097 dev_fallback_build: bool,
1098 require_checkpoint: bool,
1099 backend: &str,
1100) -> String {
1101 format!(
1102 "STRICT strict={strict} dev_fallback_build={dev_fallback_build} require_checkpoint={require_checkpoint} backend={backend}"
1103 )
1104}
1105
1106fn is_safetensors(path: &std::path::Path) -> bool {
1107 path.extension().and_then(|ext| ext.to_str()) == Some("safetensors")
1108}
1109
1110/// Explicit tokenizer path if given, else `tokenizer.json` beside the checkpoint.
1111/// The path is returned even if the file is missing; loading decides what that means.
1112fn tokenizer_for(
1113 policy: &CheckpointPolicy,
1114 checkpoint: &std::path::Path,
1115) -> Option<std::path::PathBuf> {
1116 if let Some(path) = &policy.tokenizer_path {
1117 return Some(path.clone());
1118 }
1119 checkpoint.parent().map(|dir| dir.join("tokenizer.json"))
1120}
1121
1122fn checkpoint_manifest(
1123 policy: &CheckpointPolicy,
1124 path: std::path::PathBuf,
1125 model_id: String,
1126 label: String,
1127) -> DaemonModelManifest {
1128 DaemonModelManifest {
1129 model_id,
1130 label,
1131 tokenizer_path: tokenizer_for(policy, &path),
1132 checkpoint_path: Some(path),
1133 fallback_reason: None,
1134 model_sha256: None,
1135 model_digest_kind: None,
1136 tokenizer_sha256: None,
1137 }
1138}
1139
1140fn resolve_daemon_manifest_with(policy: &CheckpointPolicy) -> DaemonModelManifest {
1141 if let Some(path) = &policy.model_path {
1142 let model_id = path
1143 .parent()
1144 .and_then(|dir| dir.file_name())
1145 .and_then(|name| name.to_str())
1146 .unwrap_or("checkpoint")
1147 .to_string();
1148 return checkpoint_manifest(
1149 policy,
1150 path.clone(),
1151 model_id,
1152 format!("explicit AIEN_MODEL_PATH={}", path.display()),
1153 );
1154 }
1155 for dir in &policy.scan_dirs {
1156 let Ok(entries) = std::fs::read_dir(dir) else {
1157 continue;
1158 };
1159 for entry in entries.flatten() {
1160 let path = entry.path();
1161 if is_safetensors(&path) {
1162 let model_id = path
1163 .file_stem()
1164 .and_then(|name| name.to_str())
1165 .unwrap_or("checkpoint")
1166 .to_string();
1167 let label = format!(
1168 "checkpoint found at {} (model_id={})",
1169 path.display(),
1170 model_id
1171 );
1172 return checkpoint_manifest(policy, path, "checkpoint".into(), label);
1173 }
1174 if path.is_dir() {
1175 let Ok(nested) = std::fs::read_dir(&path) else {
1176 continue;
1177 };
1178 for child in nested.flatten() {
1179 let child_path = child.path();
1180 if is_safetensors(&child_path) {
1181 let model_id = path
1182 .file_name()
1183 .and_then(|name| name.to_str())
1184 .unwrap_or("checkpoint")
1185 .to_string();
1186 let label = format!("checkpoint found at {}", child_path.display());
1187 return checkpoint_manifest(policy, child_path, model_id, label);
1188 }
1189 }
1190 }
1191 }
1192 }
1193 let searched = policy
1194 .scan_dirs
1195 .iter()
1196 .map(|dir| dir.display().to_string())
1197 .collect::<Vec<_>>()
1198 .join(", ");
1199 DaemonModelManifest {
1200 model_id: "aien-daemon-reference-fallback".into(),
1201 label: "no safetensors checkpoint resolved".into(),
1202 checkpoint_path: None,
1203 tokenizer_path: None,
1204 fallback_reason: Some(format!(
1205 "no AIEN_MODEL_PATH and no *.safetensors found in [{}]",
1206 searched
1207 )),
1208 model_sha256: None,
1209 model_digest_kind: None,
1210 tokenizer_sha256: None,
1211 }
1212}
1213
1214/// Builds the native transformer backend for daemon boot with explicit fallback.
1215/// Uses the native Omega GPU engine when linked, falls back to CPU reference math.
1216/// Never returns the Mock backend: output always comes from real forward passes.
1217/// When AIEN_REQUIRE_BLACKWELL (or AIEN_GPU_BACKEND=omega) is set, a missing GPU engine is fatal:
1218/// the hardware gate must fail when fallback count is nonzero.
1219fn reference_config() -> aien_inference_abi::ModelConfig {
1220 aien_inference_abi::ModelConfig {
1221 model_id: "aien-daemon-reference-fallback".to_string(),
1222 max_sequence_length: 2048,
1223 block_size: 16,
1224 num_layers: 4,
1225 num_heads: 8,
1226 head_dim: 64,
1227 num_kv_heads: 4,
1228 hidden_dim: 512,
1229 intermediate_dim: 1408,
1230 vocab_size: 32000,
1231 rms_norm_eps: 1e-5,
1232 rope_theta: 10000.0,
1233 rope_scaling: None,
1234 tie_word_embeddings: false,
1235 eos_token_ids: Vec::new(),
1236 qk_norm: false,
1237 }
1238}
1239
1240/// Result of daemon model loading: the manifest (with SHA-256 digests filled in on
1241/// success), the weights, the tokenizer, and whether reference weights were used.
1242struct DaemonModel {
1243 manifest: DaemonModelManifest,
1244 weights: aien_inference_abi::TransformerWeights,
1245 tokenizer: Option<aien_inference_abi::ChatTokenizer>,
1246 label: String,
1247 /// The `CHECKPOINT_SHARDS` line for a sharded checkpoint (logged after the
1248 /// "checkpoint loaded" line, which keeps its pinned form); None otherwise.
1249 shards_line: Option<String>,
1250 #[allow(dead_code)] // read by tests now and by the PREFILL-E2E receipt (Cut 8)
1251 reference_weights: bool,
1252}
1253
1254/// The digests of the files the daemon actually loaded, for its generation
1255/// records. Present only when real weights AND a parsed tokenizer loaded (the
1256/// reference fallback has no file identity).
1257fn model_identity(
1258 manifest: &DaemonModelManifest,
1259 tokenizer_loaded: bool,
1260) -> Option<aien_runtime::generation::ModelIdentity> {
1261 if !tokenizer_loaded {
1262 return None;
1263 }
1264 let path_text = |p: &std::path::Path| {
1265 std::fs::canonicalize(p)
1266 .unwrap_or_else(|_| p.to_path_buf())
1267 .display()
1268 .to_string()
1269 };
1270 Some(aien_runtime::generation::ModelIdentity {
1271 model_sha256: manifest.model_sha256.clone()?,
1272 model_digest_kind: manifest.model_digest_kind?.to_string(),
1273 model_path: path_text(manifest.checkpoint_path.as_deref()?),
1274 tokenizer_sha256: manifest.tokenizer_sha256.clone()?,
1275 tokenizer_path: path_text(manifest.tokenizer_path.as_deref()?),
1276 })
1277}
1278
1279/// Hex SHA-256 of a file, streamed in 1 MiB chunks.
1280fn sha256_file_hex(path: &std::path::Path) -> std::io::Result<String> {
1281 use sha2::{Digest, Sha256};
1282 use std::io::Read;
1283 let mut file = std::fs::File::open(path)?;
1284 let mut hasher = Sha256::new();
1285 let mut buf = vec![0u8; 1 << 20];
1286 loop {
1287 let read = file.read(&mut buf)?;
1288 if read == 0 {
1289 break;
1290 }
1291 hasher.update(&buf[..read]);
1292 }
1293 Ok(hex::encode(hasher.finalize()))
1294}
1295
1296/// The digest of a checkpoint's weight bytes (sc#338), over exactly the files the
1297/// loader reads ([`aien_inference_abi::checkpoint_files`]).
1298struct CheckpointDigest {
1299 /// A single file: its own sha256. A sharded checkpoint: the sha256 of the
1300 /// manifest text `aien-checkpoint-digest v1\nindex <index sha256>\n` followed by
1301 /// one `<shard sha256> <shard name>\n` line per shard, sorted by name (the
1302 /// shard lines are `sha256sum` lines).
1303 sha256: String,
1304 /// `file` or `index+shards`.
1305 kind: &'static str,
1306 /// The index's own sha256 (sharded only).
1307 index_sha256: Option<String>,
1308 /// `(shard name, shard sha256)` in name order (sharded only).
1309 shards: Vec<(String, String)>,
1310}
1311
1312/// Errors name the file only when it is not `path` itself (the caller names `path`).
1313/// A directory is refused, as it was when `path` itself was hashed.
1314fn checkpoint_digest(path: &std::path::Path) -> Result<CheckpointDigest, String> {
1315 if path.is_dir() {
1316 return Err("is a directory, not a safetensors file or shard index".to_string());
1317 }
1318 let files = aien_inference_abi::checkpoint_files(path).map_err(|e| e.to_string())?;
1319 let sha = |p: &std::path::Path| {
1320 aien_inference_abi::checkpoint_sha256(p)
1321 .map(hex::encode)
1322 .map_err(|e| {
1323 if p == path {
1324 e.to_string()
1325 } else {
1326 format!("{}: {}", p.display(), e)
1327 }
1328 })
1329 };
1330 let Some(index) = files.index else {
1331 let Some((_, file)) = files.weights.first() else {
1332 return Err("names no weight file".to_string());
1333 };
1334 return Ok(CheckpointDigest {
1335 sha256: sha(file)?,
1336 kind: "file",
1337 index_sha256: None,
1338 shards: Vec::new(),
1339 });
1340 };
1341 if files.weights.is_empty() {
1342 return Err("its shard index names no shard".to_string());
1343 }
1344 use sha2::{Digest, Sha256};
1345 let index_sha256 = sha(&index)?;
1346 let mut manifest = format!("aien-checkpoint-digest v1\nindex {index_sha256}\n");
1347 let mut shards = Vec::with_capacity(files.weights.len());
1348 for (name, file) in &files.weights {
1349 let digest = sha(file)?;
1350 manifest.push_str(&format!("{digest} {name}\n"));
1351 shards.push((name.clone(), digest));
1352 }
1353 Ok(CheckpointDigest {
1354 sha256: hex::encode(Sha256::digest(manifest.as_bytes())),
1355 kind: "index+shards",
1356 index_sha256: Some(index_sha256),
1357 shards,
1358 })
1359}
1360
1361/// The `CHECKPOINT_SHARDS` log line (sc#338): every shard's sha256 and the index's,
1362/// so a run's log ties `model_sha256` to the shard bytes. None for a single file.
1363fn checkpoint_shards_line(d: &CheckpointDigest) -> Option<String> {
1364 let index = d.index_sha256.as_deref()?;
1365 let shards: Vec<String> = d.shards.iter().map(|(n, s)| format!("{n}:{s}")).collect();
1366 Some(format!(
1367 "CHECKPOINT_SHARDS model_sha256={} model_digest_kind={} index_sha256={} shards=[{}]",
1368 d.sha256,
1369 d.kind,
1370 index,
1371 shards.join(",")
1372 ))
1373}
1374
1375/// The single decision point for every checkpoint fallback. Under
1376/// AIEN_REQUIRE_CHECKPOINT=1 it refuses with an error naming the reason (which names
1377/// the path); otherwise it prints exactly one warn-level line and lets the caller degrade.
1378fn strict_checkpoint_gate(require_checkpoint: bool, reason: &str) -> Result<(), String> {
1379 if require_checkpoint {
1380 return Err(format!(
1381 "AIEN_REQUIRE_CHECKPOINT=1: {}; refusing to fall back",
1382 reason
1383 ));
1384 }
1385 eprintln!(
1386 "WARN aien-daemon: {}; falling back (set AIEN_REQUIRE_CHECKPOINT=1 to make this fatal)",
1387 reason
1388 );
1389 Ok(())
1390}
1391
1392fn reference_fallback(
1393 manifest: DaemonModelManifest,
1394 require_checkpoint: bool,
1395 reason: String,
1396) -> Result<DaemonModel, String> {
1397 strict_checkpoint_gate(require_checkpoint, &reason)?;
1398 let config = reference_config();
1399 Ok(DaemonModel {
1400 label: format!(
1401 "{} ({}); using reference fallback weights",
1402 manifest.label, reason
1403 ),
1404 weights: aien_inference_abi::TransformerWeights::reference_test_weights(&config),
1405 tokenizer: None,
1406 shards_line: None,
1407 reference_weights: true,
1408 manifest,
1409 })
1410}
1411
1412/// How the daemon makes the GB10 Qwen3 weights resident instead of holding host f32 copies
1413/// (sovereign-core #277 cut C). `None` anywhere means the unchanged host f32 load.
1414struct ResidentLoad<'a> {
1415 native_linked: bool,
1416 strict: bool,
1417 qwen3_enabled: bool,
1418 uploader: &'a dyn aien_inference_abi::ResidentUploader,
1419 /// Opens the GPU session (bounded retry) so every driver allocation of the upload happens
1420 /// while the process holds almost no memory.
1421 open_session: &'a dyn Fn() -> Result<(), String>,
1422}
1423
1424/// Plain-English refusal printed by `aien start` when the approval desk key is
1425/// missing or unusable (sc#414). The desk is mandatory, so this is a refusal,
1426/// never a warning. `detail` is the runtime's own reason.
1427pub fn start_refusal_text(detail: &str) -> String {
1428 format!(
1429 "AIEN will not start yet: the approval desk key has not been created.
1430 The desk is how you approve what AIEN is allowed to do, and AIEN refuses to run without it.
1431 Create it once, then start again:
1432 aien compose desk-key --create 1
1433 aien start
1434 (detail: {detail})"
1435 )
1436}
1437
1438#[cfg(test)]
1439fn load_daemon_model(
1440 manifest: DaemonModelManifest,
1441 require_checkpoint: bool,
1442) -> Result<DaemonModel, String> {
1443 load_daemon_model_with(manifest, require_checkpoint, None)
1444}
1445
1446fn load_daemon_model_with(
1447 mut manifest: DaemonModelManifest,
1448 require_checkpoint: bool,
1449 resident: Option<&ResidentLoad<'_>>,
1450) -> Result<DaemonModel, String> {
1451 let Some(path) = manifest.checkpoint_path.clone() else {
1452 let reason = manifest
1453 .fallback_reason
1454 .clone()
1455 .unwrap_or_else(|| "no checkpoint resolved".to_string());
1456 return reference_fallback(manifest, require_checkpoint, reason);
1457 };
1458 let digest = match checkpoint_digest(&path) {
1459 Ok(digest) => digest,
1460 Err(error) => {
1461 let reason = format!("checkpoint {} is unreadable: {}", path.display(), error);
1462 return reference_fallback(manifest, require_checkpoint, reason);
1463 }
1464 };
1465 // The model description: config.json beside the checkpoint (any LlamaForCausalLM
1466 // checkpoint), else the hard-wired TinyLlama-1.1B config.
1467 let model_dir = path
1468 .parent()
1469 .map(std::path::Path::to_path_buf)
1470 .unwrap_or_default();
1471 let has_config_json = model_dir.join("config.json").is_file();
1472 let config = if has_config_json {
1473 match aien_inference_abi::load_model_config(&model_dir) {
1474 Ok(config) => config,
1475 Err(error) => return reference_fallback(manifest, require_checkpoint, error),
1476 }
1477 } else {
1478 aien_inference_abi::ModelConfig::tinyllama_1_1b()
1479 };
1480 let resident = resident.filter(|r| {
1481 aien_inference_abi::resident_load_wanted(
1482 r.native_linked,
1483 r.strict,
1484 r.qwen3_enabled,
1485 &config,
1486 )
1487 });
1488 let loaded = match resident {
1489 None => aien_inference_abi::TransformerWeights::load_from_safetensors(&path, &config),
1490 Some(r) => {
1491 (r.open_session)()?;
1492 let mut count = 0usize;
1493 let loaded = aien_inference_abi::load_resident_weights(
1494 &path,
1495 &config,
1496 r.uploader,
1497 &mut |_name| count += 1,
1498 );
1499 match loaded {
1500 // An upload that fails is fatal here: the weights have no host copy to degrade to.
1501 Err(e @ aien_inference_abi::CheckpointError::ResidentUpload { .. }) => {
1502 return Err(format!("GB10_RESIDENT_LOAD failed: {e}"));
1503 }
1504 other => {
1505 if other.is_ok() {
1506 println!(
1507 " GB10_RESIDENT_LOAD: {count} matmul weights streamed from the bf16 shards to the device; no host f32 copy of any matmul weight"
1508 );
1509 }
1510 other
1511 }
1512 }
1513 }
1514 };
1515 let weights = match loaded {
1516 Ok(weights) => weights,
1517 Err(error) => {
1518 let reason = format!(
1519 "checkpoint {} failed to load against the {} config: {}",
1520 path.display(),
1521 config.model_id,
1522 error
1523 );
1524 return reference_fallback(manifest, require_checkpoint, reason);
1525 }
1526 };
1527 manifest.model_sha256 = Some(digest.sha256.clone());
1528 manifest.model_digest_kind = Some(digest.kind);
1529
1530 let mut tokenizer = None;
1531 match manifest.tokenizer_path.clone() {
1532 None => strict_checkpoint_gate(
1533 require_checkpoint,
1534 &format!("no tokenizer path for checkpoint {}", path.display()),
1535 )?,
1536 Some(tokenizer_path) => match sha256_file_hex(&tokenizer_path) {
1537 Err(error) => strict_checkpoint_gate(
1538 require_checkpoint,
1539 &format!(
1540 "tokenizer {} is unreadable: {}",
1541 tokenizer_path.display(),
1542 error
1543 ),
1544 )?,
1545 Ok(digest) => {
1546 let loaded = if has_config_json {
1547 aien_inference_abi::ChatTokenizer::from_model_dir(
1548 &model_dir,
1549 Some(&tokenizer_path),
1550 )
1551 } else {
1552 aien_inference_abi::ChatTokenizer::from_file(&tokenizer_path)
1553 };
1554 match loaded {
1555 Ok(loaded) => {
1556 manifest.tokenizer_sha256 = Some(digest);
1557 tokenizer = Some(loaded);
1558 }
1559 Err(error) => strict_checkpoint_gate(
1560 require_checkpoint,
1561 &format!(
1562 "tokenizer {} failed to parse: {}",
1563 tokenizer_path.display(),
1564 error
1565 ),
1566 )?,
1567 }
1568 }
1569 },
1570 }
1571
1572 let label = checkpoint_loaded_label(
1573 &path,
1574 tokenizer.is_some(),
1575 &manifest.model_id,
1576 &config.model_id,
1577 has_config_json,
1578 manifest.model_sha256.as_deref().unwrap_or("none"),
1579 manifest.tokenizer_sha256.as_deref().unwrap_or("none"),
1580 );
1581 Ok(DaemonModel {
1582 manifest,
1583 weights,
1584 tokenizer,
1585 label,
1586 shards_line: checkpoint_shards_line(&digest),
1587 reference_weights: false,
1588 })
1589}
1590
1591/// The one-line "checkpoint loaded" label. Its format is parsed by the interplane
1592/// verifier (interplane#76): keep it byte-identical (pinned by a test).
1593fn checkpoint_loaded_label(
1594 path: &std::path::Path,
1595 tokenizer_loaded: bool,
1596 manifest_model_id: &str,
1597 config_model_id: &str,
1598 has_config_json: bool,
1599 model_sha256: &str,
1600 tokenizer_sha256: &str,
1601) -> String {
1602 format!(
1603 "checkpoint loaded from {} ({}, model_id={}, config={}, model_sha256={}, tokenizer_sha256={})",
1604 path.display(),
1605 if tokenizer_loaded {
1606 "tokenizer loaded"
1607 } else {
1608 "tokenizer missing"
1609 },
1610 manifest_model_id,
1611 if has_config_json {
1612 format!("{} (config.json)", config_model_id)
1613 } else {
1614 format!("{} (built in)", config_model_id)
1615 },
1616 model_sha256,
1617 tokenizer_sha256,
1618 )
1619}
1620
1621/// Loaded daemon model parts: weights, tensor compute backend, backend label,
1622/// model label, tokenizer. The KV manager is built from these by
1623/// `aien_runtime::shared_kv::build_shared_kv_runtime` (one KV for spine and backend).
1624type DaemonBackendParts = (
1625 aien_inference_abi::TransformerWeights,
1626 std::sync::Arc<dyn aien_inference_abi::TensorBackend>,
1627 String,
1628 String,
1629 Option<aien_inference_abi::ChatTokenizer>,
1630 Option<aien_runtime::generation::ModelIdentity>,
1631);
1632
1633/// Runtime switch for an explicitly CPU-only run (sc#384 preflight). `AIEN_FORCE_CPU_STUB=1`
1634/// is a BUILD-time flag (crates/aien-omega-gpu/build.rs): it only stubs the GPU library when
1635/// compiling, and a binary built earlier with the GPU library ignores it at run time.
1636pub const CPU_ONLY_ENV: &str = "AIEN_BACKEND";
1637
1638/// Stable name of the refusal, so scripts and tests can match it.
1639pub const CPU_ONLY_REFUSAL: &str = "CPU_ONLY_BUT_GPU_BUILD";
1640
1641/// True when `AIEN_BACKEND=cpu` (case-insensitive) is set.
1642fn cpu_only_requested(value: Option<&str>) -> bool {
1643 value.is_some_and(|v| v.trim().eq_ignore_ascii_case("cpu"))
1644}
1645
1646/// Preflight: an explicitly CPU-only run either uses the CPU backend or refuses to start.
1647/// Decided before any model load or GPU session is opened. `native_linked` is whether this
1648/// binary carries the real GPU library.
1649fn cpu_only_preflight(value: Option<&str>, native_linked: bool) -> Result<(), String> {
1650 if cpu_only_requested(value) && native_linked {
1651 return Err(format!(
1652 "{CPU_ONLY_REFUSAL}: {CPU_ONLY_ENV}=cpu asks for a CPU-only run, but this binary has the GB10 GPU engine linked and would select it. Refusing to start. Use a CPU-stub build (AIEN_FORCE_CPU_STUB=1 at build time) or unset {CPU_ONLY_ENV}. Note AIEN_FORCE_CPU_STUB does nothing at run time."
1653 ));
1654 }
1655 Ok(())
1656}
1657
1658fn build_native_daemon_backend() -> Result<DaemonBackendParts, String> {
1659 let policy = CheckpointPolicy::from_env();
1660 let manifest = resolve_daemon_manifest_with(&policy);
1661 let DaemonModel {
1662 weights,
1663 tokenizer,
1664 label: model_label,
1665 manifest,
1666 shards_line,
1667 ..
1668 } = {
1669 let open_session = || {
1670 aien_inference_abi::open_gpu_session_with_retry(
1671 aien_inference_abi::GPU_SESSION_OPEN_ATTEMPTS,
1672 aien_inference_abi::GPU_SESSION_RETRY_DELAY,
1673 aien_inference_abi::GPU_SESSION_OPEN_DEADLINE,
1674 &aien_runtime::shared_kv::read_mem_available,
1675 )
1676 .map(|_| ())
1677 };
1678 let resident = ResidentLoad {
1679 native_linked: aien_omega_gpu::is_native(),
1680 strict: aien_inference_abi::strict::production_strict(),
1681 qwen3_enabled: aien_inference_abi::gb10_qwen3_enabled(),
1682 uploader: &aien_inference_abi::OmegaUploader,
1683 open_session: &open_session,
1684 };
1685 load_daemon_model_with(manifest, policy.require_checkpoint, Some(&resident))?
1686 };
1687 if let Some(line) = &shards_line {
1688 println!(" {line}");
1689 }
1690 let identity = model_identity(&manifest, tokenizer.is_some());
1691 // FB-1 cut 6: the native Omega engine is the only GPU backend (no CUDA). The env names
1692 // AIEN_REQUIRE_BLACKWELL (the GB10 chip, campaign spec) and AIEN_GPU_BACKEND=omega both
1693 // make a missing engine fatal instead of falling back to CPU reference math.
1694 let require_gpu = aien_inference_abi::omega_backend_selected()
1695 || std::env::var("AIEN_REQUIRE_BLACKWELL")
1696 .map(|v| v.trim() == "1" || v.trim().eq_ignore_ascii_case("true"))
1697 .unwrap_or(false);
1698 // T4 launch budget: parsed before the backend is chosen, so a bad value is
1699 // always fatal; applied before the first matmul (omega clears its kernel
1700 // cache on a change). Unset means the AIEN default (256), not omega's 64.
1701 let cta_setting = std::env::var(aien_omega_gpu::CTA_BUDGET_ENV).ok();
1702 let cta_budget = aien_omega_gpu::parse_cta_budget(cta_setting.as_deref())?;
1703 // Marker-wait spin window (omega#328): parsed here too, so a bad value is always fatal.
1704 let spin_setting = std::env::var(aien_omega_gpu::SPIN_US_ENV).ok();
1705 let spin_us = aien_omega_gpu::parse_spin_us(spin_setting.as_deref())?;
1706 let omega = aien_inference_abi::OmegaGb10Backend::new();
1707 if omega.is_available() {
1708 println!(" {}", apply_omega_cta_budget(cta_budget)?);
1709 println!(" {}", apply_omega_spin_us(spin_us)?);
1710 let name = aien_inference_abi::TensorBackend::name(&omega).to_string();
1711 let tensor_backend: std::sync::Arc<dyn aien_inference_abi::TensorBackend> =
1712 std::sync::Arc::new(omega);
1713 Ok((
1714 weights,
1715 tensor_backend,
1716 format!("NativeTransformerBackend/{name}"),
1717 model_label,
1718 tokenizer,
1719 identity,
1720 ))
1721 } else if require_gpu {
1722 Err(
1723 "the GB10 GPU is required (AIEN_REQUIRE_BLACKWELL or AIEN_GPU_BACKEND=omega) but the Omega GPU engine is not linked (stub build)"
1724 .to_string(),
1725 )
1726 } else {
1727 if let Some(budget) = cta_budget {
1728 println!(
1729 " Omega CTA budget: {}={} has no effect (CPU reference backend)",
1730 aien_omega_gpu::CTA_BUDGET_ENV,
1731 budget.get()
1732 );
1733 }
1734 let tensor_backend: std::sync::Arc<dyn aien_inference_abi::TensorBackend> =
1735 std::sync::Arc::new(aien_inference_abi::ReferenceCpuBackend::new());
1736 Ok((
1737 weights,
1738 tensor_backend,
1739 "NativeTransformerBackend/CPU-reference (Omega GPU engine not linked, explicit fallback)"
1740 .to_string(),
1741 model_label,
1742 tokenizer,
1743 identity,
1744 ))
1745 }
1746}
1747
1748/// The budget the daemon uses and where it came from: the explicit
1749/// `AIEN_OMEGA_CTA_BUDGET`, else the AIEN daemon default (1024, sealed GB10
1750/// evidence in `aien_omega_gpu::DAEMON_DEFAULT_CTA_BUDGET_EVIDENCE`). Omega's
1751/// own library default (64) is never relied on by the daemon.
1752fn daemon_cta_budget(
1753 budget: Option<aien_omega_gpu::CtaBudget>,
1754) -> (aien_omega_gpu::CtaBudget, String) {
1755 let env = aien_omega_gpu::CTA_BUDGET_ENV;
1756 match budget {
1757 Some(b) => (b, format!("{env}={}", b.get())),
1758 None => (
1759 aien_omega_gpu::DAEMON_DEFAULT_CTA_BUDGET,
1760 format!(
1761 "AIEN default, {env} unset; evidence {}; omega library default {} not used",
1762 aien_omega_gpu::DAEMON_DEFAULT_CTA_BUDGET_EVIDENCE,
1763 aien_omega_gpu::ffi::OMEGA_GPU_MATMUL_MAX_CTAS
1764 ),
1765 ),
1766 }
1767}
1768
1769/// Apply the daemon's marker-wait spin window (always set explicitly at start, omega#328)
1770/// and return the startup log line with the window omega reports back.
1771fn apply_omega_spin_us(us: Option<u32>) -> Result<String, String> {
1772 let env = aien_omega_gpu::SPIN_US_ENV;
1773 let (us, source) = match us {
1774 Some(v) => (v, format!("{env} set")),
1775 None => (
1776 aien_omega_gpu::DAEMON_DEFAULT_SPIN_US,
1777 format!(
1778 "AIEN default, {env} unset; evidence {}",
1779 aien_omega_gpu::DAEMON_DEFAULT_SPIN_US_EVIDENCE
1780 ),
1781 ),
1782 };
1783 aien_omega_gpu::set_spin_us(us)
1784 .map_err(|e| format!("Omega marker spin {us} us ({source}): {e}"))?;
1785 let active = aien_omega_gpu::spin_us().ok_or_else(|| {
1786 format!(
1787 "Omega marker spin {us} us ({source}): the Omega GPU engine is not linked (stub build)"
1788 )
1789 })?;
1790 Ok(format!("Omega marker spin: {active} us ({source})"))
1791}
1792
1793/// Apply the daemon's CTA budget (always set explicitly at start) and return
1794/// the startup log line with the budget omega reports back
1795/// (`omega_gpu_matmul_cta_budget`).
1796fn apply_omega_cta_budget(budget: Option<aien_omega_gpu::CtaBudget>) -> Result<String, String> {
1797 let (b, source) = daemon_cta_budget(budget);
1798 aien_omega_gpu::set_cta_budget(b)
1799 .map_err(|e| format!("Omega CTA budget {} ({source}): {e}", b.get()))?;
1800 let active = aien_omega_gpu::cta_budget().ok_or_else(|| {
1801 format!(
1802 "Omega CTA budget {} ({source}): the Omega GPU engine is not linked (stub build)",
1803 b.get()
1804 )
1805 })?;
1806 if active != b.get() {
1807 return Err(format!(
1808 "Omega CTA budget: set {} but omega reports {active}",
1809 b.get()
1810 ));
1811 }
1812 Ok(format!(
1813 "Omega CTA budget: {active} CTAs per matmul launch ({source})"
1814 ))
1815}
1816
1817/// The scheduler limits the daemon declares. One definition for `run_daemon_server` and the tests
1818/// of the GB10 serving reservation, whose bounds (decode rows, prefill chunk) come from it.
1819fn daemon_scheduler_config() -> aien_scheduler::SchedulerConfig {
1820 aien_scheduler::SchedulerConfig {
1821 max_batch_size: 256,
1822 max_batch_tokens: 16384,
1823 max_prefill_tokens: 8192,
1824 prefill_chunk_size: 128,
1825 chunk_prefill: true,
1826 watermark_blocks: 64,
1827 }
1828}
1829
1830/// The daemon's start-up decision for the GB10 serving reservation, apart from the chip so a CPU
1831/// test can run it: derives the bounds from the KV plan's context and the scheduler limits, makes
1832/// runs reserve, prepare of every (rows, weight shape) kernel, then seal through `ops` on the opt-in
1833/// Qwen3 GB10 path (and never elsewhere), and returns the log line, or the named refusal that stops the daemon (no on-demand fallback).
1834/// `run_daemon_server` calls it once, before the server is built, hence before any request.
1835fn daemon_serving_reservation(
1836 model_config: &aien_inference_abi::ModelConfig,
1837 kv_context_tokens: usize,
1838 sched: &aien_scheduler::SchedulerConfig,
1839 gpu_native: bool,
1840 qwen3_enabled: bool,
1841 ops: &dyn aien_inference_abi::gb10_serving::ServingOps,
1842) -> Result<Option<String>, String> {
1843 let limits = aien_inference_abi::gb10_serving::ServingLimits {
1844 context_tokens: kv_context_tokens,
1845 max_batch_rows: sched.max_batch_size,
1846 prefill_chunk_rows: sched.prefill_chunk_size,
1847 };
1848 aien_inference_abi::gb10_serving::reserve_gb10_serving_with(
1849 model_config,
1850 &limits,
1851 gpu_native,
1852 qwen3_enabled,
1853 ops,
1854 )
1855 .map(|r| r.map(|r| r.log_line()))
1856}
1857
1858pub async fn run_daemon_server() {
1859 println!(
1860 "{}",
1861 "⚡ Starting AIEN Sovereign Runtime Daemon...".cyan().bold()
1862 );
1863 // sc#384 preflight: an explicitly CPU-only run never reaches a GPU build.
1864 if let Err(fatal) = cpu_only_preflight(
1865 std::env::var(CPU_ONLY_ENV).ok().as_deref(),
1866 aien_omega_gpu::is_native(),
1867 ) {
1868 eprintln!("Fatal: {}", fatal.red().bold());
1869 std::process::exit(1);
1870 }
1871 // NEXT-PHASE-2 (ACCEPTANCE-v2 2.8): damaged idempotency state refuses the
1872 // start; it is never reset silently.
1873 if let Err(fatal) = aien_runtime::control::RuntimeController::load() {
1874 eprintln!("Fatal: {}", fatal.red().bold());
1875 std::process::exit(1);
1876 }
1877 // sc#328: the approval desk is required by default; a missing desk key
1878 // refuses the start here, before any model or GPU work.
1879 if let Err(fatal) = aien_runtime::compose::authorize_desk_at_start_from_env() {
1880 eprintln!("Fatal: {}", fatal.red().bold());
1881 std::process::exit(1);
1882 }
1883 let socket_path = aien_runtime::client::AienRuntimeClient::default_socket_path();
1884 let sched_cfg = daemon_scheduler_config();
1885
1886 let (weights, tensor_backend, backend_label, model_label, tokenizer, identity) =
1887 match build_native_daemon_backend() {
1888 Ok(parts) => parts,
1889 Err(fatal) => {
1890 eprintln!("Fatal: {}", fatal.red().bold());
1891 std::process::exit(1);
1892 }
1893 };
1894 println!(
1895 " {}",
1896 strict_start_line(
1897 aien_inference_abi::strict::production_strict(),
1898 aien_inference_abi::strict::DEV_FALLBACK,
1899 CheckpointPolicy::from_env().require_checkpoint,
1900 tensor_backend.name(),
1901 )
1902 );
1903
1904 // One KV for runtime and backend: the spine's block tables and the
1905 // backend's K/V writes go to the same pooled manager. The pool is sized
1906 // from the loaded model's config and declared context, and the host's
1907 // MemAvailable is checked before it is allocated (#239). AIEN_KV_CONTEXT_TOKENS
1908 // may lower the context budget below the model's declared context, never raise it.
1909 let model_config = weights.config.clone();
1910 let sched_for_reservation = sched_cfg.clone();
1911 let kv_context_cap = match aien_runtime::shared_kv::kv_context_cap_from_env() {
1912 Ok(cap) => cap,
1913 Err(fatal) => {
1914 eprintln!("Fatal: shared KV pool: {}", fatal.red().bold());
1915 std::process::exit(1);
1916 }
1917 };
1918 let gpu_native = aien_inference_abi::OmegaGb10Backend::new().is_available();
1919 // Persistent KV (ADR 0003, cut C7): settings are checked now, so a bad value
1920 // stops the start with its name; persistence is off unless AIEN_KV_STORE_DIR is set.
1921 let kv_persist = match aien_runtime::shared_kv::KvPersistSettings::from_env() {
1922 Ok(s) => s,
1923 Err(fatal) => {
1924 eprintln!("Fatal: persistent KV: {}", fatal.red().bold());
1925 std::process::exit(1);
1926 }
1927 };
1928 let kv_arith_id = tensor_backend.name().to_string();
1929 let (mut spine, backend, _kv_plan) =
1930 match aien_runtime::shared_kv::build_shared_kv_runtime_for_model(
1931 weights,
1932 tensor_backend,
1933 sched_cfg,
1934 4096,
1935 kv_context_cap,
1936 &aien_runtime::shared_kv::read_mem_available_checked,
1937 aien_runtime::shared_kv::allow_unchecked_memory_from_env(),
1938 ) {
1939 Ok(parts) => parts,
1940 Err(fatal) => {
1941 eprintln!("Fatal: shared KV pool: {}", fatal.red().bold());
1942 std::process::exit(1);
1943 }
1944 };
1945 if kv_persist.enabled() {
1946 // The namespace binds the weights digest; without it nothing could
1947 // tell this model's K/V from another's, so the start is refused.
1948 let digest = identity
1949 .as_ref()
1950 .ok_or_else(|| {
1951 "AIEN_KV_STORE_DIR is set but the model weights digest is unknown".to_string()
1952 })
1953 .and_then(|id| {
1954 aien_runtime::shared_kv::parse_sha256_hex(&id.model_sha256)
1955 .map(|sha| (sha, id.model_digest_kind.clone()))
1956 });
1957 // The host TensorBackend path: weights as the file holds them, this
1958 // build, the backend name plus KV_ARITH_EPOCH as the rounding class, a
1959 // dense engine config (ADR 0003 section 1.2.2).
1960 let host_engine = aien_runtime::compute_config::HostEngineIdentity::reference(&kv_arith_id)
1961 .map_err(|e| format!("persistent KV engine identity: {e}"));
1962 let enabled = digest.and_then(|d| host_engine.map(|e| (d, e))).and_then(
1963 |((sha, kind), host_engine)| {
1964 aien_runtime::shared_kv::enable_persistent_kv(
1965 &mut spine,
1966 &kv_persist,
1967 &aien_runtime::shared_kv::ModelKvBinding {
1968 model: &model_config,
1969 arith_id: &kv_arith_id,
1970 model_sha256: sha,
1971 model_digest_kind: &kind,
1972 engine: host_engine.identity(),
1973 },
1974 kv_context_cap,
1975 )
1976 },
1977 );
1978 match enabled {
1979 Ok(Some(line)) => println!(" {line}"),
1980 Ok(None) => {}
1981 Err(fatal) => {
1982 eprintln!("Fatal: persistent KV: {}", fatal.red().bold());
1983 std::process::exit(1);
1984 }
1985 }
1986 }
1987 // Open the GPU session before serving, with a bounded retry, so a failed
1988 // channel open is a clear refusal with status and free memory per attempt
1989 // instead of the strict-fallback panic at warm-up (#239, #236).
1990 if gpu_native {
1991 if let Err(fatal) = aien_inference_abi::open_gpu_session_with_retry(
1992 aien_inference_abi::GPU_SESSION_OPEN_ATTEMPTS,
1993 aien_inference_abi::GPU_SESSION_RETRY_DELAY,
1994 aien_inference_abi::GPU_SESSION_OPEN_DEADLINE,
1995 &aien_runtime::shared_kv::read_mem_available,
1996 ) {
1997 eprintln!("Fatal: {}", fatal.red().bold());
1998 std::process::exit(1);
1999 }
2000 }
2001 // GB10 Qwen3 (enabled by default, #277): reserve the serving buffers once, from the declared
2002 // bounds, before the first request. A refusal stops the daemon by name; there is no
2003 // on-demand fallback (sovereign-core#277, omega#327, omega#333). The outcome is logged
2004 // either way so a chip run can measure it.
2005 let mut serving_probe: Option<
2006 std::sync::Arc<dyn aien_inference_abi::gb10_serving::ServingProbe>,
2007 > = None;
2008 match daemon_serving_reservation(
2009 &model_config,
2010 _kv_plan.context_tokens,
2011 &sched_for_reservation,
2012 gpu_native,
2013 aien_inference_abi::gb10_qwen3_enabled(),
2014 &aien_inference_abi::gb10_serving::OmegaServingOps,
2015 ) {
2016 Ok(Some(line)) => {
2017 println!(" {line}");
2018 serving_probe = Some(std::sync::Arc::new(
2019 aien_inference_abi::gb10_serving::AllocProbe::omega(),
2020 ));
2021 }
2022 Ok(None) => {}
2023 Err(fatal) => {
2024 eprintln!("Fatal: {}", fatal.red().bold());
2025 std::process::exit(1);
2026 }
2027 }
2028 let server = aien_runtime::server::AienRuntimeServer::new(spine, &socket_path);
2029 if let Some(probe) = serving_probe {
2030 server.set_serving_probe(probe);
2031 }
2032
2033 println!(" Backend: {}", backend_label.green());
2034 println!(" Model: {}", model_label.yellow());
2035 println!(
2036 " KV: {}",
2037 "one pooled KV shared by runtime and backend".green()
2038 );
2039 if let Some(tokenizer) = tokenizer {
2040 println!(
2041 " Tokenizer: {} chat template, stop ids {:?}",
2042 tokenizer.template().name().green(),
2043 tokenizer.stop_token_ids()
2044 );
2045 server.set_tokenizer(tokenizer);
2046 if let Some(identity) = identity {
2047 // The daemon's generation records name these digests (docs/DAEMON_GENERATION_RECORD.md).
2048 server.set_model_identity(identity);
2049 }
2050 // NEXT-PHASE-1 v4: one declared 1-token warm-up before serving.
2051 server.enable_warm_up();
2052 } else {
2053 println!(
2054 " Tokenizer: {}",
2055 "not loaded; native chat will refuse turns until tokenizer.json is present".yellow()
2056 );
2057 }
2058 println!("✓ Binding socket at {}", socket_path.display());
2059 if let Err(e) = server.run(backend).await {
2060 eprintln!("Runtime daemon error: {}", e);
2061 // A refused start (sc#328: no desk key) must not exit as a success.
2062 std::process::exit(1);
2063 }
2064}
2065
2066pub async fn handle_start_command() {
2067 let client = aien_runtime::client::AienRuntimeClient::default_client();
2068 if client.is_alive().await {
2069 println!(
2070 "{}",
2071 "✓ AIEN Sovereign Runtime is already active.".green().bold()
2072 );
2073 if let Ok(status) = client.get_status().await {
2074 render_runtime_status(&status);
2075 }
2076 return;
2077 }
2078
2079 // First-run guard (sc#414): the approval desk is mandatory, so refuse here in
2080 // plain words instead of spawning a daemon that exits unseen.
2081 if let Err(detail) = aien_runtime::compose::authorize_desk_at_start_from_env() {
2082 eprintln!("{}", start_refusal_text(&detail).red().bold());
2083 std::process::exit(1);
2084 }
2085 println!(
2086 "{}",
2087 "⚡ Starting AIEN Sovereign Runtime Machine..."
2088 .cyan()
2089 .bold()
2090 );
2091 let exe = std::env::current_exe().unwrap_or_else(|_| std::path::PathBuf::from("aien"));
2092 let mut cmd = std::process::Command::new(exe);
2093 cmd.arg("--daemon");
2094
2095 match cmd.spawn() {
2096 Ok(_) => {
2097 let mut ready = false;
2098 for _ in 0..60 {
2099 tokio::time::sleep(std::time::Duration::from_millis(50)).await;
2100 if client.is_alive().await {
2101 ready = true;
2102 break;
2103 }
2104 }
2105
2106 if ready {
2107 println!("{}", "✓ AIEN Sovereign Runtime Online".green().bold());
2108 println!(
2109 " Socket: {}",
2110 aien_runtime::client::AienRuntimeClient::default_socket_path().display()
2111 );
2112 println!(
2113 " Runtime: Unified Sequence Arena, Transactional PagedAttention KV Pool, In-Process Cortex Memory"
2114 );
2115 if let Ok(status) = client.get_status().await {
2116 render_runtime_status(&status);
2117 }
2118 } else {
2119 eprintln!(
2120 "{}",
2121 "⚠ Runtime daemon spawned but socket did not become ready in 3s.".yellow()
2122 );
2123 }
2124 }
2125 Err(e) => {
2126 eprintln!("Failed to spawn AIEN runtime daemon: {}", e);
2127 }
2128 }
2129}
2130
2131pub async fn handle_stop_command() {
2132 println!("{}", "Stopping AIEN Sovereign Runtime...".yellow().bold());
2133 let client = aien_runtime::client::AienRuntimeClient::default_client();
2134 if client.is_alive().await {
2135 match client.shutdown().await {
2136 Ok(()) => println!("{}", "✓ Runtime daemon stopped cleanly over IPC".green()),
2137 Err(e) => eprintln!("Failed to send shutdown command: {}", e),
2138 }
2139 } else {
2140 println!("{}", "ℹ Runtime daemon is not running".dimmed());
2141 }
2142
2143 let _ = std::process::Command::new("pkill")
2144 .args(["-f", "spark-cockpit"])
2145 .status();
2146}
2147
2148pub fn render_runtime_status(status: &aien_runtime::control::RuntimeStatusReport) {
2149 let sharing_pct =
2150 if status.total_kv_blocks > status.free_kv_blocks && status.total_kv_blocks > 0 {
2151 let allocated = status.total_kv_blocks - status.free_kv_blocks;
2152 (status.shared_kv_pages as f64 / (allocated + status.shared_kv_pages) as f64) * 100.0
2153 } else {
2154 0.0
2155 };
2156
2157 println!(" - Active Sequences: {}", status.active_sequences);
2158 println!(" - Active Swarms: {}", status.active_swarms);
2159 println!(" - Active Worlds: {}", status.active_worlds);
2160 println!(
2161 " - KV Cache Pool: {}/{} blocks free",
2162 status.free_kv_blocks, status.total_kv_blocks
2163 );
2164 println!(
2165 " - Shared KV Pages: {} ({:.1}% deduplication)",
2166 status.shared_kv_pages, sharing_pct
2167 );
2168 println!(" - COW Faults: {}", status.cow_faults);
2169 println!(" - Engine Status: ONLINE");
2170}
2171
2172pub async fn handle_status_command() {
2173 println!("{}", "=== AIEN Sovereign Machine Status ===".cyan().bold());
2174 let client = aien_runtime::client::AienRuntimeClient::default_client();
2175
2176 match client.get_status().await {
2177 Ok(status) => {
2178 render_runtime_status(&status);
2179 }
2180 Err(_) => {
2181 println!(
2182 "{}",
2183 " ℹ Native Runtime: OFFLINE (Run 'aien start' to initialize)".yellow()
2184 );
2185 }
2186 }
2187
2188 println!("\n{}", "=== Hardware & Ancillary Services ===".cyan());
2189 let http_client = reqwest::Client::builder()
2190 .timeout(std::time::Duration::from_millis(500))
2191 .build()
2192 .unwrap_or_default();
2193
2194 let checks = [
2195 ("Model Seat", "http://127.0.0.1:18006/health", 18006),
2196 (
2197 "Cortex Memory Store",
2198 "http://127.0.0.1:18080/health",
2199 18080,
2200 ),
2201 (
2202 "Cortex ONNX Encoder",
2203 "http://127.0.0.1:18081/health",
2204 18081,
2205 ),
2206 (
2207 "Sovereign Glass Cockpit",
2208 "http://127.0.0.1:18095/api/pulse",
2209 18095,
2210 ),
2211 ("Matrix Conduit Federation", "http://127.0.0.1:6167", 6167),
2212 (
2213 "Sovereign Loopback Mail",
2214 "http://127.0.0.1:18092/health",
2215 2525,
2216 ),
2217 ];
2218
2219 for (name, url, port) in checks {
2220 let t0 = std::time::Instant::now();
2221 match http_client.get(url).send().await {
2222 Ok(resp) if resp.status().is_success() => {
2223 let elapsed = t0.elapsed().as_millis();
2224 println!(
2225 " ✓ {:<28} (Port {:<5}): {} ({} ms)",
2226 name.green(),
2227 port,
2228 "ONLINE".green().bold(),
2229 elapsed
2230 );
2231 }
2232 _ => {
2233 println!(
2234 " ℹ {:<28} (Port {:<5}): {}",
2235 name.yellow(),
2236 port,
2237 "STANDBY / OFFLINE".dimmed()
2238 );
2239 }
2240 }
2241 }
2242}
2243
2244pub async fn handle_swarm_command(args: &[String]) {
2245 let client = aien_runtime::client::AienRuntimeClient::default_client();
2246 if !client.is_alive().await {
2247 eprintln!(
2248 "{}",
2249 "Error: AIEN runtime is not running. Run 'aien start' first.".red()
2250 );
2251 return;
2252 }
2253
2254 if args.is_empty() || args[0] == "help" {
2255 println!("{}", "AIEN Swarm Management:".cyan().bold());
2256 println!(" aien swarm launch [--branches N] [--tokens M] [--prompt \"<text>\"]");
2257 println!(" aien swarm status");
2258 println!(" aien swarm inspect <ID>");
2259 println!(" aien swarm cancel <ID>");
2260 return;
2261 }
2262
2263 match args[0].as_str() {
2264 "launch" => {
2265 let mut branch_count = 16;
2266 let mut max_tokens = 32;
2267 let mut prompt_str = "Explain sovereign systems architecture".to_string();
2268
2269 let mut i = 1;
2270 while i < args.len() {
2271 match args[i].as_str() {
2272 "--branches" | "-b" if i + 1 < args.len() => {
2273 branch_count = args[i + 1].parse().unwrap_or(16);
2274 i += 2;
2275 }
2276 "--tokens" | "-t" if i + 1 < args.len() => {
2277 max_tokens = args[i + 1].parse().unwrap_or(32);
2278 i += 2;
2279 }
2280 "--prompt" | "-p" if i + 1 < args.len() => {
2281 prompt_str = args[i + 1].clone();
2282 i += 2;
2283 }
2284 _ => i += 1,
2285 }
2286 }
2287
2288 let prompt_tokens: Vec<u32> = prompt_str.bytes().map(|b| b as u32).collect();
2289 let req = aien_runtime::control::LaunchSwarmReq {
2290 model_handle: 1,
2291 branch_count,
2292 max_active_sequences: branch_count * 2,
2293 max_tokens_per_branch: max_tokens,
2294 root_world_id: 0,
2295 priority: 1,
2296 prompt_tokens,
2297 };
2298
2299 println!(
2300 "{}",
2301 format!(
2302 "🚀 Launching Swarm with {} branches sharing root World...",
2303 branch_count
2304 )
2305 .cyan()
2306 );
2307 match client.launch_swarm(req).await {
2308 Ok(swarm_id) => {
2309 println!(
2310 "{}",
2311 format!("✓ Swarm #{} launched successfully.", swarm_id)
2312 .green()
2313 .bold()
2314 );
2315 println!(
2316 "Use 'aien swarm inspect {}' or 'aien status' to monitor.",
2317 swarm_id
2318 );
2319 }
2320 Err(e) => eprintln!("Failed to launch swarm: {}", e),
2321 }
2322 }
2323 "inspect" if args.len() > 1 => {
2324 if let Ok(swarm_id) = args[1].parse::<u64>() {
2325 match client.inspect_swarm(swarm_id).await {
2326 Ok(status) => render_runtime_status(&status),
2327 Err(e) => eprintln!("Error inspecting swarm: {}", e),
2328 }
2329 } else {
2330 eprintln!("Invalid swarm ID: {}", args[1]);
2331 }
2332 }
2333 "cancel" if args.len() > 1 => {
2334 if let Ok(swarm_id) = args[1].parse::<u64>() {
2335 match client.cancel_swarm(swarm_id).await {
2336 Ok(()) => println!("{}", format!("✓ Swarm #{} cancelled.", swarm_id).green()),
2337 Err(e) => eprintln!("Error cancelling swarm: {}", e),
2338 }
2339 } else {
2340 eprintln!("Invalid swarm ID: {}", args[1]);
2341 }
2342 }
2343 "status" => {
2344 if let Ok(status) = client.get_status().await {
2345 render_runtime_status(&status);
2346 }
2347 }
2348 unknown => {
2349 eprintln!("Unknown swarm subcommand: {}", unknown);
2350 }
2351 }
2352}
2353
2354pub async fn handle_cockpit_command() {
2355 println!(
2356 "{}",
2357 "==================================================================".cyan()
2358 );
2359 println!(
2360 "{}",
2361 " ⚡ AIEN Sovereign Glass Terminal & Cockpit "
2362 .cyan()
2363 .bold()
2364 );
2365 println!(
2366 "{}",
2367 "==================================================================".cyan()
2368 );
2369 println!(" Local: http://127.0.0.1:18095");
2370 println!(" Mascot: AIEN Cosmic Monkey Warrior");
2371 println!(" Audio: Natural Voice Response Enabled");
2372 println!(
2373 "{}",
2374 "==================================================================".cyan()
2375 );
2376 let _ = std::process::Command::new("xdg-open")
2377 .arg("http://127.0.0.1:18095")
2378 .spawn();
2379}
2380
2381/// `aien harness` is not shipped in this release (sc#414 defect 2). It used to
2382/// call `spark-harness check`, a subcommand that never existed. The real
2383/// `spark-harness test` needs data files (workflows.json, evals.json) that the
2384/// installer does not copy, so nothing real backs this command on an installed
2385/// machine. It refuses, with a non-zero exit, instead of faking a pass.
2386pub fn harness_refusal_text() -> &'static str {
2387 "`aien harness` is not shipped in this release, so nothing was checked or certified. \
2388 Use `aien doctor` to probe this machine."
2389}
2390
2391pub async fn handle_harness_command() {
2392 eprintln!("{}", harness_refusal_text().red().bold());
2393 std::process::exit(1);
2394}
2395
2396pub async fn handle_aegis_command() {
2397 println!(
2398 "{}",
2399 "🛡️ Running Aegis Defensive Boundary Audit...".cyan().bold()
2400 );
2401 let status = std::process::Command::new("spark-aegis")
2402 .arg("audit")
2403 .status();
2404 match status {
2405 Ok(s) if s.success() => println!(
2406 "{}",
2407 "\n✓ Aegis Defense: Zero Disk Secrets & Boundary Secured."
2408 .green()
2409 .bold()
2410 ),
2411 _ => {
2412 println!("{}", "Auditing hardware TPM key vault directly...".yellow());
2413 let _ = std::process::Command::new("atlas-vault")
2414 .arg("list")
2415 .status();
2416 }
2417 }
2418}
2419
2420#[cfg(test)]
2421mod tests {
2422 use super::*;
2423
2424 #[test]
2425 fn cpu_only_switch_never_selects_gpu() {
2426 // GPU-capable build: refuses with the named error.
2427 let e = cpu_only_preflight(Some("cpu"), true).unwrap_err();
2428 assert!(e.starts_with(CPU_ONLY_REFUSAL), "{e}");
2429 assert!(cpu_only_preflight(Some(" CPU "), true).is_err());
2430 // Stub build: allowed, the CPU reference backend is then the only one possible.
2431 assert!(cpu_only_preflight(Some("cpu"), false).is_ok());
2432 // Not requested: unchanged behaviour.
2433 assert!(cpu_only_preflight(None, true).is_ok());
2434 assert!(cpu_only_preflight(Some("gpu"), true).is_ok());
2435 // AIEN_FORCE_CPU_STUB alone is not the switch.
2436 assert!(!cpu_only_requested(Some("1")));
2437 }
2438
2439 #[test]
2440 fn start_refusal_names_the_exact_command() {
2441 let t = start_refusal_text("no key at /x");
2442 assert!(t.contains("aien compose desk-key --create 1"), "{t}");
2443 assert!(t.contains("will not start"), "{t}");
2444 assert!(t.contains("no key at /x"), "{t}");
2445 }
2446
2447 #[test]
2448 fn harness_refuses_plainly_instead_of_faking_a_pass() {
2449 let t = harness_refusal_text();
2450 assert!(t.contains("not shipped in this release"), "{t}");
2451 assert!(!t.contains("PASS"), "{t}");
2452 }
2453
2454 #[test]
2455 fn strict_start_line_names_every_protection() {
2456 assert_eq!(
2457 strict_start_line(true, false, true, "omega-gb10"),
2458 "STRICT strict=true dev_fallback_build=false require_checkpoint=true backend=omega-gb10"
2459 );
2460 assert_eq!(
2461 strict_start_line(false, true, false, "ReferenceCpuBackend"),
2462 "STRICT strict=false dev_fallback_build=true require_checkpoint=false backend=ReferenceCpuBackend"
2463 );
2464 }
2465
2466 // ---- GB10 serving reservation: the daemon's start-up decision (sovereign-core#277) ----
2467
2468 fn qwen3_4b_config() -> aien_inference_abi::ModelConfig {
2469 let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2470 .join("../aien-inference-abi/fixtures/qwen3-4b-instruct-2507-config");
2471 let cfg = std::fs::read_to_string(dir.join("config.json")).unwrap();
2472 let gen = std::fs::read_to_string(dir.join("generation_config.json")).unwrap();
2473 aien_inference_abi::model_config_from_hf_json(
2474 "Qwen/Qwen3-4B-Instruct-2507",
2475 &cfg,
2476 Some(&gen),
2477 )
2478 .unwrap()
2479 }
2480
2481 use aien_inference_abi::gb10_serving::ServingOps;
2482 use std::cell::RefCell;
2483
2484 #[derive(Debug, Clone, PartialEq, Eq)]
2485 enum Ev {
2486 Reserve(aien_omega_gpu::ServingBounds),
2487 Prepare(u32, u32, u32),
2488 Seal,
2489 }
2490
2491 /// Records every omega call in order; `fail_prepare_at` makes that (0-based) prepare fail.
2492 struct Recorder {
2493 events: RefCell<Vec<Ev>>,
2494 fail_prepare_at: Option<usize>,
2495 refuse_reserve: bool,
2496 }
2497
2498 impl Recorder {
2499 fn new() -> Self {
2500 Recorder {
2501 events: RefCell::new(Vec::new()),
2502 fail_prepare_at: None,
2503 refuse_reserve: false,
2504 }
2505 }
2506 }
2507
2508 impl ServingOps for Recorder {
2509 fn reserve(&self, b: &aien_omega_gpu::ServingBounds) -> Result<(), String> {
2510 self.events.borrow_mut().push(Ev::Reserve(*b));
2511 if self.refuse_reserve {
2512 return Err("omega_gpu rc=-4 (CHIP_FAIL)".to_string());
2513 }
2514 Ok(())
2515 }
2516 fn prepare(&self, m: u32, k: u32, n: u32) -> Result<(), String> {
2517 let mut ev = self.events.borrow_mut();
2518 let nth = ev.iter().filter(|e| matches!(e, Ev::Prepare(..))).count();
2519 ev.push(Ev::Prepare(m, k, n));
2520 if self.fail_prepare_at == Some(nth) {
2521 return Err("omega_gpu rc=-4 (CHIP_FAIL)".to_string());
2522 }
2523 Ok(())
2524 }
2525 fn seal(&self) {
2526 self.events.borrow_mut().push(Ev::Seal);
2527 }
2528 }
2529
2530 fn run(
2531 rec: &Recorder,
2532 ctx: usize,
2533 native: bool,
2534 opted_in: bool,
2535 ) -> Result<Option<String>, String> {
2536 daemon_serving_reservation(
2537 &qwen3_4b_config(),
2538 ctx,
2539 &daemon_scheduler_config(),
2540 native,
2541 opted_in,
2542 rec,
2543 )
2544 }
2545
2546 #[test]
2547 fn opt_in_qwen3_gb10_reserves_prepares_every_shape_and_seals_in_order() {
2548 let cfg = qwen3_4b_config();
2549 // the plan the daemon builds (context capped like AIEN_KV_CONTEXT_TOKENS=2048)
2550 let plan = aien_runtime::shared_kv::plan_checked_model_kv(
2551 &cfg,
2552 Some(2048),
2553 &|| Ok(u64::MAX),
2554 false,
2555 )
2556 .unwrap();
2557 let rec = Recorder::new();
2558 let line = run(&rec, plan.context_tokens, true, true)
2559 .unwrap()
2560 .expect("reserved on the opt-in path");
2561 let ev = rec.events.borrow();
2562 // exactly one reserve, first, with bounds from the KV plan and the scheduler
2563 let Ev::Reserve(b) = &ev[0] else {
2564 panic!("the first omega call must be the reservation: {:?}", ev[0])
2565 };
2566 assert_eq!(ev.iter().filter(|e| matches!(e, Ev::Reserve(_))).count(), 1);
2567 assert_eq!(b.max_context, 2048, "from the KV plan");
2568 assert_eq!(b.max_rows, 256, "from the scheduler");
2569 assert_eq!(b.kernel_slots, 128);
2570 // every (rows 1..=256) x (shape from the model config) is prepared, each exactly once
2571 let shapes = aien_inference_abi::gb10_serving::serving_matmul_shapes(&cfg).unwrap();
2572 assert_eq!(shapes.len(), 6, "q, kv, o, gate/up, down, logits");
2573 assert!(
2574 shapes.contains(&(2560, cfg.vocab_size as u32)),
2575 "logits included"
2576 );
2577 let prepared: Vec<_> = ev
2578 .iter()
2579 .filter_map(|e| match e {
2580 Ev::Prepare(m, k, n) => Some((*m, *k, *n)),
2581 _ => None,
2582 })
2583 .collect();
2584 let want: std::collections::BTreeSet<_> = (1..=256u32)
2585 .flat_map(|m| shapes.iter().map(move |&(k, n)| (m, k, n)))
2586 .collect();
2587 assert_eq!(prepared.len(), 256 * 6);
2588 assert_eq!(
2589 prepared
2590 .iter()
2591 .copied()
2592 .collect::<std::collections::BTreeSet<_>>(),
2593 want
2594 );
2595 // seal is last: after all prepares, before serving can start
2596 assert_eq!(ev.last(), Some(&Ev::Seal));
2597 assert_eq!(ev.iter().filter(|e| **e == Ev::Seal).count(), 1);
2598 assert_eq!(ev.len(), 1 + 256 * 6 + 1);
2599 assert!(
2600 line.contains("prepared 1536 matmul kernel calls in"),
2601 "{line}"
2602 );
2603 assert!(
2604 line.starts_with("GB10_SERVING_RESERVATION reserved bytes="),
2605 "{line}"
2606 );
2607 }
2608
2609 #[test]
2610 fn a_refused_reservation_stops_the_daemon_by_name_before_any_prepare() {
2611 let mut rec = Recorder::new();
2612 rec.refuse_reserve = true;
2613 let err = run(&rec, 4096, true, true).unwrap_err();
2614 assert!(err.contains("GB10_SERVING_RESERVATION refused"), "{err}");
2615 assert!(
2616 err.contains("CHIP_FAIL") && err.contains("no on-demand fallback"),
2617 "{err}"
2618 );
2619 assert_eq!(
2620 rec.events.borrow().len(),
2621 1,
2622 "nothing after a refused reserve"
2623 );
2624 }
2625
2626 #[test]
2627 fn a_prepare_failure_is_the_same_named_refusal_and_never_seals() {
2628 let mut rec = Recorder::new();
2629 rec.fail_prepare_at = Some(7);
2630 let err = run(&rec, 4096, true, true).unwrap_err();
2631 assert!(err.contains("GB10_SERVING_RESERVATION refused"), "{err}");
2632 assert!(err.contains("matmul kernel prepare m="), "{err}");
2633 let ev = rec.events.borrow();
2634 assert_eq!(
2635 ev.len(),
2636 1 + 8,
2637 "reserve + 8 prepares, the 8th failed, stop"
2638 );
2639 assert!(!ev.contains(&Ev::Seal), "a failed start-up must not seal");
2640 }
2641
2642 #[test]
2643 fn default_path_makes_no_omega_call() {
2644 // Qwen3 switched off with AIEN_GB10_QWEN3_DECLARED_ATTEMPT=0
2645 let rec = Recorder::new();
2646 assert_eq!(run(&rec, 4096, true, false), Ok(None));
2647 // CPU daemon (no GB10 engine linked)
2648 assert_eq!(run(&rec, 4096, false, true), Ok(None));
2649 assert!(rec.events.borrow().is_empty());
2650 }
2651
2652 #[test]
2653 fn the_shared_scheduler_config_is_the_daemons() {
2654 let s = daemon_scheduler_config();
2655 assert_eq!((s.max_batch_size, s.prefill_chunk_size), (256, 128));
2656 }
2657
2658 #[test]
2659 fn model_identity_needs_real_weights_and_a_parsed_tokenizer() {
2660 let loaded = DaemonModelManifest {
2661 model_id: "m".into(),
2662 label: "l".into(),
2663 checkpoint_path: Some("/nonexistent/model.safetensors".into()),
2664 tokenizer_path: Some("/nonexistent/tokenizer.json".into()),
2665 fallback_reason: None,
2666 model_sha256: Some("aa".into()),
2667 model_digest_kind: Some("index+shards"),
2668 tokenizer_sha256: Some("bb".into()),
2669 };
2670 let id = model_identity(&loaded, true).expect("identity");
2671 assert_eq!(
2672 (id.model_sha256.as_str(), id.tokenizer_sha256.as_str()),
2673 ("aa", "bb")
2674 );
2675 assert_eq!(id.model_path, "/nonexistent/model.safetensors");
2676 assert_eq!(id.model_digest_kind, "index+shards");
2677 // No parsed tokenizer, no weights digest, or no tokenizer digest: no identity.
2678 assert!(model_identity(&loaded, false).is_none());
2679 for strip in [0, 1] {
2680 let mut m = DaemonModelManifest {
2681 model_sha256: loaded.model_sha256.clone(),
2682 model_digest_kind: loaded.model_digest_kind,
2683 tokenizer_sha256: loaded.tokenizer_sha256.clone(),
2684 checkpoint_path: loaded.checkpoint_path.clone(),
2685 tokenizer_path: loaded.tokenizer_path.clone(),
2686 model_id: "m".into(),
2687 label: "l".into(),
2688 fallback_reason: None,
2689 };
2690 if strip == 0 {
2691 m.model_sha256 = None;
2692 } else {
2693 m.tokenizer_sha256 = None;
2694 }
2695 assert!(model_identity(&m, true).is_none());
2696 }
2697 }
2698
2699 #[test]
2700 fn checkpoint_loaded_line_format_is_pinned() {
2701 // interplane#76 parses this line; the text must not drift.
2702 let line = checkpoint_loaded_label(
2703 std::path::Path::new("/m/dir"),
2704 true,
2705 "mid",
2706 "cfgid",
2707 true,
2708 "aaa",
2709 "bbb",
2710 );
2711 assert_eq!(
2712 line,
2713 "checkpoint loaded from /m/dir (tokenizer loaded, model_id=mid, config=cfgid (config.json), model_sha256=aaa, tokenizer_sha256=bbb)"
2714 );
2715 let line = checkpoint_loaded_label(
2716 std::path::Path::new("/m/dir"),
2717 false,
2718 "mid",
2719 "cfgid",
2720 false,
2721 "none",
2722 "none",
2723 );
2724 assert_eq!(
2725 line,
2726 "checkpoint loaded from /m/dir (tokenizer missing, model_id=mid, config=cfgid (built in), model_sha256=none, tokenizer_sha256=none)"
2727 );
2728 }
2729
2730 /// T4 launch budget: unset means the AIEN default 256 (not omega's 64),
2731 /// the log names it as the AIEN default with the evidence dir, and an
2732 /// explicit setting wins.
2733 #[test]
2734 fn daemon_cta_budget_defaults_to_1024_with_evidence() {
2735 let (b, source) = daemon_cta_budget(None);
2736 assert_eq!(b.get(), 1024);
2737 assert!(source.contains("AIEN default"), "{source}");
2738 assert!(
2739 source.contains("docs/inference/evidence/cta1024-20261012T0315Z"),
2740 "{source}"
2741 );
2742 let explicit = aien_omega_gpu::parse_cta_budget(Some("64"))
2743 .unwrap()
2744 .unwrap();
2745 let (b, source) = daemon_cta_budget(Some(explicit));
2746 assert_eq!(b.get(), 64);
2747 assert_eq!(source, "AIEN_OMEGA_CTA_BUDGET=64");
2748 }
2749
2750 /// On the CPU stub the helper never claims a budget it could not set and
2751 /// read back from omega, and names the value it tried.
2752 #[test]
2753 fn omega_cta_budget_helper_refuses_on_the_stub() {
2754 if aien_omega_gpu::is_native() {
2755 eprintln!(
2756 "native build: stub refusal check skipped (chip calls not made in unit tests)"
2757 );
2758 return;
2759 }
2760 let none = apply_omega_cta_budget(None).expect_err("stub cannot set the default");
2761 assert!(
2762 none.contains("Omega CTA budget 1024 (AIEN default"),
2763 "{none}"
2764 );
2765 assert!(none.contains("stub"), "{none}");
2766 let b = aien_omega_gpu::parse_cta_budget(Some("128"))
2767 .unwrap()
2768 .unwrap();
2769 let set = apply_omega_cta_budget(Some(b)).expect_err("stub cannot set a budget");
2770 assert!(set.contains("AIEN_OMEGA_CTA_BUDGET=128"), "{set}");
2771 }
2772
2773 #[tokio::test]
2774 async fn test_slash_command_adapter_suite() {
2775 // Test /adapter list
2776 let handled_list = handle_slash_command("/adapter list").await;
2777 assert!(handled_list);
2778
2779 // Test /adapter pr
2780 let handled_pr = handle_slash_command("/adapter pr candle-qwen2-5-coder-paged-kv").await;
2781 assert!(handled_pr);
2782
2783 // Test /adapter emit
2784 let handled_emit =
2785 handle_slash_command("/adapter emit candle-qwen2-5-coder-paged-kv").await;
2786 assert!(handled_emit);
2787
2788 // Test /adapter lattice
2789 let handled_lattice = handle_slash_command("/adapter lattice").await;
2790 assert!(handled_lattice);
2791 }
2792
2793 /// PE2E-C1 Step A probe (asserts nothing). Runs the daemon's real checkpoint
2794 /// resolve + load over the directory named by AIEN_VERIFY_MODELS_DIR (same scan
2795 /// as the daemon, no explicit path, flag off) and prints which file was chosen
2796 /// and whether reference weights were used.
2797 #[test]
2798 fn verify_daemon_checkpoint_resolution_probe() {
2799 let Ok(dir) = std::env::var("AIEN_VERIFY_MODELS_DIR") else {
2800 eprintln!("PROBE: AIEN_VERIFY_MODELS_DIR unset; nothing to probe");
2801 return;
2802 };
2803 let policy = CheckpointPolicy {
2804 scan_dirs: vec![std::path::PathBuf::from(&dir)],
2805 ..CheckpointPolicy::default()
2806 };
2807 let manifest = resolve_daemon_manifest_with(&policy);
2808 eprintln!(
2809 "PROBE: models_dir={} chosen_checkpoint={:?} tokenizer={:?} model_id={}",
2810 dir, manifest.checkpoint_path, manifest.tokenizer_path, manifest.model_id
2811 );
2812 let model = load_daemon_model(manifest, false).expect("flag off never errors");
2813 eprintln!(
2814 "PROBE: reference_weights_used={} weights_model_id={} tokenizer_loaded={} label={}",
2815 model.reference_weights,
2816 model.weights.config.model_id,
2817 model.tokenizer.is_some(),
2818 model.label
2819 );
2820 }
2821
2822 // ---- PE2E-C1 strict checkpoint tests ----
2823
2824 fn strict_policy(model_path: Option<std::path::PathBuf>) -> CheckpointPolicy {
2825 CheckpointPolicy {
2826 model_path,
2827 require_checkpoint: true,
2828 ..CheckpointPolicy::default()
2829 }
2830 }
2831
2832 /// Writes a tiny valid safetensors file whose only tensor is a BF16
2833 /// `model.embed_tokens.weight` of shape [4, 8]: parseable, but not TinyLlama-shaped.
2834 fn write_mismatched_safetensors(path: &std::path::Path) {
2835 let payload = vec![0u8; 4 * 8 * 2];
2836 let header = format!(
2837 "{{\"model.embed_tokens.weight\":{{\"dtype\":\"BF16\",\"shape\":[4,8],\"data_offsets\":[0,{}]}}}}",
2838 payload.len()
2839 );
2840 let mut bytes = (header.len() as u64).to_le_bytes().to_vec();
2841 bytes.extend_from_slice(header.as_bytes());
2842 bytes.extend_from_slice(&payload);
2843 std::fs::write(path, bytes).unwrap();
2844 std::fs::write(path.with_file_name("tokenizer.json"), b"{}").unwrap();
2845 }
2846
2847 #[test]
2848 fn checkpoint_policy_reads_explicit_paths_and_flag() {
2849 let env = |key: &str| match key {
2850 "AIEN_MODEL_PATH" => Some("/m/model.safetensors".to_string()),
2851 "AIEN_TOKENIZER_PATH" => Some("/t/tokenizer.json".to_string()),
2852 "AIEN_REQUIRE_CHECKPOINT" => Some("1".to_string()),
2853 "HOME" => Some("/h".to_string()),
2854 _ => None,
2855 };
2856 let policy = CheckpointPolicy::from_lookup(env);
2857 assert_eq!(
2858 policy.model_path.as_deref(),
2859 Some(std::path::Path::new("/m/model.safetensors"))
2860 );
2861 assert_eq!(
2862 policy.tokenizer_path.as_deref(),
2863 Some(std::path::Path::new("/t/tokenizer.json"))
2864 );
2865 assert!(policy.require_checkpoint);
2866 assert!(policy
2867 .scan_dirs
2868 .contains(&std::path::PathBuf::from("/h/models")));
2869
2870 let off = CheckpointPolicy::from_lookup(|key| {
2871 (key == "AIEN_REQUIRE_CHECKPOINT").then(|| "0".to_string())
2872 });
2873 assert!(!off.require_checkpoint);
2874 assert!(off.model_path.is_none());
2875 }
2876
2877 #[test]
2878 fn checkpoint_explicit_path_beats_directory_scan() {
2879 let scan = tempfile::tempdir().unwrap();
2880 let nested = scan.path().join("AAA-first");
2881 std::fs::create_dir(&nested).unwrap();
2882 write_mismatched_safetensors(&nested.join("model.safetensors"));
2883 let explicit = scan.path().join("chosen").join("model.safetensors");
2884 let policy = CheckpointPolicy {
2885 model_path: Some(explicit.clone()),
2886 scan_dirs: vec![scan.path().to_path_buf()],
2887 ..CheckpointPolicy::default()
2888 };
2889 let manifest = resolve_daemon_manifest_with(&policy);
2890 assert_eq!(manifest.checkpoint_path, Some(explicit.clone()));
2891 assert_eq!(
2892 manifest.tokenizer_path,
2893 Some(explicit.with_file_name("tokenizer.json"))
2894 );
2895 }
2896
2897 #[test]
2898 fn strict_checkpoint_refuses_missing_file() {
2899 let dir = tempfile::tempdir().unwrap();
2900 let missing = dir.path().join("absent.safetensors");
2901 let policy = strict_policy(Some(missing.clone()));
2902 let manifest = resolve_daemon_manifest_with(&policy);
2903 let err = load_daemon_model(manifest, policy.require_checkpoint)
2904 .err()
2905 .expect("missing checkpoint under AIEN_REQUIRE_CHECKPOINT must be an error");
2906 assert!(err.contains("AIEN_REQUIRE_CHECKPOINT=1"), "{err}");
2907 assert!(err.contains(&missing.display().to_string()), "{err}");
2908 }
2909
2910 #[test]
2911 fn strict_checkpoint_refuses_shape_mismatch() {
2912 let dir = tempfile::tempdir().unwrap();
2913 let path = dir.path().join("model.safetensors");
2914 write_mismatched_safetensors(&path);
2915 let policy = strict_policy(Some(path.clone()));
2916 let manifest = resolve_daemon_manifest_with(&policy);
2917 let err = load_daemon_model(manifest, policy.require_checkpoint)
2918 .err()
2919 .expect("mis-shaped checkpoint under AIEN_REQUIRE_CHECKPOINT must be an error");
2920 assert!(err.contains(&path.display().to_string()), "{err}");
2921 assert!(err.contains("model.embed_tokens.weight"), "{err}");
2922 }
2923
2924 #[test]
2925 fn strict_checkpoint_refuses_scan_mismatch() {
2926 // Directory scan picks a non-TinyLlama checkpoint (the Qwen-first case).
2927 let dir = tempfile::tempdir().unwrap();
2928 let nested = dir.path().join("Qwen-like");
2929 std::fs::create_dir(&nested).unwrap();
2930 let path = nested.join("model.safetensors");
2931 write_mismatched_safetensors(&path);
2932 let policy = CheckpointPolicy {
2933 scan_dirs: vec![dir.path().to_path_buf()],
2934 require_checkpoint: true,
2935 ..CheckpointPolicy::default()
2936 };
2937 let manifest = resolve_daemon_manifest_with(&policy);
2938 assert_eq!(manifest.checkpoint_path, Some(path.clone()));
2939 let err = load_daemon_model(manifest, true)
2940 .err()
2941 .expect("scan finding a non-matching checkpoint must be an error under the flag");
2942 assert!(err.contains(&path.display().to_string()), "{err}");
2943 }
2944
2945 #[test]
2946 fn strict_checkpoint_refuses_empty_scan() {
2947 let dir = tempfile::tempdir().unwrap();
2948 let policy = CheckpointPolicy {
2949 scan_dirs: vec![dir.path().to_path_buf()],
2950 require_checkpoint: true,
2951 ..CheckpointPolicy::default()
2952 };
2953 let manifest = resolve_daemon_manifest_with(&policy);
2954 assert!(manifest.checkpoint_path.is_none());
2955 let err = load_daemon_model(manifest, true)
2956 .err()
2957 .expect("empty scan must be an error under the flag");
2958 assert!(err.contains(&dir.path().display().to_string()), "{err}");
2959 }
2960
2961 #[test]
2962 fn checkpoint_fallback_without_flag_is_reported() {
2963 let dir = tempfile::tempdir().unwrap();
2964 let missing = dir.path().join("absent.safetensors");
2965 let policy = CheckpointPolicy {
2966 model_path: Some(missing.clone()),
2967 ..CheckpointPolicy::default()
2968 };
2969 let manifest = resolve_daemon_manifest_with(&policy);
2970 let model = load_daemon_model(manifest, false).expect("flag off degrades");
2971 assert!(model.reference_weights);
2972 assert!(model.manifest.model_sha256.is_none());
2973 assert!(
2974 model.label.contains(&missing.display().to_string()),
2975 "{}",
2976 model.label
2977 );
2978 }
2979
2980 /// Copies the tiny Qwen3 fixture into `dir` as two shards plus a
2981 /// `model.safetensors.index.json` (tensors split by sorted name, half each).
2982 fn write_two_shard_qwen3_tiny(dir: &std::path::Path) -> std::path::PathBuf {
2983 let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2984 .join("../aien-inference-abi/fixtures/qwen3-tiny");
2985 std::fs::copy(fixture.join("config.json"), dir.join("config.json")).unwrap();
2986 let bytes = std::fs::read(fixture.join("model.safetensors")).unwrap();
2987 let header_len = u64::from_le_bytes(bytes[..8].try_into().unwrap()) as usize;
2988 let header: serde_json::Map<String, serde_json::Value> =
2989 serde_json::from_slice(&bytes[8..8 + header_len]).unwrap();
2990 let data = &bytes[8 + header_len..];
2991 let mut names: Vec<&String> = header.keys().filter(|k| *k != "__metadata__").collect();
2992 names.sort();
2993 let (first, second) = names.split_at(names.len() / 2);
2994 let mut weight_map = serde_json::Map::new();
2995 for (file, part) in [
2996 ("model-00001-of-00002.safetensors", first),
2997 ("model-00002-of-00002.safetensors", second),
2998 ] {
2999 let mut shard_header = serde_json::Map::new();
3000 let mut payload = Vec::new();
3001 for name in part {
3002 let mut info = header[*name].clone();
3003 let offsets = info["data_offsets"].as_array().unwrap();
3004 let (a, b) = (
3005 offsets[0].as_u64().unwrap() as usize,
3006 offsets[1].as_u64().unwrap() as usize,
3007 );
3008 let start = payload.len();
3009 payload.extend_from_slice(&data[a..b]);
3010 info["data_offsets"] = serde_json::json!([start, payload.len()]);
3011 shard_header.insert((*name).clone(), info);
3012 weight_map.insert((*name).clone(), serde_json::json!(file));
3013 }
3014 let text = serde_json::Value::Object(shard_header).to_string();
3015 let mut out = (text.len() as u64).to_le_bytes().to_vec();
3016 out.extend_from_slice(text.as_bytes());
3017 out.extend_from_slice(&payload);
3018 std::fs::write(dir.join(file), out).unwrap();
3019 }
3020 let index = dir.join("model.safetensors.index.json");
3021 std::fs::write(
3022 &index,
3023 serde_json::json!({"metadata": {}, "weight_map": weight_map}).to_string(),
3024 )
3025 .unwrap();
3026 index
3027 }
3028
3029 fn file_sha(path: &std::path::Path) -> String {
3030 use sha2::{Digest, Sha256};
3031 hex::encode(Sha256::digest(std::fs::read(path).unwrap()))
3032 }
3033
3034 /// sc#338: a sharded checkpoint's `model_sha256` binds the index AND every
3035 /// shard it names (the documented manifest form), not the index alone; a
3036 /// changed shard under the same index changes it.
3037 #[test]
3038 fn a_sharded_checkpoint_digest_binds_every_shard() {
3039 use sha2::{Digest, Sha256};
3040 let dir = tempfile::tempdir().unwrap();
3041 let index = write_two_shard_qwen3_tiny(dir.path());
3042 let load = || {
3043 let policy = CheckpointPolicy {
3044 model_path: Some(index.clone()),
3045 ..CheckpointPolicy::default()
3046 };
3047 let model = load_daemon_model(resolve_daemon_manifest_with(&policy), false)
3048 .expect("the two-shard fixture loads");
3049 assert!(!model.reference_weights, "{}", model.label);
3050 model
3051 };
3052 let model = load();
3053 assert_eq!(model.manifest.model_digest_kind, Some("index+shards"));
3054 let shard = |n| {
3055 dir.path()
3056 .join(format!("model-0000{n}-of-00002.safetensors"))
3057 };
3058 let expected = hex::encode(Sha256::digest(format!(
3059 "aien-checkpoint-digest v1\nindex {}\n{} model-00001-of-00002.safetensors\n{} model-00002-of-00002.safetensors\n",
3060 file_sha(&index),
3061 file_sha(&shard(1)),
3062 file_sha(&shard(2)),
3063 )));
3064 let digest = model.manifest.model_sha256.clone().unwrap();
3065 assert_eq!(digest, expected);
3066 assert_ne!(digest, file_sha(&index), "not the index alone");
3067 let line = model
3068 .shards_line
3069 .clone()
3070 .expect("a sharded load logs its shards");
3071 assert_eq!(
3072 line,
3073 format!(
3074 "CHECKPOINT_SHARDS model_sha256={digest} model_digest_kind=index+shards index_sha256={} shards=[model-00001-of-00002.safetensors:{},model-00002-of-00002.safetensors:{}]",
3075 file_sha(&index),
3076 file_sha(&shard(1)),
3077 file_sha(&shard(2)),
3078 )
3079 );
3080 // The "checkpoint loaded" line keeps its pinned form and carries the new digest.
3081 assert!(
3082 model.label.contains(&format!("model_sha256={digest},")),
3083 "{}",
3084 model.label
3085 );
3086
3087 // Change one weight byte in the second shard, same index: a new digest.
3088 let mut bytes = std::fs::read(shard(2)).unwrap();
3089 let last = bytes.len() - 1;
3090 bytes[last] ^= 0x01;
3091 std::fs::write(shard(2), bytes).unwrap();
3092 let changed = load().manifest.model_sha256.unwrap();
3093 assert_ne!(changed, digest, "a changed shard must change the digest");
3094 }
3095
3096 #[test]
3097 fn checkpoint_digest_refuses_index_escape_before_hashing() {
3098 let dir = tempfile::tempdir().unwrap();
3099 let model = dir.path().join("model");
3100 std::fs::create_dir(&model).unwrap();
3101 std::fs::write(dir.path().join("outside.safetensors"), b"fixture").unwrap();
3102 let index = model.join("model.safetensors.index.json");
3103 std::fs::write(&index, r#"{"weight_map":{"w":"../outside.safetensors"}}"#).unwrap();
3104 assert!(checkpoint_digest(&index).is_err());
3105 }
3106
3107 /// sc#338 review: the digest changes no refusal. A model directory as the
3108 /// checkpoint path is still refused (as when the path itself was hashed),
3109 /// and an index naming no shard is refused, with the path named once.
3110 #[test]
3111 fn a_directory_or_an_index_without_shards_is_still_refused() {
3112 let dir = tempfile::tempdir().unwrap();
3113 write_two_shard_qwen3_tiny(dir.path());
3114 let err = load_daemon_model(
3115 resolve_daemon_manifest_with(&strict_policy(Some(dir.path().to_path_buf()))),
3116 true,
3117 )
3118 .err()
3119 .expect("a directory path is refused");
3120 assert!(err.contains("AIEN_REQUIRE_CHECKPOINT=1"), "{err}");
3121 assert!(err.contains("is a directory"), "{err}");
3122
3123 let empty = tempfile::tempdir().unwrap();
3124 let index = empty.path().join("model.safetensors.index.json");
3125 std::fs::write(&index, r#"{"weight_map":{}}"#).unwrap();
3126 let err = load_daemon_model(
3127 resolve_daemon_manifest_with(&strict_policy(Some(index.clone()))),
3128 true,
3129 )
3130 .err()
3131 .expect("an index without shards is refused");
3132 assert!(err.contains("names no shard"), "{err}");
3133 assert_eq!(
3134 err.matches(&index.display().to_string()).count(),
3135 1,
3136 "{err}"
3137 );
3138 }
3139
3140 /// sc#338: a single safetensors file keeps `model_sha256` = the file's own
3141 /// sha256 (`model_digest_kind` = `file`) and logs no shard line.
3142 #[test]
3143 fn a_single_file_checkpoint_digest_is_the_file_sha256() {
3144 let dir = tempfile::tempdir().unwrap();
3145 let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
3146 .join("../aien-inference-abi/fixtures/qwen3-tiny");
3147 for f in ["config.json", "model.safetensors"] {
3148 std::fs::copy(fixture.join(f), dir.path().join(f)).unwrap();
3149 }
3150 let path = dir.path().join("model.safetensors");
3151 let policy = CheckpointPolicy {
3152 model_path: Some(path.clone()),
3153 ..CheckpointPolicy::default()
3154 };
3155 let model = load_daemon_model(resolve_daemon_manifest_with(&policy), false).unwrap();
3156 assert!(!model.reference_weights, "{}", model.label);
3157 assert_eq!(model.manifest.model_digest_kind, Some("file"));
3158 assert_eq!(model.manifest.model_sha256, Some(file_sha(&path)));
3159 assert_eq!(model.shards_line, None);
3160 }
3161
3162 /// Real-checkpoint proof. Ignored in plain `cargo test`; the forge runs it with
3163 /// `--include-ignored`, and then an unset AIEN_E2E_CHECKPOINT is a FAILURE, not a skip.
3164 #[test]
3165 #[ignore = "needs AIEN_E2E_CHECKPOINT (TinyLlama dir or model.safetensors); forge runs it"]
3166 fn strict_checkpoint_real_tinyllama_loads() {
3167 use sha2::{Digest, Sha256};
3168 let raw = std::env::var("AIEN_E2E_CHECKPOINT")
3169 .expect("AIEN_E2E_CHECKPOINT must point at the TinyLlama checkpoint");
3170 let mut model_path = std::path::PathBuf::from(raw);
3171 if model_path.is_dir() {
3172 model_path = model_path.join("model.safetensors");
3173 }
3174 let policy = strict_policy(Some(model_path.clone()));
3175 let manifest = resolve_daemon_manifest_with(&policy);
3176 let model = load_daemon_model(manifest, true).expect("real TinyLlama must load");
3177 assert!(!model.reference_weights);
3178 assert_eq!(
3179 model.weights.config.model_id,
3180 aien_inference_abi::ModelConfig::tinyllama_1_1b().model_id
3181 );
3182 assert!(model.tokenizer.is_some());
3183
3184 let model_sha = model.manifest.model_sha256.clone().expect("model digest");
3185 assert_eq!(model_sha.len(), 64);
3186 assert!(model_sha.chars().all(|c| c.is_ascii_hexdigit()));
3187 let expected = hex::encode(Sha256::digest(std::fs::read(&model_path).unwrap()));
3188 assert_eq!(model_sha, expected);
3189
3190 let tokenizer_path = model_path.with_file_name("tokenizer.json");
3191 let tokenizer_sha = model
3192 .manifest
3193 .tokenizer_sha256
3194 .clone()
3195 .expect("tokenizer digest");
3196 let expected = hex::encode(Sha256::digest(std::fs::read(&tokenizer_path).unwrap()));
3197 assert_eq!(tokenizer_sha, expected);
3198 }
3199}