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 / cortex-rs / src / compiler.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 serde::{Deserialize, Serialize}; |
| 17 | use std::sync::Arc; |
| 18 | use uuid::Uuid; |
| 19 | |
| 20 | use crate::db::Database; |
| 21 | use crate::models::{ClaimStatus, VerificationTier}; |
| 22 | use crate::security::SecurityMembrane; |
| 23 | |
| 24 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] |
| 25 | #[serde(rename_all = "snake_case")] |
| 26 | pub enum MemoryIntent { |
| 27 | #[default] |
| 28 | Conversation, |
| 29 | Coding, |
| 30 | Planning, |
| 31 | Research, |
| 32 | ToolExecution, |
| 33 | Reflection, |
| 34 | MemoryAdjudication, |
| 35 | } |
| 36 | |
| 37 | #[derive(Debug, Clone, Deserialize)] |
| 38 | #[serde(rename_all = "camelCase")] |
| 39 | pub struct MemoryQuery { |
| 40 | pub query: String, |
| 41 | pub session_id: Option<String>, |
| 42 | pub branch_id: Option<String>, |
| 43 | #[serde(default = "default_space")] |
| 44 | pub space: String, |
| 45 | #[serde(default)] |
| 46 | pub intent: MemoryIntent, |
| 47 | #[serde(default = "default_compiler_token_budget")] |
| 48 | pub token_budget: usize, |
| 49 | #[serde(default)] |
| 50 | pub include_candidates: bool, |
| 51 | pub minimum_verification: Option<VerificationTier>, |
| 52 | } |
| 53 | |
| 54 | fn default_space() -> String { |
| 55 | "atlas-memory".to_string() |
| 56 | } |
| 57 | |
| 58 | fn default_compiler_token_budget() -> usize { |
| 59 | 2048 |
| 60 | } |
| 61 | |
| 62 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 63 | #[serde(rename_all = "camelCase")] |
| 64 | pub struct CanonicalContextItem { |
| 65 | pub text: String, |
| 66 | pub claim_id: String, |
| 67 | pub verification_tier: VerificationTier, |
| 68 | pub status: ClaimStatus, |
| 69 | pub evidence_count: usize, |
| 70 | } |
| 71 | |
| 72 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 73 | #[serde(rename_all = "camelCase")] |
| 74 | pub struct EpisodicContextItem { |
| 75 | pub kind: String, |
| 76 | pub level: Option<i64>, |
| 77 | pub sequence_range: Option<String>, |
| 78 | pub text: String, |
| 79 | } |
| 80 | |
| 81 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 82 | #[serde(rename_all = "camelCase")] |
| 83 | pub struct HypothesisContextItem { |
| 84 | pub candidate_id: String, |
| 85 | pub assertion: String, |
| 86 | pub confidence: f64, |
| 87 | pub verification: String, |
| 88 | pub advisory: String, |
| 89 | } |
| 90 | |
| 91 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 92 | #[serde(rename_all = "camelCase")] |
| 93 | pub struct MemoryContext { |
| 94 | pub episodic: Vec<EpisodicContextItem>, |
| 95 | pub canonical: Vec<CanonicalContextItem>, |
| 96 | pub hypotheses: Vec<HypothesisContextItem>, |
| 97 | pub rendered_prompt: String, |
| 98 | pub omitted_count: usize, |
| 99 | pub token_count: usize, |
| 100 | pub context_revision: String, |
| 101 | } |
| 102 | |
| 103 | pub struct MemoryCompiler { |
| 104 | db: Arc<Database>, |
| 105 | } |
| 106 | |
| 107 | impl MemoryCompiler { |
| 108 | pub fn new(db: Arc<Database>) -> Self { |
| 109 | Self { db } |
| 110 | } |
| 111 | |
| 112 | /// Approximate token count using word/whitespace heuristic (~4 chars per token). |
| 113 | fn estimate_tokens(text: &str) -> usize { |
| 114 | (text.len() / 4).max(1) |
| 115 | } |
| 116 | |
| 117 | /// Compile a structured, bounded MemoryContext from episodic, canonical, and candidate tiers. |
| 118 | pub fn compile_context(&self, q: &MemoryQuery) -> Result<MemoryContext, rusqlite::Error> { |
| 119 | let budget = q.token_budget; |
| 120 | |
| 121 | // Partition budget based on intent |
| 122 | let (episodic_share, canonical_share, hypothesis_share): (f64, f64, f64) = match q.intent { |
| 123 | MemoryIntent::Conversation => (0.50, 0.40, 0.0), |
| 124 | MemoryIntent::Coding | MemoryIntent::ToolExecution => (0.25, 0.65, 0.0), |
| 125 | MemoryIntent::Planning | MemoryIntent::Research => (0.35, 0.55, 0.0), |
| 126 | MemoryIntent::Reflection => (0.45, 0.45, 0.0), |
| 127 | MemoryIntent::MemoryAdjudication => (0.30, 0.40, 0.20), |
| 128 | }; |
| 129 | |
| 130 | let ep_budget = (budget as f64 * episodic_share) as usize; |
| 131 | let can_budget = (budget as f64 * canonical_share) as usize; |
| 132 | let hyp_budget = if q.include_candidates { |
| 133 | (budget as f64 * hypothesis_share.max(0.15)) as usize |
| 134 | } else { |
| 135 | 0 |
| 136 | }; |
| 137 | |
| 138 | let mut episodic_items = Vec::new(); |
| 139 | let mut canonical_items = Vec::new(); |
| 140 | let mut hypothesis_items = Vec::new(); |
| 141 | let mut used_tokens = 0; |
| 142 | let mut omitted_count = 0; |
| 143 | |
| 144 | // 1. Compile Episodic Context (if session_id provided) |
| 145 | if let Some(session_id) = &q.session_id { |
| 146 | let branch = q.branch_id.as_deref().unwrap_or("main"); |
| 147 | |
| 148 | // A. Include highest level summary if available |
| 149 | let summaries = self.db.get_session_summaries(session_id, branch, None)?; |
| 150 | for s in summaries.iter().rev() { |
| 151 | let text = format!( |
| 152 | "[Summary L{}: seq {}-{}] {}", |
| 153 | s.level, s.start_seq, s.end_seq, s.summary_text |
| 154 | ); |
| 155 | let cost = Self::estimate_tokens(&text); |
| 156 | if used_tokens + cost <= ep_budget { |
| 157 | used_tokens += cost; |
| 158 | episodic_items.push(EpisodicContextItem { |
| 159 | kind: "summary".to_string(), |
| 160 | level: Some(s.level), |
| 161 | sequence_range: Some(format!("{}-{}", s.start_seq, s.end_seq)), |
| 162 | text, |
| 163 | }); |
| 164 | break; // Include top summary |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | // B. Include recent raw safe events |
| 169 | let recent_events = self.db.get_recent_session_events(session_id, branch, 15)?; |
| 170 | for ev in &recent_events { |
| 171 | let view = SecurityMembrane::to_safe_view(ev, self.db.hmac_key()); |
| 172 | if let Some(content) = view.safe_content { |
| 173 | let role = view.role.as_deref().unwrap_or("event"); |
| 174 | let text = format!("[{}: seq {}] {}", role, view.sequence, content); |
| 175 | let cost = Self::estimate_tokens(&text); |
| 176 | if used_tokens + cost <= ep_budget { |
| 177 | used_tokens += cost; |
| 178 | episodic_items.push(EpisodicContextItem { |
| 179 | kind: "event".to_string(), |
| 180 | level: None, |
| 181 | sequence_range: Some(view.sequence.to_string()), |
| 182 | text, |
| 183 | }); |
| 184 | } else { |
| 185 | omitted_count += 1; |
| 186 | } |
| 187 | } |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | // 2. Compile Canonical Knowledge (entities and claims) |
| 192 | let recall_results = self.db.recall_entities(&q.query, None, Some(&q.space), 8)?; |
| 193 | for item in recall_results { |
| 194 | let ent = &item.entity; |
| 195 | |
| 196 | // Fetch active claims for this entity |
| 197 | let claims = self |
| 198 | .db |
| 199 | .traverse_claims(&ent.canonical_name, Some(&q.space))?; |
| 200 | for cl in claims { |
| 201 | let tier = cl.verification_tier; |
| 202 | if let Some(min_t) = q.minimum_verification { |
| 203 | if tier < min_t { |
| 204 | continue; |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | let val_str = cl |
| 209 | .literal_value |
| 210 | .as_ref() |
| 211 | .map(|v| v.to_string()) |
| 212 | .unwrap_or_else(|| "true".to_string()); |
| 213 | let text = format!( |
| 214 | "[{}] {} -> {} = {}", |
| 215 | tier.as_str(), |
| 216 | ent.canonical_name, |
| 217 | cl.predicate, |
| 218 | val_str |
| 219 | ); |
| 220 | let cost = Self::estimate_tokens(&text); |
| 221 | |
| 222 | if used_tokens + cost <= ep_budget + can_budget { |
| 223 | used_tokens += cost; |
| 224 | canonical_items.push(CanonicalContextItem { |
| 225 | text, |
| 226 | claim_id: cl.id, |
| 227 | verification_tier: tier, |
| 228 | status: cl.status, |
| 229 | evidence_count: cl.evidence_count, |
| 230 | }); |
| 231 | } else { |
| 232 | omitted_count += 1; |
| 233 | } |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | // 3. Compile Unverified Hypotheses (STRICTLY QUARANTINED) |
| 238 | if q.include_candidates && hyp_budget > 0 { |
| 239 | let candidates = self |
| 240 | .db |
| 241 | .get_memory_candidates(Some(&q.space), Some("pending"), 5)?; |
| 242 | for cand in candidates { |
| 243 | let val_str = cand.object_value.to_string(); |
| 244 | let text = format!( |
| 245 | "Candidate {}: {} -> {} = {}", |
| 246 | cand.id, cand.subject, cand.predicate, val_str |
| 247 | ); |
| 248 | let cost = Self::estimate_tokens(&text); |
| 249 | |
| 250 | if used_tokens + cost <= budget { |
| 251 | used_tokens += cost; |
| 252 | hypothesis_items.push(HypothesisContextItem { |
| 253 | candidate_id: cand.id, |
| 254 | assertion: text, |
| 255 | confidence: cand.confidence, |
| 256 | verification: cand.verification_tier.as_str().to_string(), |
| 257 | advisory: "UNVERIFIED HYPOTHESIS: Do not treat as established fact." |
| 258 | .to_string(), |
| 259 | }); |
| 260 | } else { |
| 261 | omitted_count += 1; |
| 262 | } |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | // 4. Render prompt section |
| 267 | let mut prompt_lines = Vec::new(); |
| 268 | prompt_lines.push("<CORTEX_MEMORY>".to_string()); |
| 269 | |
| 270 | prompt_lines.push("<EPISODIC_CONTEXT>".to_string()); |
| 271 | if episodic_items.is_empty() { |
| 272 | prompt_lines.push("None.".to_string()); |
| 273 | } else { |
| 274 | for item in &episodic_items { |
| 275 | prompt_lines.push(item.text.clone()); |
| 276 | } |
| 277 | } |
| 278 | prompt_lines.push("</EPISODIC_CONTEXT>".to_string()); |
| 279 | |
| 280 | prompt_lines.push("<VERIFIED_KNOWLEDGE>".to_string()); |
| 281 | if canonical_items.is_empty() { |
| 282 | prompt_lines.push("None.".to_string()); |
| 283 | } else { |
| 284 | for item in &canonical_items { |
| 285 | prompt_lines.push(item.text.clone()); |
| 286 | } |
| 287 | } |
| 288 | prompt_lines.push("</VERIFIED_KNOWLEDGE>".to_string()); |
| 289 | |
| 290 | prompt_lines.push("<UNVERIFIED_HYPOTHESES>".to_string()); |
| 291 | if hypothesis_items.is_empty() { |
| 292 | prompt_lines.push("None.".to_string()); |
| 293 | } else { |
| 294 | for item in &hypothesis_items { |
| 295 | prompt_lines.push(format!( |
| 296 | "[{}] {} (Confidence: {:.2}) - {}", |
| 297 | item.candidate_id, item.assertion, item.confidence, item.advisory |
| 298 | )); |
| 299 | } |
| 300 | } |
| 301 | prompt_lines.push("</UNVERIFIED_HYPOTHESES>".to_string()); |
| 302 | |
| 303 | prompt_lines.push("</CORTEX_MEMORY>".to_string()); |
| 304 | |
| 305 | let rendered_prompt = prompt_lines.join("\n"); |
| 306 | let context_revision = format!("ctx-{}", Uuid::new_v4().simple()); |
| 307 | |
| 308 | Ok(MemoryContext { |
| 309 | episodic: episodic_items, |
| 310 | canonical: canonical_items, |
| 311 | hypotheses: hypothesis_items, |
| 312 | rendered_prompt, |
| 313 | omitted_count, |
| 314 | token_count: used_tokens, |
| 315 | context_revision, |
| 316 | }) |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | #[cfg(test)] |
| 321 | mod tests { |
| 322 | use super::*; |
| 323 | use crate::models::{ |
| 324 | CandidateWriteInput, ClaimWriteInput, CreateSessionInput, EntityWriteInput, |
| 325 | SessionEventInput, |
| 326 | }; |
| 327 | use serde_json::json; |
| 328 | |
| 329 | #[test] |
| 330 | fn test_memory_compiler_knapsack_and_quarantine() { |
| 331 | let db = Arc::new(Database::open_in_memory().unwrap()); |
| 332 | |
| 333 | // 1. Seed canonical memory |
| 334 | let ent = db |
| 335 | .upsert_entity( |
| 336 | &EntityWriteInput { |
| 337 | id: None, |
| 338 | space: "atlas-memory".to_string(), |
| 339 | entity_type: "architecture".to_string(), |
| 340 | canonical_name: "Cortex_Store".to_string(), |
| 341 | content: "Cortex engine uses SQLite WAL mode".to_string(), |
| 342 | aliases: vec![], |
| 343 | metadata: json!({}), |
| 344 | confidence: 1.0, |
| 345 | valid_from: None, |
| 346 | valid_to: None, |
| 347 | external_id: None, |
| 348 | }, |
| 349 | None, |
| 350 | ) |
| 351 | .unwrap(); |
| 352 | |
| 353 | db.upsert_claim(&ClaimWriteInput { |
| 354 | id: None, |
| 355 | space: "atlas-memory".to_string(), |
| 356 | subject_entity_id: ent.target_id.clone(), |
| 357 | predicate: "concurrency_mode".to_string(), |
| 358 | object_entity_id: None, |
| 359 | literal_value: Some(json!("single_writer_multi_reader")), |
| 360 | confidence: 1.0, |
| 361 | metadata: json!({}), |
| 362 | }) |
| 363 | .unwrap(); |
| 364 | |
| 365 | // 2. Seed session and episodic turns |
| 366 | let sess = db |
| 367 | .create_session(&CreateSessionInput { |
| 368 | id: Some("sess-compiler".to_string()), |
| 369 | space: "atlas-memory".to_string(), |
| 370 | agent_id: Some("atlas".to_string()), |
| 371 | world_id: None, |
| 372 | parent_session_id: None, |
| 373 | fork_event_id: None, |
| 374 | retention_class: "standard".to_string(), |
| 375 | metadata: json!({}), |
| 376 | }) |
| 377 | .unwrap(); |
| 378 | |
| 379 | db.batch_append_events( |
| 380 | &sess.id, |
| 381 | "main", |
| 382 | &[SessionEventInput { |
| 383 | id: Some("ev-c1".to_string()), |
| 384 | branch_id: Some("main".to_string()), |
| 385 | parent_event_id: None, |
| 386 | event_type: "user_message".to_string(), |
| 387 | role: Some("user".to_string()), |
| 388 | content: Some("How does the memory compiler work?".to_string()), |
| 389 | payload: json!({}), |
| 390 | sensitivity: None, |
| 391 | }], |
| 392 | ) |
| 393 | .unwrap(); |
| 394 | |
| 395 | // 3. Seed pending candidate |
| 396 | db.insert_memory_candidate(&CandidateWriteInput { |
| 397 | id: Some("cand-unverified".to_string()), |
| 398 | space: "atlas-memory".to_string(), |
| 399 | session_id: sess.id.clone(), |
| 400 | branch_id: "main".to_string(), |
| 401 | memory_type: "speculation".to_string(), |
| 402 | subject: "Compiler".to_string(), |
| 403 | predicate: "performance_improvement".to_string(), |
| 404 | object_value: json!("50x"), |
| 405 | scope: "global".to_string(), |
| 406 | confidence: 0.65, |
| 407 | verification_tier: Some(VerificationTier::T0Direct), |
| 408 | extractor_version: "0.2.0".to_string(), |
| 409 | evidence_ids: vec![], |
| 410 | }) |
| 411 | .unwrap(); |
| 412 | |
| 413 | let compiler = MemoryCompiler::new(Arc::clone(&db)); |
| 414 | |
| 415 | // Test A: Normal query (include_candidates = false) |
| 416 | let q_normal = MemoryQuery { |
| 417 | query: "Cortex_Store".to_string(), |
| 418 | session_id: Some(sess.id.clone()), |
| 419 | branch_id: Some("main".to_string()), |
| 420 | space: "atlas-memory".to_string(), |
| 421 | intent: MemoryIntent::Coding, |
| 422 | token_budget: 1024, |
| 423 | include_candidates: false, |
| 424 | minimum_verification: None, |
| 425 | }; |
| 426 | |
| 427 | let ctx_normal = compiler.compile_context(&q_normal).unwrap(); |
| 428 | assert!(!ctx_normal.canonical.is_empty()); |
| 429 | assert!(!ctx_normal.episodic.is_empty()); |
| 430 | assert!(ctx_normal.hypotheses.is_empty()); |
| 431 | assert!(ctx_normal.rendered_prompt.contains("<VERIFIED_KNOWLEDGE>")); |
| 432 | assert!(ctx_normal |
| 433 | .rendered_prompt |
| 434 | .contains("<UNVERIFIED_HYPOTHESES>\nNone.")); |
| 435 | |
| 436 | // Test B: Adjudication query with candidates enabled |
| 437 | let q_adjudicate = MemoryQuery { |
| 438 | query: "Cortex_Store".to_string(), |
| 439 | session_id: Some(sess.id.clone()), |
| 440 | branch_id: Some("main".to_string()), |
| 441 | space: "atlas-memory".to_string(), |
| 442 | intent: MemoryIntent::MemoryAdjudication, |
| 443 | token_budget: 1024, |
| 444 | include_candidates: true, |
| 445 | minimum_verification: None, |
| 446 | }; |
| 447 | |
| 448 | let ctx_adj = compiler.compile_context(&q_adjudicate).unwrap(); |
| 449 | assert!(!ctx_adj.hypotheses.is_empty()); |
| 450 | assert_eq!(ctx_adj.hypotheses[0].candidate_id, "cand-unverified"); |
| 451 | assert!(ctx_adj |
| 452 | .rendered_prompt |
| 453 | .contains("UNVERIFIED HYPOTHESIS: Do not treat as established fact.")); |
| 454 | } |
| 455 | } |