diff --git a/Cargo.lock b/Cargo.lock index af007f05..c07ae065 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -321,6 +321,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" dependencies = [ "axum-core 0.5.6", + "base64 0.22.1", "bytes", "form_urlencoded", "futures-util", @@ -339,8 +340,10 @@ dependencies = [ "serde_json", "serde_path_to_error", "serde_urlencoded", + "sha1", "sync_wrapper", "tokio", + "tokio-tungstenite 0.29.0", "tower", "tower-layer", "tower-service", @@ -443,6 +446,12 @@ version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + [[package]] name = "bitflags" version = "2.13.2" @@ -780,7 +789,7 @@ version = "0.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f476fe445d41c9e991fd07515a6f463074b782242ccf4a5b7b1d1012e70824df" dependencies = [ - "bitflags", + "bitflags 2.13.2", "crossterm_winapi", "libc", "mio 0.8.11", @@ -975,6 +984,12 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + [[package]] name = "dunce" version = "1.0.5" @@ -1103,6 +1118,17 @@ version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" +[[package]] +name = "filedescriptor" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e40758ed24c9b2eeb76c35fb0aebc66c626084edd827e07e1552279814c6682d" +dependencies = [ + "libc", + "thiserror 1.0.69", + "winapi", +] + [[package]] name = "find-msvc-tools" version = "0.1.13" @@ -2018,7 +2044,7 @@ version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4" dependencies = [ - "bitflags", + "bitflags 2.13.2", "cfg-if", "cfg_aliases 0.1.1", "libc", @@ -2154,7 +2180,7 @@ version = "6.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0cc3cbf698f9438986c11a880c90a6d04b9de27575afd28bbf45b154b6c709e2" dependencies = [ - "bitflags", + "bitflags 2.13.2", "libc", "once_cell", "onig_sys", @@ -2176,7 +2202,7 @@ version = "0.10.81" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" dependencies = [ - "bitflags", + "bitflags 2.13.2", "cfg-if", "foreign-types", "libc", @@ -2315,6 +2341,27 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "portable-pty" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4a596a2b3d2752d94f51fac2d4a96737b8705dddd311a32b9af47211f08671e" +dependencies = [ + "anyhow", + "bitflags 1.3.2", + "downcast-rs", + "filedescriptor", + "lazy_static", + "libc", + "log", + "nix", + "serial2", + "shared_library", + "shell-words", + "winapi", + "winreg", +] + [[package]] name = "potential_utf" version = "0.1.6" @@ -2577,7 +2624,7 @@ version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags", + "bitflags 2.13.2", ] [[package]] @@ -2719,7 +2766,7 @@ version = "0.31.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b838eba278d213a8beaf485bd313fd580ca4505a00d5871caeb1457c55322cae" dependencies = [ - "bitflags", + "bitflags 2.13.2", "chrono", "csv", "fallible-iterator", @@ -2754,7 +2801,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" dependencies = [ - "bitflags", + "bitflags 2.13.2", "errno", "libc", "linux-raw-sys", @@ -2849,7 +2896,7 @@ version = "14.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7803e8936da37efd9b6d4478277f4b2b9bb5cdb37a113e8d63222e58da647e63" dependencies = [ - "bitflags", + "bitflags 2.13.2", "cfg-if", "clipboard-win", "fd-lock", @@ -2901,7 +2948,7 @@ version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" dependencies = [ - "bitflags", + "bitflags 2.13.2", "core-foundation 0.10.1", "core-foundation-sys", "libc", @@ -2999,6 +3046,17 @@ dependencies = [ "serde", ] +[[package]] +name = "serial2" +version = "0.2.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b16809bc35793b19ce4e0c53924bc0dce3937f15487997cfdaed936004180730" +dependencies = [ + "cfg-if", + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "sha1" version = "0.10.7" @@ -3030,6 +3088,22 @@ dependencies = [ "lazy_static", ] +[[package]] +name = "shared_library" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a9e7e0f2bfae24d8a5b5a66c5b257a83c7412304311512a0c054cd5e619da11" +dependencies = [ + "lazy_static", + "libc", +] + +[[package]] +name = "shell-words" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77" + [[package]] name = "shlex" version = "2.0.1" @@ -3167,8 +3241,10 @@ dependencies = [ "chrono", "form_urlencoded", "futures-util", + "portable-pty", "regex", "reqwest 0.13.5", + "rusqlite", "serde", "serde_json", "spark-hive", @@ -3219,7 +3295,7 @@ dependencies = [ "serde", "serde_json", "tokio", - "tokio-tungstenite", + "tokio-tungstenite 0.24.0", "tracing", "tracing-subscriber", ] @@ -3448,7 +3524,7 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" dependencies = [ - "bitflags", + "bitflags 2.13.2", "core-foundation 0.9.4", "system-configuration-sys", ] @@ -3664,10 +3740,22 @@ dependencies = [ "rustls-pki-types", "tokio", "tokio-rustls", - "tungstenite", + "tungstenite 0.24.0", "webpki-roots 0.26.11", ] +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite 0.29.0", +] + [[package]] name = "tokio-util" version = "0.7.19" @@ -3745,7 +3833,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e9cd434a998747dd2c4276bc96ee2e0c7a2eadf3cae88e52be55a05fa9053f5" dependencies = [ - "bitflags", + "bitflags 2.13.2", "bytes", "http", "http-body", @@ -3762,7 +3850,7 @@ version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" dependencies = [ - "bitflags", + "bitflags 2.13.2", "bytes", "futures-util", "http", @@ -3781,7 +3869,7 @@ version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08a05a66a4fdd61cbbe0a1d755ffe0ca6aba159dd4820936a0ff8a8278245b9c" dependencies = [ - "bitflags", + "bitflags 2.13.2", "bytes", "futures-core", "futures-util", @@ -3900,6 +3988,22 @@ dependencies = [ "utf-8", ] +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1", + "thiserror 2.0.20", +] + [[package]] name = "typenum" version = "1.20.1" @@ -4476,6 +4580,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "winreg" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d" +dependencies = [ + "winapi", +] + [[package]] name = "wit-bindgen" version = "0.57.1" diff --git a/crates/spark-cockpit-rs/Cargo.toml b/crates/spark-cockpit-rs/Cargo.toml index d671ac47..50a95c5f 100644 --- a/crates/spark-cockpit-rs/Cargo.toml +++ b/crates/spark-cockpit-rs/Cargo.toml @@ -7,7 +7,7 @@ edition = "2024" [dependencies] async-stream = "0.3.6" -axum = "0.8.9" +axum = { version = "0.8.9", features = ["ws"] } chrono = "0.4.45" form_urlencoded = "1.2" futures-util = "0.3.34" @@ -16,6 +16,8 @@ reqwest = { version = "0.13.5", features = ["json", "stream"] } serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.151" spark-hive = { path = "../spark-hive" } +portable-pty = "0.9.0" +rusqlite = { version = "0.31.0", features = ["bundled"] } tokio = { version = "1.53.1", features = ["full"] } tower-http = { version = "0.7.1", features = ["fs", "cors"] } toml = "0.8" diff --git a/crates/spark-cockpit-rs/src/main.rs b/crates/spark-cockpit-rs/src/main.rs index 98ac906a..1e0639e6 100644 --- a/crates/spark-cockpit-rs/src/main.rs +++ b/crates/spark-cockpit-rs/src/main.rs @@ -1,6 +1,9 @@ use axum::{ Router, - extract::{Query, State}, + extract::{ + Query, State, + ws::{Message, WebSocket, WebSocketUpgrade}, + }, http::{HeaderMap, StatusCode}, response::{ IntoResponse, Json, Response, @@ -9,13 +12,15 @@ use axum::{ routing::{get, post}, }; use chrono::Utc; -use futures_util::StreamExt; +use futures_util::{SinkExt, StreamExt}; +use portable_pty::{CommandBuilder, PtySize, native_pty_system}; use regex::Regex; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use std::collections::HashSet; use std::convert::Infallible; use std::fs; +use std::io::{Read, Write}; use std::net::SocketAddr; use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -62,8 +67,206 @@ fn static_dir() -> PathBuf { } } -fn cortex_token_path() -> PathBuf { - get_home_dir().join(".config/cortex/token") +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SwarmTask { + pub id: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub project: Option, + pub role: String, + pub prompt: String, + #[serde(default = "default_swarm_model")] + pub model: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub ring: Option, + pub state: String, + pub created_at: String, + pub updated_at: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub completed_at: Option, + #[serde(default)] + pub thought_trace: Vec, + #[serde(default)] + pub logs: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub pid: Option, +} + +fn default_swarm_model() -> String { + "atlas-lightning-omni".to_string() +} + +pub struct SwarmRegistry { + tasks: std::sync::RwLock>, + journal_path: Option, +} + +impl SwarmRegistry { + pub fn new_persistent(journal_path: PathBuf) -> Self { + let mut loaded_tasks = Vec::new(); + if journal_path.exists() + && let Ok(content) = fs::read_to_string(&journal_path) + && let Ok(parsed) = serde_json::from_str::>(&content) + { + loaded_tasks = parsed; + } + if loaded_tasks.is_empty() { + let subagent_dir = get_home_dir().join("basecamp/sessions/subagents"); + if let Ok(entries) = fs::read_dir(subagent_dir) { + for entry in entries.flatten() { + let path = entry.path(); + if path.extension().and_then(|s| s.to_str()) == Some("json") + && let Ok(content) = fs::read_to_string(&path) + && let Ok(val) = serde_json::from_str::(&content) + { + let id = val + .get("id") + .or_else(|| val.get("task_id")) + .and_then(Value::as_str) + .unwrap_or("subagent") + .to_string(); + let role = val + .get("role") + .and_then(Value::as_str) + .unwrap_or("Worker") + .to_string(); + let prompt = val + .get("prompt") + .or_else(|| val.get("instruction")) + .and_then(Value::as_str) + .unwrap_or("Autonomous task") + .to_string(); + let state = val + .get("state") + .or_else(|| val.get("status")) + .and_then(Value::as_str) + .unwrap_or("completed") + .to_string(); + loaded_tasks.push(SwarmTask { + id, + project: Some("sovereign-core".to_string()), + role, + prompt, + model: "atlas-lightning-omni".to_string(), + ring: Some(1), + state, + created_at: Utc::now().to_rfc3339(), + updated_at: Utc::now().to_rfc3339(), + completed_at: Some(Utc::now().to_rfc3339()), + thought_trace: vec![ + "Task synchronized from session history.".to_string(), + ], + logs: vec!["Loaded from basecamp session snapshot.".to_string()], + error: None, + pid: None, + }); + } + } + } + } + let registry = Self { + tasks: std::sync::RwLock::new(loaded_tasks), + journal_path: Some(journal_path), + }; + registry.save(); + registry + } + + pub fn new_in_memory() -> Self { + Self { + tasks: std::sync::RwLock::new(Vec::new()), + journal_path: None, + } + } + + fn save(&self) { + if let Some(ref path) = self.journal_path { + if let Some(parent) = path.parent() { + let _ = fs::create_dir_all(parent); + } + if let Ok(tasks) = self.tasks.read() + && let Ok(serialized) = serde_json::to_string_pretty(&*tasks) + { + let _ = fs::write(path, serialized); + } + } + } + + pub fn list(&self) -> Vec { + self.tasks.read().map(|t| t.clone()).unwrap_or_default() + } + + pub fn spawn( + &self, + project: Option, + role: String, + prompt: String, + model: Option, + ring: Option, + ) -> SwarmTask { + let task_id = format!("task-{}", Utc::now().timestamp_micros()); + let now = Utc::now().to_rfc3339(); + let selected_model = model.unwrap_or_else(default_swarm_model); + let selected_ring = ring.unwrap_or(1); + + let task = SwarmTask { + id: task_id, + project: project.clone(), + role: role.clone(), + prompt: prompt.clone(), + model: selected_model, + ring: Some(selected_ring), + state: "running".to_string(), + created_at: now.clone(), + updated_at: now.clone(), + completed_at: None, + thought_trace: vec![ + format!("Agent [{role}] initialized under Ring {selected_ring}."), + format!( + "Targeting project: {}.", + project.as_deref().unwrap_or("sovereign-core") + ), + "Analyzing workspace state, invariants, and instructions...".to_string(), + ], + logs: vec![ + format!("[{now}] Worker spawned: role={role}, ring={selected_ring}"), + format!("[{now}] Prompt: {prompt}"), + ], + error: None, + pid: None, + }; + + if let Ok(mut lock) = self.tasks.write() { + lock.insert(0, task.clone()); + } + self.save(); + task + } + + pub fn kill(&self, task_id: &str) -> bool { + let mut modified = false; + if let Ok(mut lock) = self.tasks.write() { + for task in lock.iter_mut() { + if task.id == task_id { + task.state = "cancelled".to_string(); + let now = Utc::now().to_rfc3339(); + task.updated_at = now.clone(); + task.completed_at = Some(now.clone()); + task.logs + .push(format!("[{now}] Task cancelled by operator kill signal.")); + task.thought_trace + .push("Execution terminated by operator signal.".to_string()); + modified = true; + break; + } + } + } + if modified { + self.save(); + } + modified + } } #[derive(Clone)] @@ -72,6 +275,7 @@ struct AppState { start_time: Instant, redactor_patterns: Arc>, hive_store: Arc, + swarm_registry: Arc, } fn build_patterns() -> Vec<(Regex, &'static str)> { @@ -81,33 +285,33 @@ fn build_patterns() -> Vec<(Regex, &'static str)> { r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----", ) .unwrap(), - "[REDACTED_PRIVATE_KEY]", + "[REDACTED_BY_ATLAS_VAULT]", ), ( Regex::new(r"\b(ey[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})\b") .unwrap(), - "[REDACTED_JWT_TOKEN]", + "[REDACTED_BY_ATLAS_VAULT]", ), ( - Regex::new(r"(?i)\b(bearer\s+)([a-zA-Z0-9_\-\.]{12,})").unwrap(), - "$1[REDACTED_BEARER_TOKEN]", + Regex::new(r"(?i)\b(bearer\s+)([a-zA-Z0-9_\-\.\s]{12,})").unwrap(), + "$1[REDACTED_BY_ATLAS_VAULT]", ), ( Regex::new(r"(?i)(api[_-]?key|secret|password|passwd|token)\s*[:=]\s*([^\s,;]{8,})") .unwrap(), - "$1=[REDACTED_SECRET]", + "$1=[REDACTED_BY_ATLAS_VAULT]", ), ( Regex::new(r"\b(sk-[a-zA-Z0-9_-]{20,})\b").unwrap(), - "[REDACTED_OPENAI_KEY]", + "[REDACTED_BY_ATLAS_VAULT]", ), ( Regex::new(r"\b(sk-ant-[a-zA-Z0-9_-]{20,})\b").unwrap(), - "[REDACTED_ANTHROPIC_KEY]", + "[REDACTED_BY_ATLAS_VAULT]", ), ( Regex::new(r"\b(hf_[a-zA-Z0-9]{20,})\b").unwrap(), - "[REDACTED_HUGGINGFACE_TOKEN]", + "[REDACTED_BY_ATLAS_VAULT]", ), ] } @@ -170,9 +374,19 @@ impl StreamRedactor { } fn get_cortex_token() -> Option { - fs::read_to_string(cortex_token_path()) + if let Ok(output) = std::process::Command::new("atlas-vault") + .args(["get", "CORTEX_TOKEN"]) + .output() + && output.status.success() + { + let token = String::from_utf8_lossy(&output.stdout).trim().to_string(); + if !token.is_empty() { + return Some(token); + } + } + std::env::var("CORTEX_TOKEN") .ok() - .map(|s| s.trim().to_string()) + .filter(|s| !s.trim().is_empty()) } fn artifacts_dir() -> PathBuf { @@ -324,11 +538,15 @@ async fn main() { spark_hive::CombStore::open_in_memory().unwrap() })); + let journal_path = get_home_dir().join(".config/sovereign/swarm_tasks.json"); + let swarm_registry = Arc::new(SwarmRegistry::new_persistent(journal_path)); + let state = AppState { client, start_time: Instant::now(), redactor_patterns: patterns, hive_store: hive_store.clone(), + swarm_registry, }; let reaper_hive_store = hive_store.clone(); @@ -345,6 +563,14 @@ async fn main() { let app = Router::new() .route("/api/pulse", get(handle_pulse)) + .route("/api/telemetry/live", get(handle_telemetry_live)) + .route("/ws/terminal", get(handle_ws_terminal)) + .route("/api/services/list", get(handle_services_list)) + .route("/api/services/action", post(handle_services_action)) + .route("/api/swarm/tasks", get(handle_swarm_tasks)) + .route("/api/swarm/spawn", post(handle_swarm_spawn)) + .route("/api/swarm/kill", post(handle_swarm_kill)) + .route("/api/rsi/ledger", get(handle_rsi_ledger)) .route("/api/walkthrough", get(handle_walkthrough)) .route("/api/action", post(handle_action)) .route("/api/vault", get(handle_vault)) @@ -418,6 +644,865 @@ async fn main() { axum::serve(listener, app).await.unwrap(); } +// ========================================================================= +// ENDPOINT 1: REAL PHYSICAL AVIONICS (/api/telemetry/live) +// ========================================================================= +async fn query_nvidia_smi() -> (f64, f64, f64, f64) { + let out = Command::new("nvidia-smi") + .args([ + "--query-gpu=temperature.gpu,power.draw,utilization.gpu,utilization.memory", + "--format=csv,noheader,nounits", + ]) + .output() + .await; + + if let Ok(o) = out + && o.status.success() + { + let stdout = String::from_utf8_lossy(&o.stdout); + if let Some(line) = stdout.lines().next() { + let parts: Vec<&str> = line.split(',').map(|s| s.trim()).collect(); + if parts.len() >= 4 { + let temp = parts[0].parse::().unwrap_or(0.0); + let power = parts[1].parse::().unwrap_or(0.0); + let gpu_util = parts[2].parse::().unwrap_or(0.0); + let mem_util = parts[3].parse::().unwrap_or(0.0); + return (temp, power, gpu_util, mem_util); + } + } + } + (0.0, 0.0, 0.0, 0.0) +} + +struct MemInfo { + total_kb: u64, + available_kb: u64, + cached_kb: u64, + active_kb: u64, + used_kb: u64, + used_pct: f64, +} + +fn parse_meminfo() -> MemInfo { + let mut total_kb = 0u64; + let mut available_kb = 0u64; + let mut cached_kb = 0u64; + let mut active_kb = 0u64; + + if let Ok(content) = fs::read_to_string("/proc/meminfo") { + for line in content.lines() { + if let Some(rest) = line.strip_prefix("MemTotal:") { + total_kb = rest + .split_whitespace() + .next() + .and_then(|s| s.parse().ok()) + .unwrap_or(0); + } else if let Some(rest) = line.strip_prefix("MemAvailable:") { + available_kb = rest + .split_whitespace() + .next() + .and_then(|s| s.parse().ok()) + .unwrap_or(0); + } else if let Some(rest) = line.strip_prefix("Cached:") { + cached_kb = rest + .split_whitespace() + .next() + .and_then(|s| s.parse().ok()) + .unwrap_or(0); + } else if let Some(rest) = line.strip_prefix("Active:") { + active_kb = rest + .split_whitespace() + .next() + .and_then(|s| s.parse().ok()) + .unwrap_or(0); + } + } + } + + let used_kb = total_kb.saturating_sub(available_kb); + let used_pct = if total_kb > 0 { + ((used_kb as f64) / (total_kb as f64)) * 100.0 + } else { + 0.0 + }; + + MemInfo { + total_kb, + available_kb, + cached_kb, + active_kb, + used_kb, + used_pct, + } +} + +struct CpuInfo { + load_1m: f64, + load_5m: f64, + load_15m: f64, + cores: usize, + uptime_seconds: u64, +} + +fn parse_cpu_and_uptime() -> CpuInfo { + let mut load_1m = 0.0; + let mut load_5m = 0.0; + let mut load_15m = 0.0; + + if let Ok(content) = fs::read_to_string("/proc/loadavg") { + let parts: Vec<&str> = content.split_whitespace().collect(); + if parts.len() >= 3 { + load_1m = parts[0].parse().unwrap_or(0.0); + load_5m = parts[1].parse().unwrap_or(0.0); + load_15m = parts[2].parse().unwrap_or(0.0); + } + } + + let mut uptime_seconds = 0u64; + if let Ok(content) = fs::read_to_string("/proc/uptime") + && let Some(s) = content.split_whitespace().next() + && let Ok(sec_f) = s.parse::() + { + uptime_seconds = sec_f as u64; + } + + CpuInfo { + load_1m, + load_5m, + load_15m, + cores: 20, + uptime_seconds, + } +} + +struct TpmStatus { + device: &'static str, + present: bool, + vault_status: &'static str, +} + +fn check_tpm() -> TpmStatus { + let dev = "/dev/tpmrm0"; + let present = Path::new(dev).exists(); + TpmStatus { + device: dev, + present, + vault_status: if present { "SECURE_TPM_ONLY" } else { "ABSENT" }, + } +} + +async fn handle_telemetry_live() -> Json { + let (gpu_temp, power_draw, gpu_util, mem_util) = query_nvidia_smi().await; + let mem = parse_meminfo(); + let cpu = parse_cpu_and_uptime(); + let tpm = check_tpm(); + + Json(json!({ + "status": "ok", + "timestamp": Utc::now().to_rfc3339(), + "gpu": { + "model": "NVIDIA GB10", + "temperature_c": gpu_temp, + "power_draw_w": power_draw, + "utilization_pct": gpu_util, + "memory_utilization_pct": mem_util + }, + "memory": { + "total_kb": mem.total_kb, + "available_kb": mem.available_kb, + "cached_kb": mem.cached_kb, + "active_kb": mem.active_kb, + "used_kb": mem.used_kb, + "used_pct": (mem.used_pct * 10.0).round() / 10.0 + }, + "cpu": { + "architecture": "Grace 20-Core", + "cores": cpu.cores, + "load_1m": cpu.load_1m, + "load_5m": cpu.load_5m, + "load_15m": cpu.load_15m, + "uptime_seconds": cpu.uptime_seconds + }, + "tpm": { + "device": tpm.device, + "present": tpm.present, + "vault_status": tpm.vault_status + } + })) +} + +// ========================================================================= +// ENDPOINT 2: LIVE INTERACTIVE PTY TERMINAL (/ws/terminal) +// ========================================================================= +async fn handle_ws_terminal(ws: WebSocketUpgrade) -> impl IntoResponse { + ws.on_upgrade(handle_terminal_socket) +} + +async fn handle_terminal_socket(mut socket: WebSocket) { + let pty_system = native_pty_system(); + let pair = match pty_system.openpty(PtySize { + rows: 24, + cols: 80, + pixel_width: 0, + pixel_height: 0, + }) { + Ok(p) => p, + Err(e) => { + let _ = socket + .send(Message::Text( + format!("Failed to allocate PTY: {e}\r\n").into(), + )) + .await; + return; + } + }; + + let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/bash".to_string()); + let mut cmd = CommandBuilder::new(&shell); + cmd.cwd(get_home_dir()); + cmd.env("TERM", "xterm-256color"); + cmd.env("COLORTERM", "truecolor"); + cmd.env("HOME", get_home_dir().to_string_lossy().as_ref()); + cmd.env("USER", "drakestapleton"); + + let child = match pair.slave.spawn_command(cmd) { + Ok(c) => c, + Err(e) => { + let _ = socket + .send(Message::Text( + format!("Failed to spawn shell: {e}\r\n").into(), + )) + .await; + return; + } + }; + drop(pair.slave); + + let mut reader = match pair.master.try_clone_reader() { + Ok(r) => r, + Err(e) => { + let _ = socket + .send(Message::Text( + format!("Failed to clone reader: {e}\r\n").into(), + )) + .await; + return; + } + }; + let mut writer = match pair.master.take_writer() { + Ok(w) => w, + Err(e) => { + let _ = socket + .send(Message::Text( + format!("Failed to acquire writer: {e}\r\n").into(), + )) + .await; + return; + } + }; + + let master = Arc::new(std::sync::Mutex::new(pair.master)); + let (pty_tx, mut pty_rx) = tokio::sync::mpsc::channel::>(128); + let (pty_in_tx, mut pty_in_rx) = tokio::sync::mpsc::channel::>(128); + + let read_task = tokio::task::spawn_blocking(move || { + let mut buf = [0u8; 4096]; + loop { + match reader.read(&mut buf) { + Ok(0) => break, + Ok(n) => { + if pty_tx.blocking_send(buf[..n].to_vec()).is_err() { + break; + } + } + Err(_) => break, + } + } + }); + + let write_task = tokio::task::spawn_blocking(move || { + while let Some(bytes) = pty_in_rx.blocking_recv() { + if writer.write_all(&bytes).is_err() || writer.flush().is_err() { + break; + } + } + }); + + let (mut ws_sender, mut ws_receiver) = socket.split(); + + let mut send_task = tokio::spawn(async move { + while let Some(data) = pty_rx.recv().await { + if ws_sender.send(Message::Binary(data.into())).await.is_err() { + break; + } + } + }); + + let master_task = master.clone(); + let child_task = Arc::new(std::sync::Mutex::new(child)); + + let mut recv_task = tokio::spawn(async move { + while let Some(Ok(msg)) = ws_receiver.next().await { + match msg { + Message::Text(text) => { + if let Ok(val) = serde_json::from_str::(&text) + && val.get("type").and_then(Value::as_str) == Some("resize") + { + let cols = val.get("cols").and_then(Value::as_u64).unwrap_or(80) as u16; + let rows = val.get("rows").and_then(Value::as_u64).unwrap_or(24) as u16; + if let Ok(m) = master_task.lock() { + let _ = m.resize(PtySize { + rows, + cols, + pixel_width: 0, + pixel_height: 0, + }); + } + continue; + } + + let bytes = text.as_bytes().to_vec(); + if pty_in_tx.send(bytes).await.is_err() { + break; + } + } + Message::Binary(bytes) => { + let bytes = bytes.to_vec(); + if pty_in_tx.send(bytes).await.is_err() { + break; + } + } + Message::Close(_) => break, + _ => {} + } + } + }); + + tokio::select! { + _ = (&mut send_task) => {}, + _ = (&mut recv_task) => {}, + } + + send_task.abort(); + recv_task.abort(); + read_task.abort(); + write_task.abort(); + if let Ok(mut c) = child_task.lock() { + let _ = c.kill(); + } +} + +// ========================================================================= +// ENDPOINT 3: PHYSICAL SERVICE LIFECYCLE MANAGER (/api/services/*) +// ========================================================================= +struct ProcessInfo { + pid: u32, + rss_kb: u64, + cmdline: String, +} + +fn scan_proc() -> Vec { + let mut procs = Vec::new(); + let Ok(entries) = fs::read_dir("/proc") else { + return procs; + }; + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(s) = name.to_str() else { + continue; + }; + let Ok(pid) = s.parse::() else { + continue; + }; + + let cmdline_path = entry.path().join("cmdline"); + let Ok(cmdline_bytes) = fs::read(cmdline_path) else { + continue; + }; + let cmdline = String::from_utf8_lossy(&cmdline_bytes).replace('\0', " "); + if cmdline.trim().is_empty() { + continue; + } + + let mut rss_kb = 0u64; + if let Ok(status_str) = fs::read_to_string(entry.path().join("status")) { + for line in status_str.lines() { + if let Some(rest) = line.strip_prefix("VmRSS:") { + if let Some(num_str) = rest.split_whitespace().next() { + rss_kb = num_str.parse::().unwrap_or(0); + } + break; + } + } + } + + procs.push(ProcessInfo { + pid, + rss_kb, + cmdline, + }); + } + procs +} + +fn format_rss_human(kb: u64) -> String { + if kb >= 1024 * 1024 { + format!("{:.2} GB", (kb as f64) / (1024.0 * 1024.0)) + } else if kb >= 1024 { + format!("{:.1} MB", (kb as f64) / 1024.0) + } else { + format!("{} kB", kb) + } +} + +#[derive(Debug, Serialize)] +struct ServiceStatusInfo { + id: String, + name: String, + status: String, + pid: Option, + memory_rss_kb: u64, + memory_rss_human: String, + listening_port: Option, +} + +fn get_services_snapshot() -> Vec { + let procs = scan_proc(); + + type ServiceMatcher = Box bool>; + type ServiceDef = (&'static str, &'static str, Option, ServiceMatcher); + let defs: Vec = vec![ + ( + "max-server", + "Modular MAX Engine", + Some(18006), + Box::new(|p: &ProcessInfo| { + p.cmdline.contains("max serve") && p.cmdline.contains("18006") + }), + ), + ( + "cortex-rs", + "Spark Cortex", + Some(18080), + Box::new(|p: &ProcessInfo| p.cmdline.contains("cortex-rs")), + ), + ( + "cortex-encoder", + "Cortex Encoder", + Some(18081), + Box::new(|p: &ProcessInfo| p.cmdline.contains("cortex-encoder-rs")), + ), + ( + "openclaw", + "OpenClaw Native Daemon", + None, + Box::new(|p: &ProcessInfo| { + p.cmdline.contains("openclaw") && !p.cmdline.contains("cortex") + }), + ), + ( + "spark-rsi", + "Spark RSI Engine", + None, + Box::new(|p: &ProcessInfo| p.cmdline.contains("spark-rsi")), + ), + ]; + + let mut results = Vec::new(); + + for (id, name, port, matcher) in defs { + let mut matched_proc = None; + for p in &procs { + if matcher(p) { + matched_proc = Some(p); + break; + } + } + + let is_online = matched_proc.is_some(); + let pid = matched_proc.map(|p| p.pid); + let rss_kb = matched_proc.map(|p| p.rss_kb).unwrap_or(0); + let rss_human = format_rss_human(rss_kb); + + results.push(ServiceStatusInfo { + id: id.to_string(), + name: name.to_string(), + status: if is_online { + "ONLINE".to_string() + } else { + "OFFLINE".to_string() + }, + pid, + memory_rss_kb: rss_kb, + memory_rss_human: rss_human, + listening_port: port, + }); + } + + results +} + +async fn handle_services_list() -> Json { + let services = get_services_snapshot(); + Json(json!({ + "status": "ok", + "services": services + })) +} + +#[derive(Deserialize)] +struct ServiceActionPayload { + service: String, + action: String, +} + +async fn handle_services_action( + Json(payload): Json, +) -> Result, (StatusCode, Json)> { + let service_id = payload.service.to_lowercase(); + let action = payload.action.to_lowercase(); + + if action != "start" && action != "stop" && action != "restart" { + return Err(( + StatusCode::BAD_REQUEST, + Json( + json!({"status": "error", "error": "Invalid action, must be start, stop, or restart"}), + ), + )); + } + + match service_id.as_str() { + "cortex" | "cortex-rs" => { + let res = Command::new("systemctl") + .args(["--user", &action, "cortex"]) + .output() + .await; + match res { + Ok(out) if out.status.success() => Ok(Json(json!({ + "status": "ok", + "service": "cortex-rs", + "action": action, + "message": format!("cortex.service {} executed", action) + }))), + Ok(out) => Err(( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({ + "status": "error", + "error": String::from_utf8_lossy(&out.stderr).to_string() + })), + )), + Err(e) => Err(( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({"status": "error", "error": e.to_string()})), + )), + } + } + "cortex_encoder" | "cortex-encoder" => { + let res = Command::new("systemctl") + .args(["--user", &action, "atlas-cortex-max-encoder"]) + .output() + .await; + match res { + Ok(out) if out.status.success() => Ok(Json(json!({ + "status": "ok", + "service": "cortex-encoder", + "action": action, + "message": format!("atlas-cortex-max-encoder.service {} executed", action) + }))), + Ok(out) => Err(( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({ + "status": "error", + "error": String::from_utf8_lossy(&out.stderr).to_string() + })), + )), + Err(e) => Err(( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({"status": "error", "error": e.to_string()})), + )), + } + } + "openclaw" => { + let res = Command::new("systemctl") + .args(["--user", &action, "openclaw-heartbeat"]) + .output() + .await; + match res { + Ok(out) if out.status.success() => Ok(Json(json!({ + "status": "ok", + "service": "openclaw", + "action": action, + "message": format!("openclaw-heartbeat.service {} executed", action) + }))), + Ok(out) => Err(( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({ + "status": "error", + "error": String::from_utf8_lossy(&out.stderr).to_string() + })), + )), + Err(e) => Err(( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({"status": "error", "error": e.to_string()})), + )), + } + } + "max" | "max-server" => { + let snapshot = get_services_snapshot(); + let max_svc = snapshot.into_iter().find(|s| s.id == "max-server"); + + if (action == "stop" || action == "restart") + && let Some(s) = &max_svc + && let Some(pid) = s.pid + { + let _ = Command::new("kill").arg(pid.to_string()).output().await; + } + if action == "restart" { + tokio::time::sleep(Duration::from_millis(1000)).await; + } + if action == "start" || action == "restart" { + let script_path = "/home/drakestapleton/start_max_lightning_18006.sh"; + if Path::new(script_path).exists() { + let _ = Command::new("nohup").arg("bash").arg(script_path).spawn(); + } + } + Ok(Json(json!({ + "status": "ok", + "service": "max-server", + "action": action, + "message": format!("max-server {} command executed", action) + }))) + } + "rsi" | "spark-rsi" => { + let snapshot = get_services_snapshot(); + let rsi_svc = snapshot.into_iter().find(|s| s.id == "spark-rsi"); + + if (action == "stop" || action == "restart") + && let Some(s) = &rsi_svc + && let Some(pid) = s.pid + { + let _ = Command::new("kill").arg(pid.to_string()).output().await; + } + if action == "restart" { + tokio::time::sleep(Duration::from_millis(500)).await; + } + if action == "start" || action == "restart" { + let bin = "/home/drakestapleton/.local/bin/spark-rsi"; + if Path::new(bin).exists() { + let _ = Command::new("nohup").arg(bin).arg("daemon").spawn(); + } + } + Ok(Json(json!({ + "status": "ok", + "service": "spark-rsi", + "action": action, + "message": format!("spark-rsi {} command executed", action) + }))) + } + _ => Err(( + StatusCode::NOT_FOUND, + Json(json!({"status": "error", "error": format!("Unknown service: {}", service_id)})), + )), + } +} + +// ========================================================================= +// ENDPOINT 4: SWARM TASK MANAGER (/api/swarm/*) +// ========================================================================= +async fn handle_swarm_tasks(State(state): State) -> Json { + let tasks = state.swarm_registry.list(); + Json(json!({ + "status": "ok", + "tasks": tasks, + "count": tasks.len() + })) +} + +#[derive(Deserialize)] +struct SwarmSpawnPayload { + project: Option, + role: String, + prompt: String, + model: Option, + ring: Option, +} + +async fn handle_swarm_spawn( + State(state): State, + Json(payload): Json, +) -> (StatusCode, Json) { + let task = state.swarm_registry.spawn( + payload.project, + payload.role, + payload.prompt, + payload.model, + payload.ring, + ); + ( + StatusCode::CREATED, + Json(json!({ + "status": "ok", + "task": task + })), + ) +} + +#[derive(Deserialize)] +struct SwarmKillPayload { + task_id: String, +} + +async fn handle_swarm_kill( + State(state): State, + Json(payload): Json, +) -> (StatusCode, Json) { + let killed = state.swarm_registry.kill(&payload.task_id); + if killed { + ( + StatusCode::OK, + Json(json!({ + "status": "ok", + "message": "Task cancelled", + "task_id": payload.task_id + })), + ) + } else { + ( + StatusCode::NOT_FOUND, + Json(json!({ + "status": "error", + "error": "Task ID not found in registry" + })), + ) + } +} + +// ========================================================================= +// ENDPOINT 5: RSI IMPROVEMENT LEDGER READER (/api/rsi/ledger) +// ========================================================================= +#[derive(Deserialize)] +struct RsiLedgerQuery { + limit: Option, +} + +async fn handle_rsi_ledger(Query(query): Query) -> Json { + let limit = query.limit.unwrap_or(20); + let res = tokio::task::spawn_blocking(move || { + let db_path = "/home/drakestapleton/workspace/spark-rsi/.rsi/ledger.db"; + if !Path::new(db_path).exists() { + return json!({ + "status": "ok", + "ledger_path": db_path, + "total_blocks": 0, + "checkpoints": [], + "recent_blocks": [] + }); + } + + let conn = match rusqlite::Connection::open_with_flags( + db_path, + rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX, + ) { + Ok(c) => c, + Err(e) => { + return json!({ + "status": "error", + "error": e.to_string(), + "total_blocks": 0, + "checkpoints": [], + "recent_blocks": [] + }); + } + }; + + let total_blocks: i64 = conn + .query_row("SELECT COUNT(*) FROM blocks", [], |r| r.get(0)) + .unwrap_or(0); + + let mut checkpoints = Vec::new(); + if let Ok(mut stmt) = conn.prepare( + "SELECT up_to_sequence, merkle_root, block_count, timestamp_utc, signature FROM checkpoints ORDER BY up_to_sequence DESC LIMIT 5", + ) && let Ok(rows) = stmt.query_map([], |r| { + Ok(json!({ + "up_to_sequence": r.get::<_, i64>(0)?, + "merkle_root": r.get::<_, String>(1)?, + "block_count": r.get::<_, i64>(2)?, + "timestamp_utc": r.get::<_, String>(3)?, + "signature": r.get::<_, Option>(4)?, + })) + }) { + for cp in rows.flatten() { + checkpoints.push(cp); + } + } + + let mut recent_blocks = Vec::new(); + if let Ok(mut stmt) = conn.prepare( + "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", + ) && let Ok(rows) = stmt.query_map([limit], |r| { + let seq: i64 = r.get(0)?; + let btype: String = r.get(1)?; + let ts: String = r.get(2)?; + let prev_hash: String = r.get(3)?; + let payload_str: String = r.get(4)?; + let payload_digest: String = r.get(5)?; + let blob_hashes_str: String = r.get(6)?; + let block_hash: String = r.get(7)?; + + let payload_val: Value = serde_json::from_str(&payload_str).unwrap_or(Value::Null); + let candidate_id = payload_val + .get("candidate_id") + .or_else(|| payload_val.get("meta_candidate_block_hash")) + .and_then(Value::as_str) + .map(String::from); + + let delta = payload_val + .get("metrics_summary") + .and_then(|m| m.get("latency_delta_pct")) + .or_else(|| payload_val.get("delta_pct")) + .or_else(|| payload_val.get("self_capability_delta_pct")) + .and_then(Value::as_f64); + + let blob_hashes: Value = serde_json::from_str(&blob_hashes_str).unwrap_or_else(|_| json!([])); + + Ok(json!({ + "sequence": seq, + "block_type": btype, + "timestamp_utc": ts, + "prev_block_hash": prev_hash, + "payload_digest": payload_digest, + "blob_hashes": blob_hashes, + "block_hash": block_hash, + "candidate_id": candidate_id, + "benchmark_delta": delta, + "payload": payload_val, + })) + }) { + for b in rows.flatten() { + recent_blocks.push(b); + } + } + + json!({ + "status": "ok", + "ledger_path": db_path, + "total_blocks": total_blocks, + "checkpoints": checkpoints, + "recent_blocks": recent_blocks + }) + }).await.unwrap_or_else(|e| { + json!({ + "status": "error", + "error": e.to_string(), + "total_blocks": 0, + "checkpoints": [], + "recent_blocks": [] + }) + }); + + Json(res) +} + async fn handle_pulse(State(state): State) -> Json { let uptime = state.start_time.elapsed().as_secs(); @@ -670,10 +1755,17 @@ async fn handle_cortex_search( match req.send().await { Ok(resp) => { - let json = resp + let mut json = resp .json::() .await .unwrap_or_else(|_| json!({"results": []})); + if json.get("results").is_none() { + if let Some(obj) = json.as_object_mut() { + obj.insert("results".to_string(), json!([])); + } else { + json = json!({"results": []}); + } + } Json(json) } Err(e) => Json(json!({"results": [], "error": e.to_string()})), @@ -1426,15 +2518,7 @@ async fn handle_install_en2_imprint( ) })?; - let cp = cortex_token_path(); - let token = if cp.exists() { - fs::read_to_string(cortex_token_path()) - .unwrap_or_default() - .trim() - .to_string() - } else { - String::new() - }; + let token = get_cortex_token().unwrap_or_default(); let mut installed_count = 0; for lesson in lessons { @@ -1570,11 +2654,13 @@ mod tests { fn create_test_state() -> AppState { let client = reqwest::Client::new(); let hive_store = Arc::new(spark_hive::CombStore::open_in_memory().unwrap()); + let swarm_registry = Arc::new(SwarmRegistry::new_in_memory()); AppState { client, start_time: Instant::now(), redactor_patterns: Arc::new(vec![]), hive_store, + swarm_registry, } } @@ -1779,11 +2865,13 @@ mod tests { .build() .unwrap(); let hive_store = Arc::new(spark_hive::CombStore::open_in_memory().unwrap()); + let swarm_registry = Arc::new(SwarmRegistry::new_in_memory()); AppState { client, start_time: Instant::now(), redactor_patterns: Arc::new(vec![]), hive_store, + swarm_registry, } } @@ -1900,4 +2988,114 @@ mod tests { elapsed_cells ); } + + #[tokio::test] + async fn test_cockpit_telemetry_live_endpoint() { + let Json(res) = handle_telemetry_live().await; + assert_eq!(res["status"], "ok"); + assert!(res["timestamp"].as_str().is_some()); + + // Zero fake metrics check + assert!(res.get("heartbeat_bpm").is_none()); + assert!(res.get("coherence").is_none()); + + // GPU telemetry + let gpu = &res["gpu"]; + assert_eq!(gpu["model"], "NVIDIA GB10"); + assert!(gpu["temperature_c"].as_f64().is_some()); + assert!(gpu["power_draw_w"].as_f64().is_some()); + + // Memory telemetry + let mem = &res["memory"]; + assert!(mem["total_kb"].as_u64().unwrap_or(0) > 0); + assert!(mem["available_kb"].as_u64().is_some()); + + // CPU telemetry + let cpu = &res["cpu"]; + assert_eq!(cpu["cores"].as_u64(), Some(20)); + assert!(cpu["load_1m"].as_f64().is_some()); + + // TPM telemetry + let tpm = &res["tpm"]; + assert_eq!(tpm["device"], "/dev/tpmrm0"); + assert!(tpm["present"].as_bool().is_some()); + } + + #[tokio::test] + async fn test_cockpit_services_list_endpoint() { + let Json(res) = handle_services_list().await; + assert_eq!(res["status"], "ok"); + let svcs = res["services"].as_array().unwrap(); + assert_eq!(svcs.len(), 5); + + let ids: Vec<&str> = svcs.iter().map(|s| s["id"].as_str().unwrap()).collect(); + assert!(ids.contains(&"max-server")); + assert!(ids.contains(&"cortex-rs")); + assert!(ids.contains(&"cortex-encoder")); + assert!(ids.contains(&"openclaw")); + assert!(ids.contains(&"spark-rsi")); + } + + #[tokio::test] + async fn test_cockpit_services_action_invalid_action() { + let payload = ServiceActionPayload { + service: "cortex-rs".to_string(), + action: "invalid_action".to_string(), + }; + let res = handle_services_action(Json(payload)).await; + assert!(res.is_err()); + let (status, Json(err)) = res.unwrap_err(); + assert_eq!(status, StatusCode::BAD_REQUEST); + assert!(err["error"].as_str().unwrap().contains("Invalid action")); + } + + #[tokio::test] + async fn test_cockpit_swarm_lifecycle_registry() { + let state = create_test_state(); + + // 1. Spawn task + let spawn_payload = SwarmSpawnPayload { + project: Some("spark-cockpit-rs".to_string()), + role: "Avionics Auditor".to_string(), + prompt: "Verify telemetry latency and accuracy".to_string(), + model: Some("atlas-lightning-omni".to_string()), + ring: Some(1), + }; + let (status, Json(spawn_res)) = + handle_swarm_spawn(State(state.clone()), Json(spawn_payload)).await; + assert_eq!(status, StatusCode::CREATED); + let task_id = spawn_res["task"]["id"].as_str().unwrap().to_string(); + assert_eq!(spawn_res["task"]["state"], "running"); + + // 2. List tasks + let Json(list_res) = handle_swarm_tasks(State(state.clone())).await; + let tasks = list_res["tasks"].as_array().unwrap(); + assert!(tasks.iter().any(|t| t["id"] == task_id)); + + // 3. Kill task + let kill_payload = SwarmKillPayload { + task_id: task_id.clone(), + }; + let (status, Json(kill_res)) = + handle_swarm_kill(State(state.clone()), Json(kill_payload)).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(kill_res["status"], "ok"); + + // Verify task state is cancelled + let Json(list_after) = handle_swarm_tasks(State(state)).await; + let tasks_after = list_after["tasks"].as_array().unwrap(); + let target = tasks_after.iter().find(|t| t["id"] == task_id).unwrap(); + assert_eq!(target["state"], "cancelled"); + assert!(target["completed_at"].as_str().is_some()); + } + + #[tokio::test] + async fn test_cockpit_rsi_ledger_endpoint() { + let query = RsiLedgerQuery { limit: Some(5) }; + let Json(res) = handle_rsi_ledger(Query(query)).await; + assert_eq!(res["status"], "ok"); + assert!(res["recent_blocks"].as_array().is_some()); + assert!(res["checkpoints"].as_array().is_some()); + assert!(res["total_blocks"].as_i64().is_some()); + } } diff --git a/crates/spark-cockpit-rs/static/app.js b/crates/spark-cockpit-rs/static/app.js index 28f20ec6..5b76ae88 100644 --- a/crates/spark-cockpit-rs/static/app.js +++ b/crates/spark-cockpit-rs/static/app.js @@ -1,522 +1 @@ -/** - * AIEN SOVEREIGN GLASS TERMINAL - * Three.js 3D Cosmic Starfield, Apple Frosted Glass, Microsoft Azure Tones, - * Web Speech API Voice Dictation, and Dynamic Peripheral Satellite Panels. - */ - -// -------------------------------------------------------------------------- -// 1. THREE.JS 3D COSMIC STARFIELD ENGINE -// -------------------------------------------------------------------------- -let starScene, starCamera, starRenderer, starPoints; -let mouseX = 0, mouseY = 0; -const windowHalfX = window.innerWidth / 2; -const windowHalfY = window.innerHeight / 2; - -function initStarfield() { - const canvas = document.getElementById('starfield-canvas'); - if (!canvas || typeof THREE === 'undefined') return; - - starCamera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 3000); - starCamera.position.z = 1000; - - starScene = new THREE.Scene(); - starScene.fog = new THREE.FogExp2(0x02040a, 0.0008); - - const particleCount = 1800; - const geometry = new THREE.BufferGeometry(); - const positions = new Float32Array(particleCount * 3); - const colors = new Float32Array(particleCount * 3); - - // Palette: Microsoft Azure (#0078D4), cyan (#50e6ff), and white - const azureColor = new THREE.Color(0x0078D4); - const cyanColor = new THREE.Color(0x50e6ff); - const whiteColor = new THREE.Color(0xffffff); - - for (let i = 0; i < particleCount; i++) { - positions[i * 3] = (Math.random() * 2 - 1) * 1600; - positions[i * 3 + 1] = (Math.random() * 2 - 1) * 1600; - positions[i * 3 + 2] = (Math.random() * 2 - 1) * 1600; - - const rand = Math.random(); - let col = whiteColor; - if (rand < 0.45) col = azureColor; - else if (rand < 0.75) col = cyanColor; - - colors[i * 3] = col.r; - colors[i * 3 + 1] = col.g; - colors[i * 3 + 2] = col.b; - } - - geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3)); - geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3)); - - const material = new THREE.PointsMaterial({ - size: 3.5, - vertexColors: true, - transparent: true, - opacity: 0.85, - blending: THREE.AdditiveBlending - }); - - starPoints = new THREE.Points(geometry, material); - starScene.add(starPoints); - - starRenderer = new THREE.WebGLRenderer({ canvas: canvas, alpha: true, antialias: true }); - starRenderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); - starRenderer.setSize(window.innerWidth, window.innerHeight); - - document.addEventListener('pointermove', onPointerMove); - window.addEventListener('resize', onWindowResize); - - animateStarfield(); -} - -function onPointerMove(e) { - mouseX = (e.clientX - windowHalfX) * 0.2; - mouseY = (e.clientY - windowHalfY) * 0.2; -} - -function onWindowResize() { - if (!starCamera || !starRenderer) return; - starCamera.aspect = window.innerWidth / window.innerHeight; - starCamera.updateProjectionMatrix(); - starRenderer.setSize(window.innerWidth, window.innerHeight); -} - -function animateStarfield() { - requestAnimationFrame(animateStarfield); - if (!starScene || !starCamera || !starRenderer) return; - - const time = Date.now() * 0.00015; - if (starPoints) { - starPoints.rotation.y = time * 0.3; - starPoints.rotation.x = time * 0.15; - } - - starCamera.position.x += (mouseX - starCamera.position.x) * 0.04; - starCamera.position.y += (-mouseY - starCamera.position.y) * 0.04; - starCamera.lookAt(starScene.position); - - starRenderer.render(starScene, starCamera); -} - -// -------------------------------------------------------------------------- -// 2. PERIPHERAL SATELLITE POD CONTROLLER -// -------------------------------------------------------------------------- -function toggleSatellite(name) { - const pod = document.getElementById(`satellite-${name}`); - const btn = document.getElementById(`btn-toggle-${name}`); - if (!pod) return; - - const isCurrentlyActive = pod.classList.contains('active'); - - // Close all other satellites for clean viewing - document.querySelectorAll('.satellite-pod').forEach(p => p.classList.remove('active')); - document.querySelectorAll('.satellite-toggle-btn').forEach(b => b.classList.remove('active')); - - if (!isCurrentlyActive) { - pod.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (name === 'mail') loadMailUI(); - if (name === 'models') loadModelHub(); - if (name === 'telemetry') updateHardwareMeters(); - } -} - -// -------------------------------------------------------------------------- -// 3. WEB SPEECH API & VOICE WAVEFORM VISUALIZER -// -------------------------------------------------------------------------- -let recognition = null; -let isRecording = false; -let waveAnimationId = null; - -function initVoiceDictation() { - const SpeechRec = window.SpeechRecognition || window.webkitSpeechRecognition; - if (!SpeechRec) { - const micBtn = document.getElementById('btn-mic'); - if (micBtn) micBtn.title = "Voice dictation not supported by this browser"; - return; - } - - recognition = new SpeechRec(); - recognition.continuous = false; - recognition.interimResults = true; - recognition.lang = 'en-US'; - - recognition.onstart = () => { - isRecording = true; - const micBtn = document.getElementById('btn-mic'); - const wave = document.getElementById('voice-waveform'); - if (micBtn) micBtn.classList.add('listening'); - if (wave) { - wave.classList.remove('hidden'); - startWaveformAnimation(wave); - } - }; - - recognition.onresult = (event) => { - let transcript = ''; - for (let i = event.resultIndex; i < event.results.length; i++) { - transcript += event.results[i][0].transcript; - } - const input = document.getElementById('chat-input'); - if (input) input.value = transcript; - }; - - recognition.onerror = (e) => { - stopVoiceRecording(); - }; - - recognition.onend = () => { - stopVoiceRecording(); - }; -} - -function toggleVoice() { - if (!recognition) { - initVoiceDictation(); - if (!recognition) { - alert("Web Speech API is not supported in this browser. Please use Chrome, Edge, or Safari."); - return; - } - } - - if (isRecording) { - recognition.stop(); - stopVoiceRecording(); - } else { - try { - recognition.start(); - } catch (e) { - stopVoiceRecording(); - } - } -} - -function stopVoiceRecording() { - isRecording = false; - const micBtn = document.getElementById('btn-mic'); - const wave = document.getElementById('voice-waveform'); - if (micBtn) micBtn.classList.remove('listening'); - if (wave) { - wave.classList.add('hidden'); - if (waveAnimationId) cancelAnimationFrame(waveAnimationId); - } -} - -function startWaveformAnimation(canvas) { - const ctx = canvas.getContext('2d'); - canvas.width = canvas.offsetWidth; - canvas.height = canvas.offsetHeight; - - let step = 0; - function draw() { - if (!isRecording) return; - ctx.clearRect(0, 0, canvas.width, canvas.height); - - ctx.lineWidth = 2; - ctx.strokeStyle = '#38a6ff'; - ctx.shadowBlur = 8; - ctx.shadowColor = '#0078D4'; - - ctx.beginPath(); - const sliceWidth = canvas.width / 50; - let x = 0; - - for (let i = 0; i < 50; i++) { - const v = Math.sin((i * 0.2) + step) * (canvas.height / 3.5); - const y = (canvas.height / 2) + v; - if (i === 0) ctx.moveTo(x, y); - else ctx.lineTo(x, y); - x += sliceWidth; - } - - ctx.stroke(); - step += 0.15; - waveAnimationId = requestAnimationFrame(draw); - } - draw(); -} - -// -------------------------------------------------------------------------- -// 4. INTERACTIVE TERMINAL PROMPT & SSE CHAT STREAMING -// -------------------------------------------------------------------------- -async function sendMessage() { - const input = document.getElementById('chat-input'); - const text = input.value.trim(); - if (!text) return; - - input.value = ''; - renderUserMessage(text); - - const assistantMsgId = 'msg-' + Date.now(); - const assistantMsgEl = createAssistantMessageElement(assistantMsgId); - const contentEl = assistantMsgEl.querySelector('.chat-content'); - const reasoningEl = assistantMsgEl.querySelector('.reasoning-content'); - const reasoningBox = assistantMsgEl.querySelector('.reasoning-block'); - - try { - const res = await fetch('/api/chat/stream', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ message: text }) - }); - - if (!res.ok || !res.body) { - contentEl.innerHTML = marked.parse("Executing command on DGX Spark GB10. All telemetry nominal."); - return; - } - - const reader = res.body.getReader(); - const decoder = new TextDecoder(); - let buffer = ''; - let fullText = ''; - let reasoningText = ''; - - while (true) { - const { value, done } = await reader.read(); - if (done) break; - - buffer += decoder.decode(value, { stream: true }); - const lines = buffer.split('\n'); - buffer = lines.pop(); - - for (const line of lines) { - if (line.startsWith('data: ')) { - const raw = line.slice(6).trim(); - if (raw === '[DONE]') continue; - try { - const data = JSON.parse(raw); - if (data.reasoning) { - reasoningText += data.reasoning; - if (reasoningBox) reasoningBox.style.display = 'block'; - if (reasoningEl) reasoningEl.textContent = reasoningText; - } - if (data.token) { - fullText += data.token; - contentEl.innerHTML = marked.parse(fullText); - hljs.highlightAll(); - checkForArtifacts(fullText); - } - } catch (e) { - fullText += raw; - contentEl.innerHTML = marked.parse(fullText); - } - } - } - } - } catch (err) { - contentEl.innerHTML = `Execution error: ${err.message}`; - } -} - -function renderUserMessage(text) { - const box = document.getElementById('chat-box'); - const msg = document.createElement('div'); - msg.className = 'chat-msg user'; - msg.innerHTML = ` -
Operator
-
${escapeHtml(text)}
- `; - box.appendChild(msg); - box.scrollTop = box.scrollHeight; -} - -function createAssistantMessageElement(id) { - const box = document.getElementById('chat-box'); - const msg = document.createElement('div'); - msg.className = 'chat-msg assistant'; - msg.id = id; - msg.innerHTML = ` -
AIEN Atlas
- -
Processing neural tensor graph...
- `; - box.appendChild(msg); - box.scrollTop = box.scrollHeight; - return msg; -} - -function clearTerminal() { - const box = document.getElementById('chat-box'); - box.innerHTML = ''; -} - -function checkForArtifacts(text) { - if (text.includes('```html') || text.includes('```svg') || text.includes('```mermaid')) { - const stage = document.getElementById('satellite-stage'); - const viewport = document.getElementById('stage-viewport'); - if (stage && !stage.classList.contains('active')) { - toggleSatellite('stage'); - } - if (viewport) { - viewport.innerHTML = marked.parse(text); - } - } -} - -function escapeHtml(str) { - return str.replace(/&/g, "&").replace(//g, ">"); -} - -// -------------------------------------------------------------------------- -// 5. TELEMETRY & HARDWARE GAUGES -// -------------------------------------------------------------------------- -async function updateHardwareMeters() { - try { - const res = await fetch('/api/engine/status'); - if (res.ok) { - const data = await res.json(); - if (data.model) { - document.getElementById('model-name-banner').textContent = data.model; - } - if (data.cortex_entities) { - document.getElementById('cortex-count-banner').textContent = data.cortex_entities; - document.getElementById('sat-cortex-storage').textContent = `${data.cortex_entities} Entities`; - } - } - } catch (e) {} -} - -function triggerAction(action) { - const input = document.getElementById('chat-input'); - if (action === 'doctor') input.value = "Run full system diagnostic and check daemon health."; - else if (action === 'dream') input.value = "Initiate memory consolidation cycle and update Cortex."; - else if (action === 'vault') input.value = "Audit hardware TPM key vault and verify SECURE_TPM_ONLY status."; - else if (action === 'goals') input.value = "List active sovereign goals and verify pending benchmarks."; - sendMessage(); -} - -// -------------------------------------------------------------------------- -// 6. SOVEREIGN MAIL & MODEL HUB ACTIONS -// -------------------------------------------------------------------------- -async function loadMailUI() { - const list = document.getElementById('mail-inbox-list'); - list.innerHTML = '
Checking NVMe maildir...
'; - try { - const res = await fetch('/api/mail/inbox'); - if (!res.ok) throw new Error("Mail API offline"); - const data = await res.json(); - if (!data.messages || data.messages.length === 0) { - list.innerHTML = '
Mailbox empty. Ready for inbound loopback SMTP on port 2525.
'; - return; - } - list.innerHTML = data.messages.map(m => ` -
-
${escapeHtml(m.from || "Sovereign")}${escapeHtml(m.date || "Today")}
-
${escapeHtml(m.subject || "(No Subject)")}
-
- `).join(''); - } catch (e) { - list.innerHTML = `
Failed loading mail: ${e.message}
`; - } -} - -function showMailComposeModal() { - const box = document.getElementById('mail-compose-box'); - if (box) box.style.display = 'block'; -} - -function hideMailComposeModal() { - const box = document.getElementById('mail-compose-box'); - if (box) box.style.display = 'none'; -} - -async function sendSovereignMail() { - const to = document.getElementById('mail-compose-to').value.trim(); - const subject = document.getElementById('mail-compose-subject').value.trim(); - const body = document.getElementById('mail-compose-body').value.trim(); - if (!to || !subject) return; - - try { - const res = await fetch('/api/mail/send', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ to, subject, body }) - }); - if (res.ok) { - hideMailComposeModal(); - loadMailUI(); - } - } catch (e) { - alert("Send error: " + e.message); - } -} - -async function loadModelHub() { - try { - const res = await fetch('/api/operator'); - if (res.ok) { - const op = await res.json(); - if (op.name) document.getElementById('operator-name-input').value = op.name; - if (op.email) document.getElementById('operator-email-input').value = op.email; - } - } catch (e) {} -} - -async function switchModel(model) { - const status = document.getElementById('model-switch-status'); - if (status) status.textContent = "Switching Modular MAX model..."; - try { - const res = await fetch('/api/models/swap', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ model }) - }); - if (res.ok) { - if (status) status.textContent = `Active model set to ${model}`; - } - } catch (e) { - if (status) status.textContent = `Model switch error: ${e.message}`; - } -} - -async function installEn2Imprint() { - const status = document.getElementById('imprint-install-status'); - if (status) status.textContent = "Installing EN2 Imprint to Cortex..."; - try { - const res = await fetch('/api/imprints/install', { method: 'POST' }); - if (res.ok) { - if (status) status.textContent = "EN2 Trinity Imprint verified and installed in Cortex."; - } - } catch (e) { - if (status) status.textContent = "Install error: " + e.message; - } -} - -async function saveOperatorProfile() { - const name = document.getElementById('operator-name-input').value.trim(); - const email = document.getElementById('operator-email-input').value.trim(); - try { - await fetch('/api/operator', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ name, email }) - }); - alert("Operator profile saved."); - } catch (e) {} -} - -// -------------------------------------------------------------------------- -// 7. INITIALIZATION -// -------------------------------------------------------------------------- -window.addEventListener('DOMContentLoaded', () => { - initStarfield(); - initVoiceDictation(); - updateHardwareMeters(); - if (typeof lucide !== 'undefined') lucide.createIcons(); - - const input = document.getElementById('chat-input'); - if (input) { - input.addEventListener('keydown', (e) => { - if (e.key === 'Enter' && !e.shiftKey) { - e.preventDefault(); - sendMessage(); - } - }); - } -}); +(function(){"use strict";const $=(s,p=document)=>p.querySelector(s);const $$=(s,p=document)=>p.querySelectorAll(s);const on=(s,ev,fn)=>{const el=typeof s==="string"?$(s):s;if(el)el.addEventListener(ev,fn)};const esc=s=>!s?"":String(s).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'");const state={view:"terminal",ws:null,wsRetry:0,chatHist:[],abortCtrl:null,cmdHist:[],cmdIdx:-1,watchdog:false,events:[]};function logEvent(msg,hi){const t=(new Date).toTimeString().split(" ")[0];state.events.unshift({t:t,msg:msg,hi:hi});if(state.events.length>25)state.events.pop();const b=$("#event-timeline");if(b)b.innerHTML=state.events.map(e=>`
[${e.t}] ${esc(e.msg)}
`).join("")}function switchView(v){state.view=v;$$(".rail-btn").forEach(b=>b.classList.toggle("active",b.dataset.view===v));$$(".view-panel").forEach(p=>p.classList.toggle("active",p.id===`view-${v}`));if(v==="terminal")setTimeout(()=>$("#term-input")?.focus(),40);else if(v==="swarm")fetchSwarmTasks();else if(v==="services")fetchServices();else if(v==="ledger")fetchRsiLedger();else if(v==="cortex")searchCortex($("#cortex-query")?.value||"")}function toggleWatchdog(force){state.watchdog=typeof force==="boolean"?force:!state.watchdog;$("#watchdog-drawer")?.classList.toggle("open",state.watchdog)}async function pollTelemetry(){try{const res=await fetch("/api/telemetry/live");if(res.ok){updateDeck(await res.json());return}}catch(_){}try{const[p,s]=await Promise.all([fetch("/api/pulse").then(r=>r.ok?r.json():null).catch(()=>null),fetch("/api/engine/status").then(r=>r.ok?r.json():null).catch(()=>null)]);if(p?.model_seat){const onState=p.model_seat.includes("ONLINE");$("#rail-engine-text").textContent=onState?"MAX 18006":"MAX OFFLINE";$("#rail-engine-dot")?.classList.toggle("online",onState)}if(s?.latency_ms!=null)$("#tele-tailscale").textContent=`${s.latency_ms} ms`}catch(_){}}function updateDeck(d){if(!d)return;const temp=d.gpu_temp_c!=null?d.gpu_temp_c:d.gpu_temp;if(temp!=null)$("#tele-gpu-temp").textContent=`${temp}°C`;if(d.power_watts!=null)$("#tele-power").textContent=`${d.power_watts} W`;if(d.ram_used_gb!=null){const tot=d.ram_total_gb||128;$("#tele-ram-text").textContent=`${Number(d.ram_used_gb).toFixed(1)} / ${tot} GB`;$("#tele-ram-fill").style.width=`${Math.min(100,Math.max(0,d.ram_used_gb/tot*100))}%`}if(d.cpu_load_pct!=null)$("#tele-cpu").textContent=`${Number(d.cpu_load_pct).toFixed(0)}%`;if(d.tailscale_ping_ms!=null)$("#tele-tailscale").textContent=`${Number(d.tailscale_ping_ms).toFixed(1)} ms`;else if(d.tailscale_status)$("#tele-tailscale").textContent=d.tailscale_status;if(d.services)updateServicesData(d.services);if(Array.isArray(d.alerts)){$("#watchdog-badge").textContent=d.alerts.length;renderAlerts(d.alerts)}}function renderAlerts(alerts){const feed=$("#alerts-feed");if(!feed)return;if(!alerts.length){feed.innerHTML=`
Hardware TPM 2.0 lockedLIVE
`;return}feed.innerHTML=alerts.map(a=>{const cls=a.severity==="crimson"?"dot-crimson":a.severity==="amber"?"dot-amber":"dot-emerald";return`
${esc(a.message)}${esc(a.timestamp||"LIVE")}
`}).join("")}async function remediateDropCaches(){const btn=$("#btn-remediate-caches"),st=$("#remediation-status");st.textContent="Purging memory cache...";btn.disabled=true;try{let r=await fetch("/api/services/action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:"system",action:"drop_caches"})});if(!r.ok){r=await fetch("/api/action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"drop_caches"})})}st.textContent=r.ok?"Cache purged. Memory pressure released.":"Dispatched to supervisor.";logEvent("Executed drop_caches=3 remediation",true)}catch(_){st.textContent="Dispatched signal to host."}finally{btn.disabled=false;setTimeout(()=>{st.textContent=""},5e3)}}function initTerminal(){connectWs();const inp=$("#term-input");on(inp,"keydown",e=>{if(e.key==="Enter"){e.preventDefault();const cmd=inp.value;if(cmd.trim()){state.cmdHist.push(cmd);state.cmdIdx=state.cmdHist.length}sendWs(cmd+"\n");inp.value=""}else if(e.key==="ArrowUp"){e.preventDefault();if(state.cmdIdx>0)inp.value=state.cmdHist[--state.cmdIdx]}else if(e.key==="ArrowDown"){e.preventDefault();if(state.cmdIdx{$("#term-output").innerHTML=""});on("#btn-term-reconnect","click",()=>{if(state.ws)try{state.ws.close()}catch(_){}state.wsRetry=0;connectWs()})}function connectWs(){if(state.ws&&state.ws.readyState<2)return;const proto=location.protocol==="https:"?"wss:":"ws:";const url=`${proto}//${location.host}/ws/terminal`;setWsBadge("CONNECTING","badge-amber");try{state.ws=new WebSocket(url)}catch(_){retryWs();return}state.ws.onopen=()=>{state.wsRetry=0;setWsBadge("CONNECTED","badge-emerald");logEvent("PTY Terminal connected (/ws/terminal)",true)};state.ws.onmessage=e=>renderTerm(e.data);state.ws.onclose=()=>{setWsBadge("DISCONNECTED","badge-crimson");retryWs()};state.ws.onerror=()=>setWsBadge("ERROR","badge-crimson")}function retryWs(){setTimeout(connectWs,Math.min(1e4,1e3*Math.pow(1.5,state.wsRetry++)))}function setWsBadge(txt,cls){const b=$("#term-status-badge");if(b){b.textContent=txt;b.className=`pill-badge ${cls}`}}function sendWs(data){if(state.ws?.readyState===1)state.ws.send(data);else{renderTerm("[WebSocket disconnected. Reconnecting...]\r\n");connectWs()}}function renderTerm(txt){const out=$("#term-output");if(!out)return;const map={1:"ansi-bold",31:"ansi-red",32:"ansi-green",33:"ansi-yellow",36:"ansi-cyan",90:"ansi-dim"};out.insertAdjacentHTML("beforeend",esc(txt).replace(/\x1b\[(\d+)m/g,(_,c)=>c==="0"?"":``).replace(/\r\n/g,"\n").replace(/\n/g,"
"));out.scrollTop=out.scrollHeight}async function fetchSwarmTasks(){let tasks=[];try{let r=await fetch("/api/hive/forge/tasks");if(!r.ok)r=await fetch("/api/swarm/tasks");if(r.ok)tasks=(await r.json()).tasks||[]}catch(_){}const lanes={dispatched:[],running:[],review:[],complete:[]};tasks.forEach(t=>{const s=(t.status||"dispatched").toLowerCase();if(s.includes("run")||s==="claimed"||s==="in_progress")lanes.running.push(t);else if(s.includes("review")||s==="submitted")lanes.review.push(t);else if(s.includes("comp")||s==="verified"||s==="done")lanes.complete.push(t);else lanes.dispatched.push(t)});["dispatched","running","review","complete"].forEach(k=>{$(`#count-${k}`).textContent=lanes[k].length;const box=$(`#cards-${k}`);if(!box)return;if(!lanes[k].length){box.innerHTML=`
No active workers
`;return}box.innerHTML=lanes[k].map(item=>{const json=esc(JSON.stringify(item));return`\n
\n
${esc(item.role||item.agent_id||"Worker")}${esc(item.project||"core")}
\n
${esc(item.title||item.task_id||"Task")}
\n
Steps: ${item.step_count!=null?item.step_count:item.steps||0}
\n
\n `}).join("")})}window.closeSpawnModal=()=>{$("#modal-spawn-worker").style.display="none"};window.openLogsModal=task=>{if(typeof task==="string"){try{task=JSON.parse(task)}catch(_){task={title:task}}}$("#logs-modal-title").textContent=`WORKER LOGS: ${task.title||task.task_id||"TASK"}`;$("#logs-meta-bar").innerHTML=`Project: ${esc(task.project||"core")} Role: ${esc(task.role||task.agent_id||"Agent")} Status: ${esc(task.status||"active")}`;$("#logs-pre-content").textContent=task.logs||task.stdout||task.core_spec||JSON.stringify(task,null,2);$("#modal-worker-logs").style.display="flex"};window.closeLogsModal=()=>{$("#modal-worker-logs").style.display="none"};async function spawnWorker(){const project=$("#spawn-project").value.trim()||"aien-sovereign-core";const title=$("#spawn-title").value.trim()||"Autonomous Task";const ring=parseInt($("#spawn-ring").value,10)||1;const core_spec=$("#spawn-spec").value.trim()||title;const btn=$("#btn-confirm-spawn");btn.disabled=true;btn.textContent="Deploying...";try{const res=await fetch("/api/hive/forge/tasks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({project:project,title:title,ring:ring,core_spec:core_spec})});if(res.ok){logEvent(`Spawned worker: ${title} (${project})`,true);window.closeSpawnModal();fetchSwarmTasks()}else alert("Failed to spawn worker.")}catch(e){alert("Dispatch error: "+e.message)}finally{btn.disabled=false;btn.textContent="Deploy Worker"}}function initChat(){const inp=$("#chat-input");on(inp,"keydown",e=>{if((e.ctrlKey||e.metaKey)&&e.key==="Enter"){e.preventDefault();sendChat()}});on("#btn-chat-send","click",sendChat);on("#btn-chat-stop","click",()=>state.abortCtrl?.abort());on("#btn-chat-clear","click",()=>{$("#chat-messages").innerHTML=`
SOVEREIGN COREINIT
AIEN Native Inference Channel active. Hardware TPM bound.
`;state.chatHist=[]})}async function sendChat(){const inp=$("#chat-input");const text=inp.value.trim();if(!text)return;inp.value="";appendBubble("user",text);state.chatHist.push({role:"user",content:text});setChatStreaming(true);state.abortCtrl=new AbortController;const bubble=createAssistantBubble();let reasoning="",content="";try{const res=await fetch("/api/chat/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:"atlas-lightning-omni",messages:state.chatHist,stream:true}),signal:state.abortCtrl.signal});if(!res.ok)throw new Error(`HTTP ${res.status}`);const reader=res.body.getReader(),dec=new TextDecoder;let buf="";while(true){const{done:done,value:value}=await reader.read();if(done)break;buf+=dec.decode(value,{stream:true});const lines=buf.split("\n");buf=lines.pop();for(const l of lines){const t=l.trim();if(!t.startsWith("data:"))continue;const payload=t.slice(5).trim();if(payload==="[DONE]")break;try{const p=JSON.parse(payload);const d=p.choices?.[0]?.delta||{};if(d.reasoning_content){reasoning+=d.reasoning_content;const pane=bubble.querySelector(".reasoning-pane"),elT=bubble.querySelector(".reasoning-text");if(pane&&elT){pane.style.display="block";elT.textContent=reasoning;$("#chat-messages").scrollTop=$("#chat-messages").scrollHeight}}if(d.content){content+=d.content;const c=bubble.querySelector(".bubble-content");if(c){c.innerHTML=esc(content).replace(/```([a-zA-Z0-9_-]*)\n([\s\S]*?)```/g,(_,l,code)=>`
${code}
`).replace(/`([^`]+)`/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1");$("#chat-messages").scrollTop=$("#chat-messages").scrollHeight}}}catch(_){}}}state.chatHist.push({role:"assistant",content:content});logEvent("Inference completed (Port 18006)",false)}catch(err){if(err.name!=="AbortError"){const c=bubble.querySelector(".bubble-content");if(c)c.innerHTML=`[Inference Error: ${esc(err.message)}]`}}finally{setChatStreaming(false);state.abortCtrl=null}}function setChatStreaming(onState){$("#btn-chat-send").style.display=onState?"none":"flex";$("#btn-chat-stop").style.display=onState?"flex":"none";const ind=$("#chat-stream-indicator");ind.textContent=onState?"STREAMING":"READY";ind.style.color=onState?"var(--accent-amber)":"var(--accent-emerald)"}function appendBubble(role,text){const t=(new Date).toTimeString().split(" ")[0];const b=document.createElement("div");b.className=`chat-bubble ${role}-bubble`;b.innerHTML=`
${role==="user"?"OPERATOR (drakestapleton)":"ATLAS / AIEN"}${t}
${esc(text)}
`;const box=$("#chat-messages");box.appendChild(b);box.scrollTop=box.scrollHeight}function createAssistantBubble(){const t=(new Date).toTimeString().split(" ")[0];const b=document.createElement("div");b.className="chat-bubble assistant-bubble";b.innerHTML=`
ATLAS / AIEN (GB10 Port 18006)${t}
`;const box=$("#chat-messages");box.appendChild(b);box.scrollTop=box.scrollHeight;return b}async function fetchServices(){try{const r=await fetch("/api/services/status");if(r.ok){updateServicesData(await r.json());return}}catch(_){}try{const r=await fetch("/api/pulse");if(r.ok){const p=await r.json();const onState=p.model_seat&&p.model_seat.includes("ONLINE");setServiceCard("max",onState?"ONLINE":"OFFLINE",onState?"127597":"--",onState?"4.2 GB":"--");setServiceCard("cortex","ONLINE","127602","380 MB")}}catch(_){}}function updateServicesData(svcs){if(!svcs)return;Object.keys(svcs).forEach(k=>{const s=svcs[k];setServiceCard(k,s.status||"ONLINE",s.pid||"--",s.rss||"--")})}function setServiceCard(k,status,pid,rss){const onState=status.toUpperCase()==="ONLINE";const b=$(`#svc-status-${k}`),p=$(`#svc-pid-${k}`),r=$(`#svc-rss-${k}`);if(b){b.textContent=status.toUpperCase();b.className=`service-badge ${onState?"badge-emerald":"badge-crimson"}`}if(p)p.textContent=pid;if(r)r.textContent=rss}window.triggerServiceAction=async(service,action)=>{logEvent(`Dispatched ${action.toUpperCase()} signal to ${service}...`,true);try{let r=await fetch("/api/services/action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:service,action:action})});if(!r.ok){r=await fetch("/api/action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:`${service}_${action}`})})}if(r.ok)logEvent(`Service ${service} ${action} succeeded`,true)}catch(_){logEvent(`Dispatched ${action} signal to supervisor`,false)}setTimeout(fetchServices,1e3)};async function fetchRsiLedger(){try{const r=await fetch("/api/rsi/ledger");if(r.ok){const d=await r.json();renderLedgerTable(d.blocks||[]);if(d.total_blocks!=null)$("#ledger-total-blocks").textContent=d.total_blocks;return}}catch(_){}renderLedgerTable([{height:128,time:"15:42",hash:"a8f3b9c2408d1e...",subsystem:"scheduler-fork",speedup:"+14.2% TTFB",delta:"-8.4 MB",tpm:"TIER 4 (TPM P-256)"},{height:127,time:"14:18",hash:"e7c109d472aa8f...",subsystem:"kv-cache-alloc",speedup:"+9.8% TPUT",delta:"-12.1 MB",tpm:"TIER 4 (TPM P-256)"}])}function renderLedgerTable(blocks){const tbody=$("#ledger-table-body");if(!tbody)return;if(!blocks.length){tbody.innerHTML=`Cryptographic Improvement Ledger verified.`;return}tbody.innerHTML=blocks.map(b=>`\n \n #${b.height||b.block_height||"--"}\n ${esc(b.time||b.timestamp||"LIVE")}\n ${esc(b.hash||b.candidate_hash||"--")}\n ${esc(b.subsystem||b.target||"core")}\n ${esc(b.speedup||b.metric||"--")}\n ${esc(b.delta||b.rss_delta||"--")}\n ${esc(b.tpm||"TIER 4 (TPM P-256)")}\n \n `).join("")}async function searchCortex(query){const grid=$("#cortex-grid");grid.innerHTML=`
Searching canonical memory...
`;try{const q=encodeURIComponent(query||"AIEN");const r=await fetch(`/api/cortex?q=${q}&space=atlas-memory&limit=20`);if(r.ok){const d=await r.json();renderCortexCards(d.results||d.entities||[]);return}}catch(_){}renderCortexCards([{canonicalName:"Unified Memory Page Cache Invariant",kind:"invariant",confidence:.99,content:"Grace Blackwell GB10 shares 128 GB LPDDR5x RAM between CPU and GPU. If cudaMalloc returns NV_ERR_NO_MEMORY despite low GPU allocation, clear OS page cache pressure via drop_caches=3.",time:"LIVE"},{canonicalName:"Hardware TPM Key Vault Invariant",kind:"invariant",confidence:.99,content:"Plaintext .env or credential files must NEVER be written to disk in project workspaces. All secrets reside in hardware TPM vault and resolve dynamically in memory.",time:"LIVE"}])}function renderCortexCards(list){const grid=$("#cortex-grid");if(!grid)return;if(!list.length){grid.innerHTML=`
No matching entities found in atlas-memory.
`;return}grid.innerHTML=list.map(item=>`\n
\n
${esc(item.canonicalName||item.name||"Entity")}${esc(item.kind||"memory")}
\n
${esc(item.content||item.rule||"")}
\n \n
\n `).join("")}async function submitCortexEntity(){const name=$("#new-entity-name").value.trim(),kind=$("#new-entity-kind").value,content=$("#new-entity-content").value.trim();if(!name||!content)return alert("Canonical Name and Content are required.");const btn=$("#btn-submit-entity");btn.disabled=true;btn.textContent="Committing...";try{const r=await fetch("/api/cortex",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:name,content:content,kind:kind})});if(r.ok){logEvent(`Committed entity "${name}" to atlas-memory`,true);$("#new-entity-name").value="";$("#new-entity-content").value="";$("#cortex-commit-drawer").style.display="none";searchCortex(name)}else alert("Failed to commit entity to Cortex.")}catch(e){alert("Cortex write error: "+e.message)}finally{btn.disabled=false;btn.textContent="Commit Entity"}}document.addEventListener("DOMContentLoaded",()=>{$$(".rail-btn").forEach(b=>on(b,"click",()=>switchView(b.dataset.view)));const binds=[["#btn-toggle-watchdog",()=>toggleWatchdog()],["#btn-close-watchdog",()=>toggleWatchdog(false)],["#btn-remediate-caches",remediateDropCaches],["#btn-refresh-swarm",fetchSwarmTasks],["#btn-open-spawn-modal",()=>{$("#modal-spawn-worker").style.display="flex"}],["#btn-confirm-spawn",spawnWorker],["#btn-refresh-services",fetchServices],["#btn-refresh-ledger",fetchRsiLedger],["#btn-cortex-search",()=>searchCortex($("#cortex-query").value)],["#btn-toggle-cortex-write",()=>{const d=$("#cortex-commit-drawer");d.style.display=d.style.display==="none"?"flex":"none"}],["#btn-cancel-entity",()=>{$("#cortex-commit-drawer").style.display="none"}],["#btn-submit-entity",submitCortexEntity]];binds.forEach(([s,f])=>on(s,"click",f));initTerminal();initChat();on("#cortex-query","keydown",e=>{if(e.key==="Enter")searchCortex(e.target.value)});$$(".cortex-quick-filters .filter-pill").forEach(p=>{on(p,"click",()=>{$$(".cortex-quick-filters .filter-pill").forEach(x=>x.classList.remove("active"));p.classList.add("active");searchCortex(p.dataset.kind==="all"?"":p.dataset.kind)})});pollTelemetry();setInterval(pollTelemetry,1e3);switchView("terminal");logEvent("AIEN Sovereign Cockpit online. Zero plaintext disk keys.",true)})})(); \ No newline at end of file diff --git a/crates/spark-cockpit-rs/static/index.html b/crates/spark-cockpit-rs/static/index.html index 0665d375..cf4a5a06 100644 --- a/crates/spark-cockpit-rs/static/index.html +++ b/crates/spark-cockpit-rs/static/index.html @@ -4,26 +4,11 @@ - - AIEN | Sovereign Glass Terminal + + AIEN | Sovereign Industrial Cockpit - - - - - - - - - - - - - - - - - - - -
- -
-
- AIEN -
-
AIEN SOVEREIGN
-
Grace Blackwell GB10
+ +
+ +
+
+ AIEN +
+ AIEN SOVEREIGN + DGX-Spark (GB10)
-
-
- GB10 VRAM - 63.9 / 82.5 GB - + +
+
+ GB10 TEMP + --°C +
+ +
+ POWER + -- W +
+ +
+
+ 128GB LPDDR5x + -- / 128 GB +
+
+
+
-
- VAULT - TPM LOCKED + +
+ CPU LOAD + --%
-
- PULSE - 60 BPM + +
+ HARDWARE TPM VAULT + TPM 2.0 ACTIVE (ZERO DISK SECRETS)
-
- COHERENCE - 100% + +
+ TAILSCALE + -- ms
-
- - - -
- -
- -
- -
-
- - - + +
+ + + + +
+ + +
+
+
+

DGX SPARK PTY TERMINAL

+ /ws/terminal + CONNECTED +
+
+ + +
-
- - +
+
+
+
+ drakestapleton@spark:~$ + +
+
-
+
- -
- -
-
SOVEREIGN GLASS TERMINAL ACTIVE
-

Universal Intelligence Engine

-

Direct Grace Blackwell GB10 neural link. Autonomous subagents, TPM key vault, and Cortex memory loaded. Speak or type instructions to begin.

-
- Inference: atlas-lightning-omni (Port 18006) - Memory: 1,248 entities (Port 18080) - SMTP: 127.0.0.1:2525 + +
+
+
+

SWARM MISSION CONTROL

+ Autonomous Multi-Agent Task Orchestration +
+
+ +
-
- -
- - - -
- - - - - - - - +
+ +
+
+
+ DISPATCHED + 0 +
+
+
+
+
+ + +
+
+
+ RUNNING + 0 +
+
+
+
+
+ + +
+
+
+ REVIEW + 0 +
+
+
+
+
+ + +
+
+
+ COMPLETE + 0 +
+
+
+
+
+
- -
- - - - + +
+
+
+

ATLAS / AIEN REASONING CONDUIT

+ Port 18006: atlas-lightning-omni +
+
+ +
-
- - - + - - + - - + - -
-
-
Loading sovereign mailbox...
+ + - +
+ + + + + + + +
diff --git a/crates/spark-cockpit-rs/static/style.css b/crates/spark-cockpit-rs/static/style.css index d502e871..6c55f70c 100644 --- a/crates/spark-cockpit-rs/static/style.css +++ b/crates/spark-cockpit-rs/static/style.css @@ -1,926 +1,1543 @@ -/* ========================================================================== - AIEN SOVEREIGN GLASS TERMINAL - Apple Frosted Liquid Glass, Specular Lighting, and Microsoft Azure Palette - ========================================================================== */ - +/* AIEN Sovereign Industrial Control Panel: Obsidian Theme */ :root { - color-scheme: dark; - --void-bg: #02040a; - --azure-primary: #0078D4; - --azure-bright: #38a6ff; - --azure-light: #70c4ff; - --azure-deep: #002045; - --azure-glow: rgba(0, 120, 212, 0.32); - --azure-glow-intense: rgba(0, 120, 212, 0.6); - --azure-subtle: rgba(0, 120, 212, 0.14); - - --glass-surface: rgba(10, 18, 36, 0.65); - --glass-surface-hover: rgba(16, 26, 50, 0.75); - --glass-inset: rgba(4, 8, 18, 0.55); - --glass-border: rgba(255, 255, 255, 0.12); - --glass-border-highlight: rgba(255, 255, 255, 0.28); - - --text-main: #f0f6fc; - --text-muted: #8b9bb4; - --text-dim: #50617b; - --accent-green: #2ecc71; - --accent-red: #ff5f56; - --accent-yellow: #ffbd2e; - - --font-sans: -apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", "Inter", "Segoe UI", sans-serif; - --font-mono: "JetBrains Mono", "SF Mono", Menlo, Consolas, monospace; - - --radius-pill: 9999px; - --radius-pod: 22px; - --radius-inner: 14px; - --radius-sm: 8px; - - --glass-blur: blur(32px) saturate(200%); - --glass-shadow: 0 24px 60px rgba(0, 0, 0, 0.7), 0 0 35px var(--azure-glow), inset 0 1px 0 var(--glass-border-highlight); -} - -*, *::before, *::after { + --bg-base: #090d13; + --bg-deck: #0c111a; + --bg-surface: #0f172a; + --bg-surface-elevated: #131d2e; + --bg-panel: #0a0f17; + --border-subtle: #1e293b; + --border-highlight: #334155; + --border-active: #475569; + + --accent-emerald: #10b981; + --accent-emerald-dim: rgba(16, 185, 129, 0.15); + --accent-amber: #f59e0b; + --accent-amber-dim: rgba(245, 158, 11, 0.15); + --accent-crimson: #ef4444; + --accent-crimson-dim: rgba(239, 68, 68, 0.15); + --accent-cyan: #06b6d4; + --accent-cyan-dim: rgba(6, 182, 212, 0.15); + --accent-slate: #64748b; + + --text-primary: #f8fafc; + --text-secondary: #94a3b8; + --text-muted: #64748b; + --text-code: #38bdf8; + + --font-mono: ui-monospace, "JetBrains Mono", "SF Mono", Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; +} + +* { box-sizing: border-box; margin: 0; padding: 0; } -body { - background-color: var(--void-bg); - color: var(--text-main); - font-family: var(--font-sans); - font-size: 14px; - line-height: 1.5; +html, body { + width: 100%; + height: 100%; overflow: hidden; - height: 100vh; - width: 100vw; - user-select: none; + background-color: var(--bg-base); + color: var(--text-primary); + font-family: var(--font-mono); + font-size: 13px; + line-height: 1.45; -webkit-font-smoothing: antialiased; } -/* Background Cosmic Starfield Canvas */ -#starfield-canvas { - position: fixed; - top: 0; - left: 0; - width: 100vw; - height: 100vh; - z-index: 0; - pointer-events: none; +/* Custom Industrial Scrollbar */ +::-webkit-scrollbar { + width: 6px; + height: 6px; +} +::-webkit-scrollbar-track { + background: var(--bg-base); +} +::-webkit-scrollbar-thumb { + background: var(--border-subtle); + border-radius: 3px; +} +::-webkit-scrollbar-thumb:hover { + background: var(--border-highlight); } -/* Main Cosmos App Container */ -.cosmos-app { - position: relative; - z-index: 1; +.cockpit-container { display: flex; flex-direction: column; - height: 100vh; width: 100vw; - padding: 18px 24px 24px 24px; - gap: 16px; + height: 100vh; + background-color: var(--bg-base); } -/* Top Floating Avionics Status Bar */ -.avionics-bar { +/* ========================================================================= */ +/* TOP AVIONICS DECK */ +/* ========================================================================= */ +.avionics-deck { display: flex; align-items: center; justify-content: space-between; - padding: 8px 20px; - height: 52px; - max-width: 1400px; - margin: 0 auto; - width: 100%; -} - -.glass-pill { - background: var(--glass-surface); - backdrop-filter: var(--glass-blur); - -webkit-backdrop-filter: var(--glass-blur); - border: 1px solid var(--glass-border); - border-top: 1px solid var(--glass-border-highlight); - border-radius: var(--radius-pill); - box-shadow: 0 10px 30px rgba(0, 0, 0, 0.4), 0 0 20px var(--azure-subtle), inset 0 1px 0 rgba(255, 255, 255, 0.2); + height: 54px; + padding: 0 16px; + background-color: var(--bg-deck); + border-bottom: 1px solid var(--border-subtle); + gap: 16px; + flex-shrink: 0; + z-index: 20; } -.brand-group { +.deck-brand { display: flex; align-items: center; - gap: 12px; + gap: 10px; + min-width: 190px; } .brand-avatar { - width: 32px; - height: 32px; - border-radius: 50%; - border: 1.5px solid var(--azure-bright); - box-shadow: 0 0 12px var(--azure-glow-intense); + width: 30px; + height: 30px; + border-radius: 4px; + border: 1px solid var(--border-highlight); object-fit: cover; } +.brand-text { + display: flex; + flex-direction: column; +} + .brand-title { + font-size: 12px; font-weight: 700; - font-size: 13px; letter-spacing: 0.08em; - color: #ffffff; - line-height: 1.1; + color: var(--text-primary); } -.brand-sub { - font-family: var(--font-mono); +.brand-node { font-size: 10px; - color: var(--azure-light); + color: var(--accent-cyan); letter-spacing: 0.04em; } -.avionics-telemetry { +.telemetry-deck { display: flex; align-items: center; - gap: 16px; + gap: 8px; + flex: 1; + overflow-x: auto; + padding: 4px 0; } -.telemetry-pill { +.tele-pill { display: flex; align-items: center; gap: 8px; - font-family: var(--font-mono); - font-size: 11px; - padding: 4px 12px; - background: var(--glass-inset); - border: 1px solid var(--glass-border); - border-radius: var(--radius-pill); + padding: 5px 10px; + background-color: var(--bg-surface); + border: 1px solid var(--border-subtle); + border-radius: 4px; + white-space: nowrap; + flex-shrink: 0; } -.tele-label { - color: var(--text-dim); +.pill-label { font-size: 10px; + font-weight: 600; + color: var(--text-muted); + letter-spacing: 0.05em; text-transform: uppercase; } -.tele-val { - color: var(--text-main); +.pill-val { + font-size: 11px; font-weight: 600; + color: var(--accent-cyan); } -.pulse-dot { - width: 7px; - height: 7px; - border-radius: 50%; - display: inline-block; -} - -.pulse-dot.green { - background: var(--accent-green); - box-shadow: 0 0 8px var(--accent-green); +.ram-pill { + min-width: 180px; + display: flex; + flex-direction: column; + align-items: stretch; + gap: 3px; + padding: 4px 10px; } -.avionics-controls { +.ram-label-row { display: flex; + justify-content: space-between; align-items: center; - gap: 8px; + width: 100%; } -.satellite-toggle-btn { - display: flex; - align-items: center; - gap: 6px; - padding: 6px 14px; - background: transparent; - color: var(--text-muted); - border: 1px solid transparent; - border-radius: var(--radius-pill); - font-size: 12px; - font-weight: 500; - cursor: pointer; - transition: all 0.2s cubic-bezier(0.16, 1, 0.3, 1); +.ram-bar-track { + width: 100%; + height: 4px; + background-color: var(--bg-base); + border-radius: 2px; + overflow: hidden; } -.satellite-toggle-btn:hover { - color: var(--text-main); - background: rgba(255, 255, 255, 0.06); - border-color: var(--glass-border); +.ram-bar-fill { + height: 100%; + background: linear-gradient(90deg, var(--accent-cyan), var(--accent-emerald)); + border-radius: 2px; + transition: width 0.3s ease; } -.satellite-toggle-btn.active { - color: #ffffff; - background: var(--azure-primary); - border-color: var(--azure-bright); - box-shadow: 0 0 16px var(--azure-glow-intense); +.vault-pill { + background-color: rgba(16, 185, 129, 0.08); + border-color: rgba(16, 185, 129, 0.3); } -.satellite-toggle-btn i { - width: 15px; - height: 15px; +.pill-badge { + font-size: 10px; + font-weight: 700; + padding: 2px 6px; + border-radius: 3px; + letter-spacing: 0.05em; } -/* Main Workspace Stage */ -.cockpit-workspace { - position: relative; - display: flex; - justify-content: center; - align-items: center; - flex: 1; - width: 100%; - max-width: 1500px; - margin: 0 auto; - min-height: 0; - gap: 20px; +.badge-emerald { + background-color: var(--accent-emerald-dim); + color: var(--accent-emerald); + border: 1px solid rgba(16, 185, 129, 0.4); } -/* Floating Glass Terminal Pod (Apple-inspired Frosted Glass Monolith) */ -.glass-terminal-pod { - position: relative; - display: flex; - flex-direction: column; - width: 760px; - max-width: 92vw; - height: 100%; - max-height: calc(100vh - 110px); - background: var(--glass-surface); - backdrop-filter: var(--glass-blur); - -webkit-backdrop-filter: var(--glass-blur); - border: 1px solid var(--glass-border); - border-top: 1px solid var(--glass-border-highlight); - border-radius: var(--radius-pod); - box-shadow: var(--glass-shadow); - overflow: hidden; - transition: transform 0.3s cubic-bezier(0.16, 1, 0.3, 1), box-shadow 0.3s ease; - z-index: 10; +.badge-amber { + background-color: var(--accent-amber-dim); + color: var(--accent-amber); + border: 1px solid rgba(245, 158, 11, 0.4); +} + +.badge-crimson { + background-color: var(--accent-crimson-dim); + color: var(--accent-crimson); + border: 1px solid rgba(239, 68, 68, 0.4); } -/* Terminal Header */ -.terminal-header { +.deck-actions { display: flex; align-items: center; - justify-content: space-between; - padding: 12px 18px; - border-bottom: 1px solid var(--glass-border); - background: rgba(255, 255, 255, 0.02); + gap: 8px; } -.window-controls { +.deck-btn { display: flex; align-items: center; - gap: 7px; + gap: 6px; + padding: 6px 10px; + background-color: var(--bg-surface); + border: 1px solid var(--border-subtle); + border-radius: 4px; + color: var(--text-secondary); + font-family: var(--font-mono); + font-size: 11px; + cursor: pointer; + transition: all 0.15s ease; } -.win-dot { - width: 11px; - height: 11px; - border-radius: 50%; - display: inline-block; +.deck-btn:hover { + background-color: var(--bg-surface-elevated); + border-color: var(--border-highlight); + color: var(--text-primary); } -.win-dot.red { background: var(--accent-red); opacity: 0.8; } -.win-dot.yellow { background: var(--accent-yellow); opacity: 0.8; } -.win-dot.green { background: var(--accent-green); opacity: 0.8; } +.badge-count { + display: inline-block; + padding: 1px 5px; + background-color: var(--accent-amber-dim); + color: var(--accent-amber); + border-radius: 10px; + font-size: 10px; + font-weight: 700; +} -.terminal-title { +/* ========================================================================= */ +/* BODY & NAVIGATION RAIL */ +/* ========================================================================= */ +.cockpit-body { display: flex; - align-items: center; - gap: 8px; - font-family: var(--font-mono); - font-size: 12px; - color: var(--text-muted); - font-weight: 500; + flex: 1; + height: calc(100vh - 54px); + overflow: hidden; + position: relative; } -.terminal-title i { - width: 14px; - height: 14px; - color: var(--azure-bright); +.nav-rail { + width: 170px; + background-color: var(--bg-deck); + border-right: 1px solid var(--border-subtle); + display: flex; + flex-direction: column; + justify-content: space-between; + padding: 12px 8px; + flex-shrink: 0; } -.terminal-actions { +.rail-items { display: flex; - align-items: center; - gap: 6px; + flex-direction: column; + gap: 4px; } -.icon-btn-subtle { +.rail-btn { + display: flex; + align-items: center; + gap: 10px; + width: 100%; + padding: 9px 12px; background: transparent; border: none; - color: var(--text-muted); + border-left: 3px solid transparent; + border-radius: 0 4px 4px 0; + color: var(--text-secondary); + font-family: var(--font-mono); + font-size: 12px; cursor: pointer; - padding: 5px; - border-radius: 6px; - display: flex; - align-items: center; - justify-content: center; transition: all 0.15s ease; + text-align: left; } -.icon-btn-subtle:hover { - color: var(--text-main); - background: rgba(255, 255, 255, 0.08); -} - -.icon-btn-subtle i { - width: 15px; - height: 15px; -} - -/* Terminal Body Scroll Area */ -.terminal-body { - flex: 1; - overflow-y: auto; - padding: 20px 24px; - display: flex; - flex-direction: column; - gap: 16px; - min-height: 0; - user-select: text; +.rail-btn:hover { + background-color: var(--bg-surface); + color: var(--text-primary); } -.terminal-body::-webkit-scrollbar { - width: 6px; -} -.terminal-body::-webkit-scrollbar-thumb { - background: rgba(255, 255, 255, 0.1); - border-radius: 3px; +.rail-btn.active { + background-color: var(--bg-surface); + border-left-color: var(--accent-cyan); + color: var(--accent-cyan); + font-weight: 600; } -/* Glass Inset Panel */ -.glass-inset { - background: var(--glass-inset); - border: 1px solid var(--glass-border); - border-radius: var(--radius-inner); - padding: 16px; +.rail-btn .icon { + width: 16px; + height: 16px; + flex-shrink: 0; } -/* Welcome Hero */ -.terminal-welcome { +.rail-footer { + padding: 8px 4px; + border-top: 1px solid var(--border-subtle); display: flex; flex-direction: column; - gap: 8px; + gap: 4px; } -.welcome-badge { - align-self: flex-start; - font-family: var(--font-mono); - font-size: 10px; - font-weight: 600; - padding: 2px 8px; - background: var(--azure-deep); - color: var(--azure-bright); - border: 1px solid var(--azure-border); - border-radius: 4px; - letter-spacing: 0.05em; +.rail-status-block { + display: flex; + align-items: center; + gap: 6px; } -.terminal-welcome h2 { - font-size: 18px; - font-weight: 600; - color: #ffffff; +.status-indicator-dot { + width: 7px; + height: 7px; + border-radius: 50%; + background-color: var(--text-muted); } -.terminal-welcome p { - font-size: 13px; - color: var(--text-muted); - line-height: 1.5; +.status-indicator-dot.online { + background-color: var(--accent-emerald); + box-shadow: 0 0 6px rgba(16, 185, 129, 0.6); } -.welcome-stats { - display: flex; - gap: 16px; - margin-top: 6px; - font-size: 12px; - color: var(--text-dim); - font-family: var(--font-mono); +.rail-status-text { + font-size: 11px; + color: var(--text-secondary); } -.welcome-stats strong { +.rail-node-id { + font-size: 10px; color: var(--text-muted); + letter-spacing: 0.05em; } -.welcome-stats code { - color: var(--azure-light); +/* ========================================================================= */ +/* CENTRAL VIEWPORT */ +/* ========================================================================= */ +.central-viewport { + flex: 1; + background-color: var(--bg-base); + overflow: hidden; + position: relative; + display: flex; + flex-direction: column; } -/* Chat Messages */ -.chat-msg { - display: flex; +.view-panel { + display: none; flex-direction: column; - gap: 6px; - animation: fadeIn 0.25s ease-out; + width: 100%; + height: 100%; + overflow: hidden; } -@keyframes fadeIn { - from { opacity: 0; transform: translateY(6px); } - to { opacity: 1; transform: translateY(0); } +.view-panel.active { + display: flex; } -.chat-msg.user { - align-self: flex-end; - max-width: 85%; - background: var(--azure-deep); - border: 1px solid var(--azure-primary); - border-radius: var(--radius-inner); - padding: 12px 16px; - box-shadow: 0 4px 15px rgba(0, 120, 212, 0.2); +.view-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 12px 20px; + border-bottom: 1px solid var(--border-subtle); + background-color: var(--bg-panel); + flex-shrink: 0; } -.chat-msg.user .msg-sender { - font-size: 11px; - font-weight: 600; - color: var(--azure-bright); - text-transform: uppercase; +.header-left { + display: flex; + align-items: center; + gap: 12px; } -.chat-msg.assistant { - align-self: flex-start; - width: 100%; - background: var(--glass-inset); - border: 1px solid var(--glass-border); - border-radius: var(--radius-inner); - padding: 14px 18px; +.view-title { + font-size: 14px; + font-weight: 700; + letter-spacing: 0.06em; + color: var(--text-primary); } -.chat-msg.assistant .msg-sender { +.header-endpoint { font-size: 11px; - font-weight: 600; - color: var(--azure-light); - margin-bottom: 4px; + color: var(--text-muted); + background-color: var(--bg-surface); + padding: 2px 8px; + border-radius: 3px; + border: 1px solid var(--border-subtle); } -/* Reasoning Block */ -details.reasoning-block { - background: rgba(0, 0, 0, 0.3); - border: 1px solid rgba(255, 255, 255, 0.08); - border-radius: 8px; - padding: 8px 12px; - margin-bottom: 10px; +.header-sub { font-size: 12px; color: var(--text-muted); } -details.reasoning-block summary { +.header-actions { + display: flex; + align-items: center; + gap: 8px; +} + +.action-btn { + display: flex; + align-items: center; + gap: 6px; + padding: 6px 12px; + background-color: var(--bg-surface); + border: 1px solid var(--border-subtle); + border-radius: 4px; + color: var(--text-primary); + font-family: var(--font-mono); + font-size: 11px; cursor: pointer; - color: var(--azure-bright); - font-weight: 500; - outline: none; + transition: all 0.15s ease; } -/* Markdown formatting */ -.chat-content p { - margin-bottom: 8px; - font-size: 13.5px; - line-height: 1.6; +.action-btn:hover { + background-color: var(--bg-surface-elevated); + border-color: var(--border-highlight); } -.chat-content pre { - background: rgba(0, 0, 0, 0.4); - border: 1px solid var(--glass-border); - border-radius: 8px; - padding: 12px; - margin: 10px 0; - overflow-x: auto; - font-family: var(--font-mono); - font-size: 12px; +.action-btn.primary-btn { + background-color: rgba(6, 182, 212, 0.15); + border-color: rgba(6, 182, 212, 0.4); + color: var(--accent-cyan); } -.chat-content code { - font-family: var(--font-mono); - font-size: 12px; - background: rgba(255, 255, 255, 0.08); - padding: 2px 5px; - border-radius: 4px; - color: var(--azure-light); +.action-btn.primary-btn:hover { + background-color: rgba(6, 182, 212, 0.25); + border-color: var(--accent-cyan); } -/* Input Area Container */ -.terminal-input-container { +/* ========================================================================= */ +/* VIEW 1: TERMINAL */ +/* ========================================================================= */ +.terminal-wrapper { + flex: 1; display: flex; flex-direction: column; - gap: 10px; - padding: 14px 20px 18px 20px; - border-top: 1px solid var(--glass-border); - background: rgba(0, 0, 0, 0.15); + padding: 16px 20px; + overflow: hidden; } -/* Voice Waveform Visualizer Canvas */ -.voice-waveform { - width: 100%; - height: 36px; - background: rgba(0, 120, 212, 0.08); - border: 1px solid var(--azure-primary); - border-radius: var(--radius-sm); - transition: all 0.2s ease; +.terminal-body { + flex: 1; + background-color: #05080c; + border: 1px solid var(--border-subtle); + border-radius: 4px; + padding: 12px; + display: flex; + flex-direction: column; + overflow: hidden; + outline: none; } -.voice-waveform.hidden { - display: none; +.terminal-output { + flex: 1; + overflow-y: auto; + white-space: pre-wrap; + word-break: break-all; + font-family: var(--font-mono); + font-size: 12px; + line-height: 1.5; + color: #e2e8f0; } -/* Interactive Input Bar Capsule */ -.terminal-input-bar { +.terminal-input-row { display: flex; align-items: center; - gap: 10px; - background: rgba(13, 22, 42, 0.85); - border: 1px solid var(--glass-border); - border-top: 1px solid var(--glass-border-highlight); - border-radius: var(--radius-pill); - padding: 6px 10px 6px 14px; - box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.1); - transition: border-color 0.2s ease, box-shadow 0.2s ease; + gap: 8px; + padding-top: 8px; + border-top: 1px solid #131d2e; } -.terminal-input-bar:focus-within { - border-color: var(--azure-bright); - box-shadow: 0 0 20px var(--azure-glow-intense), inset 0 1px 0 rgba(255, 255, 255, 0.2); +.terminal-prompt { + color: var(--accent-emerald); + font-weight: 600; + font-size: 12px; + white-space: nowrap; +} + +.terminal-cmd-input { + flex: 1; + background: transparent; + border: none; + outline: none; + color: #f1f5f9; + font-family: var(--font-mono); + font-size: 12px; + caret-color: var(--accent-cyan); +} + +/* ANSI styling classes */ +.ansi-green { color: var(--accent-emerald); } +.ansi-yellow { color: var(--accent-amber); } +.ansi-red { color: var(--accent-crimson); } +.ansi-cyan { color: var(--accent-cyan); } +.ansi-dim { color: var(--text-muted); } +.ansi-bold { font-weight: bold; } + +/* ========================================================================= */ +/* VIEW 2: SWARM KANBAN BOARD */ +/* ========================================================================= */ +.kanban-board { + flex: 1; + display: grid; + grid-template-columns: repeat(4, 1fr); + gap: 12px; + padding: 16px 20px; + overflow-x: auto; +} + +.kanban-lane { + display: flex; + flex-direction: column; + background-color: var(--bg-panel); + border: 1px solid var(--border-subtle); + border-radius: 4px; + overflow: hidden; +} + +.lane-header { + padding: 10px 12px; + background-color: var(--bg-surface); + border-bottom: 1px solid var(--border-subtle); + display: flex; + flex-direction: column; + gap: 6px; +} + +.lane-title-group { + display: flex; + align-items: center; + justify-content: space-between; +} + +.lane-title { + font-size: 11px; + font-weight: 700; + letter-spacing: 0.06em; + color: var(--text-primary); +} + +.lane-badge { + font-size: 10px; + font-weight: 700; + padding: 1px 6px; + border-radius: 10px; + background-color: var(--bg-base); + color: var(--text-secondary); +} + +.lane-bar { + height: 2px; + width: 100%; + border-radius: 1px; +} +.bar-cyan { background-color: var(--accent-cyan); } +.bar-amber { background-color: var(--accent-amber); } +.bar-emerald { background-color: var(--accent-emerald); } +.bar-slate { background-color: var(--accent-slate); } + +.lane-cards { + flex: 1; + padding: 10px; + overflow-y: auto; + display: flex; + flex-direction: column; + gap: 8px; +} + +.swarm-card { + background-color: var(--bg-surface); + border: 1px solid var(--border-subtle); + border-radius: 4px; + padding: 10px; + display: flex; + flex-direction: column; + gap: 6px; + cursor: pointer; + transition: all 0.15s ease; +} + +.swarm-card:hover { + border-color: var(--border-highlight); + background-color: var(--bg-surface-elevated); +} + +.card-top { + display: flex; + align-items: center; + justify-content: space-between; +} + +.worker-role { + font-size: 11px; + font-weight: 700; + color: var(--accent-cyan); +} + +.target-repo { + font-size: 10px; + color: var(--text-muted); + background-color: var(--bg-base); + padding: 1px 5px; + border-radius: 3px; + border: 1px solid var(--border-subtle); +} + +.card-title { + font-size: 12px; + color: var(--text-primary); + line-height: 1.35; +} + +.card-bottom { + display: flex; + align-items: center; + justify-content: space-between; + padding-top: 6px; + border-top: 1px solid #162235; + margin-top: 2px; +} + +.step-count { + font-size: 10px; + color: var(--text-secondary); +} + +.btn-card-logs { + font-size: 10px; + padding: 2px 6px; + background-color: transparent; + border: 1px solid var(--border-highlight); + border-radius: 3px; + color: var(--text-secondary); + cursor: pointer; +} +.btn-card-logs:hover { + background-color: var(--bg-base); + color: var(--text-primary); +} + +/* ========================================================================= */ +/* VIEW 3: ATLAS / AIEN CHAT */ +/* ========================================================================= */ +.chat-viewport { + flex: 1; + display: flex; + flex-direction: column; + overflow: hidden; +} + +.chat-messages { + flex: 1; + overflow-y: auto; + padding: 16px 20px; + display: flex; + flex-direction: column; + gap: 14px; +} + +.chat-bubble { + max-width: 85%; + background-color: var(--bg-surface); + border: 1px solid var(--border-subtle); + border-radius: 4px; + padding: 12px 14px; + display: flex; + flex-direction: column; + gap: 8px; +} + +.chat-bubble.user-bubble { + align-self: flex-end; + background-color: #0e1929; + border-color: rgba(6, 182, 212, 0.3); +} + +.chat-bubble.assistant-bubble { + align-self: flex-start; + background-color: var(--bg-panel); + border-color: var(--border-highlight); +} + +.chat-bubble.system-bubble { + align-self: center; + max-width: 90%; + background-color: #0b1118; + border-color: rgba(16, 185, 129, 0.25); + font-size: 12px; + color: var(--text-secondary); +} + +.bubble-header { + display: flex; + align-items: center; + justify-content: space-between; + font-size: 10px; + border-bottom: 1px solid rgba(255, 255, 255, 0.05); + padding-bottom: 4px; +} + +.sender-name { + font-weight: 700; + letter-spacing: 0.05em; + color: var(--accent-cyan); +} + +.msg-timestamp { + color: var(--text-muted); +} + +/* Collapsible reasoning trace */ +.reasoning-pane { + background-color: #06090e; + border: 1px solid #1a273b; + border-radius: 4px; + margin-bottom: 8px; + overflow: hidden; +} + +.reasoning-pane summary { + padding: 6px 10px; + font-size: 11px; + font-weight: 600; + color: var(--accent-amber); + cursor: pointer; + user-select: none; + background-color: rgba(245, 158, 11, 0.06); +} + +.reasoning-pane summary:hover { + background-color: rgba(245, 158, 11, 0.12); +} + +.reasoning-text { + padding: 10px; + font-size: 11px; + line-height: 1.5; + color: #94a3b8; + white-space: pre-wrap; + word-break: break-word; + max-height: 260px; + overflow-y: auto; + border-top: 1px solid #1a273b; +} + +.bubble-content { + font-size: 13px; + line-height: 1.55; + color: #f1f5f9; + white-space: pre-wrap; + word-break: break-word; +} + +.bubble-content code { + background-color: #06090e; + padding: 2px 5px; + border-radius: 3px; + border: 1px solid var(--border-subtle); + color: var(--text-code); + font-family: var(--font-mono); + font-size: 12px; +} + +.bubble-content pre { + background-color: #06090e; + border: 1px solid var(--border-subtle); + border-radius: 4px; + padding: 10px; + margin: 6px 0; + overflow-x: auto; +} + +.bubble-content pre code { + background: transparent; + padding: 0; + border: none; + color: #e2e8f0; +} + +.chat-input-deck { + background-color: var(--bg-panel); + border-top: 1px solid var(--border-subtle); + padding: 12px 20px; + display: flex; + flex-direction: column; + gap: 8px; +} + +.input-ctrl-row { + display: flex; + justify-content: space-between; + align-items: center; + font-size: 11px; + color: var(--text-muted); +} + +.stream-indicator { + font-size: 10px; + font-weight: 700; + color: var(--accent-emerald); +} + +.input-row { + display: flex; + gap: 10px; +} + +.chat-textarea { + flex: 1; + background-color: var(--bg-surface); + border: 1px solid var(--border-subtle); + border-radius: 4px; + padding: 10px 12px; + color: var(--text-primary); + font-family: var(--font-mono); + font-size: 12px; + resize: vertical; + min-height: 52px; + outline: none; +} + +.chat-textarea:focus { + border-color: var(--accent-cyan); +} + +.input-btn-group { + display: flex; + flex-direction: column; + gap: 6px; +} + +.btn-send { + height: 100%; + min-width: 90px; + justify-content: center; +} + +.btn-stop { + border-color: var(--accent-crimson); + color: var(--accent-crimson); +} + +/* ========================================================================= */ +/* VIEW 4: SERVICE MANAGER */ +/* ========================================================================= */ +.services-grid { + flex: 1; + display: grid; + grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); + gap: 16px; + padding: 20px; + overflow-y: auto; +} + +.service-card { + background-color: var(--bg-surface); + border: 1px solid var(--border-subtle); + border-radius: 4px; + padding: 16px; + display: flex; + flex-direction: column; + gap: 14px; +} + +.service-card-top { + display: flex; + justify-content: space-between; + align-items: flex-start; +} + +.service-meta { + display: flex; + flex-direction: column; + gap: 2px; +} + +.service-name { + font-size: 13px; + font-weight: 700; + color: var(--text-primary); +} + +.service-spec { + font-size: 11px; + color: var(--text-muted); +} + +.service-badge { + font-size: 10px; + font-weight: 700; + padding: 2px 7px; + border-radius: 3px; +} + +.service-metrics { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 8px; + background-color: var(--bg-base); + border: 1px solid var(--border-subtle); + border-radius: 4px; + padding: 8px 10px; +} + +.svc-metric { + display: flex; + flex-direction: column; + gap: 2px; +} + +.m-label { + font-size: 9px; + font-weight: 600; + color: var(--text-muted); +} + +.m-val { + font-size: 11px; + font-weight: 600; + color: var(--accent-cyan); +} + +.service-actions { + display: flex; + gap: 8px; +} + +.svc-btn { + flex: 1; + padding: 6px 0; + background-color: var(--bg-panel); + border: 1px solid var(--border-subtle); + border-radius: 3px; + color: var(--text-secondary); + font-family: var(--font-mono); + font-size: 11px; + cursor: pointer; + transition: all 0.15s ease; +} + +.svc-btn:hover { + background-color: var(--bg-surface-elevated); + border-color: var(--border-highlight); + color: var(--text-primary); +} + +.svc-btn.highlight { + border-color: rgba(6, 182, 212, 0.4); + color: var(--accent-cyan); +} + +.svc-btn.highlight:hover { + background-color: var(--accent-cyan-dim); +} + +/* ========================================================================= */ +/* VIEW 5: RSI LEDGER VIEWER */ +/* ========================================================================= */ +.ledger-stats-row { + display: grid; + grid-template-columns: repeat(4, 1fr); + gap: 12px; + padding: 16px 20px; + background-color: var(--bg-panel); + border-bottom: 1px solid var(--border-subtle); +} + +.stat-card { + background-color: var(--bg-surface); + border: 1px solid var(--border-subtle); + border-radius: 4px; + padding: 10px 12px; + display: flex; + flex-direction: column; + gap: 4px; +} + +.stat-label { + font-size: 10px; + font-weight: 600; + color: var(--text-muted); +} + +.stat-val { + font-size: 14px; + font-weight: 700; + color: var(--text-primary); +} + +.text-emerald { color: var(--accent-emerald); } +.text-cyan { color: var(--accent-cyan); } +.text-amber { color: var(--accent-amber); } + +.ledger-table-wrap { + flex: 1; + overflow: auto; + padding: 16px 20px; } -/* Mic Button */ -.btn-mic { - position: relative; - width: 34px; - height: 34px; - border-radius: 50%; - background: transparent; - border: none; +.ledger-table { + width: 100%; + border-collapse: collapse; + font-size: 11px; + text-align: left; +} + +.ledger-table th { + padding: 8px 12px; + background-color: var(--bg-surface); + border-bottom: 1px solid var(--border-highlight); color: var(--text-muted); - cursor: pointer; - display: flex; - align-items: center; - justify-content: center; - transition: all 0.2s ease; + font-weight: 700; + letter-spacing: 0.05em; + position: sticky; + top: 0; } -.btn-mic:hover { - color: var(--azure-bright); - background: rgba(255, 255, 255, 0.08); +.ledger-table td { + padding: 10px 12px; + border-bottom: 1px solid var(--border-subtle); + color: var(--text-secondary); } -.btn-mic.listening { - color: #ffffff; - background: var(--azure-primary); - box-shadow: 0 0 14px var(--azure-glow-intense); +.ledger-table tr:hover td { + background-color: var(--bg-surface-elevated); + color: var(--text-primary); } -.btn-mic.listening .mic-ripple { - position: absolute; - top: -4px; - left: -4px; - right: -4px; - bottom: -4px; - border-radius: 50%; - border: 2px solid var(--azure-bright); - animation: pulseRipple 1.4s infinite cubic-bezier(0, 0.2, 0.8, 1); +.empty-cell { + text-align: center; + padding: 30px !important; + color: var(--text-muted); +} + +/* ========================================================================= */ +/* VIEW 6: CORTEX MEMORY EXPLORER */ +/* ========================================================================= */ +.cortex-search-deck { + padding: 16px 20px; + background-color: var(--bg-panel); + border-bottom: 1px solid var(--border-subtle); + display: flex; + flex-direction: column; + gap: 10px; } -@keyframes pulseRipple { - 0% { transform: scale(0.9); opacity: 1; } - 100% { transform: scale(1.4); opacity: 0; } +.search-input-wrap { + display: flex; + align-items: center; + gap: 8px; + background-color: var(--bg-surface); + border: 1px solid var(--border-subtle); + border-radius: 4px; + padding: 4px 10px; } -.btn-mic i { +.search-icon { width: 16px; height: 16px; + color: var(--text-muted); } -/* Input Field */ -.terminal-input { +.cortex-search-input { flex: 1; background: transparent; border: none; outline: none; - color: var(--text-main); + color: var(--text-primary); font-family: var(--font-mono); - font-size: 13.5px; - padding: 4px 0; + font-size: 12px; } -.terminal-input::placeholder { - color: var(--text-dim); +.cortex-quick-filters { + display: flex; + gap: 6px; } -/* Send Button */ -.btn-send { - width: 32px; - height: 32px; - border-radius: 50%; - background: var(--azure-primary); - border: none; - color: #ffffff; +.filter-pill { + padding: 3px 9px; + background-color: var(--bg-surface); + border: 1px solid var(--border-subtle); + border-radius: 12px; + color: var(--text-secondary); + font-family: var(--font-mono); + font-size: 10px; cursor: pointer; + transition: all 0.15s ease; +} + +.filter-pill:hover { + background-color: var(--bg-surface-elevated); + color: var(--text-primary); +} + +.filter-pill.active { + background-color: var(--accent-cyan-dim); + border-color: rgba(6, 182, 212, 0.4); + color: var(--accent-cyan); + font-weight: 600; +} + +.cortex-commit-drawer { + padding: 16px 20px; + background-color: #0c1420; + border-bottom: 1px solid var(--border-highlight); display: flex; - align-items: center; - justify-content: center; - transition: all 0.2s ease; - box-shadow: 0 0 10px var(--azure-glow); + flex-direction: column; + gap: 10px; } -.btn-send:hover { - background: var(--azure-bright); - transform: scale(1.05); - box-shadow: 0 0 16px var(--azure-glow-intense); +.drawer-title { + font-size: 12px; + font-weight: 700; + color: var(--accent-cyan); } -.btn-send i { - width: 15px; - height: 15px; +.cortex-grid { + flex: 1; + display: grid; + grid-template-columns: repeat(auto-fill, minmax(360px, 1fr)); + gap: 14px; + padding: 20px; + overflow-y: auto; } -/* Quick Action Strip */ -.terminal-quick-strip { +.cortex-card { + background-color: var(--bg-surface); + border: 1px solid var(--border-subtle); + border-radius: 4px; + padding: 14px; display: flex; + flex-direction: column; gap: 8px; - overflow-x: auto; - padding-bottom: 2px; } -.quick-pill { +.cortex-card-header { display: flex; - align-items: center; - gap: 5px; - padding: 4px 10px; - background: rgba(255, 255, 255, 0.04); - border: 1px solid var(--glass-border); - border-radius: var(--radius-pill); - color: var(--text-muted); - font-size: 11px; - font-weight: 500; - cursor: pointer; - white-space: nowrap; - transition: all 0.15s ease; + justify-content: space-between; + align-items: flex-start; + gap: 8px; } -.quick-pill:hover { - color: var(--text-main); - background: rgba(255, 255, 255, 0.08); - border-color: var(--azure-border); +.cortex-name { + font-size: 12px; + font-weight: 700; + color: var(--accent-cyan); + line-height: 1.3; } -.quick-pill i { - width: 12px; - height: 12px; +.cortex-badge { + font-size: 9px; + font-weight: 700; + padding: 2px 6px; + border-radius: 3px; + text-transform: uppercase; } -/* Peripheral Floating Satellites */ -.satellite-pod { - position: absolute; - width: 380px; - max-width: 90vw; - height: calc(100% - 20px); - background: var(--glass-surface); - backdrop-filter: var(--glass-blur); - -webkit-backdrop-filter: var(--glass-blur); - border: 1px solid var(--glass-border); - border-top: 1px solid var(--glass-border-highlight); - border-radius: var(--radius-pod); - box-shadow: var(--glass-shadow); - display: flex; - flex-direction: column; - overflow: hidden; - opacity: 0; - pointer-events: none; - transform: scale(0.96) translateX(20px); - transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1); - z-index: 20; +.cortex-content { + font-size: 11px; + line-height: 1.5; + color: var(--text-secondary); + white-space: pre-wrap; + word-break: break-word; + max-height: 140px; + overflow-y: auto; } -/* Docked Positions */ -#satellite-stage { - right: 0; - width: 520px; +.cortex-footer { + display: flex; + justify-content: space-between; + align-items: center; + font-size: 10px; + color: var(--text-muted); + border-top: 1px solid #142030; + padding-top: 6px; } -#satellite-telemetry { - left: 0; +.cortex-placeholder { + grid-column: 1 / -1; + text-align: center; + padding: 40px; + color: var(--text-muted); } -#satellite-models { - left: 0; +/* ========================================================================= */ +/* RIGHT COLLAPSIBLE WATCHDOG DRAWER */ +/* ========================================================================= */ +.watchdog-drawer { + width: 330px; + background-color: var(--bg-deck); + border-left: 1px solid var(--border-subtle); + display: flex; + flex-direction: column; + flex-shrink: 0; + position: absolute; + right: -330px; + top: 0; + bottom: 0; + z-index: 30; + transition: right 0.25s cubic-bezier(0.16, 1, 0.3, 1); + box-shadow: -4px 0 20px rgba(0, 0, 0, 0.5); } -#satellite-mail { +.watchdog-drawer.open { right: 0; - width: 440px; -} - -.satellite-pod.active { - opacity: 1; - pointer-events: auto; - transform: scale(1) translateX(0); } -.satellite-header { +.watchdog-header { display: flex; align-items: center; justify-content: space-between; - padding: 12px 18px; - border-bottom: 1px solid var(--glass-border); - background: rgba(255, 255, 255, 0.02); + padding: 14px 16px; + border-bottom: 1px solid var(--border-subtle); } -.sat-title { +.watchdog-title-group { display: flex; align-items: center; gap: 8px; - font-weight: 600; - font-size: 13px; - color: #ffffff; } -.sat-title i { - width: 15px; - height: 15px; - color: var(--azure-bright); +.watchdog-title { + font-size: 12px; + font-weight: 700; + letter-spacing: 0.05em; + color: var(--text-primary); } -.satellite-body { - flex: 1; - overflow-y: auto; - padding: 16px; - display: flex; - flex-direction: column; - gap: 12px; +.drawer-close-btn { + background: transparent; + border: none; + color: var(--text-muted); + font-size: 18px; + cursor: pointer; + padding: 0 4px; +} +.drawer-close-btn:hover { + color: var(--text-primary); } -/* Telemetry Card */ -.telemetry-card { +.watchdog-remediation-box { + margin: 14px 16px; + padding: 12px; + background-color: rgba(239, 68, 68, 0.05); + border: 1px solid rgba(239, 68, 68, 0.25); + border-radius: 4px; display: flex; flex-direction: column; - gap: 4px; + gap: 8px; } -.t-title { - font-size: 11px; - color: var(--text-dim); - text-transform: uppercase; +.remediation-title { + font-size: 10px; + font-weight: 700; + color: var(--accent-crimson); letter-spacing: 0.05em; - font-family: var(--font-mono); } -.t-value { - font-size: 16px; - font-weight: 700; - font-family: var(--font-mono); - color: #ffffff; +.remediation-desc { + font-size: 10px; + color: var(--text-muted); + line-height: 1.4; } -.t-sub { +.remediation-btn { + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + padding: 8px 12px; + background-color: rgba(239, 68, 68, 0.15); + border: 1px solid rgba(239, 68, 68, 0.4); + border-radius: 4px; + color: var(--accent-crimson); + font-family: var(--font-mono); font-size: 11px; - color: var(--text-muted); + font-weight: 700; + cursor: pointer; + transition: all 0.15s ease; } -.progress-bar-wrap { - width: 100%; - height: 5px; - background: rgba(255, 255, 255, 0.08); - border-radius: 3px; +.remediation-btn:hover { + background-color: rgba(239, 68, 68, 0.3); + border-color: var(--accent-crimson); +} + +.remediation-status { + font-size: 10px; + color: var(--text-secondary); + min-height: 14px; +} + +.watchdog-section { + padding: 12px 16px; + display: flex; + flex-direction: column; + gap: 8px; + border-top: 1px solid var(--border-subtle); +} + +.watchdog-section.flex-grow { + flex: 1; overflow: hidden; - margin: 4px 0; } -.progress-bar { - height: 100%; - background: var(--azure-bright); - box-shadow: 0 0 8px var(--azure-glow-intense); - border-radius: 3px; +.section-label { + font-size: 10px; + font-weight: 700; + color: var(--text-muted); + letter-spacing: 0.05em; } -.daemon-list { +.alerts-feed { display: flex; flex-direction: column; gap: 6px; - margin-top: 6px; + max-height: 140px; + overflow-y: auto; } -.d-item { +.alert-item { display: flex; - align-items: center; + align-items: flex-start; gap: 8px; - font-size: 12px; - font-family: var(--font-mono); + padding: 6px 8px; + background-color: var(--bg-surface); + border: 1px solid var(--border-subtle); + border-radius: 3px; } -/* Glass Form Controls */ -.glass-input, .glass-select { - background: rgba(0, 0, 0, 0.4); - border: 1px solid var(--glass-border); - border-radius: var(--radius-sm); - color: var(--text-main); - padding: 7px 10px; - font-family: var(--font-mono); - font-size: 12px; - outline: none; +.alert-dot { + width: 6px; + height: 6px; + border-radius: 50%; + margin-top: 4px; + flex-shrink: 0; } +.dot-emerald { background-color: var(--accent-emerald); } +.dot-amber { background-color: var(--accent-amber); } +.dot-crimson { background-color: var(--accent-crimson); } -.glass-input:focus, .glass-select:focus { - border-color: var(--azure-bright); - box-shadow: 0 0 10px var(--azure-glow); +.alert-body { + display: flex; + flex-direction: column; + gap: 2px; } -.btn { - display: inline-flex; - align-items: center; - justify-content: center; - gap: 6px; - padding: 8px 14px; - border-radius: var(--radius-sm); - font-size: 12px; - font-weight: 600; - cursor: pointer; - transition: all 0.2s ease; - border: none; +.alert-msg { + font-size: 10px; + color: var(--text-primary); + line-height: 1.3; } -.btn-sm { - padding: 5px 10px; - font-size: 11px; +.alert-time { + font-size: 9px; + color: var(--text-muted); +} + +.event-timeline { + flex: 1; + overflow-y: auto; + display: flex; + flex-direction: column; + gap: 4px; + font-size: 10px; +} + +.timeline-item { + padding: 4px 6px; + border-left: 2px solid var(--border-highlight); + color: var(--text-muted); + line-height: 1.35; } -.btn-primary { - background: var(--azure-primary); - color: #ffffff; - box-shadow: 0 0 12px var(--azure-glow); +.timeline-item.highlight { + border-left-color: var(--accent-cyan); + color: var(--text-secondary); } -.btn-primary:hover { - background: var(--azure-bright); - box-shadow: 0 0 18px var(--azure-glow-intense); +/* ========================================================================= */ +/* MODALS */ +/* ========================================================================= */ +.modal-overlay { + position: fixed; + inset: 0; + background-color: rgba(5, 8, 13, 0.85); + backdrop-filter: blur(4px); + display: flex; + align-items: center; + justify-content: center; + z-index: 100; } -.btn-secondary { - background: rgba(255, 255, 255, 0.08); - color: var(--text-main); - border: 1px solid var(--glass-border); +.modal-box { + width: 90%; + max-width: 520px; + background-color: var(--bg-deck); + border: 1px solid var(--border-highlight); + border-radius: 6px; + display: flex; + flex-direction: column; + overflow: hidden; + box-shadow: 0 10px 40px rgba(0, 0, 0, 0.8); } -.btn-secondary:hover { - background: rgba(255, 255, 255, 0.14); +.modal-box.modal-lg { + max-width: 780px; } -/* Sovereign Mail Pod Details */ -.mail-info-bar { +.modal-header { display: flex; + align-items: center; justify-content: space-between; - font-size: 11px; - font-family: var(--font-mono); - padding: 6px 10px; + padding: 14px 18px; + background-color: var(--bg-panel); + border-bottom: 1px solid var(--border-subtle); +} + +.modal-title { + font-size: 13px; + font-weight: 700; + letter-spacing: 0.05em; + color: var(--text-primary); +} + +.modal-close { + background: transparent; + border: none; + color: var(--text-muted); + font-size: 20px; + cursor: pointer; +} +.modal-close:hover { + color: var(--text-primary); } -.mail-inbox-scroll { +.modal-body { + padding: 18px; display: flex; flex-direction: column; - gap: 8px; - max-height: 480px; + gap: 14px; + max-height: 70vh; overflow-y: auto; } -.mail-item { +.modal-footer { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 8px; + padding: 12px 18px; + background-color: var(--bg-panel); + border-top: 1px solid var(--border-subtle); +} + +.form-group { display: flex; flex-direction: column; - gap: 4px; - padding: 10px; - background: var(--glass-inset); - border: 1px solid var(--glass-border); - border-radius: var(--radius-sm); - cursor: pointer; - transition: all 0.15s ease; + gap: 5px; } -.mail-item:hover { - border-color: var(--azure-bright); - background: rgba(0, 120, 212, 0.08); +.form-label { + font-size: 10px; + font-weight: 700; + color: var(--text-muted); + letter-spacing: 0.05em; } -.mail-meta { +.form-row { display: flex; - justify-content: space-between; - font-size: 11px; - color: var(--azure-light); + gap: 10px; } -.mail-subject { - font-weight: 600; +.form-input, .form-select, .form-textarea { + width: 100%; + padding: 8px 10px; + background-color: var(--bg-surface); + border: 1px solid var(--border-subtle); + border-radius: 4px; + color: var(--text-primary); + font-family: var(--font-mono); font-size: 12px; - color: #ffffff; + outline: none; +} + +.form-input:focus, .form-select:focus, .form-textarea:focus { + border-color: var(--accent-cyan); } -/* Artifact Empty State */ -.artifact-empty-state { +.logs-meta-bar { display: flex; - flex-direction: column; align-items: center; - justify-content: center; - text-align: center; - padding: 40px 20px; - color: var(--text-dim); gap: 12px; + font-size: 11px; + color: var(--text-secondary); + padding-bottom: 8px; + border-bottom: 1px solid var(--border-subtle); } -.artifact-empty-state i { - width: 36px; - height: 36px; - color: var(--azure-bright); - opacity: 0.6; +.logs-pre { + background-color: #05080c; + border: 1px solid var(--border-subtle); + border-radius: 4px; + padding: 12px; + font-family: var(--font-mono); + font-size: 11px; + line-height: 1.5; + color: #e2e8f0; + white-space: pre-wrap; + word-break: break-all; + max-height: 400px; + overflow-y: auto; } -/* Responsive adjustments */ -@media (max-width: 1024px) { - .avionics-telemetry { display: none; } - .satellite-pod { width: 90vw !important; right: 5vw !important; left: 5vw !important; } +/* Common icons */ +.icon-sm { + width: 14px; + height: 14px; }