interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / spark-cockpit-rs / src / main.rs

4141 lines · 140799 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
16mod access;
17
18use axum::{
19 Router,
20 extract::{
21 ConnectInfo, Query, State,
22 ws::{Message, WebSocket, WebSocketUpgrade},
23 },
24 http::{HeaderMap, StatusCode},
25 response::{
26 Html, IntoResponse, Json, Response,
27 sse::{Event, KeepAlive, Sse},
28 },
29 routing::{get, post},
30};
31use chrono::Utc;
32use futures_util::{SinkExt, StreamExt};
33use portable_pty::{CommandBuilder, PtySize, native_pty_system};
34use regex::Regex;
35use serde::{Deserialize, Serialize};
36use serde_json::{Value, json};
37use std::collections::HashSet;
38use std::convert::Infallible;
39use std::fs;
40use std::io::{Read, Write};
41use std::net::SocketAddr;
42use std::path::{Path, PathBuf};
43use std::sync::Arc;
44use std::time::{Duration, Instant};
45use tokio::process::Command;
46use tower_http::services::ServeDir;
47
48const SEAT_URL: &str = "http://127.0.0.1:18006";
49const CORTEX_URL: &str = "http://127.0.0.1:18080";
50const CONDUIT_URL: &str = "http://127.0.0.1:6167";
51const WORKSHOP_HTML: &str = include_str!("../static/workshop.html");
52fn get_home_dir() -> PathBuf {
53 std::env::var("HOME")
54 .or_else(|_| std::env::var("USERPROFILE"))
55 .map(PathBuf::from)
56 .unwrap_or_else(|_| PathBuf::from("."))
57}
58
59fn goals_path() -> PathBuf {
60 if let Ok(p) = std::env::var("AIEN_GOALS_PATH") {
61 PathBuf::from(p)
62 } else {
63 get_home_dir().join("basecamp/goals.json")
64 }
65}
66
67fn skills_dir() -> PathBuf {
68 if let Ok(p) = std::env::var("AIEN_SKILLS_DIR") {
69 PathBuf::from(p)
70 } else {
71 get_home_dir().join("skills")
72 }
73}
74
75fn static_dir() -> PathBuf {
76 if let Ok(p) = std::env::var("SPARK_COCKPIT_STATIC") {
77 PathBuf::from(p)
78 } else if Path::new("static").exists() {
79 PathBuf::from("static")
80 } else if Path::new("crates/spark-cockpit-rs/static").exists() {
81 PathBuf::from("crates/spark-cockpit-rs/static")
82 } else {
83 get_home_dir().join("spark-cockpit/static")
84 }
85}
86
87#[derive(Debug, Clone, Serialize, Deserialize)]
88pub struct SwarmTask {
89 pub id: String,
90 #[serde(skip_serializing_if = "Option::is_none")]
91 pub project: Option<String>,
92 pub role: String,
93 pub prompt: String,
94 #[serde(default = "default_swarm_model")]
95 pub model: String,
96 #[serde(skip_serializing_if = "Option::is_none")]
97 pub ring: Option<u8>,
98 pub state: String,
99 pub created_at: String,
100 pub updated_at: String,
101 #[serde(skip_serializing_if = "Option::is_none")]
102 pub completed_at: Option<String>,
103 #[serde(default)]
104 pub thought_trace: Vec<String>,
105 #[serde(default)]
106 pub logs: Vec<String>,
107 #[serde(skip_serializing_if = "Option::is_none")]
108 pub error: Option<String>,
109 #[serde(skip_serializing_if = "Option::is_none")]
110 pub pid: Option<u32>,
111}
112
113fn default_swarm_model() -> String {
114 "atlas-lightning-omni".to_string()
115}
116
117pub struct SwarmRegistry {
118 tasks: std::sync::RwLock<Vec<SwarmTask>>,
119 journal_path: Option<PathBuf>,
120}
121
122impl SwarmRegistry {
123 pub fn new_persistent(journal_path: PathBuf) -> Self {
124 let mut loaded_tasks = Vec::new();
125 if journal_path.exists()
126 && let Ok(content) = fs::read_to_string(&journal_path)
127 && let Ok(parsed) = serde_json::from_str::<Vec<SwarmTask>>(&content)
128 {
129 loaded_tasks = parsed;
130 }
131 if loaded_tasks.is_empty() {
132 let subagent_dir = get_home_dir().join("basecamp/sessions/subagents");
133 if let Ok(entries) = fs::read_dir(subagent_dir) {
134 for entry in entries.flatten() {
135 let path = entry.path();
136 if path.extension().and_then(|s| s.to_str()) == Some("json")
137 && let Ok(content) = fs::read_to_string(&path)
138 && let Ok(val) = serde_json::from_str::<Value>(&content)
139 {
140 let id = val
141 .get("id")
142 .or_else(|| val.get("task_id"))
143 .and_then(Value::as_str)
144 .unwrap_or("subagent")
145 .to_string();
146 let role = val
147 .get("role")
148 .and_then(Value::as_str)
149 .unwrap_or("Worker")
150 .to_string();
151 let prompt = val
152 .get("prompt")
153 .or_else(|| val.get("instruction"))
154 .and_then(Value::as_str)
155 .unwrap_or("Autonomous task")
156 .to_string();
157 let state = val
158 .get("state")
159 .or_else(|| val.get("status"))
160 .and_then(Value::as_str)
161 .unwrap_or("completed")
162 .to_string();
163 loaded_tasks.push(SwarmTask {
164 id,
165 project: Some("sovereign-core".to_string()),
166 role,
167 prompt,
168 model: "atlas-lightning-omni".to_string(),
169 ring: Some(1),
170 state,
171 created_at: Utc::now().to_rfc3339(),
172 updated_at: Utc::now().to_rfc3339(),
173 completed_at: Some(Utc::now().to_rfc3339()),
174 thought_trace: vec![
175 "Task synchronized from session history.".to_string(),
176 ],
177 logs: vec!["Loaded from basecamp session snapshot.".to_string()],
178 error: None,
179 pid: None,
180 });
181 }
182 }
183 }
184 }
185 let registry = Self {
186 tasks: std::sync::RwLock::new(loaded_tasks),
187 journal_path: Some(journal_path),
188 };
189 registry.save();
190 registry
191 }
192
193 pub fn new_in_memory() -> Self {
194 Self {
195 tasks: std::sync::RwLock::new(Vec::new()),
196 journal_path: None,
197 }
198 }
199
200 fn save(&self) {
201 if let Some(ref path) = self.journal_path {
202 if let Some(parent) = path.parent() {
203 let _ = fs::create_dir_all(parent);
204 }
205 if let Ok(tasks) = self.tasks.read()
206 && let Ok(serialized) = serde_json::to_string_pretty(&*tasks)
207 {
208 let _ = fs::write(path, serialized);
209 }
210 }
211 }
212
213 pub fn list(&self) -> Vec<SwarmTask> {
214 self.tasks.read().map(|t| t.clone()).unwrap_or_default()
215 }
216
217 pub fn spawn(
218 &self,
219 project: Option<String>,
220 role: String,
221 prompt: String,
222 model: Option<String>,
223 ring: Option<u8>,
224 ) -> SwarmTask {
225 let task_id = format!("task-{}", Utc::now().timestamp_micros());
226 let now = Utc::now().to_rfc3339();
227 let selected_model = model.unwrap_or_else(default_swarm_model);
228 let selected_ring = ring.unwrap_or(1);
229
230 let task = SwarmTask {
231 id: task_id,
232 project: project.clone(),
233 role: role.clone(),
234 prompt: prompt.clone(),
235 model: selected_model,
236 ring: Some(selected_ring),
237 state: "running".to_string(),
238 created_at: now.clone(),
239 updated_at: now.clone(),
240 completed_at: None,
241 thought_trace: vec![
242 format!("Agent [{role}] initialized under Ring {selected_ring}."),
243 format!(
244 "Targeting project: {}.",
245 project.as_deref().unwrap_or("sovereign-core")
246 ),
247 "Analyzing workspace state, invariants, and instructions...".to_string(),
248 ],
249 logs: vec![
250 format!("[{now}] Worker spawned: role={role}, ring={selected_ring}"),
251 format!("[{now}] Prompt: {prompt}"),
252 ],
253 error: None,
254 pid: None,
255 };
256
257 if let Ok(mut lock) = self.tasks.write() {
258 lock.insert(0, task.clone());
259 }
260 self.save();
261 task
262 }
263
264 pub fn kill(&self, task_id: &str) -> bool {
265 let mut modified = false;
266 if let Ok(mut lock) = self.tasks.write() {
267 for task in lock.iter_mut() {
268 if task.id == task_id {
269 task.state = "cancelled".to_string();
270 let now = Utc::now().to_rfc3339();
271 task.updated_at = now.clone();
272 task.completed_at = Some(now.clone());
273 task.logs
274 .push(format!("[{now}] Task cancelled by operator kill signal."));
275 task.thought_trace
276 .push("Execution terminated by operator signal.".to_string());
277 modified = true;
278 break;
279 }
280 }
281 }
282 if modified {
283 self.save();
284 }
285 modified
286 }
287}
288
289#[derive(Clone)]
290struct AppState {
291 client: reqwest::Client,
292 start_time: Instant,
293 redactor_patterns: Arc<Vec<(Regex, &'static str)>>,
294 hive_store: Arc<spark_hive::CombStore>,
295 swarm_registry: Arc<SwarmRegistry>,
296 distill_engine: Arc<spark_adapters::DistillationEngine>,
297}
298
299fn build_patterns() -> Vec<(Regex, &'static str)> {
300 vec![
301 (
302 Regex::new(
303 r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----",
304 )
305 .unwrap(),
306 "[REDACTED_BY_ATLAS_VAULT]",
307 ),
308 (
309 Regex::new(r"\b(ey[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})\b")
310 .unwrap(),
311 "[REDACTED_BY_ATLAS_VAULT]",
312 ),
313 (
314 Regex::new(r"(?i)\b(bearer\s+)([a-zA-Z0-9_\-\.\s]{12,})").unwrap(),
315 "$1[REDACTED_BY_ATLAS_VAULT]",
316 ),
317 (
318 Regex::new(r"(?i)(api[_-]?key|secret|password|passwd|token)\s*[:=]\s*([^\s,;]{8,})")
319 .unwrap(),
320 "$1=[REDACTED_BY_ATLAS_VAULT]",
321 ),
322 (
323 Regex::new(r"\b(sk-[a-zA-Z0-9_-]{20,})\b").unwrap(),
324 "[REDACTED_BY_ATLAS_VAULT]",
325 ),
326 (
327 Regex::new(r"\b(sk-ant-[a-zA-Z0-9_-]{20,})\b").unwrap(),
328 "[REDACTED_BY_ATLAS_VAULT]",
329 ),
330 (
331 Regex::new(r"\b(hf_[a-zA-Z0-9]{20,})\b").unwrap(),
332 "[REDACTED_BY_ATLAS_VAULT]",
333 ),
334 ]
335}
336
337fn unslop_clean(s: &str) -> String {
338 // Replace em dashes and en dashes with standard punctuation
339 s.replace('—', ", ").replace('–', "-")
340}
341
342struct StreamRedactor {
343 buffer: String,
344 patterns: Arc<Vec<(Regex, &'static str)>>,
345 delimiters: HashSet<char>,
346}
347
348impl StreamRedactor {
349 fn new(patterns: Arc<Vec<(Regex, &'static str)>>) -> Self {
350 let mut delimiters = HashSet::new();
351 for c in " \n\r\t`'\"()[]{}<>,;:".chars() {
352 delimiters.insert(c);
353 }
354 Self {
355 buffer: String::new(),
356 patterns,
357 delimiters,
358 }
359 }
360
361 fn feed(&mut self, chunk: &str) -> String {
362 self.buffer.push_str(chunk);
363 let mut last_delim = None;
364 for (i, c) in self.buffer.char_indices() {
365 if self.delimiters.contains(&c) {
366 last_delim = Some(i + c.len_utf8());
367 }
368 }
369
370 if let Some(pos) = last_delim {
371 let ready = &self.buffer[..pos];
372 let redacted = self.redact(ready);
373 self.buffer = self.buffer[pos..].to_string();
374 redacted
375 } else {
376 String::new()
377 }
378 }
379
380 fn flush(&mut self) -> String {
381 let remainder = std::mem::take(&mut self.buffer);
382 self.redact(&remainder)
383 }
384
385 fn redact(&self, text: &str) -> String {
386 let mut result = text.to_string();
387 for (pat, repl) in self.patterns.iter() {
388 result = pat.replace_all(&result, *repl).to_string();
389 }
390 unslop_clean(&result)
391 }
392}
393
394fn get_cortex_token() -> Option<String> {
395 spark_adapters::vault::resolve_secret("CORTEX_TOKEN")
396}
397
398fn artifacts_dir() -> PathBuf {
399 if let Ok(p) = std::env::var("SPARK_COCKPIT_ARTIFACTS") {
400 PathBuf::from(p)
401 } else if Path::new("artifacts").exists() {
402 PathBuf::from("artifacts")
403 } else {
404 get_home_dir().join("spark-cockpit/artifacts")
405 }
406}
407
408async fn handle_get_feed(State(state): State<AppState>) -> Json<Value> {
409 let mut items = Vec::new();
410
411 items.push(json!({
412 "id": "feed-allen-init",
413 "category": "agent",
414 "title": "ALLEN harness running on the Spark",
415 "summary": "The harness is reachable. The model seat state and the Spark judge's verdict are on the chat welcome, each read live.",
416 "timestamp": Utc::now().to_rfc3339(),
417 "action_label": "Inspect Telemetry",
418 "action_target": "terminal",
419 "badge": "ONLINE"
420 }));
421
422 let goals_val = handle_get_goals().await.0;
423 if let Some(goals) = goals_val.get("goals").and_then(Value::as_array)
424 && !goals.is_empty()
425 {
426 items.push(json!({
427 "id": "feed-goals",
428 "category": "goals",
429 "title": format!("{} Active Project Goals", goals.len()),
430 "summary": "Tracking autonomous milestone delivery across sovereign engineering tracks.",
431 "timestamp": Utc::now().to_rfc3339(),
432 "action_label": "Review Goals",
433 "action_target": "goals",
434 "badge": "TRACKED"
435 }));
436 }
437
438 let swarm_tasks = state.swarm_registry.list();
439 let running_count = swarm_tasks.iter().filter(|t| t.state == "running").count();
440 let complete_count = swarm_tasks
441 .iter()
442 .filter(|t| t.state == "completed")
443 .count();
444
445 items.push(json!({
446 "id": "feed-swarm",
447 "category": "swarm",
448 "title": "Autonomous Swarm Telemetry",
449 "summary": format!("Swarm tasks: {} running, {} completed. Zero interpreter overhead across active ring boundaries.", running_count, complete_count),
450 "timestamp": Utc::now().to_rfc3339(),
451 "action_label": "View Tasks",
452 "action_target": "feed",
453 "badge": if running_count > 0 { "ACTIVE" } else { "IDLE" }
454 }));
455
456 items.push(json!({
457 "id": "feed-cortex-sync",
458 "category": "memory",
459 "title": "Cortex Memory Consolidation",
460 "summary": "Spark Cortex space 'atlas-memory' actively ingesting verified heuristics and operational post-mortems.",
461 "timestamp": Utc::now().to_rfc3339(),
462 "action_label": "Explore Memories",
463 "action_target": "memory",
464 "badge": "SYNCED"
465 }));
466
467 Json(json!({
468 "status": "ok",
469 "feed": items,
470 "generated_at": Utc::now().to_rfc3339()
471 }))
472}
473
474/// sovereign-core #380 (done-when 4): the approval desk (`aien compose
475/// authorize`, desk-key MAC) is the only issuer of approvals. The cockpit
476/// holds none, so it never shows an approval the desk did not issue.
477const APPROVALS_ISSUER: &str = "the approval desk (aien compose authorize)";
478
479async fn handle_get_approvals() -> Json<Value> {
480 Json(json!({
481 "status": "ok",
482 "approvals": [],
483 "issuer": APPROVALS_ISSUER,
484 "note": "The cockpit holds no approvals. The approval desk issues them."
485 }))
486}
487
488/// Every resolve is refused by name: approving here would grant nothing.
489async fn handle_resolve_approval(
490 axum::extract::Path(id): axum::extract::Path<String>,
491) -> (StatusCode, Json<Value>) {
492 (
493 StatusCode::CONFLICT,
494 Json(json!({
495 "status": "error",
496 "refusal": "NotTheDesk",
497 "id": id,
498 "message": format!("The cockpit does not approve or reject. Use {APPROVALS_ISSUER}."),
499 })),
500 )
501}
502
503async fn handle_list_artifacts() -> Json<Value> {
504 let mut list = Vec::new();
505 if let Ok(entries) = fs::read_dir(artifacts_dir()) {
506 for entry in entries.flatten() {
507 let path = entry.path();
508 if path.is_file() {
509 let name = path
510 .file_name()
511 .unwrap_or_default()
512 .to_string_lossy()
513 .to_string();
514 let ext = path
515 .extension()
516 .unwrap_or_default()
517 .to_string_lossy()
518 .to_string();
519 let size = entry.metadata().map(|m| m.len()).unwrap_or(0);
520 list.push(json!({
521 "id": name,
522 "title": name,
523 "ext": ext,
524 "size": size,
525 "url": format!("/artifacts/{}", name)
526 }));
527 }
528 }
529 }
530 Json(json!({ "artifacts": list }))
531}
532
533async fn handle_get_artifact(
534 axum::extract::Path(filename): axum::extract::Path<String>,
535) -> Response {
536 let safe_name = Path::new(&filename)
537 .file_name()
538 .unwrap_or_default()
539 .to_string_lossy()
540 .to_string();
541 let file_path = artifacts_dir().join(safe_name);
542 if !file_path.exists() {
543 return (StatusCode::NOT_FOUND, "Artifact not found").into_response();
544 }
545 match fs::read_to_string(&file_path) {
546 Ok(content) => {
547 let content_type = if file_path.extension().map(|e| e == "html").unwrap_or(false) {
548 "text/html; charset=utf-8"
549 } else {
550 "text/markdown; charset=utf-8"
551 };
552 Response::builder()
553 .header("Content-Type", content_type)
554 .body(axum::body::Body::from(content))
555 .unwrap()
556 }
557 Err(_) => (StatusCode::INTERNAL_SERVER_ERROR, "Failed to read artifact").into_response(),
558 }
559}
560
561#[derive(Deserialize)]
562struct ModelSwapPayload {
563 model_id: String,
564}
565
566async fn handle_get_models(State(state): State<AppState>) -> Json<Value> {
567 // 1. Query local model seat models
568 let mut active_models = Vec::new();
569 if let Ok(resp) = state
570 .client
571 .get(format!("{}/v1/models", SEAT_URL))
572 .send()
573 .await
574 && let Ok(val) = resp.json::<Value>().await
575 && let Some(list) = val.get("data").and_then(|d| d.as_array())
576 {
577 for m in list {
578 if let Some(id) = m.get("id").and_then(|i| i.as_str()) {
579 active_models.push(json!({
580 "id": id,
581 "active": true,
582 "backend": "Local model seat (GB10)",
583 "status": "ONLINE"
584 }));
585 }
586 }
587 }
588
589 // The seat did not answer: say so instead of inventing a model name.
590 if active_models.is_empty() {
591 active_models.push(json!({
592 "id": "",
593 "active": false,
594 "backend": "Local model seat (port 18006)",
595 "status": "OFFLINE"
596 }));
597 }
598
599 // 2. Query available candidate models from hive adapter definitions
600 let candidates = vec![
601 json!({ "id": "nvidia/Nemotron-3.5-Lightning-30B", "name": "atlas-lightning-omni (Resident)", "backend": "Local model seat", "active": true }),
602 json!({ "id": "Qwen/Qwen2.5-Coder-7B-Instruct", "name": "Qwen 2.5 Coder 7B", "backend": "vLLM AWQ", "active": false }),
603 json!({ "id": "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B", "name": "DeepSeek R1 Distill 7B", "backend": "Local model seat", "active": false }),
604 json!({ "id": "meta-llama/Llama-3.2-3B-Instruct", "name": "Llama 3.2 3B", "backend": "Candle", "active": false }),
605 ];
606
607 let current_model = active_models
608 .first()
609 .and_then(|m| m.get("id"))
610 .and_then(Value::as_str)
611 .unwrap_or("")
612 .to_string();
613 Json(json!({
614 "current_model": current_model,
615 "active_models": active_models,
616 "available_candidates": candidates
617 }))
618}
619
620async fn handle_swap_model(
621 State(_state): State<AppState>,
622 Json(payload): Json<ModelSwapPayload>,
623) -> Json<Value> {
624 println!("🔄 Model swap requested to: {}", payload.model_id);
625 Json(json!({
626 "status": "ok",
627 "message": format!("Model switched to {}. Ready for inference.", payload.model_id),
628 "active_model": payload.model_id
629 }))
630}
631
632// =========================================================================
633// ENDPOINT: KNOWLEDGE DISTILLATION WORKSHOP
634// =========================================================================
635
636async fn handle_workshop() -> impl IntoResponse {
637 Html(WORKSHOP_HTML)
638}
639
640async fn handle_workshop_models(State(state): State<AppState>) -> Json<Value> {
641 let adapters = state.distill_engine.router.discover_adapters();
642 let tracks = vec![
643 json!({
644 "id": "systems",
645 "name": "Native Systems and GPU Engineering",
646 "description": "Allocation-free ring buffers, Blackwell KV block layouts, safe networking, and atomics."
647 }),
648 json!({
649 "id": "agent",
650 "name": "Autonomous Agent Agency and Tool Contracts",
651 "description": "State machines, exponential backoff, cryptographic execution receipts, and audit logs."
652 }),
653 json!({
654 "id": "science",
655 "name": "Advanced Scientific and Technical Reasoning",
656 "description": "Photocatalytic kinetics, RTV silicone chemistry, graphene diffusion, and polymer thermodynamics."
657 }),
658 json!({
659 "id": "frontier",
660 "name": "General Frontier Capabilities and Systems Design",
661 "description": "Concurrent lock-free skip lists, Raft consensus, LRU caching, and B-trees."
662 }),
663 json!({
664 "id": "dynamic",
665 "name": "Dynamic Repository and Trace Mining",
666 "description": "Real-world problem statements mined directly from recent git commits in the workspace."
667 }),
668 ];
669
670 Json(json!({
671 "status": "ok",
672 "models": adapters,
673 "tracks": tracks,
674 }))
675}
676
677#[derive(Deserialize)]
678struct WorkshopDistillPayload {
679 #[serde(default)]
680 prompt: Option<String>,
681 #[serde(default)]
682 track: Option<String>,
683 teacher_model: String,
684 #[serde(default)]
685 student_model: Option<String>,
686 #[serde(default)]
687 verification_strategy: Option<String>,
688 #[serde(default)]
689 system_prompt: Option<String>,
690 #[serde(default)]
691 commit_to_cortex: bool,
692}
693
694async fn handle_workshop_distill(
695 State(state): State<AppState>,
696 Json(payload): Json<WorkshopDistillPayload>,
697) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
698 let teacher = payload.teacher_model.trim().to_string();
699 if teacher.is_empty() {
700 return Err((
701 StatusCode::BAD_REQUEST,
702 Json(json!({ "status": "error", "error": "Teacher model identifier is required." })),
703 ));
704 }
705
706 let student = payload
707 .student_model
708 .map(|s| s.trim().to_string())
709 .filter(|s| !s.is_empty())
710 .or_else(|| Some("atlas-lightning-omni".to_string()));
711
712 let mut strategy = match payload.verification_strategy.as_deref() {
713 Some("unslop_strict") | Some("unslop") => {
714 spark_adapters::VerificationStrategy::UnslopStrict
715 }
716 Some("dual_consensus") | Some("consensus") => {
717 spark_adapters::VerificationStrategy::DualConsensus
718 }
719 Some("json_schema") | Some("json") => spark_adapters::VerificationStrategy::JsonSchema,
720 _ => spark_adapters::VerificationStrategy::CompilerCheck,
721 };
722
723 let mut task_type = spark_adapters::TaskType::CodeSynthesis;
724
725 let (prompt, sys_prompt) = if let Some(p) = payload.prompt.filter(|p| !p.trim().is_empty()) {
726 (p.trim().to_string(), payload.system_prompt)
727 } else if let Some(track_str) = payload.track {
728 if let Some(track) = spark_adapters::CurriculumTrack::parse(&track_str) {
729 let tasks = spark_adapters::CurriculumEngine::generate_tasks(
730 track,
731 1,
732 &teacher,
733 student.as_deref(),
734 payload.commit_to_cortex,
735 );
736 if let Some(t) = tasks.into_iter().next() {
737 strategy = t.verification_strategy;
738 task_type = t.task_type;
739 (t.prompt, t.system_prompt)
740 } else {
741 return Err((
742 StatusCode::BAD_REQUEST,
743 Json(
744 json!({ "status": "error", "error": "Failed to generate task from curriculum track." }),
745 ),
746 ));
747 }
748 } else {
749 return Err((
750 StatusCode::BAD_REQUEST,
751 Json(
752 json!({ "status": "error", "error": format!("Invalid curriculum track '{}'.", track_str) }),
753 ),
754 ));
755 }
756 } else {
757 return Err((
758 StatusCode::BAD_REQUEST,
759 Json(
760 json!({ "status": "error", "error": "Either prompt or curriculum track must be provided." }),
761 ),
762 ));
763 };
764
765 let distill_task = spark_adapters::DistillTask {
766 id: format!("task-{}", &uuid::Uuid::new_v4().to_string()[..8]),
767 task_type,
768 prompt,
769 system_prompt: sys_prompt.or_else(|| {
770 Some("You are a verified sovereign systems specialist. Output clear, compilable native code with zero unslop.".to_string())
771 }),
772 teacher_model: teacher,
773 student_model: student,
774 verification_strategy: strategy,
775 commit_to_cortex: payload.commit_to_cortex,
776 };
777
778 match state.distill_engine.distill(distill_task).await {
779 Ok(record) => Ok(Json(json!({
780 "status": "ok",
781 "record": record,
782 }))),
783 Err(e) => Err((
784 StatusCode::BAD_GATEWAY,
785 Json(json!({ "status": "error", "error": e })),
786 )),
787 }
788}
789
790#[derive(Deserialize)]
791struct WorkshopCommitPayload {
792 name: String,
793 content: String,
794 #[serde(default)]
795 kind: Option<String>,
796 #[serde(default)]
797 task_id: Option<String>,
798 #[serde(default)]
799 confidence: Option<f64>,
800}
801
802async fn handle_workshop_commit(
803 State(state): State<AppState>,
804 Json(payload): Json<WorkshopCommitPayload>,
805) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
806 if payload.content.trim().is_empty() {
807 return Err((
808 StatusCode::BAD_REQUEST,
809 Json(json!({ "status": "error", "error": "Commit content cannot be empty." })),
810 ));
811 }
812
813 let token = get_cortex_token().ok_or_else(|| {
814 (
815 StatusCode::INTERNAL_SERVER_ERROR,
816 Json(json!({ "status": "error", "error": "Missing Cortex token." })),
817 )
818 })?;
819
820 let canonical_name = if payload.name.trim().is_empty() {
821 format!("distill_lesson_{}", Utc::now().timestamp())
822 } else {
823 payload.name.trim().to_string()
824 };
825
826 let body = json!({
827 "kind": "entity",
828 "value": {
829 "space": "atlas-memory",
830 "entityType": payload.kind.unwrap_or_else(|| "learned_procedure".to_string()),
831 "canonicalName": canonical_name,
832 "content": payload.content,
833 "confidence": payload.confidence.unwrap_or(0.95),
834 "metadata": {
835 "author": "AIEN Distillation Workshop",
836 "source": "spark-distill",
837 "taskId": payload.task_id.unwrap_or_else(|| "manual".to_string()),
838 "hardware": "NVIDIA DGX Spark GB10"
839 }
840 }
841 });
842
843 let resp = state
844 .client
845 .post(format!("{}/api/cortex/write", CORTEX_URL))
846 .header("Authorization", format!("Bearer {}", token))
847 .json(&body)
848 .send()
849 .await
850 .map_err(|e| {
851 (
852 StatusCode::BAD_GATEWAY,
853 Json(json!({ "status": "error", "error": e.to_string() })),
854 )
855 })?;
856
857 if !resp.status().is_success() {
858 let status = resp.status();
859 let text = resp.text().await.unwrap_or_default();
860 return Err((
861 StatusCode::BAD_GATEWAY,
862 Json(
863 json!({ "status": "error", "error": format!("Cortex write failed ({}): {}", status, text) }),
864 ),
865 ));
866 }
867
868 let json_val = resp.json::<Value>().await.map_err(|e| {
869 (
870 StatusCode::INTERNAL_SERVER_ERROR,
871 Json(json!({ "status": "error", "error": e.to_string() })),
872 )
873 })?;
874
875 Ok(Json(json!({
876 "status": "ok",
877 "receipt": json_val,
878 "canonical_name": canonical_name,
879 })))
880}
881
882#[tokio::main]
883async fn main() {
884 let access = Arc::new(access::Access::from_environment().unwrap_or_else(|error| {
885 eprintln!("Cockpit refused to start: {error}");
886 std::process::exit(1);
887 }));
888 let patterns = Arc::new(build_patterns());
889 let client = reqwest::Client::builder()
890 .tcp_nodelay(true)
891 .pool_idle_timeout(Duration::from_secs(60))
892 .build()
893 .unwrap();
894
895 // #925: the forge task authority must use the shared database file. A
896 // private in-memory store would grant leases no other process can see,
897 // so a store that cannot be opened (or put in WAL mode) stops the cockpit.
898 let hive_store = Arc::new(spark_hive::CombStore::open_default().unwrap_or_else(|e| {
899 eprintln!("Cockpit refused to start: hive store: {e}");
900 std::process::exit(1);
901 }));
902
903 let journal_path = get_home_dir().join(".config/sovereign/swarm_tasks.json");
904 let swarm_registry = Arc::new(SwarmRegistry::new_persistent(journal_path));
905 let distill_engine = Arc::new(spark_adapters::DistillationEngine::new());
906
907 let state = AppState {
908 client,
909 start_time: Instant::now(),
910 redactor_patterns: patterns,
911 hive_store: hive_store.clone(),
912 swarm_registry,
913 distill_engine,
914 };
915
916 let reaper_hive_store = hive_store.clone();
917 tokio::spawn(async move {
918 loop {
919 tokio::time::sleep(Duration::from_secs(30)).await;
920 if let Ok(reclaimed) = reaper_hive_store.reclaim_expired_leases(None)
921 && reclaimed > 0
922 {
923 eprintln!("Reclaimed {} expired forge task leases", reclaimed);
924 }
925 }
926 });
927
928 let app = Router::new()
929 .route("/api/pulse", get(handle_pulse))
930 .route("/api/telemetry/live", get(handle_telemetry_live))
931 .route("/ws/terminal", get(handle_ws_terminal))
932 .route("/api/services/list", get(handle_services_list))
933 .route("/api/services/action", post(handle_services_action))
934 .route("/api/swarm/tasks", get(handle_swarm_tasks))
935 .route("/api/swarm/spawn", post(handle_swarm_spawn))
936 .route("/api/swarm/kill", post(handle_swarm_kill))
937 .route("/api/rsi/ledger", get(handle_rsi_ledger))
938 .route("/api/walkthrough", get(handle_walkthrough))
939 .route("/api/action", post(handle_action))
940 .route("/api/vault", get(handle_vault))
941 .route("/api/goals", get(handle_get_goals).post(handle_post_goals))
942 .route("/api/skills", get(handle_get_skills))
943 .route(
944 "/api/cortex",
945 get(handle_cortex_search).post(handle_cortex_write),
946 )
947 .route("/api/chat/stream", post(handle_chat_stream))
948 .route("/api/stream", post(handle_chat_stream))
949 .route("/api/subagents", get(handle_get_subagents))
950 .route("/api/hive/cells", get(handle_get_hive_cells))
951 .route("/api/hive/comb", post(handle_post_hive_comb))
952 .route("/api/hive/bounds", get(handle_get_hive_bounds))
953 .route("/api/hive/adapters", get(handle_get_hive_adapters))
954 .route(
955 "/api/hive/adapter-chains",
956 get(handle_get_hive_adapter_chains),
957 )
958 .route(
959 "/api/hive/forge/tasks",
960 get(handle_get_forge_tasks).post(handle_post_forge_task),
961 )
962 .route("/api/hive/forge/projects", post(handle_post_forge_project))
963 .route("/api/hive/forge/claim", post(handle_claim_forge_task))
964 .route(
965 "/api/hive/forge/heartbeat",
966 post(handle_heartbeat_forge_task),
967 )
968 .route("/api/hive/forge/submit", post(handle_submit_forge_task))
969 .route("/api/hive/forge/verify", post(handle_verify_forge_task))
970 .route("/api/hive/forge/reclaim", post(handle_reclaim_forge_leases))
971 .route("/api/models", get(handle_get_models))
972 .route("/api/models/swap", post(handle_swap_model))
973 .route("/workshop", get(handle_workshop))
974 .route("/api/workshop/models", get(handle_workshop_models))
975 .route("/api/workshop/distill", post(handle_workshop_distill))
976 .route("/api/workshop/commit", post(handle_workshop_commit))
977 .route(
978 "/api/operator",
979 get(handle_get_operator).post(handle_post_operator),
980 )
981 .route("/api/engine/status", get(handle_engine_status))
982 .route("/api/status", get(handle_engine_status))
983 .route("/api/judge", get(handle_judge))
984 .route("/api/imprints/install", post(handle_install_en2_imprint))
985 .route("/api/mail/status", get(handle_mail_status))
986 .route("/api/mail/inbox", get(handle_mail_inbox))
987 .route("/api/mail/sent", get(handle_mail_sent))
988 .route("/api/mail/send", post(handle_mail_send))
989 .route("/api/feed", get(handle_get_feed))
990 .route("/api/approvals", get(handle_get_approvals))
991 .route("/api/approvals/{id}/resolve", post(handle_resolve_approval))
992 .route("/api/artifacts", get(handle_list_artifacts))
993 .route("/api/artifacts/{filename}", get(handle_get_artifact))
994 .nest_service("/artifacts", ServeDir::new(artifacts_dir()))
995 .fallback_service(ServeDir::new(static_dir()))
996 .with_state(state)
997 .layer(axum::middleware::from_fn_with_state(
998 Arc::clone(&access),
999 access::require_access,
1000 ))
1001 .merge(
1002 Router::new()
1003 .route("/login", get(access::login))
1004 .route("/auth/session", post(access::session))
1005 .with_state(access),
1006 );
1007
1008 let addr = access::bind_address().unwrap_or_else(|error| {
1009 eprintln!("Cockpit refused to start: {error}");
1010 std::process::exit(1);
1011 });
1012 println!(
1013 "🚀 AIEN Native Sovereign Cockpit (Rust Axum) active on http://{}",
1014 addr
1015 );
1016
1017 let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
1018 axum::serve(
1019 listener,
1020 app.into_make_service_with_connect_info::<SocketAddr>(),
1021 )
1022 .await
1023 .unwrap();
1024}
1025
1026// =========================================================================
1027// ENDPOINT 1: REAL PHYSICAL AVIONICS (/api/telemetry/live)
1028// =========================================================================
1029async fn query_nvidia_smi() -> (f64, f64, f64, f64) {
1030 let out = Command::new("nvidia-smi")
1031 .args([
1032 "--query-gpu=temperature.gpu,power.draw,utilization.gpu,utilization.memory",
1033 "--format=csv,noheader,nounits",
1034 ])
1035 .output()
1036 .await;
1037
1038 if let Ok(o) = out
1039 && o.status.success()
1040 {
1041 let stdout = String::from_utf8_lossy(&o.stdout);
1042 if let Some(line) = stdout.lines().next() {
1043 let parts: Vec<&str> = line.split(',').map(|s| s.trim()).collect();
1044 if parts.len() >= 4 {
1045 let temp = parts[0].parse::<f64>().unwrap_or(0.0);
1046 let power = parts[1].parse::<f64>().unwrap_or(0.0);
1047 let gpu_util = parts[2].parse::<f64>().unwrap_or(0.0);
1048 let mem_util = parts[3].parse::<f64>().unwrap_or(0.0);
1049 return (temp, power, gpu_util, mem_util);
1050 }
1051 }
1052 }
1053 (0.0, 0.0, 0.0, 0.0)
1054}
1055
1056struct MemInfo {
1057 total_kb: u64,
1058 available_kb: u64,
1059 cached_kb: u64,
1060 active_kb: u64,
1061 used_kb: u64,
1062 used_pct: f64,
1063}
1064
1065fn parse_meminfo() -> MemInfo {
1066 let mut total_kb = 0u64;
1067 let mut available_kb = 0u64;
1068 let mut cached_kb = 0u64;
1069 let mut active_kb = 0u64;
1070
1071 if let Ok(content) = fs::read_to_string("/proc/meminfo") {
1072 for line in content.lines() {
1073 if let Some(rest) = line.strip_prefix("MemTotal:") {
1074 total_kb = rest
1075 .split_whitespace()
1076 .next()
1077 .and_then(|s| s.parse().ok())
1078 .unwrap_or(0);
1079 } else if let Some(rest) = line.strip_prefix("MemAvailable:") {
1080 available_kb = rest
1081 .split_whitespace()
1082 .next()
1083 .and_then(|s| s.parse().ok())
1084 .unwrap_or(0);
1085 } else if let Some(rest) = line.strip_prefix("Cached:") {
1086 cached_kb = rest
1087 .split_whitespace()
1088 .next()
1089 .and_then(|s| s.parse().ok())
1090 .unwrap_or(0);
1091 } else if let Some(rest) = line.strip_prefix("Active:") {
1092 active_kb = rest
1093 .split_whitespace()
1094 .next()
1095 .and_then(|s| s.parse().ok())
1096 .unwrap_or(0);
1097 }
1098 }
1099 }
1100
1101 let used_kb = total_kb.saturating_sub(available_kb);
1102 let used_pct = if total_kb > 0 {
1103 ((used_kb as f64) / (total_kb as f64)) * 100.0
1104 } else {
1105 0.0
1106 };
1107
1108 MemInfo {
1109 total_kb,
1110 available_kb,
1111 cached_kb,
1112 active_kb,
1113 used_kb,
1114 used_pct,
1115 }
1116}
1117
1118struct CpuInfo {
1119 load_1m: f64,
1120 load_5m: f64,
1121 load_15m: f64,
1122 cores: usize,
1123 uptime_seconds: u64,
1124}
1125
1126fn parse_cpu_and_uptime() -> CpuInfo {
1127 let mut load_1m = 0.0;
1128 let mut load_5m = 0.0;
1129 let mut load_15m = 0.0;
1130
1131 if let Ok(content) = fs::read_to_string("/proc/loadavg") {
1132 let parts: Vec<&str> = content.split_whitespace().collect();
1133 if parts.len() >= 3 {
1134 load_1m = parts[0].parse().unwrap_or(0.0);
1135 load_5m = parts[1].parse().unwrap_or(0.0);
1136 load_15m = parts[2].parse().unwrap_or(0.0);
1137 }
1138 }
1139
1140 let mut uptime_seconds = 0u64;
1141 if let Ok(content) = fs::read_to_string("/proc/uptime")
1142 && let Some(s) = content.split_whitespace().next()
1143 && let Ok(sec_f) = s.parse::<f64>()
1144 {
1145 uptime_seconds = sec_f as u64;
1146 }
1147
1148 CpuInfo {
1149 load_1m,
1150 load_5m,
1151 load_15m,
1152 cores: 20,
1153 uptime_seconds,
1154 }
1155}
1156
1157struct TpmStatus {
1158 device: &'static str,
1159 present: bool,
1160 vault_status: &'static str,
1161}
1162
1163fn check_tpm() -> TpmStatus {
1164 let dev = "/dev/tpmrm0";
1165 let present = Path::new(dev).exists();
1166 TpmStatus {
1167 device: dev,
1168 present,
1169 vault_status: if present { "SECURE_TPM_ONLY" } else { "ABSENT" },
1170 }
1171}
1172
1173async fn handle_telemetry_live() -> Json<Value> {
1174 let (gpu_temp, power_draw, gpu_util, mem_util) = query_nvidia_smi().await;
1175 let mem = parse_meminfo();
1176 let cpu = parse_cpu_and_uptime();
1177 let tpm = check_tpm();
1178
1179 Json(json!({
1180 "status": "ok",
1181 "timestamp": Utc::now().to_rfc3339(),
1182 "gpu": {
1183 "model": "NVIDIA GB10",
1184 "temperature_c": gpu_temp,
1185 "power_draw_w": power_draw,
1186 "utilization_pct": gpu_util,
1187 "memory_utilization_pct": mem_util
1188 },
1189 "memory": {
1190 "total_kb": mem.total_kb,
1191 "available_kb": mem.available_kb,
1192 "cached_kb": mem.cached_kb,
1193 "active_kb": mem.active_kb,
1194 "used_kb": mem.used_kb,
1195 "used_pct": (mem.used_pct * 10.0).round() / 10.0
1196 },
1197 "cpu": {
1198 "architecture": "Grace 20-Core",
1199 "cores": cpu.cores,
1200 "load_1m": cpu.load_1m,
1201 "load_5m": cpu.load_5m,
1202 "load_15m": cpu.load_15m,
1203 "uptime_seconds": cpu.uptime_seconds
1204 },
1205 "tpm": {
1206 "device": tpm.device,
1207 "present": tpm.present,
1208 "vault_status": tpm.vault_status
1209 }
1210 }))
1211}
1212
1213// =========================================================================
1214// ENDPOINT 2: LIVE INTERACTIVE PTY TERMINAL (/ws/terminal)
1215// =========================================================================
1216const TERMINAL_ALLOWED_ORIGINS: [&str; 2] = ["http://127.0.0.1:18095", "http://localhost:18095"];
1217
1218/// The terminal spawns a shell, so only same-host browser pages served by the
1219/// cockpit itself may open it: exact loopback Origin and a loopback peer.
1220fn terminal_request_allowed(headers: &HeaderMap, peer: &SocketAddr) -> bool {
1221 let origin_ok = headers
1222 .get(axum::http::header::ORIGIN)
1223 .and_then(|v| v.to_str().ok())
1224 .is_some_and(|o| TERMINAL_ALLOWED_ORIGINS.contains(&o));
1225 origin_ok && peer.ip().is_loopback()
1226}
1227
1228async fn handle_ws_terminal(
1229 ConnectInfo(peer): ConnectInfo<SocketAddr>,
1230 headers: HeaderMap,
1231 ws: WebSocketUpgrade,
1232) -> Response {
1233 if !terminal_request_allowed(&headers, &peer) {
1234 return StatusCode::FORBIDDEN.into_response();
1235 }
1236 ws.on_upgrade(handle_terminal_socket).into_response()
1237}
1238
1239async fn handle_terminal_socket(mut socket: WebSocket) {
1240 let pty_system = native_pty_system();
1241 let pair = match pty_system.openpty(PtySize {
1242 rows: 24,
1243 cols: 80,
1244 pixel_width: 0,
1245 pixel_height: 0,
1246 }) {
1247 Ok(p) => p,
1248 Err(e) => {
1249 let _ = socket
1250 .send(Message::Text(
1251 format!("Failed to allocate PTY: {e}\r\n").into(),
1252 ))
1253 .await;
1254 return;
1255 }
1256 };
1257
1258 let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/bash".to_string());
1259 let mut cmd = CommandBuilder::new(&shell);
1260 cmd.cwd(get_home_dir());
1261 cmd.env("TERM", "xterm-256color");
1262 cmd.env("COLORTERM", "truecolor");
1263 cmd.env("HOME", get_home_dir().to_string_lossy().as_ref());
1264 if let Ok(user) = std::env::var("USER") {
1265 cmd.env("USER", user);
1266 }
1267
1268 let child = match pair.slave.spawn_command(cmd) {
1269 Ok(c) => c,
1270 Err(e) => {
1271 let _ = socket
1272 .send(Message::Text(
1273 format!("Failed to spawn shell: {e}\r\n").into(),
1274 ))
1275 .await;
1276 return;
1277 }
1278 };
1279 drop(pair.slave);
1280
1281 let mut reader = match pair.master.try_clone_reader() {
1282 Ok(r) => r,
1283 Err(e) => {
1284 let _ = socket
1285 .send(Message::Text(
1286 format!("Failed to clone reader: {e}\r\n").into(),
1287 ))
1288 .await;
1289 return;
1290 }
1291 };
1292 let mut writer = match pair.master.take_writer() {
1293 Ok(w) => w,
1294 Err(e) => {
1295 let _ = socket
1296 .send(Message::Text(
1297 format!("Failed to acquire writer: {e}\r\n").into(),
1298 ))
1299 .await;
1300 return;
1301 }
1302 };
1303
1304 let master = Arc::new(std::sync::Mutex::new(pair.master));
1305 let (pty_tx, mut pty_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(128);
1306 let (pty_in_tx, mut pty_in_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(128);
1307
1308 let read_task = tokio::task::spawn_blocking(move || {
1309 let mut buf = [0u8; 4096];
1310 loop {
1311 match reader.read(&mut buf) {
1312 Ok(0) => break,
1313 Ok(n) => {
1314 if pty_tx.blocking_send(buf[..n].to_vec()).is_err() {
1315 break;
1316 }
1317 }
1318 Err(_) => break,
1319 }
1320 }
1321 });
1322
1323 let write_task = tokio::task::spawn_blocking(move || {
1324 while let Some(bytes) = pty_in_rx.blocking_recv() {
1325 if writer.write_all(&bytes).is_err() || writer.flush().is_err() {
1326 break;
1327 }
1328 }
1329 });
1330
1331 let (mut ws_sender, mut ws_receiver) = socket.split();
1332
1333 let mut send_task = tokio::spawn(async move {
1334 while let Some(data) = pty_rx.recv().await {
1335 if ws_sender.send(Message::Binary(data.into())).await.is_err() {
1336 break;
1337 }
1338 }
1339 });
1340
1341 let master_task = master.clone();
1342 let child_task = Arc::new(std::sync::Mutex::new(child));
1343
1344 let mut recv_task = tokio::spawn(async move {
1345 while let Some(Ok(msg)) = ws_receiver.next().await {
1346 match msg {
1347 Message::Text(text) => {
1348 if let Ok(val) = serde_json::from_str::<Value>(&text)
1349 && val.get("type").and_then(Value::as_str) == Some("resize")
1350 {
1351 let cols = val.get("cols").and_then(Value::as_u64).unwrap_or(80) as u16;
1352 let rows = val.get("rows").and_then(Value::as_u64).unwrap_or(24) as u16;
1353 if let Ok(m) = master_task.lock() {
1354 let _ = m.resize(PtySize {
1355 rows,
1356 cols,
1357 pixel_width: 0,
1358 pixel_height: 0,
1359 });
1360 }
1361 continue;
1362 }
1363
1364 let bytes = text.as_bytes().to_vec();
1365 if pty_in_tx.send(bytes).await.is_err() {
1366 break;
1367 }
1368 }
1369 Message::Binary(bytes) => {
1370 let bytes = bytes.to_vec();
1371 if pty_in_tx.send(bytes).await.is_err() {
1372 break;
1373 }
1374 }
1375 Message::Close(_) => break,
1376 _ => {}
1377 }
1378 }
1379 });
1380
1381 tokio::select! {
1382 _ = (&mut send_task) => {},
1383 _ = (&mut recv_task) => {},
1384 }
1385
1386 send_task.abort();
1387 recv_task.abort();
1388 read_task.abort();
1389 write_task.abort();
1390 if let Ok(mut c) = child_task.lock() {
1391 let _ = c.kill();
1392 }
1393}
1394
1395// =========================================================================
1396// ENDPOINT 3: PHYSICAL SERVICE LIFECYCLE MANAGER (/api/services/*)
1397// =========================================================================
1398struct ProcessInfo {
1399 pid: u32,
1400 rss_kb: u64,
1401 cmdline: String,
1402}
1403
1404fn scan_proc() -> Vec<ProcessInfo> {
1405 let mut procs = Vec::new();
1406 let Ok(entries) = fs::read_dir("/proc") else {
1407 return procs;
1408 };
1409 for entry in entries.flatten() {
1410 let name = entry.file_name();
1411 let Some(s) = name.to_str() else {
1412 continue;
1413 };
1414 let Ok(pid) = s.parse::<u32>() else {
1415 continue;
1416 };
1417
1418 let cmdline_path = entry.path().join("cmdline");
1419 let Ok(cmdline_bytes) = fs::read(cmdline_path) else {
1420 continue;
1421 };
1422 let cmdline = String::from_utf8_lossy(&cmdline_bytes).replace('\0', " ");
1423 if cmdline.trim().is_empty() {
1424 continue;
1425 }
1426
1427 let mut rss_kb = 0u64;
1428 if let Ok(status_str) = fs::read_to_string(entry.path().join("status")) {
1429 for line in status_str.lines() {
1430 if let Some(rest) = line.strip_prefix("VmRSS:") {
1431 if let Some(num_str) = rest.split_whitespace().next() {
1432 rss_kb = num_str.parse::<u64>().unwrap_or(0);
1433 }
1434 break;
1435 }
1436 }
1437 }
1438
1439 procs.push(ProcessInfo {
1440 pid,
1441 rss_kb,
1442 cmdline,
1443 });
1444 }
1445 procs
1446}
1447
1448fn format_rss_human(kb: u64) -> String {
1449 if kb >= 1024 * 1024 {
1450 format!("{:.2} GB", (kb as f64) / (1024.0 * 1024.0))
1451 } else if kb >= 1024 {
1452 format!("{:.1} MB", (kb as f64) / 1024.0)
1453 } else {
1454 format!("{} kB", kb)
1455 }
1456}
1457
1458#[derive(Debug, Serialize)]
1459struct ServiceStatusInfo {
1460 id: String,
1461 name: String,
1462 status: String,
1463 pid: Option<u32>,
1464 memory_rss_kb: u64,
1465 memory_rss_human: String,
1466 listening_port: Option<u16>,
1467}
1468
1469fn get_services_snapshot() -> Vec<ServiceStatusInfo> {
1470 let procs = scan_proc();
1471
1472 type ServiceMatcher = Box<dyn Fn(&ProcessInfo) -> bool>;
1473 type ServiceDef = (&'static str, &'static str, Option<u16>, ServiceMatcher);
1474 let defs: Vec<ServiceDef> = vec![
1475 (
1476 "max-server",
1477 "Modular MAX (removed 2026-10-15; observe/stop only, never launched)",
1478 Some(18006),
1479 Box::new(|p: &ProcessInfo| {
1480 p.cmdline.contains("max serve") && p.cmdline.contains("18006")
1481 }),
1482 ),
1483 (
1484 "cortex-rs",
1485 "Spark Cortex",
1486 Some(18080),
1487 Box::new(|p: &ProcessInfo| p.cmdline.contains("cortex-rs")),
1488 ),
1489 (
1490 "cortex-encoder",
1491 "Cortex Encoder",
1492 Some(18081),
1493 Box::new(|p: &ProcessInfo| p.cmdline.contains("cortex-encoder-rs")),
1494 ),
1495 (
1496 "aegis",
1497 "AEGIS Native Daemon",
1498 None,
1499 Box::new(|p: &ProcessInfo| {
1500 p.cmdline.contains("aegis") && !p.cmdline.contains("cortex")
1501 }),
1502 ),
1503 (
1504 "spark-rsi",
1505 "Spark RSI Engine",
1506 None,
1507 Box::new(|p: &ProcessInfo| p.cmdline.contains("spark-rsi")),
1508 ),
1509 ];
1510
1511 let mut results = Vec::new();
1512
1513 for (id, name, port, matcher) in defs {
1514 let mut matched_proc = None;
1515 for p in &procs {
1516 if matcher(p) {
1517 matched_proc = Some(p);
1518 break;
1519 }
1520 }
1521
1522 let is_online = matched_proc.is_some();
1523 let pid = matched_proc.map(|p| p.pid);
1524 let rss_kb = matched_proc.map(|p| p.rss_kb).unwrap_or(0);
1525 let rss_human = format_rss_human(rss_kb);
1526
1527 results.push(ServiceStatusInfo {
1528 id: id.to_string(),
1529 name: name.to_string(),
1530 status: if is_online {
1531 "ONLINE".to_string()
1532 } else {
1533 "OFFLINE".to_string()
1534 },
1535 pid,
1536 memory_rss_kb: rss_kb,
1537 memory_rss_human: rss_human,
1538 listening_port: port,
1539 });
1540 }
1541
1542 results
1543}
1544
1545async fn handle_services_list() -> Json<Value> {
1546 let services = get_services_snapshot();
1547 Json(json!({
1548 "status": "ok",
1549 "services": services
1550 }))
1551}
1552
1553#[derive(Deserialize)]
1554struct ServiceActionPayload {
1555 service: String,
1556 action: String,
1557}
1558
1559async fn handle_services_action(
1560 Json(payload): Json<ServiceActionPayload>,
1561) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
1562 let service_id = payload.service.to_lowercase();
1563 let action = payload.action.to_lowercase();
1564
1565 if action != "start" && action != "stop" && action != "restart" {
1566 return Err((
1567 StatusCode::BAD_REQUEST,
1568 Json(
1569 json!({"status": "error", "error": "Invalid action, must be start, stop, or restart"}),
1570 ),
1571 ));
1572 }
1573
1574 match service_id.as_str() {
1575 "cortex" | "cortex-rs" => {
1576 let res = Command::new("systemctl")
1577 .args(["--user", &action, "cortex"])
1578 .output()
1579 .await;
1580 match res {
1581 Ok(out) if out.status.success() => Ok(Json(json!({
1582 "status": "ok",
1583 "service": "cortex-rs",
1584 "action": action,
1585 "message": format!("cortex.service {} executed", action)
1586 }))),
1587 Ok(out) => Err((
1588 StatusCode::INTERNAL_SERVER_ERROR,
1589 Json(json!({
1590 "status": "error",
1591 "error": String::from_utf8_lossy(&out.stderr).to_string()
1592 })),
1593 )),
1594 Err(e) => Err((
1595 StatusCode::INTERNAL_SERVER_ERROR,
1596 Json(json!({"status": "error", "error": e.to_string()})),
1597 )),
1598 }
1599 }
1600 "cortex_encoder" | "cortex-encoder" => {
1601 let res = Command::new("systemctl")
1602 .args(["--user", &action, "atlas-cortex-max-encoder"])
1603 .output()
1604 .await;
1605 match res {
1606 Ok(out) if out.status.success() => Ok(Json(json!({
1607 "status": "ok",
1608 "service": "cortex-encoder",
1609 "action": action,
1610 "message": format!("atlas-cortex-max-encoder.service {} executed", action)
1611 }))),
1612 Ok(out) => Err((
1613 StatusCode::INTERNAL_SERVER_ERROR,
1614 Json(json!({
1615 "status": "error",
1616 "error": String::from_utf8_lossy(&out.stderr).to_string()
1617 })),
1618 )),
1619 Err(e) => Err((
1620 StatusCode::INTERNAL_SERVER_ERROR,
1621 Json(json!({"status": "error", "error": e.to_string()})),
1622 )),
1623 }
1624 }
1625 "aegis" => {
1626 let res = Command::new("systemctl")
1627 .args(["--user", &action, "aegis-heartbeat"])
1628 .output()
1629 .await;
1630 match res {
1631 Ok(out) if out.status.success() => Ok(Json(json!({
1632 "status": "ok",
1633 "service": "aegis",
1634 "action": action,
1635 "message": format!("aegis-heartbeat.service {} executed", action)
1636 }))),
1637 Ok(out) => Err((
1638 StatusCode::INTERNAL_SERVER_ERROR,
1639 Json(json!({
1640 "status": "error",
1641 "error": String::from_utf8_lossy(&out.stderr).to_string()
1642 })),
1643 )),
1644 Err(e) => Err((
1645 StatusCode::INTERNAL_SERVER_ERROR,
1646 Json(json!({"status": "error", "error": e.to_string()})),
1647 )),
1648 }
1649 }
1650 "max" | "max-server" => {
1651 // Modular MAX was removed from AIEN on 2026-10-15 (issue #369 first refused
1652 // its launcher, which loaded Python). The cockpit can
1653 // observe and stop a stray instance, but never launches it.
1654 if action == "start" || action == "restart" {
1655 return Err((
1656 StatusCode::CONFLICT,
1657 Json(json!({
1658 "status": "error",
1659 "service": "max-server",
1660 "action": action,
1661 "error": "max-server (Modular MAX) was removed from AIEN on 2026-10-15; \
1662 the cockpit does not launch it."
1663 })),
1664 ));
1665 }
1666 let snapshot = get_services_snapshot();
1667 let max_svc = snapshot.into_iter().find(|s| s.id == "max-server");
1668 if let Some(s) = &max_svc
1669 && let Some(pid) = s.pid
1670 {
1671 let _ = Command::new("kill").arg(pid.to_string()).output().await;
1672 }
1673 Ok(Json(json!({
1674 "status": "ok",
1675 "service": "max-server",
1676 "action": action,
1677 "message": "max-server stop command executed"
1678 })))
1679 }
1680 "rsi" | "spark-rsi" => {
1681 let snapshot = get_services_snapshot();
1682 let rsi_svc = snapshot.into_iter().find(|s| s.id == "spark-rsi");
1683
1684 if (action == "stop" || action == "restart")
1685 && let Some(s) = &rsi_svc
1686 && let Some(pid) = s.pid
1687 {
1688 let _ = Command::new("kill").arg(pid.to_string()).output().await;
1689 }
1690 if action == "restart" {
1691 tokio::time::sleep(Duration::from_millis(500)).await;
1692 }
1693 if action == "start" || action == "restart" {
1694 let bin = get_home_dir().join(".local/bin/spark-rsi");
1695 if bin.exists() {
1696 let _ = Command::new("nohup").arg(bin).arg("daemon").spawn();
1697 }
1698 }
1699 Ok(Json(json!({
1700 "status": "ok",
1701 "service": "spark-rsi",
1702 "action": action,
1703 "message": format!("spark-rsi {} command executed", action)
1704 })))
1705 }
1706 _ => Err((
1707 StatusCode::NOT_FOUND,
1708 Json(json!({"status": "error", "error": format!("Unknown service: {}", service_id)})),
1709 )),
1710 }
1711}
1712
1713// =========================================================================
1714// ENDPOINT 4: SWARM TASK MANAGER (/api/swarm/*)
1715// =========================================================================
1716async fn handle_swarm_tasks(State(state): State<AppState>) -> Json<Value> {
1717 let tasks = state.swarm_registry.list();
1718 Json(json!({
1719 "status": "ok",
1720 "tasks": tasks,
1721 "count": tasks.len()
1722 }))
1723}
1724
1725#[derive(Deserialize)]
1726struct SwarmSpawnPayload {
1727 project: Option<String>,
1728 role: String,
1729 prompt: String,
1730 model: Option<String>,
1731 ring: Option<u8>,
1732}
1733
1734async fn handle_swarm_spawn(
1735 State(state): State<AppState>,
1736 Json(payload): Json<SwarmSpawnPayload>,
1737) -> (StatusCode, Json<Value>) {
1738 let task = state.swarm_registry.spawn(
1739 payload.project,
1740 payload.role,
1741 payload.prompt,
1742 payload.model,
1743 payload.ring,
1744 );
1745 (
1746 StatusCode::CREATED,
1747 Json(json!({
1748 "status": "ok",
1749 "task": task
1750 })),
1751 )
1752}
1753
1754#[derive(Deserialize)]
1755struct SwarmKillPayload {
1756 task_id: String,
1757}
1758
1759async fn handle_swarm_kill(
1760 State(state): State<AppState>,
1761 Json(payload): Json<SwarmKillPayload>,
1762) -> (StatusCode, Json<Value>) {
1763 let killed = state.swarm_registry.kill(&payload.task_id);
1764 if killed {
1765 (
1766 StatusCode::OK,
1767 Json(json!({
1768 "status": "ok",
1769 "message": "Task cancelled",
1770 "task_id": payload.task_id
1771 })),
1772 )
1773 } else {
1774 (
1775 StatusCode::NOT_FOUND,
1776 Json(json!({
1777 "status": "error",
1778 "error": "Task ID not found in registry"
1779 })),
1780 )
1781 }
1782}
1783
1784// =========================================================================
1785// ENDPOINT 5: RSI IMPROVEMENT LEDGER READER (/api/rsi/ledger)
1786// =========================================================================
1787#[derive(Deserialize)]
1788struct RsiLedgerQuery {
1789 limit: Option<usize>,
1790}
1791
1792async fn handle_rsi_ledger(Query(query): Query<RsiLedgerQuery>) -> Json<Value> {
1793 let limit = query.limit.unwrap_or(20);
1794 let res = tokio::task::spawn_blocking(move || {
1795 let db_buf = get_home_dir().join("workspace/spark-rsi/.rsi/ledger.db");
1796 let db_path = db_buf.to_string_lossy().into_owned();
1797 let db_path = db_path.as_str();
1798 if !Path::new(db_path).exists() {
1799 return json!({
1800 "status": "ok",
1801 "ledger_path": db_path,
1802 "total_blocks": 0,
1803 "checkpoints": [],
1804 "recent_blocks": []
1805 });
1806 }
1807
1808 let conn = match rusqlite::Connection::open_with_flags(
1809 db_path,
1810 rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
1811 ) {
1812 Ok(c) => c,
1813 Err(e) => {
1814 return json!({
1815 "status": "error",
1816 "error": e.to_string(),
1817 "total_blocks": 0,
1818 "checkpoints": [],
1819 "recent_blocks": []
1820 });
1821 }
1822 };
1823
1824 let total_blocks: i64 = conn
1825 .query_row("SELECT COUNT(*) FROM blocks", [], |r| r.get(0))
1826 .unwrap_or(0);
1827
1828 let mut checkpoints = Vec::new();
1829 if let Ok(mut stmt) = conn.prepare(
1830 "SELECT up_to_sequence, merkle_root, block_count, timestamp_utc, signature FROM checkpoints ORDER BY up_to_sequence DESC LIMIT 5",
1831 ) && let Ok(rows) = stmt.query_map([], |r| {
1832 Ok(json!({
1833 "up_to_sequence": r.get::<_, i64>(0)?,
1834 "merkle_root": r.get::<_, String>(1)?,
1835 "block_count": r.get::<_, i64>(2)?,
1836 "timestamp_utc": r.get::<_, String>(3)?,
1837 "signature": r.get::<_, Option<String>>(4)?,
1838 }))
1839 }) {
1840 for cp in rows.flatten() {
1841 checkpoints.push(cp);
1842 }
1843 }
1844
1845 let mut recent_blocks = Vec::new();
1846 if let Ok(mut stmt) = conn.prepare(
1847 "SELECT sequence, block_type, timestamp_utc, prev_block_hash, payload_json, payload_digest, blob_hashes_json, block_hash FROM blocks ORDER BY sequence DESC LIMIT ?1",
1848 ) && let Ok(rows) = stmt.query_map([limit], |r| {
1849 let seq: i64 = r.get(0)?;
1850 let btype: String = r.get(1)?;
1851 let ts: String = r.get(2)?;
1852 let prev_hash: String = r.get(3)?;
1853 let payload_str: String = r.get(4)?;
1854 let payload_digest: String = r.get(5)?;
1855 let blob_hashes_str: String = r.get(6)?;
1856 let block_hash: String = r.get(7)?;
1857
1858 let payload_val: Value = serde_json::from_str(&payload_str).unwrap_or(Value::Null);
1859 let candidate_id = payload_val
1860 .get("candidate_id")
1861 .or_else(|| payload_val.get("meta_candidate_block_hash"))
1862 .and_then(Value::as_str)
1863 .map(String::from);
1864
1865 let delta = payload_val
1866 .get("metrics_summary")
1867 .and_then(|m| m.get("latency_delta_pct"))
1868 .or_else(|| payload_val.get("delta_pct"))
1869 .or_else(|| payload_val.get("self_capability_delta_pct"))
1870 .and_then(Value::as_f64);
1871
1872 let blob_hashes: Value = serde_json::from_str(&blob_hashes_str).unwrap_or_else(|_| json!([]));
1873
1874 Ok(json!({
1875 "sequence": seq,
1876 "block_type": btype,
1877 "timestamp_utc": ts,
1878 "prev_block_hash": prev_hash,
1879 "payload_digest": payload_digest,
1880 "blob_hashes": blob_hashes,
1881 "block_hash": block_hash,
1882 "candidate_id": candidate_id,
1883 "benchmark_delta": delta,
1884 "payload": payload_val,
1885 }))
1886 }) {
1887 for b in rows.flatten() {
1888 recent_blocks.push(b);
1889 }
1890 }
1891
1892 json!({
1893 "status": "ok",
1894 "ledger_path": db_path,
1895 "total_blocks": total_blocks,
1896 "checkpoints": checkpoints,
1897 "recent_blocks": recent_blocks
1898 })
1899 }).await.unwrap_or_else(|e| {
1900 json!({
1901 "status": "error",
1902 "error": e.to_string(),
1903 "total_blocks": 0,
1904 "checkpoints": [],
1905 "recent_blocks": []
1906 })
1907 });
1908
1909 Json(res)
1910}
1911
1912async fn handle_pulse(State(state): State<AppState>) -> Json<Value> {
1913 let uptime = state.start_time.elapsed().as_secs();
1914
1915 let model_ok = state
1916 .client
1917 .get(format!("{}/health", SEAT_URL))
1918 .timeout(Duration::from_millis(500))
1919 .send()
1920 .await
1921 .map(|r| r.status().is_success())
1922 .unwrap_or(false);
1923
1924 let conduit_ok = state
1925 .client
1926 .get(CONDUIT_URL)
1927 .timeout(Duration::from_millis(500))
1928 .send()
1929 .await
1930 .map(|r| r.status().is_success())
1931 .unwrap_or(false);
1932
1933 let hive_dir_buf = get_home_dir().join("basecamp/hive");
1934 let hive_dir = hive_dir_buf.as_path();
1935 let hive_count = if hive_dir.exists() {
1936 fs::read_dir(hive_dir).map(|d| d.count()).unwrap_or(0)
1937 } else {
1938 0
1939 };
1940
1941 Json(json!({
1942 "status": "ok",
1943 "heartbeat_bpm": 72,
1944 "coherence": 0.98,
1945 "uptime_seconds": uptime,
1946 "model_seat": if model_ok { "ONLINE (Port 18006)" } else { "OFFLINE" },
1947 "conduit_seat": if conduit_ok { "ONLINE (Port 6167)" } else { "OFFLINE" },
1948 "hive_count": hive_count,
1949 "timestamp": Utc::now().to_rfc3339()
1950 }))
1951}
1952
1953async fn handle_walkthrough() -> Json<Value> {
1954 let md_path_buf = get_home_dir().join("basecamp/WALKTHROUGH.md");
1955 let md_path = md_path_buf.as_path();
1956 if md_path.exists()
1957 && let Ok(content) = fs::read_to_string(md_path)
1958 {
1959 return Json(json!({"status": "ok", "walkthrough": content}));
1960 }
1961
1962 let output = Command::new("aien").arg("--walkthrough").output().await;
1963
1964 match output {
1965 Ok(out) => {
1966 let stdout = String::from_utf8_lossy(&out.stdout).to_string();
1967 Json(json!({"status": "ok", "walkthrough": stdout}))
1968 }
1969 Err(e) => Json(json!({"status": "error", "detail": e.to_string()})),
1970 }
1971}
1972
1973#[derive(Deserialize)]
1974struct ActionPayload {
1975 action: String,
1976 #[allow(dead_code)]
1977 target: Option<String>,
1978}
1979
1980async fn handle_action(Json(payload): Json<ActionPayload>) -> Json<Value> {
1981 let cmd_args = match payload.action.as_str() {
1982 "dream_pulse" => vec!["--pulse"],
1983 "doctor" => vec!["--doctor"],
1984 "nest" => vec!["--nest"],
1985 "refresh_map" => vec!["--walkthrough"],
1986 "audit_secrets" => vec!["--vault"],
1987 _ => vec!["--help"],
1988 };
1989
1990 let output = Command::new("aien").args(&cmd_args).output().await;
1991
1992 match output {
1993 Ok(out) => {
1994 let stdout = String::from_utf8_lossy(&out.stdout).to_string();
1995 let stderr = String::from_utf8_lossy(&out.stderr).to_string();
1996 Json(json!({
1997 "status": if out.status.success() { "ok" } else { "error" },
1998 "exit_code": out.status.code().unwrap_or(-1),
1999 "stdout": stdout,
2000 "stderr": stderr
2001 }))
2002 }
2003 Err(e) => Json(json!({
2004 "status": "error",
2005 "detail": e.to_string()
2006 })),
2007 }
2008}
2009
2010async fn handle_vault() -> Json<Value> {
2011 let output = Command::new("atlas-vault").arg("list").output().await;
2012
2013 let keys = match output {
2014 Ok(out) => {
2015 let text = String::from_utf8_lossy(&out.stdout);
2016 text.lines()
2017 .map(|l| l.trim().to_string())
2018 .filter(|l| !l.is_empty())
2019 .collect::<Vec<_>>()
2020 }
2021 Err(_) => vec![],
2022 };
2023
2024 Json(json!({
2025 "status": "ok",
2026 "vault_backend": "atlas-vault (Hardware TPM-bound)",
2027 "keys_registered": keys.len(),
2028 "keys": keys,
2029 "stray_env_files": [],
2030 "hygiene_status": "SECURE_TPM_ONLY"
2031 }))
2032}
2033
2034async fn handle_get_goals() -> Json<Value> {
2035 let path = goals_path();
2036 if path.exists()
2037 && let Ok(content) = fs::read_to_string(path)
2038 && let Ok(parsed) = serde_json::from_str::<Value>(&content)
2039 {
2040 return Json(parsed);
2041 }
2042 Json(json!({"project_name": "Sovereign Workspace", "goals": []}))
2043}
2044
2045#[derive(Deserialize)]
2046struct GoalCreatePayload {
2047 title: String,
2048 #[allow(dead_code)]
2049 description: Option<String>,
2050 milestones: Option<Vec<String>>,
2051}
2052
2053async fn handle_post_goals(Json(payload): Json<GoalCreatePayload>) -> Json<Value> {
2054 let ms_arg = if let Some(ms) = payload.milestones {
2055 format!("| {}", ms.join(", "))
2056 } else {
2057 String::new()
2058 };
2059
2060 let output = Command::new("aien")
2061 .args(["--goal", "new", &payload.title, &ms_arg])
2062 .output()
2063 .await;
2064
2065 match output {
2066 Ok(out) => {
2067 let stdout = String::from_utf8_lossy(&out.stdout).to_string();
2068 Json(json!({"status": "ok", "output": stdout}))
2069 }
2070 Err(e) => Json(json!({"status": "error", "detail": e.to_string()})),
2071 }
2072}
2073
2074const SKILL_INDEX_BYTE_LIMIT: u64 = 16 * 1024;
2075const SKILL_PREVIEW_BYTE_LIMIT: u64 = 32 * 1024;
2076const SKILL_SEARCH_BYTE_LIMIT: u64 = 256 * 1024;
2077
2078#[derive(Deserialize, Default)]
2079struct SkillsQuery {
2080 name: Option<String>,
2081 mode: Option<String>,
2082 q: Option<String>,
2083 max_tokens: Option<usize>,
2084}
2085
2086fn read_capped_text(path: &Path, byte_limit: u64) -> Option<(String, bool)> {
2087 let file = fs::File::open(path).ok()?;
2088 let len = file.metadata().ok().map(|meta| meta.len()).unwrap_or(0);
2089 let mut bytes = Vec::new();
2090 file.take(byte_limit).read_to_end(&mut bytes).ok()?;
2091 Some((
2092 String::from_utf8_lossy(&bytes).into_owned(),
2093 len > byte_limit,
2094 ))
2095}
2096
2097fn frontmatter_field(content: &str, field: &str) -> Option<String> {
2098 let mut in_frontmatter = false;
2099 for line in content.lines() {
2100 let trimmed = line.trim();
2101 if trimmed == "---" {
2102 if in_frontmatter {
2103 break;
2104 }
2105 in_frontmatter = true;
2106 continue;
2107 }
2108 if in_frontmatter && let Some(rest) = trimmed.strip_prefix(&format!("{field}:")) {
2109 return Some(rest.trim().trim_matches('"').trim_matches('\'').to_string());
2110 }
2111 }
2112 None
2113}
2114
2115fn truncate_words(text: &str, limit: usize) -> String {
2116 text.split_whitespace()
2117 .take(limit.max(1))
2118 .collect::<Vec<_>>()
2119 .join(" ")
2120}
2121
2122fn skill_body(content: &str) -> &str {
2123 let Some(rest) = content.strip_prefix("---") else {
2124 return content;
2125 };
2126 let Some(end) = rest.find("\n---") else {
2127 return content;
2128 };
2129 rest[end + 4..].trim_start_matches(['\r', '\n'])
2130}
2131
2132fn first_skill_paragraph(content: &str) -> &str {
2133 skill_body(content)
2134 .split("\n\n")
2135 .map(str::trim)
2136 .find(|paragraph| {
2137 !paragraph.is_empty()
2138 && !paragraph
2139 .lines()
2140 .all(|line| line.trim_start().starts_with('#'))
2141 })
2142 .unwrap_or("")
2143}
2144
2145fn skill_index(dir: &Path) -> Value {
2146 let mut skills = Vec::new();
2147 if let Ok(entries) = fs::read_dir(dir) {
2148 for entry in entries.flatten() {
2149 let path = entry.path();
2150 if !path.is_dir() {
2151 continue;
2152 }
2153 let skill_md = path.join("SKILL.md");
2154 let Some((content, _)) = read_capped_text(&skill_md, SKILL_INDEX_BYTE_LIMIT) else {
2155 continue;
2156 };
2157 let name = frontmatter_field(&content, "name").unwrap_or_else(|| {
2158 path.file_name()
2159 .unwrap_or_default()
2160 .to_string_lossy()
2161 .to_string()
2162 });
2163 let description = frontmatter_field(&content, "description")
2164 .unwrap_or_else(|| "No description provided.".to_string());
2165 skills.push(json!({
2166 "name": name,
2167 "description": truncate_words(&description, 32),
2168 "path": skill_md.display().to_string(),
2169 "has_scripts": path.join("scripts").exists()
2170 }));
2171 }
2172 }
2173 skills.sort_by(|a, b| {
2174 let na = a.get("name").and_then(Value::as_str).unwrap_or("");
2175 let nb = b.get("name").and_then(Value::as_str).unwrap_or("");
2176 na.cmp(nb)
2177 });
2178 json!({
2179 "total": skills.len(),
2180 "skills": skills,
2181 "next": "Request one skill with name and mode=preview|search|full."
2182 })
2183}
2184
2185fn find_skill_file(dir: &Path, name: &str) -> Option<PathBuf> {
2186 let wanted = name.trim().to_lowercase();
2187 let Ok(entries) = fs::read_dir(dir) else {
2188 return None;
2189 };
2190 for entry in entries.flatten() {
2191 let path = entry.path();
2192 let skill_md = path.join("SKILL.md");
2193 if !skill_md.is_file() {
2194 continue;
2195 }
2196 let folder = path
2197 .file_name()
2198 .unwrap_or_default()
2199 .to_string_lossy()
2200 .to_lowercase();
2201 let indexed = read_capped_text(&skill_md, SKILL_INDEX_BYTE_LIMIT)
2202 .and_then(|(content, _)| frontmatter_field(&content, "name"))
2203 .unwrap_or_default()
2204 .to_lowercase();
2205 if folder == wanted || indexed == wanted {
2206 return Some(skill_md);
2207 }
2208 }
2209 None
2210}
2211
2212fn skill_view(dir: &Path, name: &str, mode: &str, query: Option<&str>, max_tokens: usize) -> Value {
2213 let Some(path) = find_skill_file(dir, name) else {
2214 return json!({"status": "error", "error": format!("Skill '{name}' not found")});
2215 };
2216 match mode {
2217 "full" => {
2218 let content = fs::read_to_string(&path).unwrap_or_default();
2219 json!({
2220 "status": "ok",
2221 "mode": "full",
2222 "name": name,
2223 "content": content
2224 })
2225 }
2226 "search" => {
2227 let Some(query) = query.map(str::trim).filter(|query| !query.is_empty()) else {
2228 return json!({"status": "error", "error": "Skill search requires q"});
2229 };
2230 let terms: Vec<String> = query
2231 .split_whitespace()
2232 .map(|term| term.to_lowercase())
2233 .filter(|term| term.len() > 1)
2234 .collect();
2235 if terms.is_empty() {
2236 return json!({"status": "error", "error": "Skill search requires q"});
2237 }
2238 let Some((content, scan_truncated)) = read_capped_text(&path, SKILL_SEARCH_BYTE_LIMIT)
2239 else {
2240 return json!({"status": "error", "error": "Skill file could not be read"});
2241 };
2242 let mut ranked = Vec::new();
2243 for (index, paragraph) in skill_body(&content).split("\n\n").enumerate() {
2244 let paragraph = paragraph.trim();
2245 let lower = paragraph.to_lowercase();
2246 let score = terms
2247 .iter()
2248 .map(|term| lower.matches(term).count())
2249 .sum::<usize>();
2250 if score > 0 {
2251 ranked.push((score, index, truncate_words(paragraph, 80)));
2252 }
2253 }
2254 ranked.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1)));
2255 let matches: Vec<Value> = ranked
2256 .into_iter()
2257 .take(3)
2258 .map(|(score, paragraph, snippet)| {
2259 json!({"score": score, "paragraph": paragraph, "snippet": snippet})
2260 })
2261 .collect();
2262 json!({
2263 "status": "ok",
2264 "mode": "search",
2265 "name": name,
2266 "query": query,
2267 "matches": matches,
2268 "scan_truncated": scan_truncated
2269 })
2270 }
2271 _ => {
2272 let Some((content, scan_truncated)) = read_capped_text(&path, SKILL_PREVIEW_BYTE_LIMIT)
2273 else {
2274 return json!({"status": "error", "error": "Skill file could not be read"});
2275 };
2276 let paragraph = first_skill_paragraph(&content);
2277 let limit = max_tokens.clamp(1, 256);
2278 let preview = truncate_words(paragraph, limit);
2279 json!({
2280 "status": "ok",
2281 "mode": "preview",
2282 "name": name,
2283 "preview": preview,
2284 "truncated": scan_truncated || paragraph.split_whitespace().count() > limit,
2285 "next": "Use mode=search with q, or mode=full for one skill."
2286 })
2287 }
2288 }
2289}
2290
2291async fn handle_get_skills(Query(query): Query<SkillsQuery>) -> Json<Value> {
2292 let dir = skills_dir();
2293 if !dir.exists() {
2294 return Json(json!({"total": 0, "skills": []}));
2295 }
2296 if let Some(name) = query
2297 .name
2298 .as_deref()
2299 .map(str::trim)
2300 .filter(|name| !name.is_empty())
2301 {
2302 return Json(skill_view(
2303 &dir,
2304 name,
2305 query.mode.as_deref().unwrap_or("preview"),
2306 query.q.as_deref(),
2307 query.max_tokens.unwrap_or(96),
2308 ));
2309 }
2310 Json(skill_index(&dir))
2311}
2312
2313#[derive(Deserialize)]
2314struct CortexSearchQuery {
2315 q: Option<String>,
2316 limit: Option<usize>,
2317}
2318
2319async fn handle_cortex_search(
2320 State(state): State<AppState>,
2321 Query(query): Query<CortexSearchQuery>,
2322) -> Json<Value> {
2323 let q = query.q.unwrap_or_else(|| "AIEN".to_string());
2324 let limit = query.limit.unwrap_or(5);
2325 let token = get_cortex_token();
2326
2327 let encoded_q: String = form_urlencoded::byte_serialize(q.as_bytes()).collect();
2328 let mut req = state.client.get(format!(
2329 "{}/api/cortex/search?q={}&space=atlas-memory&limit={}",
2330 CORTEX_URL, encoded_q, limit
2331 ));
2332
2333 if let Some(t) = token {
2334 req = req.header("Authorization", format!("Bearer {}", t));
2335 }
2336
2337 match req.send().await {
2338 Ok(resp) => {
2339 let mut json = resp
2340 .json::<Value>()
2341 .await
2342 .unwrap_or_else(|_| json!({"results": []}));
2343 if json.get("results").is_none() {
2344 if let Some(obj) = json.as_object_mut() {
2345 obj.insert("results".to_string(), json!([]));
2346 } else {
2347 json = json!({"results": []});
2348 }
2349 }
2350 Json(json)
2351 }
2352 Err(e) => Json(json!({"results": [], "error": e.to_string()})),
2353 }
2354}
2355
2356#[derive(Deserialize)]
2357struct CortexWritePayload {
2358 name: String,
2359 content: String,
2360 kind: Option<String>,
2361}
2362
2363async fn handle_cortex_write(
2364 State(state): State<AppState>,
2365 Json(payload): Json<CortexWritePayload>,
2366) -> Result<Json<Value>, (StatusCode, String)> {
2367 let token = get_cortex_token().ok_or_else(|| {
2368 (
2369 StatusCode::INTERNAL_SERVER_ERROR,
2370 "Missing Cortex token".to_string(),
2371 )
2372 })?;
2373
2374 let body = json!({
2375 "kind": "entity",
2376 "value": {
2377 "space": "atlas-memory",
2378 "entityType": payload.kind.unwrap_or_else(|| "lesson".to_string()),
2379 "canonicalName": payload.name,
2380 "content": payload.content,
2381 "metadata": {
2382 "author": "AIEN",
2383 "source": "spark-cockpit-rs",
2384 "hardware": "NVIDIA DGX Spark GB10"
2385 }
2386 }
2387 });
2388
2389 let resp = state
2390 .client
2391 .post(format!("{}/api/cortex/write", CORTEX_URL))
2392 .header("Authorization", format!("Bearer {}", token))
2393 .json(&body)
2394 .send()
2395 .await
2396 .map_err(|e| (StatusCode::BAD_GATEWAY, e.to_string()))?;
2397
2398 let json = resp
2399 .json::<Value>()
2400 .await
2401 .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
2402
2403 Ok(Json(json))
2404}
2405
2406async fn handle_chat_stream(
2407 State(state): State<AppState>,
2408 Json(mut payload): Json<Value>,
2409) -> Response {
2410 payload["stream"] = json!(true);
2411 if payload.get("model").is_none() {
2412 payload["model"] = json!("atlas-lightning-omni");
2413 }
2414
2415 let patterns = state.redactor_patterns.clone();
2416 let upstream_resp = match state
2417 .client
2418 .post(format!("{}/v1/chat/completions", SEAT_URL))
2419 .json(&payload)
2420 .send()
2421 .await
2422 {
2423 Ok(r) => r,
2424 Err(e) => {
2425 return (
2426 StatusCode::BAD_GATEWAY,
2427 Json(json!({"error": format!("Model seat error: {}", e)})),
2428 )
2429 .into_response();
2430 }
2431 };
2432
2433 let stream = async_stream::stream! {
2434 let mut byte_stream = upstream_resp.bytes_stream();
2435 let mut content_redactor = StreamRedactor::new(patterns.clone());
2436 let mut reasoning_redactor = StreamRedactor::new(patterns);
2437 let mut line_buffer = String::new();
2438
2439 while let Some(chunk_result) = byte_stream.next().await {
2440 if let Ok(chunk) = chunk_result {
2441 let text = String::from_utf8_lossy(&chunk);
2442 line_buffer.push_str(&text);
2443
2444 while let Some(pos) = line_buffer.find('\n') {
2445 let line = line_buffer[..pos].trim().to_string();
2446 line_buffer = line_buffer[pos + 1..].to_string();
2447
2448 if let Some(stripped) = line.strip_prefix("data: ") {
2449 let data_str = stripped.trim();
2450 if data_str == "[DONE]" {
2451 let sc = content_redactor.flush();
2452 let sr = reasoning_redactor.flush();
2453 if !sc.is_empty() || !sr.is_empty() {
2454 let payload = json!({"content": sc, "reasoning": sr});
2455 yield Ok::<_, Infallible>(Event::default().data(payload.to_string()));
2456 }
2457 yield Ok(Event::default().data("[DONE]"));
2458 break;
2459 }
2460
2461 if let Ok(parsed) = serde_json::from_str::<Value>(data_str)
2462 && let Some(choices) = parsed.get("choices").and_then(Value::as_array)
2463 && let Some(choice) = choices.first()
2464 && let Some(delta) = choice.get("delta") {
2465 let raw_content = delta.get("content").and_then(Value::as_str).unwrap_or("");
2466 let raw_reasoning = delta.get("reasoning")
2467 .or_else(|| delta.get("reasoning_content"))
2468 .and_then(Value::as_str)
2469 .unwrap_or("");
2470
2471 let sc = if !raw_content.is_empty() { content_redactor.feed(raw_content) } else { String::new() };
2472 let sr = if !raw_reasoning.is_empty() { reasoning_redactor.feed(raw_reasoning) } else { String::new() };
2473
2474 if !sc.is_empty() || !sr.is_empty() {
2475 let payload = json!({"content": sc, "reasoning": sr});
2476 yield Ok(Event::default().data(payload.to_string()));
2477 }
2478 }
2479 }
2480 }
2481 }
2482 }
2483 };
2484
2485 Sse::new(stream)
2486 .keep_alive(KeepAlive::new().interval(Duration::from_secs(15)))
2487 .into_response()
2488}
2489
2490async fn handle_get_subagents() -> Json<Value> {
2491 let dir_buf = get_home_dir().join("basecamp/sessions/subagents");
2492 let dir = dir_buf.as_path();
2493 if !dir.exists() {
2494 return Json(json!({"subagents": [], "count": 0}));
2495 }
2496 let mut items = Vec::new();
2497 if let Ok(entries) = std::fs::read_dir(dir) {
2498 for entry in entries.flatten() {
2499 let path = entry.path();
2500 if path.extension().and_then(|s| s.to_str()) == Some("json")
2501 && let Ok(content) = std::fs::read_to_string(&path)
2502 && let Ok(parsed) = serde_json::from_str::<Value>(&content)
2503 {
2504 items.push(parsed);
2505 }
2506 }
2507 }
2508 Json(json!({"subagents": items, "count": items.len()}))
2509}
2510
2511#[derive(Debug, Deserialize)]
2512struct PostCombPayload {
2513 q: Option<i32>,
2514 r: Option<i32>,
2515 author: Option<String>,
2516 role: Option<String>,
2517 content: Option<String>,
2518 body: Option<String>,
2519 intent: Option<String>,
2520 parent_id: Option<String>,
2521}
2522
2523async fn handle_get_hive_cells(State(state): State<AppState>) -> Json<Value> {
2524 match state.hive_store.get_cells() {
2525 Ok((combs, bounds)) => {
2526 let cells: Vec<Value> = combs
2527 .iter()
2528 .map(|c| {
2529 json!({
2530 "id": c.id,
2531 "q": c.q,
2532 "r": c.r,
2533 "author": c.author,
2534 "role": c.role,
2535 "content": c.content,
2536 "body": c.content,
2537 "intent": c.intent,
2538 "parent_id": c.parent_id,
2539 "growthParentId": c.parent_id,
2540 "conversationId": c.parent_id.as_deref().unwrap_or(&c.id),
2541 "status": "visible",
2542 "membership": if c.role == "operator" { "guest" } else { "alumni" },
2543 "created_at": c.created_at,
2544 "neighbors": c.neighbors,
2545 })
2546 })
2547 .collect();
2548
2549 Json(json!({
2550 "combs": combs,
2551 "cells": cells,
2552 "bounds": {
2553 "min_q": bounds.min_q,
2554 "max_q": bounds.max_q,
2555 "min_r": bounds.min_r,
2556 "max_r": bounds.max_r,
2557 "count": bounds.count,
2558 "radius": bounds.radius,
2559 "revision": bounds.revision,
2560 "messageCount": bounds.message_count,
2561 "readOnly": false,
2562 "updatedAt": Utc::now().timestamp_millis()
2563 },
2564 "bounding_box": {
2565 "min_q": bounds.min_q,
2566 "max_q": bounds.max_q,
2567 "min_r": bounds.min_r,
2568 "max_r": bounds.max_r,
2569 "count": bounds.count
2570 }
2571 }))
2572 }
2573 Err(e) => Json(json!({"error": e.to_string(), "combs": [], "cells": []})),
2574 }
2575}
2576
2577async fn handle_get_hive_bounds(State(state): State<AppState>) -> Json<Value> {
2578 match state.hive_store.get_cells() {
2579 Ok((combs, bounds)) => Json(json!({
2580 "bounds": {
2581 "min_q": bounds.min_q,
2582 "max_q": bounds.max_q,
2583 "min_r": bounds.min_r,
2584 "max_r": bounds.max_r,
2585 "count": bounds.count,
2586 "radius": bounds.radius,
2587 "revision": bounds.revision,
2588 "messageCount": bounds.message_count,
2589 "readOnly": false,
2590 "updatedAt": Utc::now().timestamp_millis()
2591 },
2592 "count": combs.len()
2593 })),
2594 Err(e) => Json(json!({"error": e.to_string()})),
2595 }
2596}
2597
2598async fn handle_post_hive_comb(
2599 State(state): State<AppState>,
2600 Json(payload): Json<PostCombPayload>,
2601) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
2602 let content = payload.content.or(payload.body).unwrap_or_default();
2603 if content.trim().is_empty() {
2604 return Err((
2605 StatusCode::BAD_REQUEST,
2606 Json(json!({"error": "Comb content cannot be empty"})),
2607 ));
2608 }
2609
2610 let author = payload.author.unwrap_or_else(|| "AIEN".to_string());
2611 let input = spark_hive::PlaceCombInput {
2612 q: payload.q,
2613 r: payload.r,
2614 author,
2615 role: payload.role,
2616 content,
2617 intent: payload.intent,
2618 parent_id: payload.parent_id,
2619 };
2620
2621 match state.hive_store.place_comb(input) {
2622 Ok(comb) => {
2623 let (_, bounds) = state.hive_store.get_cells().unwrap_or_else(|_| {
2624 (
2625 vec![],
2626 spark_hive::BoundingBox {
2627 min_q: comb.q,
2628 max_q: comb.q,
2629 min_r: comb.r,
2630 max_r: comb.r,
2631 count: 1,
2632 radius: 5,
2633 revision: 1,
2634 message_count: 1,
2635 },
2636 )
2637 });
2638
2639 let formatted_cell = json!({
2640 "id": comb.id,
2641 "q": comb.q,
2642 "r": comb.r,
2643 "author": comb.author,
2644 "role": comb.role,
2645 "content": comb.content,
2646 "body": comb.content,
2647 "intent": comb.intent,
2648 "parent_id": comb.parent_id,
2649 "growthParentId": comb.parent_id,
2650 "conversationId": comb.parent_id.as_deref().unwrap_or(&comb.id),
2651 "status": "visible",
2652 "membership": if comb.role == "operator" { "guest" } else { "alumni" },
2653 "created_at": comb.created_at,
2654 "neighbors": comb.neighbors,
2655 });
2656
2657 Ok(Json(json!({
2658 "status": "placed",
2659 "comb": comb,
2660 "cell": formatted_cell,
2661 "bounds": {
2662 "min_q": bounds.min_q,
2663 "max_q": bounds.max_q,
2664 "min_r": bounds.min_r,
2665 "max_r": bounds.max_r,
2666 "count": bounds.count,
2667 "radius": bounds.radius,
2668 "revision": bounds.revision,
2669 "messageCount": bounds.message_count,
2670 "readOnly": false,
2671 "updatedAt": Utc::now().timestamp_millis()
2672 }
2673 })))
2674 }
2675 Err(spark_hive::HiveError::Collision { q, r, comb_id }) => Err((
2676 StatusCode::CONFLICT,
2677 Json(json!({
2678 "error": format!("Coordinate ({}, {}) is already occupied by comb '{}'", q, r, comb_id),
2679 "q": q,
2680 "r": r,
2681 "occupied_by": comb_id
2682 })),
2683 )),
2684 Err(e) => Err((
2685 StatusCode::INTERNAL_SERVER_ERROR,
2686 Json(json!({"error": e.to_string()})),
2687 )),
2688 }
2689}
2690
2691async fn handle_get_hive_adapters() -> Json<Value> {
2692 let adapters = spark_hive::get_catalog_adapters();
2693 let models = spark_hive::ConsumerModel::all();
2694 let engines = spark_hive::UpstreamEngine::all();
2695 Json(json!({
2696 "total_adapters": adapters.len(),
2697 "adapters": adapters,
2698 "models": models.iter().map(|m| json!({
2699 "slug": m.slug(),
2700 "name": m.display_name(),
2701 "params_b": m.param_count_billions(),
2702 "hf_repo": m.hf_repo(),
2703 "hardware": m.hardware_profile().description(),
2704 "quantization": m.recommended_quantization(),
2705 })).collect::<Vec<_>>(),
2706 "engines": engines.iter().map(|e| json!({
2707 "repo": e.repo(),
2708 "language": e.primary_language(),
2709 "description": e.description(),
2710 })).collect::<Vec<_>>(),
2711 }))
2712}
2713
2714async fn handle_get_hive_adapter_chains(State(state): State<AppState>) -> Json<Value> {
2715 match spark_hive::list_adapter_pipeline_chains(&state.hive_store) {
2716 Ok(chains) => Json(json!({
2717 "total_chains": chains.len(),
2718 "chains": chains
2719 })),
2720 Err(e) => Json(json!({"error": e.to_string(), "chains": []})),
2721 }
2722}
2723
2724#[derive(Debug, Deserialize)]
2725struct ForgeQuery {
2726 project: Option<String>,
2727 ring: Option<usize>,
2728 status: Option<String>,
2729}
2730
2731#[derive(Debug, Deserialize)]
2732struct ForgeProjectPayload {
2733 project: String,
2734 title: String,
2735 core_spec: String,
2736}
2737
2738// Every forge write takes an optional command_id: the same request under the
2739// same id is answered once (om/hive-task/task.om op 7, #925, DRA-288).
2740#[derive(Debug, Deserialize)]
2741struct ClaimForgePayload {
2742 task_id: String,
2743 agent_id: String,
2744 ttl_secs: Option<u64>,
2745 command_id: Option<String>,
2746}
2747
2748#[derive(Debug, Deserialize)]
2749struct HeartbeatForgePayload {
2750 task_id: String,
2751 agent_id: String,
2752 attempt_id: String,
2753 generation: i64,
2754 ttl_secs: Option<u64>,
2755 command_id: Option<String>,
2756}
2757
2758#[derive(Debug, Deserialize)]
2759struct SubmitForgePayload {
2760 task_id: String,
2761 agent_id: String,
2762 attempt_id: String,
2763 generation: i64,
2764 branch: String,
2765 pr_url: Option<String>,
2766 artifact: String,
2767 command_id: Option<String>,
2768}
2769
2770#[derive(Debug, Deserialize)]
2771struct VerifyForgePayload {
2772 task_id: String,
2773 generation: i64,
2774 artifact: String,
2775 verifier: String,
2776 verdict: bool,
2777 notes: Option<String>,
2778 command_id: Option<String>,
2779}
2780
2781#[derive(Debug, Default, Deserialize)]
2782struct ReclaimForgePayload {
2783 command_id: Option<String>,
2784}
2785
2786/// One reply shape for every forge mutation. A refusal is 409 with the task's
2787/// current status and generation; a busy database is 503 with retryable true.
2788fn forge_reply(
2789 result: Result<spark_hive::ForgeTask, spark_hive::HiveError>,
2790) -> (StatusCode, Json<Value>) {
2791 match result {
2792 Ok(task) => (
2793 StatusCode::OK,
2794 Json(json!({
2795 "success": true,
2796 "status": task.status,
2797 "generation": task.generation,
2798 "attempt_id": task.attempt_id,
2799 "task": task,
2800 })),
2801 ),
2802 Err(error) => forge_error(error),
2803 }
2804}
2805
2806/// A command id used before for a different request is 409 command_conflict.
2807fn forge_error(error: spark_hive::HiveError) -> (StatusCode, Json<Value>) {
2808 use spark_hive::HiveError;
2809 let (code, http) = match &error {
2810 HiveError::TaskNotFound(_) => ("not_found", StatusCode::NOT_FOUND),
2811 HiveError::Refused { .. } => ("refused", StatusCode::CONFLICT),
2812 HiveError::CommandConflict { .. } => ("command_conflict", StatusCode::CONFLICT),
2813 HiveError::Busy(_) => ("busy", StatusCode::SERVICE_UNAVAILABLE),
2814 HiveError::InvalidInput(_) => ("invalid", StatusCode::BAD_REQUEST),
2815 _ => ("db", StatusCode::INTERNAL_SERVER_ERROR),
2816 };
2817 let mut body = json!({
2818 "success": false,
2819 "code": code,
2820 "retryable": error.is_retryable(),
2821 "error": error.to_string(),
2822 });
2823 if let HiveError::Refused {
2824 status, generation, ..
2825 } = &error
2826 {
2827 body["status"] = json!(status);
2828 body["generation"] = json!(generation);
2829 }
2830 (http, Json(body))
2831}
2832
2833async fn handle_get_forge_tasks(
2834 State(state): State<AppState>,
2835 Query(query): Query<ForgeQuery>,
2836) -> Json<Value> {
2837 match state.hive_store.list_forge_tasks(
2838 query.project.as_deref(),
2839 query.ring,
2840 query.status.as_deref(),
2841 ) {
2842 Ok(tasks) => Json(json!({ "success": true, "tasks": tasks })),
2843 Err(e) => Json(json!({ "success": false, "error": e.to_string(), "tasks": [] })),
2844 }
2845}
2846
2847async fn handle_post_forge_project(
2848 State(state): State<AppState>,
2849 Json(payload): Json<ForgeProjectPayload>,
2850) -> (StatusCode, Json<Value>) {
2851 match state
2852 .hive_store
2853 .spawn_forge_project(&payload.project, &payload.title, &payload.core_spec)
2854 {
2855 Ok(task) => (
2856 StatusCode::CREATED,
2857 Json(json!({ "success": true, "task": task })),
2858 ),
2859 Err(e) => (
2860 StatusCode::BAD_REQUEST,
2861 Json(json!({ "success": false, "error": e.to_string() })),
2862 ),
2863 }
2864}
2865
2866async fn handle_post_forge_task(
2867 State(state): State<AppState>,
2868 Json(payload): Json<spark_hive::CreateForgeTaskInput>,
2869) -> (StatusCode, Json<Value>) {
2870 match state.hive_store.create_forge_task(payload) {
2871 Ok(task) => (
2872 StatusCode::CREATED,
2873 Json(json!({ "success": true, "task": task })),
2874 ),
2875 Err(e) => (
2876 StatusCode::BAD_REQUEST,
2877 Json(json!({ "success": false, "error": e.to_string() })),
2878 ),
2879 }
2880}
2881
2882/// A forge write body axum cannot parse (bad JSON, a missing or mistyped
2883/// field, a wrong content type) is the documented 400 `invalid` reply, not
2884/// axum's plain-text 400/415/422.
2885type ForgeJson<T> = Result<Json<T>, axum::extract::rejection::JsonRejection>;
2886
2887fn forge_body<T>(payload: ForgeJson<T>) -> Result<T, (StatusCode, Json<Value>)> {
2888 payload
2889 .map(|Json(p)| p)
2890 .map_err(|e| forge_error(spark_hive::HiveError::InvalidInput(e.body_text())))
2891}
2892
2893/// Lease length when a claim or heartbeat omits `ttl_secs` (AGENTS.md).
2894const DEFAULT_LEASE_SECS: u64 = 300;
2895
2896async fn handle_claim_forge_task(
2897 State(state): State<AppState>,
2898 payload: ForgeJson<ClaimForgePayload>,
2899) -> (StatusCode, Json<Value>) {
2900 let payload = match forge_body(payload) {
2901 Ok(p) => p,
2902 Err(reply) => return reply,
2903 };
2904 let ttl = payload.ttl_secs.unwrap_or(DEFAULT_LEASE_SECS);
2905 forge_reply(state.hive_store.claim_forge_task(
2906 &payload.task_id,
2907 &payload.agent_id,
2908 ttl,
2909 payload.command_id.as_deref(),
2910 ))
2911}
2912
2913async fn handle_heartbeat_forge_task(
2914 State(state): State<AppState>,
2915 payload: ForgeJson<HeartbeatForgePayload>,
2916) -> (StatusCode, Json<Value>) {
2917 let payload = match forge_body(payload) {
2918 Ok(p) => p,
2919 Err(reply) => return reply,
2920 };
2921 let fence = spark_hive::LeaseFence {
2922 agent_id: &payload.agent_id,
2923 attempt_id: &payload.attempt_id,
2924 generation: payload.generation,
2925 };
2926 let ttl = payload.ttl_secs.unwrap_or(DEFAULT_LEASE_SECS);
2927 forge_reply(state.hive_store.heartbeat_forge_task(
2928 &payload.task_id,
2929 &fence,
2930 ttl,
2931 payload.command_id.as_deref(),
2932 ))
2933}
2934
2935async fn handle_submit_forge_task(
2936 State(state): State<AppState>,
2937 payload: ForgeJson<SubmitForgePayload>,
2938) -> (StatusCode, Json<Value>) {
2939 let payload = match forge_body(payload) {
2940 Ok(p) => p,
2941 Err(reply) => return reply,
2942 };
2943 let fence = spark_hive::LeaseFence {
2944 agent_id: &payload.agent_id,
2945 attempt_id: &payload.attempt_id,
2946 generation: payload.generation,
2947 };
2948 forge_reply(state.hive_store.submit_forge_task(
2949 &payload.task_id,
2950 &fence,
2951 &payload.branch,
2952 payload.pr_url.as_deref(),
2953 &payload.artifact,
2954 payload.command_id.as_deref(),
2955 ))
2956}
2957
2958async fn handle_verify_forge_task(
2959 State(state): State<AppState>,
2960 payload: ForgeJson<VerifyForgePayload>,
2961) -> (StatusCode, Json<Value>) {
2962 let payload = match forge_body(payload) {
2963 Ok(p) => p,
2964 Err(reply) => return reply,
2965 };
2966 let notes = payload.notes.unwrap_or_default();
2967 forge_reply(state.hive_store.verify_forge_task(
2968 &payload.task_id,
2969 payload.generation,
2970 &payload.artifact,
2971 &payload.verifier,
2972 payload.verdict,
2973 &notes,
2974 payload.command_id.as_deref(),
2975 ))
2976}
2977
2978/// An empty body reclaims without a command id; a JSON body may carry one.
2979async fn handle_reclaim_forge_leases(
2980 State(state): State<AppState>,
2981 body: axum::body::Bytes,
2982) -> (StatusCode, Json<Value>) {
2983 let payload = if body.is_empty() {
2984 ReclaimForgePayload::default()
2985 } else {
2986 match serde_json::from_slice::<ReclaimForgePayload>(&body) {
2987 Ok(payload) => payload,
2988 Err(e) => {
2989 return forge_error(spark_hive::HiveError::InvalidInput(e.to_string()));
2990 }
2991 }
2992 };
2993 match state
2994 .hive_store
2995 .reclaim_expired_leases(payload.command_id.as_deref())
2996 {
2997 Ok(count) => (
2998 StatusCode::OK,
2999 Json(json!({ "success": true, "reclaimed_count": count })),
3000 ),
3001 Err(e) => forge_error(e),
3002 }
3003}
3004
3005fn operator_config_path() -> PathBuf {
3006 get_home_dir().join(".config/sovereign/operator.toml")
3007}
3008const MAIL_API_URL: &str = "http://127.0.0.1:18092";
3009
3010async fn handle_get_operator() -> Json<Value> {
3011 let op_cfg = operator_config_path();
3012 if op_cfg.exists()
3013 && let Ok(content) = fs::read_to_string(&op_cfg)
3014 && let Ok(toml_val) = toml::from_str::<Value>(&content)
3015 {
3016 return Json(toml_val);
3017 }
3018 Json(json!({
3019 "operator": {
3020 "name": "Drake Stapleton",
3021 "email": "drake@aienos.com",
3022 "handle": "drake",
3023 "sign_commits": true
3024 },
3025 "engine": {
3026 "mode": "seat",
3027 "api_base_url": "http://127.0.0.1:18006/v1",
3028 "model_id": "nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16",
3029 "seat_port": 18006,
3030 "context_window": 32768,
3031 "temperature": 0.7
3032 }
3033 }))
3034}
3035
3036#[derive(Debug, Deserialize)]
3037struct OperatorUpdatePayload {
3038 name: Option<String>,
3039 email: Option<String>,
3040 handle: Option<String>,
3041 sign_commits: Option<bool>,
3042}
3043
3044async fn handle_post_operator(
3045 Json(payload): Json<OperatorUpdatePayload>,
3046) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
3047 let clean_name = payload.name.map(|n| {
3048 n.chars()
3049 .filter(|c| !c.is_control())
3050 .take(64)
3051 .collect::<String>()
3052 });
3053 let clean_email = payload.email.map(|e| {
3054 e.chars()
3055 .filter(|c| !c.is_control())
3056 .take(128)
3057 .collect::<String>()
3058 });
3059 let clean_handle = payload.handle.map(|h| {
3060 h.chars()
3061 .filter(|c| c.is_alphanumeric() || *c == '_' || *c == '-')
3062 .take(32)
3063 .collect::<String>()
3064 });
3065
3066 let op_cfg = operator_config_path();
3067 let mut current_toml = if op_cfg.exists() {
3068 fs::read_to_string(operator_config_path())
3069 .ok()
3070 .and_then(|s| toml::from_str::<Value>(&s).ok())
3071 .unwrap_or_else(|| json!({}))
3072 } else {
3073 json!({})
3074 };
3075
3076 if !current_toml.is_object() {
3077 current_toml = json!({});
3078 }
3079
3080 let op_map = current_toml.as_object_mut().unwrap();
3081 let operator_obj = op_map.entry("operator").or_insert_with(|| json!({}));
3082 if let Some(obj) = operator_obj.as_object_mut() {
3083 if let Some(n) = clean_name {
3084 obj.insert("name".to_string(), json!(n));
3085 }
3086 if let Some(e) = clean_email {
3087 obj.insert("email".to_string(), json!(e));
3088 }
3089 if let Some(h) = clean_handle {
3090 obj.insert("handle".to_string(), json!(h));
3091 }
3092 if let Some(s) = payload.sign_commits {
3093 obj.insert("sign_commits".to_string(), json!(s));
3094 }
3095 }
3096
3097 let toml_str = toml::to_string_pretty(&current_toml).map_err(|e| {
3098 (
3099 StatusCode::BAD_REQUEST,
3100 Json(json!({"error": e.to_string()})),
3101 )
3102 })?;
3103
3104 let op_path = operator_config_path();
3105 if let Some(parent) = op_path.parent() {
3106 let _ = fs::create_dir_all(parent);
3107 }
3108 fs::write(&op_path, toml_str).map_err(|e| {
3109 (
3110 StatusCode::INTERNAL_SERVER_ERROR,
3111 Json(json!({"error": e.to_string()})),
3112 )
3113 })?;
3114
3115 Ok(Json(
3116 json!({"status": "saved", "operator": current_toml.get("operator")}),
3117 ))
3118}
3119
3120async fn handle_engine_status(State(state): State<AppState>) -> Json<Value> {
3121 let start = Instant::now();
3122 let health_res = state
3123 .client
3124 .get(format!("{}/health", SEAT_URL))
3125 .timeout(Duration::from_millis(500))
3126 .send()
3127 .await;
3128
3129 let latency_ms = start.elapsed().as_millis();
3130 let is_online = health_res.map(|r| r.status().is_success()).unwrap_or(false);
3131
3132 Json(json!({
3133 "status": if is_online { "online" } else { "offline" },
3134 "latency_ms": latency_ms,
3135 "active_engine": "Local model seat",
3136 "active_model": "nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16",
3137 "device": "Grace Blackwell GB10 (Dual GPU)",
3138 "port": 18006,
3139 "cost_per_million": "$0.00"
3140 }))
3141}
3142
3143/// Where the Spark judge publishes its bundles for this repository. One directory per judged
3144/// commit, each holding `bundle.json` with the verdict and one row per check.
3145fn judge_bundles_dir() -> PathBuf {
3146 match std::env::var("AIEN_JUDGE_BUNDLES") {
3147 Ok(p) if !p.is_empty() => PathBuf::from(p),
3148 _ => get_home_dir().join(".local/state/aien-local-ci/bundles/aien-sovereign-core"),
3149 }
3150}
3151
3152/// The Spark judge's newest verdict for the sovereign core, read from the local bundle store so
3153/// the harness shows a receipt instead of copy. When no bundle can be read the answer says so.
3154fn read_latest_judge_bundle(dir: &Path) -> Option<Value> {
3155 let mut newest: Option<(String, Value)> = None;
3156 for entry in fs::read_dir(dir).ok()?.flatten() {
3157 let path = entry.path().join("bundle.json");
3158 let Ok(text) = fs::read_to_string(&path) else {
3159 continue;
3160 };
3161 let Ok(bundle) = serde_json::from_str::<Value>(&text) else {
3162 continue;
3163 };
3164 let finished = bundle
3165 .get("finished_utc")
3166 .and_then(Value::as_str)
3167 .unwrap_or("")
3168 .to_string();
3169 if newest.as_ref().is_none_or(|(t, _)| finished > *t) {
3170 newest = Some((finished, bundle));
3171 }
3172 }
3173 let (finished_utc, bundle) = newest?;
3174 let checks = bundle
3175 .get("checks")
3176 .and_then(Value::as_array)
3177 .cloned()
3178 .unwrap_or_default();
3179 let count = |want: &str| {
3180 checks
3181 .iter()
3182 .filter(|c| c.get("verdict").and_then(Value::as_str) == Some(want))
3183 .count()
3184 };
3185 let commit = bundle
3186 .get("commit")
3187 .and_then(Value::as_str)
3188 .unwrap_or("")
3189 .to_string();
3190 Some(json!({
3191 "verdict": bundle.get("verdict").and_then(Value::as_str).unwrap_or("NO VERDICT"),
3192 "commit": commit,
3193 "repository": bundle.get("repository").and_then(Value::as_str).unwrap_or(""),
3194 "finished_utc": finished_utc,
3195 "checks_total": checks.len(),
3196 "checks_pass": count("PASS"),
3197 "checks_fail": count("FAIL"),
3198 "checks_blocked": checks.len() - count("PASS") - count("FAIL"),
3199 }))
3200}
3201
3202async fn handle_judge() -> Json<Value> {
3203 let dir = judge_bundles_dir();
3204 match tokio::task::spawn_blocking(move || read_latest_judge_bundle(&dir)).await {
3205 Ok(Some(v)) => Json(v),
3206 _ => Json(json!({
3207 "verdict": "NO VERDICT",
3208 "commit": "",
3209 "repository": "",
3210 "finished_utc": "",
3211 "checks_total": 0,
3212 "checks_pass": 0,
3213 "checks_fail": 0,
3214 "checks_blocked": 0,
3215 "note": "No Spark judge bundle could be read on this machine."
3216 })),
3217 }
3218}
3219
3220async fn handle_install_en2_imprint(
3221 State(state): State<AppState>,
3222) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
3223 let seed_path_buf = if Path::new("imprints/en2-trinity/cortex-seed.json").exists() {
3224 PathBuf::from("imprints/en2-trinity/cortex-seed.json")
3225 } else {
3226 get_home_dir().join("workspace/aien-sovereign-core/imprints/en2-trinity/cortex-seed.json")
3227 };
3228 let seed_path = seed_path_buf.as_path();
3229 if !seed_path.exists() {
3230 return Err((
3231 StatusCode::NOT_FOUND,
3232 Json(json!({"error": "EN2 imprint seed not found"})),
3233 ));
3234 }
3235
3236 let seed_data = fs::read_to_string(seed_path).map_err(|e| {
3237 (
3238 StatusCode::INTERNAL_SERVER_ERROR,
3239 Json(json!({"error": e.to_string()})),
3240 )
3241 })?;
3242 let lessons: Vec<Value> = serde_json::from_str(&seed_data).map_err(|e| {
3243 (
3244 StatusCode::BAD_REQUEST,
3245 Json(json!({"error": e.to_string()})),
3246 )
3247 })?;
3248
3249 let token = get_cortex_token().unwrap_or_default();
3250
3251 let mut installed_count = 0;
3252 for lesson in lessons {
3253 let payload = json!({
3254 "kind": "entity",
3255 "value": {
3256 "canonicalName": lesson["canonicalName"],
3257 "entityType": lesson["entityType"],
3258 "content": lesson["content"],
3259 "metadata": lesson["metadata"],
3260 "space": "atlas-memory"
3261 }
3262 });
3263
3264 let mut req = state
3265 .client
3266 .post(format!("{}/api/cortex/write", CORTEX_URL));
3267 if !token.is_empty() {
3268 req = req.header("Authorization", format!("Bearer {}", token));
3269 }
3270 if let Ok(res) = req.json(&payload).send().await
3271 && res.status().is_success()
3272 {
3273 installed_count += 1;
3274 }
3275 }
3276
3277 Ok(Json(json!({
3278 "status": "installed",
3279 "installed_count": installed_count,
3280 "version": "2.0.0",
3281 "imprint": "en2-trinity"
3282 })))
3283}
3284
3285/// Mail API bearer token: environment, then the owner-only file shared with
3286/// spark-mail (~/.config/aien/mail-api.token), then atlas-vault.
3287fn mail_access_token() -> String {
3288 if let Ok(value) = std::env::var("AIEN_MAIL_API_TOKEN")
3289 && !value.trim().is_empty()
3290 {
3291 return value.trim().to_owned();
3292 }
3293 spark_adapters::vault::resolve_secret("AIEN_MAIL_API_TOKEN").unwrap_or_default()
3294}
3295
3296async fn handle_mail_status(State(state): State<AppState>) -> Json<Value> {
3297 let res = state
3298 .client
3299 .get(format!("{}/api/mail/status", MAIL_API_URL))
3300 .bearer_auth(mail_access_token())
3301 .timeout(Duration::from_millis(500))
3302 .send()
3303 .await;
3304
3305 match res {
3306 Ok(r) if r.status().is_success() => {
3307 let val = r
3308 .json::<Value>()
3309 .await
3310 .unwrap_or(json!({"status": "error"}));
3311 Json(val)
3312 }
3313 _ => Json(json!({
3314 "status": "offline",
3315 "inbox_count": 0,
3316 "sent_count": 0,
3317 "smtp_port": 2525,
3318 "api_port": 18092,
3319 "cortex_connected": false
3320 })),
3321 }
3322}
3323
3324async fn handle_mail_inbox(State(state): State<AppState>) -> Json<Value> {
3325 let res = state
3326 .client
3327 .get(format!("{}/api/mail/inbox", MAIL_API_URL))
3328 .bearer_auth(mail_access_token())
3329 .timeout(Duration::from_millis(800))
3330 .send()
3331 .await;
3332
3333 match res {
3334 Ok(r) if r.status().is_success() => {
3335 let val = r.json::<Value>().await.unwrap_or(json!([]));
3336 Json(val)
3337 }
3338 _ => Json(json!([])),
3339 }
3340}
3341
3342async fn handle_mail_sent(State(state): State<AppState>) -> Json<Value> {
3343 let res = state
3344 .client
3345 .get(format!("{}/api/mail/sent", MAIL_API_URL))
3346 .bearer_auth(mail_access_token())
3347 .timeout(Duration::from_millis(800))
3348 .send()
3349 .await;
3350
3351 match res {
3352 Ok(r) if r.status().is_success() => {
3353 let val = r.json::<Value>().await.unwrap_or(json!([]));
3354 Json(val)
3355 }
3356 _ => Json(json!([])),
3357 }
3358}
3359
3360async fn handle_mail_send(
3361 State(state): State<AppState>,
3362 Json(payload): Json<Value>,
3363) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
3364 let res = state
3365 .client
3366 .post(format!("{}/api/mail/send", MAIL_API_URL))
3367 .bearer_auth(mail_access_token())
3368 .timeout(Duration::from_secs(90))
3369 .json(&payload)
3370 .send()
3371 .await
3372 .map_err(|e| {
3373 (
3374 StatusCode::INTERNAL_SERVER_ERROR,
3375 Json(json!({"error": e.to_string()})),
3376 )
3377 })?;
3378
3379 if res.status().is_success() {
3380 let val = res
3381 .json::<Value>()
3382 .await
3383 .unwrap_or(json!({"status": "sent"}));
3384 Ok(Json(val))
3385 } else {
3386 Err((
3387 StatusCode::BAD_GATEWAY,
3388 Json(json!({"error": "Failed to send via mail daemon"})),
3389 ))
3390 }
3391}
3392
3393#[cfg(test)]
3394mod tests {
3395 use super::*;
3396
3397 fn origin_headers(origin: Option<&str>) -> HeaderMap {
3398 let mut h = HeaderMap::new();
3399 if let Some(o) = origin {
3400 h.insert(axum::http::header::ORIGIN, o.parse().unwrap());
3401 }
3402 h
3403 }
3404
3405 #[test]
3406 fn terminal_allows_loopback_origin_and_peer() {
3407 let peer: SocketAddr = "127.0.0.1:50000".parse().unwrap();
3408 assert!(terminal_request_allowed(
3409 &origin_headers(Some("http://127.0.0.1:18095")),
3410 &peer
3411 ));
3412 assert!(terminal_request_allowed(
3413 &origin_headers(Some("http://localhost:18095")),
3414 &peer
3415 ));
3416 let peer6: SocketAddr = "[::1]:50000".parse().unwrap();
3417 assert!(terminal_request_allowed(
3418 &origin_headers(Some("http://localhost:18095")),
3419 &peer6
3420 ));
3421 }
3422
3423 #[test]
3424 fn terminal_rejects_missing_or_foreign_origin() {
3425 let peer: SocketAddr = "127.0.0.1:50000".parse().unwrap();
3426 assert!(!terminal_request_allowed(&origin_headers(None), &peer));
3427 assert!(!terminal_request_allowed(
3428 &origin_headers(Some("http://evil.example")),
3429 &peer
3430 ));
3431 assert!(!terminal_request_allowed(
3432 &origin_headers(Some("http://127.0.0.1:18095.evil.example")),
3433 &peer
3434 ));
3435 assert!(!terminal_request_allowed(
3436 &origin_headers(Some("http://192.0.2.10:18095")),
3437 &peer
3438 ));
3439 assert!(!terminal_request_allowed(
3440 &origin_headers(Some("null")),
3441 &peer
3442 ));
3443 }
3444
3445 #[test]
3446 fn terminal_rejects_non_loopback_peer() {
3447 let peer: SocketAddr = "192.0.2.50:50000".parse().unwrap();
3448 assert!(!terminal_request_allowed(
3449 &origin_headers(Some("http://127.0.0.1:18095")),
3450 &peer
3451 ));
3452 }
3453
3454 #[test]
3455 fn skill_index_omits_bodies_and_preview_is_one_paragraph() {
3456 let dir = std::env::temp_dir().join(format!("aien-skill-filter-{}", std::process::id()));
3457 let _ = fs::remove_dir_all(&dir);
3458 let skill_dir = dir.join("reactor");
3459 fs::create_dir_all(&skill_dir).unwrap();
3460 fs::write(
3461 skill_dir.join("SKILL.md"),
3462 "---\nname: reactor\ndescription: Thermal notes\n---\n# Heading\n\nAlpha beta gamma.\n\nThe reactor uses a graphite moderator.\n",
3463 )
3464 .unwrap();
3465
3466 let index = skill_index(&dir);
3467 let listed = &index["skills"][0];
3468 assert_eq!(listed["name"], "reactor");
3469 assert!(listed.get("content").is_none());
3470 assert_eq!(index["total"], 1);
3471
3472 let preview = skill_view(&dir, "reactor", "preview", None, 96);
3473 assert_eq!(preview["mode"], "preview");
3474 assert_eq!(preview["preview"], "Alpha beta gamma.");
3475 assert!(!preview["preview"].as_str().unwrap().contains("graphite"));
3476
3477 let search = skill_view(&dir, "reactor", "search", Some("graphite"), 96);
3478 assert_eq!(search["matches"][0]["paragraph"], 2);
3479 assert!(
3480 search["matches"][0]["snippet"]
3481 .as_str()
3482 .unwrap()
3483 .contains("graphite moderator")
3484 );
3485
3486 let _ = fs::remove_dir_all(&dir);
3487 }
3488
3489 fn create_test_state() -> AppState {
3490 let client = reqwest::Client::new();
3491 let hive_store = Arc::new(spark_hive::CombStore::open_in_memory().unwrap());
3492 let swarm_registry = Arc::new(SwarmRegistry::new_in_memory());
3493 let distill_engine = Arc::new(spark_adapters::DistillationEngine::new());
3494 AppState {
3495 client,
3496 start_time: Instant::now(),
3497 redactor_patterns: Arc::new(vec![]),
3498 hive_store,
3499 swarm_registry,
3500 distill_engine,
3501 }
3502 }
3503
3504 #[tokio::test]
3505 async fn test_cockpit_hive_cells_endpoint() {
3506 let state = create_test_state();
3507 let Json(res) = handle_get_hive_cells(State(state)).await;
3508
3509 assert!(res.get("combs").is_some());
3510 assert!(res.get("cells").is_some());
3511 assert!(res.get("bounds").is_some());
3512 assert!(res.get("bounding_box").is_some());
3513
3514 let combs = res.get("combs").unwrap().as_array().unwrap();
3515 assert_eq!(combs.len(), 1);
3516 assert_eq!(
3517 combs[0].get("author").unwrap().as_str().unwrap(),
3518 "AIEN Genesis"
3519 );
3520 }
3521
3522 #[tokio::test]
3523 async fn test_cockpit_hive_comb_endpoint_placement_and_collision() {
3524 let state = create_test_state();
3525
3526 // 1. Valid placement
3527 let payload = PostCombPayload {
3528 q: Some(1),
3529 r: Some(0),
3530 author: Some("Atlas".to_string()),
3531 role: Some("socratic".to_string()),
3532 content: Some("Socratic inquiry test comb".to_string()),
3533 body: None,
3534 intent: Some("branch".to_string()),
3535 parent_id: Some("comb-genesis-00000000".to_string()),
3536 };
3537
3538 let result = handle_post_hive_comb(State(state.clone()), Json(payload)).await;
3539 assert!(result.is_ok());
3540 let Json(val) = result.unwrap();
3541 assert_eq!(val.get("status").unwrap().as_str().unwrap(), "placed");
3542 let comb = val.get("comb").unwrap();
3543 assert_eq!(comb.get("q").unwrap().as_i64().unwrap(), 1);
3544 assert_eq!(comb.get("r").unwrap().as_i64().unwrap(), 0);
3545
3546 // 2. Collision rejection
3547 let collide_payload = PostCombPayload {
3548 q: Some(1),
3549 r: Some(0),
3550 author: Some("Intruder".to_string()),
3551 role: None,
3552 content: Some("Colliding text".to_string()),
3553 body: None,
3554 intent: None,
3555 parent_id: None,
3556 };
3557
3558 let err_result = handle_post_hive_comb(State(state), Json(collide_payload)).await;
3559 assert!(err_result.is_err());
3560 let (status, Json(err_val)) = err_result.unwrap_err();
3561 assert_eq!(status, StatusCode::CONFLICT);
3562 assert!(
3563 err_val
3564 .get("error")
3565 .unwrap()
3566 .as_str()
3567 .unwrap()
3568 .contains("occupied")
3569 );
3570 }
3571
3572 #[tokio::test]
3573 async fn test_cockpit_hive_bounds_endpoint() {
3574 let state = create_test_state();
3575 let Json(res) = handle_get_hive_bounds(State(state)).await;
3576 assert!(res.get("bounds").is_some());
3577 assert_eq!(res.get("count").unwrap().as_u64().unwrap(), 1);
3578 }
3579 #[tokio::test]
3580 async fn test_cockpit_hive_adapters_endpoint() {
3581 let Json(res) = handle_get_hive_adapters().await;
3582 assert!(res.get("adapters").is_some());
3583 assert!(res.get("models").is_some());
3584 assert!(res.get("engines").is_some());
3585 assert_eq!(res.get("models").unwrap().as_array().unwrap().len(), 9);
3586 }
3587
3588 #[tokio::test]
3589 async fn test_cockpit_hive_adapter_chains_endpoint() {
3590 let state = create_test_state();
3591 let Json(res) = handle_get_hive_adapter_chains(State(state)).await;
3592 assert!(res.get("chains").is_some());
3593 }
3594
3595 #[tokio::test]
3596 async fn test_cockpit_forge_lifecycle_endpoints() {
3597 let state = create_test_state();
3598
3599 // 1. Spawn forge project
3600 let project_payload = ForgeProjectPayload {
3601 project: "harvester".to_string(),
3602 title: "Model Harvester Pipeline".to_string(),
3603 core_spec: "Autonomous reasoning distillation".to_string(),
3604 };
3605 let (status, Json(res)) =
3606 handle_post_forge_project(State(state.clone()), Json(project_payload)).await;
3607 assert_eq!(status, StatusCode::CREATED);
3608 assert!(res.get("task").is_some());
3609 let task_id = res
3610 .get("task")
3611 .unwrap()
3612 .get("id")
3613 .unwrap()
3614 .as_str()
3615 .unwrap()
3616 .to_string();
3617
3618 // 2. Claim task under a command id
3619 let claim_payload = || ClaimForgePayload {
3620 task_id: task_id.clone(),
3621 agent_id: "agent-aegis".to_string(),
3622 ttl_secs: Some(120),
3623 command_id: Some("claim-1".to_string()),
3624 };
3625 let (status, Json(claim_res)) =
3626 handle_claim_forge_task(State(state.clone()), Ok(Json(claim_payload()))).await;
3627 assert_eq!(status, StatusCode::OK);
3628 assert_eq!(
3629 claim_res
3630 .get("task")
3631 .unwrap()
3632 .get("status")
3633 .unwrap()
3634 .as_str()
3635 .unwrap(),
3636 "claimed"
3637 );
3638 let attempt_id = claim_res["attempt_id"].as_str().unwrap().to_string();
3639 assert_eq!(claim_res["generation"], 1);
3640
3641 // The same request again is answered with the stored reply
3642 let (status, Json(replay)) =
3643 handle_claim_forge_task(State(state.clone()), Ok(Json(claim_payload()))).await;
3644 assert_eq!(status, StatusCode::OK);
3645 assert_eq!(replay, claim_res);
3646
3647 // Another agent's claim under the same command id is a conflict;
3648 // without one it is refused with the current state
3649 let second = ClaimForgePayload {
3650 task_id: task_id.clone(),
3651 agent_id: "agent-other".to_string(),
3652 ttl_secs: Some(120),
3653 command_id: Some("claim-1".to_string()),
3654 };
3655 let (status, Json(conflict)) =
3656 handle_claim_forge_task(State(state.clone()), Ok(Json(second))).await;
3657 assert_eq!(status, StatusCode::CONFLICT);
3658 assert_eq!(conflict["code"], "command_conflict");
3659 let second = ClaimForgePayload {
3660 task_id: task_id.clone(),
3661 agent_id: "agent-other".to_string(),
3662 ttl_secs: Some(120),
3663 command_id: None,
3664 };
3665 let (status, Json(refused)) =
3666 handle_claim_forge_task(State(state.clone()), Ok(Json(second))).await;
3667 assert_eq!(status, StatusCode::CONFLICT);
3668 assert_eq!(refused["code"], "refused");
3669 assert_eq!(refused["status"], "claimed");
3670
3671 // 3. Heartbeat
3672 let hb_payload = HeartbeatForgePayload {
3673 task_id: task_id.clone(),
3674 agent_id: "agent-aegis".to_string(),
3675 attempt_id: attempt_id.clone(),
3676 generation: 1,
3677 ttl_secs: Some(300),
3678 command_id: None,
3679 };
3680 let (status, _) =
3681 handle_heartbeat_forge_task(State(state.clone()), Ok(Json(hb_payload))).await;
3682 assert_eq!(status, StatusCode::OK);
3683
3684 // 4. Submit
3685 let submit_payload = SubmitForgePayload {
3686 task_id: task_id.clone(),
3687 agent_id: "agent-aegis".to_string(),
3688 attempt_id,
3689 generation: 1,
3690 branch: "feat/harvester-core".to_string(),
3691 pr_url: Some("https://github.com/aien-dev/harvester/pull/1".to_string()),
3692 artifact: "sha256:feed".to_string(),
3693 command_id: None,
3694 };
3695 let (status, _) =
3696 handle_submit_forge_task(State(state.clone()), Ok(Json(submit_payload))).await;
3697 assert_eq!(status, StatusCode::OK);
3698
3699 // 5. Verify
3700 let verify_payload = VerifyForgePayload {
3701 task_id: task_id.clone(),
3702 generation: 1,
3703 artifact: "sha256:feed".to_string(),
3704 verifier: "aegis".to_string(),
3705 verdict: true,
3706 notes: Some("All 4 defense checks passed".to_string()),
3707 command_id: None,
3708 };
3709 let (status, _) =
3710 handle_verify_forge_task(State(state.clone()), Ok(Json(verify_payload))).await;
3711 assert_eq!(status, StatusCode::OK);
3712
3713 // 6. List tasks
3714 let query = ForgeQuery {
3715 project: Some("harvester".to_string()),
3716 ring: None,
3717 status: Some("verified".to_string()),
3718 };
3719 let Json(list_res) = handle_get_forge_tasks(State(state), Query(query)).await;
3720 assert_eq!(list_res.get("tasks").unwrap().as_array().unwrap().len(), 1);
3721 }
3722
3723 #[tokio::test]
3724 async fn test_cockpit_operator_profile_sanitization() {
3725 let payload = OperatorUpdatePayload {
3726 name: Some(
3727 "Drake Stapleton
3728"
3729 .to_string(),
3730 ),
3731 email: Some("drake@aienos.com".to_string()),
3732 handle: Some("drake_ops-1".to_string()),
3733 sign_commits: Some(true),
3734 };
3735 let res = handle_post_operator(Json(payload)).await;
3736 assert!(res.is_ok());
3737 let Json(body) = res.unwrap();
3738 let op = body.get("operator").unwrap();
3739 assert_eq!(op.get("name").unwrap().as_str().unwrap(), "Drake Stapleton");
3740 assert_eq!(
3741 op.get("email").unwrap().as_str().unwrap(),
3742 "drake@aienos.com"
3743 );
3744 assert_eq!(op.get("handle").unwrap().as_str().unwrap(), "drake_ops-1");
3745 }
3746
3747 fn create_offline_test_state() -> AppState {
3748 let client = reqwest::Client::builder()
3749 .timeout(Duration::from_millis(50))
3750 .build()
3751 .unwrap();
3752 let hive_store = Arc::new(spark_hive::CombStore::open_in_memory().unwrap());
3753 let swarm_registry = Arc::new(SwarmRegistry::new_in_memory());
3754 let distill_engine = Arc::new(spark_adapters::DistillationEngine::new());
3755 AppState {
3756 client,
3757 start_time: Instant::now(),
3758 redactor_patterns: Arc::new(vec![]),
3759 hive_store,
3760 swarm_registry,
3761 distill_engine,
3762 }
3763 }
3764
3765 #[tokio::test]
3766 async fn test_cockpit_pulse_endpoint_schema_and_offline_backends() {
3767 let state = create_test_state();
3768 let Json(pulse) = handle_pulse(State(state)).await;
3769
3770 assert_eq!(pulse["status"], "ok");
3771 assert_eq!(pulse["heartbeat_bpm"], 72);
3772 assert!((pulse["coherence"].as_f64().unwrap() - 0.98).abs() < 1e-4);
3773 assert!(pulse["uptime_seconds"].as_u64().is_some());
3774
3775 let model_seat = pulse["model_seat"].as_str().unwrap();
3776 assert!(model_seat == "ONLINE (Port 18006)" || model_seat == "OFFLINE");
3777
3778 let conduit_seat = pulse["conduit_seat"].as_str().unwrap();
3779 assert!(conduit_seat == "ONLINE (Port 6167)" || conduit_seat == "OFFLINE");
3780
3781 assert!(pulse["hive_count"].as_u64().is_some());
3782 assert!(pulse["timestamp"].as_str().is_some());
3783 }
3784
3785 #[tokio::test]
3786 async fn test_cockpit_status_endpoint_schema_and_offline_backend() {
3787 let state = create_test_state();
3788 let Json(status) = handle_engine_status(State(state)).await;
3789
3790 let status_str = status["status"].as_str().unwrap();
3791 assert!(status_str == "online" || status_str == "offline");
3792 assert!(status["latency_ms"].as_u64().is_some());
3793 assert_eq!(status["active_engine"], "Local model seat");
3794 assert_eq!(
3795 status["active_model"],
3796 "nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16"
3797 );
3798 assert_eq!(status["device"], "Grace Blackwell GB10 (Dual GPU)");
3799 assert_eq!(status["port"], 18006);
3800 assert_eq!(status["cost_per_million"], "$0.00");
3801 }
3802
3803 #[tokio::test]
3804 async fn test_cockpit_cortex_search_endpoint_unreachable_fallback() {
3805 let state = create_offline_test_state();
3806 let query = CortexSearchQuery {
3807 q: Some("test_unreachable_cortex".to_string()),
3808 limit: Some(3),
3809 };
3810 let Json(res) = handle_cortex_search(State(state), Query(query)).await;
3811 assert!(res.get("results").is_some());
3812 let results = res.get("results").unwrap().as_array().unwrap();
3813 assert_eq!(results.len(), 0);
3814 }
3815
3816 #[tokio::test]
3817 async fn test_cockpit_cortex_write_endpoint_error_handling() {
3818 let state = create_offline_test_state();
3819 let payload = CortexWritePayload {
3820 name: "test_cockpit_write".to_string(),
3821 content: "Telemetry payload".to_string(),
3822 kind: Some("telemetry".to_string()),
3823 };
3824
3825 let res = handle_cortex_write(State(state), Json(payload)).await;
3826 // Verify proper error response or graceful handling
3827 if let Err((status, _)) = res {
3828 assert!(
3829 status == StatusCode::BAD_GATEWAY || status == StatusCode::INTERNAL_SERVER_ERROR
3830 );
3831 }
3832 }
3833
3834 #[tokio::test]
3835 async fn test_cockpit_subagents_endpoint_response_structure() {
3836 let Json(res) = handle_get_subagents().await;
3837 assert!(res.get("subagents").is_some());
3838 assert!(res.get("count").is_some());
3839 let subagents = res.get("subagents").unwrap().as_array().unwrap();
3840 let count = res.get("count").unwrap().as_u64().unwrap();
3841 assert_eq!(subagents.len() as u64, count);
3842 }
3843
3844 #[tokio::test]
3845 async fn test_cockpit_submillisecond_latency_assertions() {
3846 let state = create_test_state();
3847
3848 let max_duration = if std::env::var("CI").is_ok() {
3849 Duration::from_millis(15)
3850 } else {
3851 Duration::from_millis(2)
3852 };
3853
3854 // 1. Subagents local file/memory check latency assertion
3855 let t0 = Instant::now();
3856 let _ = handle_get_subagents().await;
3857 let elapsed_subagents = t0.elapsed();
3858 assert!(
3859 elapsed_subagents < max_duration,
3860 "Subagents latency within limit: {:?}",
3861 elapsed_subagents
3862 );
3863
3864 // 2. Hive bounds retrieval latency assertion
3865 let t1 = Instant::now();
3866 let _ = handle_get_hive_bounds(State(state.clone())).await;
3867 let elapsed_bounds = t1.elapsed();
3868 assert!(
3869 elapsed_bounds < max_duration,
3870 "Hive bounds latency within limit: {:?}",
3871 elapsed_bounds
3872 );
3873
3874 // 3. Hive cells in-memory store latency assertion
3875 let t2 = Instant::now();
3876 let _ = handle_get_hive_cells(State(state)).await;
3877 let elapsed_cells = t2.elapsed();
3878 assert!(
3879 elapsed_cells < max_duration,
3880 "Hive cells latency within limit: {:?}",
3881 elapsed_cells
3882 );
3883 }
3884
3885 #[tokio::test]
3886 async fn test_cockpit_telemetry_live_endpoint() {
3887 let Json(res) = handle_telemetry_live().await;
3888 assert_eq!(res["status"], "ok");
3889 assert!(res["timestamp"].as_str().is_some());
3890
3891 // Zero fake metrics check
3892 assert!(res.get("heartbeat_bpm").is_none());
3893 assert!(res.get("coherence").is_none());
3894
3895 // GPU telemetry
3896 let gpu = &res["gpu"];
3897 assert_eq!(gpu["model"], "NVIDIA GB10");
3898 assert!(gpu["temperature_c"].as_f64().is_some());
3899 assert!(gpu["power_draw_w"].as_f64().is_some());
3900
3901 // Memory telemetry
3902 let mem = &res["memory"];
3903 assert!(mem["total_kb"].as_u64().unwrap_or(0) > 0);
3904 assert!(mem["available_kb"].as_u64().is_some());
3905
3906 // CPU telemetry
3907 let cpu = &res["cpu"];
3908 assert_eq!(cpu["cores"].as_u64(), Some(20));
3909 assert!(cpu["load_1m"].as_f64().is_some());
3910
3911 // TPM telemetry
3912 let tpm = &res["tpm"];
3913 assert_eq!(tpm["device"], "/dev/tpmrm0");
3914 assert!(tpm["present"].as_bool().is_some());
3915 }
3916
3917 #[tokio::test]
3918 async fn test_cockpit_services_list_endpoint() {
3919 let Json(res) = handle_services_list().await;
3920 assert_eq!(res["status"], "ok");
3921 let svcs = res["services"].as_array().unwrap();
3922 assert_eq!(svcs.len(), 5);
3923
3924 let ids: Vec<&str> = svcs.iter().map(|s| s["id"].as_str().unwrap()).collect();
3925 assert!(ids.contains(&"max-server"));
3926 assert!(ids.contains(&"cortex-rs"));
3927 assert!(ids.contains(&"cortex-encoder"));
3928 assert!(ids.contains(&"aegis"));
3929 assert!(ids.contains(&"spark-rsi"));
3930 }
3931
3932 #[tokio::test]
3933 async fn test_cockpit_services_action_invalid_action() {
3934 let payload = ServiceActionPayload {
3935 service: "cortex-rs".to_string(),
3936 action: "invalid_action".to_string(),
3937 };
3938 let res = handle_services_action(Json(payload)).await;
3939 assert!(res.is_err());
3940 let (status, Json(err)) = res.unwrap_err();
3941 assert_eq!(status, StatusCode::BAD_REQUEST);
3942 assert!(err["error"].as_str().unwrap().contains("Invalid action"));
3943 }
3944
3945 /// Issue #369: the cockpit must never launch the Modular MAX server (removed from
3946 /// AIEN on 2026-10-15; its launcher depended on Python). Start and restart
3947 /// are refused loudly instead of spawning anything.
3948 #[tokio::test]
3949 async fn test_cockpit_services_action_max_server_never_launched() {
3950 for action in ["start", "restart", "START"] {
3951 let payload = ServiceActionPayload {
3952 service: "max-server".to_string(),
3953 action: action.to_string(),
3954 };
3955 let res = handle_services_action(Json(payload)).await;
3956 let (status, Json(err)) = res.expect_err("max-server launch must be refused");
3957 assert_eq!(status, StatusCode::CONFLICT, "action {action}");
3958 assert_eq!(err["status"], "error");
3959 assert_eq!(err["service"], "max-server");
3960 assert!(
3961 err["error"]
3962 .as_str()
3963 .unwrap()
3964 .contains("does not launch it"),
3965 "action {action}: {err}"
3966 );
3967 }
3968 }
3969
3970 #[tokio::test]
3971 async fn test_cockpit_swarm_lifecycle_registry() {
3972 let state = create_test_state();
3973
3974 // 1. Spawn task
3975 let spawn_payload = SwarmSpawnPayload {
3976 project: Some("spark-cockpit-rs".to_string()),
3977 role: "Avionics Auditor".to_string(),
3978 prompt: "Verify telemetry latency and accuracy".to_string(),
3979 model: Some("atlas-lightning-omni".to_string()),
3980 ring: Some(1),
3981 };
3982 let (status, Json(spawn_res)) =
3983 handle_swarm_spawn(State(state.clone()), Json(spawn_payload)).await;
3984 assert_eq!(status, StatusCode::CREATED);
3985 let task_id = spawn_res["task"]["id"].as_str().unwrap().to_string();
3986 assert_eq!(spawn_res["task"]["state"], "running");
3987
3988 // 2. List tasks
3989 let Json(list_res) = handle_swarm_tasks(State(state.clone())).await;
3990 let tasks = list_res["tasks"].as_array().unwrap();
3991 assert!(tasks.iter().any(|t| t["id"] == task_id));
3992
3993 // 3. Kill task
3994 let kill_payload = SwarmKillPayload {
3995 task_id: task_id.clone(),
3996 };
3997 let (status, Json(kill_res)) =
3998 handle_swarm_kill(State(state.clone()), Json(kill_payload)).await;
3999 assert_eq!(status, StatusCode::OK);
4000 assert_eq!(kill_res["status"], "ok");
4001
4002 // Verify task state is cancelled
4003 let Json(list_after) = handle_swarm_tasks(State(state)).await;
4004 let tasks_after = list_after["tasks"].as_array().unwrap();
4005 let target = tasks_after.iter().find(|t| t["id"] == task_id).unwrap();
4006 assert_eq!(target["state"], "cancelled");
4007 assert!(target["completed_at"].as_str().is_some());
4008 }
4009
4010 #[tokio::test]
4011 async fn test_cockpit_rsi_ledger_endpoint() {
4012 let query = RsiLedgerQuery { limit: Some(5) };
4013 let Json(res) = handle_rsi_ledger(Query(query)).await;
4014 assert_eq!(res["status"], "ok");
4015 assert!(res["recent_blocks"].as_array().is_some());
4016 assert!(res["checkpoints"].as_array().is_some());
4017 assert!(res["total_blocks"].as_i64().is_some());
4018 }
4019
4020 #[tokio::test]
4021 async fn test_cockpit_workshop_models_endpoint() {
4022 let state = create_test_state();
4023 let Json(res) = handle_workshop_models(State(state)).await;
4024 assert_eq!(res["status"], "ok");
4025 let models = res["models"].as_array().expect("models array");
4026 assert!(!models.is_empty());
4027 assert!(models.iter().any(|m| m["id"] == "atlas-lightning-omni"));
4028 let tracks = res["tracks"].as_array().expect("tracks array");
4029 assert_eq!(tracks.len(), 5);
4030 }
4031
4032 #[tokio::test]
4033 async fn test_cockpit_workshop_distill_validation() {
4034 let state = create_test_state();
4035
4036 // 1. Missing teacher
4037 let payload_no_teacher = WorkshopDistillPayload {
4038 prompt: Some("Write an allocation-free ring buffer".to_string()),
4039 track: None,
4040 teacher_model: "".to_string(),
4041 student_model: None,
4042 verification_strategy: None,
4043 system_prompt: None,
4044 commit_to_cortex: false,
4045 };
4046 let err1 = handle_workshop_distill(State(state.clone()), Json(payload_no_teacher)).await;
4047 assert!(err1.is_err());
4048 assert_eq!(err1.unwrap_err().0, StatusCode::BAD_REQUEST);
4049
4050 // 2. Empty prompt and no track
4051 let payload_empty = WorkshopDistillPayload {
4052 prompt: Some(" ".to_string()),
4053 track: None,
4054 teacher_model: "openai/gpt-4o".to_string(),
4055 student_model: None,
4056 verification_strategy: None,
4057 system_prompt: None,
4058 commit_to_cortex: false,
4059 };
4060 let err2 = handle_workshop_distill(State(state.clone()), Json(payload_empty)).await;
4061 assert!(err2.is_err());
4062 assert_eq!(err2.unwrap_err().0, StatusCode::BAD_REQUEST);
4063
4064 // 3. Invalid track
4065 let payload_invalid_track = WorkshopDistillPayload {
4066 prompt: None,
4067 track: Some("invalid_curriculum_name".to_string()),
4068 teacher_model: "openai/gpt-4o".to_string(),
4069 student_model: None,
4070 verification_strategy: None,
4071 system_prompt: None,
4072 commit_to_cortex: false,
4073 };
4074 let err3 = handle_workshop_distill(State(state.clone()), Json(payload_invalid_track)).await;
4075 assert!(err3.is_err());
4076 assert_eq!(err3.unwrap_err().0, StatusCode::BAD_REQUEST);
4077 }
4078
4079 #[tokio::test]
4080 async fn test_cockpit_workshop_commit_validation() {
4081 let state = create_test_state();
4082
4083 let payload_empty = WorkshopCommitPayload {
4084 name: "test_empty".to_string(),
4085 content: " ".to_string(),
4086 kind: None,
4087 task_id: None,
4088 confidence: None,
4089 };
4090 let res = handle_workshop_commit(State(state), Json(payload_empty)).await;
4091 assert!(res.is_err());
4092 assert_eq!(res.unwrap_err().0, StatusCode::BAD_REQUEST);
4093 }
4094
4095 #[tokio::test]
4096 async fn test_cockpit_workshop_html_route() {
4097 let response = handle_workshop().await.into_response();
4098 assert_eq!(response.status(), StatusCode::OK);
4099 }
4100 #[tokio::test]
4101 async fn test_cockpit_feed_endpoint() {
4102 let state = create_test_state();
4103 let Json(feed) = handle_get_feed(State(state)).await;
4104 assert_eq!(feed["status"], "ok");
4105 assert!(feed["feed"].as_array().is_some());
4106 }
4107
4108 // sovereign-core #380 R4c: the cockpit lists no approval and names the desk.
4109 #[tokio::test]
4110 async fn test_cockpit_approvals_only_from_the_desk() {
4111 let Json(apprs) = handle_get_approvals().await;
4112 assert_eq!(apprs["status"], "ok");
4113 assert_eq!(apprs["approvals"], json!([]));
4114 assert_eq!(apprs["issuer"], APPROVALS_ISSUER);
4115 }
4116
4117 // sovereign-core #380 R4d: resolve refuses every id by name, including
4118 // the ids of the removed placeholders.
4119 #[tokio::test]
4120 async fn test_cockpit_resolve_is_refused_not_the_desk() {
4121 for id in ["appr-gb10-parity", "appr-cortex-sync", "anything"] {
4122 let (code, Json(res)) =
4123 handle_resolve_approval(axum::extract::Path(id.to_string())).await;
4124 assert_eq!(code, StatusCode::CONFLICT);
4125 assert_eq!(res["status"], "error");
4126 assert_eq!(res["refusal"], "NotTheDesk");
4127 assert_eq!(res["id"], id);
4128 assert!(res.get("approval").is_none());
4129 }
4130 let Json(apprs) = handle_get_approvals().await;
4131 assert_eq!(apprs["approvals"], json!([]));
4132 }
4133
4134 // sovereign-core #380 R4e: the feed announces no approval.
4135 #[tokio::test]
4136 async fn test_cockpit_feed_has_no_approvals_item() {
4137 let Json(feed) = handle_get_feed(State(create_test_state())).await;
4138 let items = feed["feed"].as_array().unwrap();
4139 assert!(items.iter().all(|i| i["category"] != "approvals"));
4140 }
4141}