aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / aien-cli / src / cortex.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | use colored::*; |
| 17 | use reqwest::Client; |
| 18 | use serde_json::{json, Value}; |
| 19 | |
| 20 | const CORTEX_BASE_URL: &str = "http://127.0.0.1:18080"; |
| 21 | pub fn get_cortex_token() -> String { |
| 22 | crate::vault::get_secret("CORTEX_TOKEN").unwrap_or_default() |
| 23 | } |
| 24 | |
| 25 | pub async fn write_to_cortex( |
| 26 | canonical_name: &str, |
| 27 | content: &str, |
| 28 | entity_type: &str, |
| 29 | metadata: Value, |
| 30 | ) -> Result<Value, String> { |
| 31 | let token = get_cortex_token(); |
| 32 | if token.is_empty() { |
| 33 | return Err("CORTEX_TOKEN is unavailable from atlas-vault".to_string()); |
| 34 | } |
| 35 | |
| 36 | let et = if entity_type.is_empty() { |
| 37 | "discovery" |
| 38 | } else { |
| 39 | entity_type |
| 40 | }; |
| 41 | let payload = json!({ |
| 42 | "kind": "entity", |
| 43 | "value": { |
| 44 | "space": "atlas-memory", |
| 45 | "entityType": et, |
| 46 | "canonicalName": canonical_name, |
| 47 | "content": content, |
| 48 | "metadata": metadata, |
| 49 | } |
| 50 | }); |
| 51 | |
| 52 | let client = Client::new(); |
| 53 | let resp = client |
| 54 | .post(format!("{}/api/cortex/write", CORTEX_BASE_URL)) |
| 55 | .header("Authorization", format!("Bearer {}", token)) |
| 56 | .header("Content-Type", "application/json") |
| 57 | .header("Accept", "application/json") |
| 58 | .json(&payload) |
| 59 | .send() |
| 60 | .await |
| 61 | .map_err(|e| format!("Failed to connect to Cortex (18080): {}", e))?; |
| 62 | |
| 63 | if !resp.status().is_success() { |
| 64 | let status = resp.status(); |
| 65 | let body = resp.text().await.unwrap_or_default(); |
| 66 | return Err(format!("Cortex write failed [{}]: {}", status, body)); |
| 67 | } |
| 68 | |
| 69 | let res_json = resp |
| 70 | .json::<Value>() |
| 71 | .await |
| 72 | .map_err(|e| format!("Invalid JSON response: {}", e))?; |
| 73 | Ok(res_json) |
| 74 | } |
| 75 | |
| 76 | pub async fn search_cortex(query: &str, limit: usize) -> Result<Vec<Value>, String> { |
| 77 | let token = get_cortex_token(); |
| 78 | if token.is_empty() { |
| 79 | return Err("CORTEX_TOKEN is unavailable from atlas-vault".to_string()); |
| 80 | } |
| 81 | let url = format!("{}/api/cortex/search", CORTEX_BASE_URL); |
| 82 | let client = Client::new(); |
| 83 | let resp = client |
| 84 | .get(&url) |
| 85 | .header("Accept", "application/json") |
| 86 | .bearer_auth(token) |
| 87 | .query(&[ |
| 88 | ("q", query), |
| 89 | ("space", "atlas-memory"), |
| 90 | ("limit", &limit.to_string()), |
| 91 | ]) |
| 92 | .send() |
| 93 | .await |
| 94 | .map_err(|e| format!("Cortex connection failed: {}", e))?; |
| 95 | let resp = resp |
| 96 | .error_for_status() |
| 97 | .map_err(|e| format!("Cortex search failed: {}", e))?; |
| 98 | let data = resp |
| 99 | .json::<Value>() |
| 100 | .await |
| 101 | .map_err(|e| format!("Invalid Cortex search response: {}", e))?; |
| 102 | data.get("results") |
| 103 | .and_then(Value::as_array) |
| 104 | .cloned() |
| 105 | .ok_or_else(|| "Cortex search response lacks results array".to_string()) |
| 106 | } |
| 107 | |
| 108 | /// Automatically assembles relevant memories and procedures from Spark Cortex based on active task context. |
| 109 | pub async fn assemble_cortex_recall(query: &str, limit: usize) -> Option<String> { |
| 110 | let trimmed = query.trim(); |
| 111 | if trimmed.len() < 3 { |
| 112 | return None; |
| 113 | } |
| 114 | |
| 115 | // Clean query: take first 150 chars or first line to avoid giant search strings |
| 116 | let clean_query = if let Some(idx) = trimmed.find('\n') { |
| 117 | &trimmed[..idx] |
| 118 | } else if trimmed.len() > 150 { |
| 119 | &trimmed[..150] |
| 120 | } else { |
| 121 | trimmed |
| 122 | }; |
| 123 | |
| 124 | match search_cortex(clean_query, limit).await { |
| 125 | Ok(items) if !items.is_empty() => { |
| 126 | let mut recall_entries = Vec::new(); |
| 127 | for it in items { |
| 128 | let name = it |
| 129 | .get("canonicalName") |
| 130 | .and_then(Value::as_str) |
| 131 | .unwrap_or("Untitled"); |
| 132 | let score = it.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0); |
| 133 | let content = it.get("content").and_then(Value::as_str).unwrap_or(""); |
| 134 | let kind = it |
| 135 | .get("entityType") |
| 136 | .and_then(Value::as_str) |
| 137 | .unwrap_or("memory"); |
| 138 | |
| 139 | if score >= 0.05 { |
| 140 | let snippet = if content.len() > 300 { |
| 141 | &content[..300] |
| 142 | } else { |
| 143 | content |
| 144 | }; |
| 145 | recall_entries.push(format!( |
| 146 | "• [{}] {} (relevance: {:.2}):\n {}", |
| 147 | kind, |
| 148 | name, |
| 149 | score, |
| 150 | snippet.trim() |
| 151 | )); |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | if recall_entries.is_empty() { |
| 156 | return None; |
| 157 | } |
| 158 | |
| 159 | Some(format!( |
| 160 | "<cortex-recall>\nVerified durable knowledge recalled from Spark Cortex:\n{}\n</cortex-recall>", |
| 161 | recall_entries.join("\n") |
| 162 | )) |
| 163 | } |
| 164 | _ => None, |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | /// Assemble bounded context from durable Cortex memory and the founding neuroscience corpus. |
| 169 | pub async fn assemble_model_context(query: &str) -> Option<String> { |
| 170 | let durable = assemble_cortex_recall(query, 5).await; |
| 171 | let science = crate::science_context::render_foundation_science(query, 3); |
| 172 | match (durable, science) { |
| 173 | (Some(durable), Some(science)) => Some(format!("{}\n\n{}", science, durable)), |
| 174 | (Some(durable), None) => Some(durable), |
| 175 | (None, Some(science)) => Some(science), |
| 176 | (None, None) => None, |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | /// Asynchronously capture an action outcome or lesson into Spark Cortex without blocking execution. |
| 181 | pub fn trigger_background_capture(action: &str, target: &str, details: &str) { |
| 182 | let action_owned = action.to_string(); |
| 183 | let target_owned = target.to_string(); |
| 184 | let details_owned = details.to_string(); |
| 185 | |
| 186 | tokio::spawn(async move { |
| 187 | let canonical_name = format!( |
| 188 | "discovery-{}-{}", |
| 189 | action_owned.replace(" ", "-"), |
| 190 | chrono::Utc::now().timestamp() |
| 191 | ); |
| 192 | let content = format!( |
| 193 | "Autonomous action '{}' executed on target '{}'. Summary: {}", |
| 194 | action_owned, target_owned, details_owned |
| 195 | ); |
| 196 | let metadata = json!({ |
| 197 | "source": "aien-cli-auto-capture", |
| 198 | "action": action_owned, |
| 199 | "target": target_owned, |
| 200 | "timestamp": chrono::Utc::now().to_rfc3339() |
| 201 | }); |
| 202 | let _ = write_to_cortex(&canonical_name, &content, "discovery", metadata).await; |
| 203 | }); |
| 204 | } |
| 205 | |
| 206 | pub async fn handle_cortex_command(parts: &[&str]) { |
| 207 | if parts.is_empty() { |
| 208 | println!("Usage: /cortex [search <query> | write <name> | <content>]"); |
| 209 | return; |
| 210 | } |
| 211 | |
| 212 | match parts[0] { |
| 213 | "search" | "find" => { |
| 214 | let q = parts[1..].join(" "); |
| 215 | println!( |
| 216 | "{}", |
| 217 | format!("Searching Cortex (atlas-memory) for '{}'...", q).yellow() |
| 218 | ); |
| 219 | match search_cortex(&q, 5).await { |
| 220 | Ok(items) if !items.is_empty() => { |
| 221 | println!( |
| 222 | "{}", |
| 223 | format!("\nCortex Knowledge Recall ({} found):", items.len()) |
| 224 | .cyan() |
| 225 | .bold() |
| 226 | ); |
| 227 | for (i, it) in items.iter().enumerate() { |
| 228 | let name = it |
| 229 | .get("canonicalName") |
| 230 | .and_then(Value::as_str) |
| 231 | .unwrap_or("Untitled"); |
| 232 | let score = it.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0); |
| 233 | let content = it.get("content").and_then(Value::as_str).unwrap_or(""); |
| 234 | let snippet = if content.len() > 180 { |
| 235 | &content[..180] |
| 236 | } else { |
| 237 | content |
| 238 | }; |
| 239 | println!("{}. {} ({:.2})", i + 1, name.bold().yellow(), score); |
| 240 | println!(" {}\n", snippet.dimmed()); |
| 241 | } |
| 242 | } |
| 243 | Ok(_) => println!("{}", "No matching entities found in atlas-memory.".dimmed()), |
| 244 | Err(e) => println!("{}", format!("Error querying Cortex: {}", e).red()), |
| 245 | } |
| 246 | } |
| 247 | "write" | "remember" => { |
| 248 | let full_text = parts[1..].join(" "); |
| 249 | let split: Vec<&str> = full_text.split('|').collect(); |
| 250 | if split.len() < 2 { |
| 251 | println!("Usage: /cortex write <canonical_name> | <content>"); |
| 252 | return; |
| 253 | } |
| 254 | let name = split[0].trim(); |
| 255 | let content = split[1..].join("|").trim().to_string(); |
| 256 | |
| 257 | println!( |
| 258 | "{}", |
| 259 | format!("Committing memory entity '{}' to Spark Cortex...", name).yellow() |
| 260 | ); |
| 261 | match write_to_cortex( |
| 262 | name, |
| 263 | &content, |
| 264 | "lesson", |
| 265 | json!({"source": "aien-cli", "author": "operator"}), |
| 266 | ) |
| 267 | .await |
| 268 | { |
| 269 | Ok(res) => { |
| 270 | let r_id = res |
| 271 | .get("receipt") |
| 272 | .and_then(|r| r.get("id")) |
| 273 | .and_then(Value::as_str) |
| 274 | .unwrap_or("confirmed"); |
| 275 | println!( |
| 276 | "{}", |
| 277 | format!("✓ Committed to Spark Cortex Memory! Receipt: {}", r_id) |
| 278 | .green() |
| 279 | .bold() |
| 280 | ); |
| 281 | } |
| 282 | Err(e) => println!( |
| 283 | "{}", |
| 284 | format!("Failed to commit to Cortex: {}", e).red().bold() |
| 285 | ), |
| 286 | } |
| 287 | } |
| 288 | _ => { |
| 289 | let q = parts.join(" "); |
| 290 | println!( |
| 291 | "{}", |
| 292 | format!("Searching Cortex (atlas-memory) for '{}'...", q).yellow() |
| 293 | ); |
| 294 | match search_cortex(&q, 5).await { |
| 295 | Ok(items) if !items.is_empty() => { |
| 296 | println!( |
| 297 | "{}", |
| 298 | format!("\nCortex Knowledge Recall ({} found):", items.len()) |
| 299 | .cyan() |
| 300 | .bold() |
| 301 | ); |
| 302 | for (i, it) in items.iter().enumerate() { |
| 303 | let name = it |
| 304 | .get("canonicalName") |
| 305 | .and_then(Value::as_str) |
| 306 | .unwrap_or("Untitled"); |
| 307 | let score = it.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0); |
| 308 | let content = it.get("content").and_then(Value::as_str).unwrap_or(""); |
| 309 | let snippet = if content.len() > 180 { |
| 310 | &content[..180] |
| 311 | } else { |
| 312 | content |
| 313 | }; |
| 314 | println!("{}. {} ({:.2})", i + 1, name.bold().yellow(), score); |
| 315 | println!(" {}\n", snippet.dimmed()); |
| 316 | } |
| 317 | } |
| 318 | Ok(_) => println!("{}", "No matching entities found in atlas-memory.".dimmed()), |
| 319 | Err(e) => println!("{}", format!("Error querying Cortex: {}", e).red()), |
| 320 | } |
| 321 | } |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | pub async fn cortex_dispatch_tool(args: &Value) -> Value { |
| 326 | let action = args |
| 327 | .get("action") |
| 328 | .and_then(Value::as_str) |
| 329 | .unwrap_or("search"); |
| 330 | |
| 331 | match action { |
| 332 | "write" | "remember" => { |
| 333 | let name = args |
| 334 | .get("name") |
| 335 | .and_then(Value::as_str) |
| 336 | .unwrap_or("unnamed_memory"); |
| 337 | let content = args.get("content").and_then(Value::as_str).unwrap_or(""); |
| 338 | let kind = args |
| 339 | .get("kind") |
| 340 | .and_then(Value::as_str) |
| 341 | .unwrap_or("discovery"); |
| 342 | let meta = args |
| 343 | .get("metadata") |
| 344 | .cloned() |
| 345 | .unwrap_or(json!({"source": "model_dispatch"})); |
| 346 | |
| 347 | match write_to_cortex(name, content, kind, meta).await { |
| 348 | Ok(receipt) => json!({ |
| 349 | "status": "ok", |
| 350 | "receipt": receipt, |
| 351 | "message": format!("Committed '{}' to Spark Cortex (atlas-memory).", name) |
| 352 | }), |
| 353 | Err(e) => json!({"status": "error", "error": e}), |
| 354 | } |
| 355 | } |
| 356 | "search" => { |
| 357 | let q = args.get("query").and_then(Value::as_str).unwrap_or(""); |
| 358 | let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(5) as usize; |
| 359 | match search_cortex(q, limit).await { |
| 360 | Ok(results) => json!({"status": "ok", "results": results}), |
| 361 | Err(e) => json!({"status": "error", "error": e}), |
| 362 | } |
| 363 | } |
| 364 | _ => json!({"error": format!("Unknown cortex action '{}'", action)}), |
| 365 | } |
| 366 | } |