interplane.Get Omega
Read in your language

aien-sovereign-core-mv

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

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / cortex-rs / src / workers.rs

406 lines · 14823 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use sha2::{Digest, Sha256};
17use std::sync::Arc;
18
19use crate::db::{Database, SessionSummaryWrite};
20use crate::models::{CandidateWriteInput, MemoryCandidate, SessionSummary, VerificationTier};
21use crate::security::{SafeEventView, SecurityMembrane};
22
23pub const SUMMARY_PROCESSOR_VERSION: &str = "0.2.0";
24pub const EXTRACTOR_PROCESSOR_VERSION: &str = "0.2.0";
25
26pub struct SummaryWorker {
27 db: Arc<Database>,
28}
29
30impl SummaryWorker {
31 pub fn new(db: Arc<Database>) -> Self {
32 Self { db }
33 }
34
35 /// Process unsummarized events for a session branch up to `batch_size` events.
36 pub fn process_session_branch(
37 &self,
38 session_id: &str,
39 branch_id: &str,
40 segment_size: usize,
41 ) -> Result<Option<SessionSummary>, rusqlite::Error> {
42 let watermark = self
43 .db
44 .get_watermark(session_id, "summary", SUMMARY_PROCESSOR_VERSION)?
45 .unwrap_or(0);
46
47 let events =
48 self.db
49 .get_session_events(session_id, branch_id, Some(watermark), segment_size)?;
50 if events.is_empty() {
51 return Ok(None);
52 }
53
54 // Project events into SafeEventView
55 let safe_views: Vec<SafeEventView> = events
56 .iter()
57 .map(|ev| SecurityMembrane::to_safe_view(ev, self.db.hmac_key()))
58 .collect();
59
60 let start_seq = safe_views.first().unwrap().sequence;
61 let end_seq = safe_views.last().unwrap().sequence;
62
63 // Compute source hash of safe event sequence
64 let mut hasher = Sha256::new();
65 for ev in &safe_views {
66 hasher.update(ev.event_id.as_bytes());
67 hasher.update(ev.sequence.to_string().as_bytes());
68 if let Some(c) = &ev.safe_content {
69 hasher.update(c.as_bytes());
70 }
71 }
72 let source_hash = format!("SHA256:{:x}", hasher.finalize());
73
74 // Generate deterministic summary text from SafeEventView
75 let mut lines = Vec::new();
76 for ev in &safe_views {
77 if let Some(content) = &ev.safe_content {
78 let role = ev.role.as_deref().unwrap_or("agent");
79 lines.push(format!("[{}:{}] {}", role, ev.event_type, content));
80 }
81 }
82 let summary_text = if lines.is_empty() {
83 format!(
84 "Events {}..{} with withheld/redacted content",
85 start_seq, end_seq
86 )
87 } else {
88 lines.join(" | ")
89 };
90
91 // Insert Level-0 summary
92 let summary = self.db.insert_session_summary(&SessionSummaryWrite {
93 session_id,
94 branch_id,
95 level: 0,
96 start_seq,
97 end_seq,
98 summary_text: &summary_text,
99 source_hash: &source_hash,
100 processor_version: SUMMARY_PROCESSOR_VERSION,
101 })?;
102
103 // Advance summary watermark
104 self.db
105 .set_watermark(session_id, "summary", SUMMARY_PROCESSOR_VERSION, end_seq)?;
106
107 // Hierarchical Level-1 Compaction check:
108 // If there are at least 4 level-0 summaries, compact them into level-1
109 let summaries_l0 = self
110 .db
111 .get_session_summaries(session_id, branch_id, Some(0))?;
112 if summaries_l0.len() >= 4 && summaries_l0.len() % 4 == 0 {
113 let chunk = &summaries_l0[summaries_l0.len() - 4..];
114 let h_start = chunk.first().unwrap().start_seq;
115 let h_end = chunk.last().unwrap().end_seq;
116 let mut h_hasher = Sha256::new();
117 let mut h_text_parts = Vec::new();
118 for s in chunk {
119 h_hasher.update(s.source_hash.as_bytes());
120 h_text_parts.push(s.summary_text.clone());
121 }
122 let h_hash = format!("SHA256:{:x}", h_hasher.finalize());
123 let h_text = format!("Hierarchical Summary (L1): {}", h_text_parts.join(" => "));
124
125 let _ = self.db.insert_session_summary(&SessionSummaryWrite {
126 session_id,
127 branch_id,
128 level: 1,
129 start_seq: h_start,
130 end_seq: h_end,
131 summary_text: &h_text,
132 source_hash: &h_hash,
133 processor_version: SUMMARY_PROCESSOR_VERSION,
134 });
135 }
136
137 Ok(Some(summary))
138 }
139}
140
141pub struct ExtractionWorker {
142 db: Arc<Database>,
143}
144
145impl ExtractionWorker {
146 pub fn new(db: Arc<Database>) -> Self {
147 Self { db }
148 }
149
150 /// Extract durable memory candidates from unextracted safe events.
151 pub fn process_session_branch(
152 &self,
153 session_id: &str,
154 branch_id: &str,
155 batch_size: usize,
156 ) -> Result<Vec<MemoryCandidate>, rusqlite::Error> {
157 let watermark = self
158 .db
159 .get_watermark(session_id, "extractor", EXTRACTOR_PROCESSOR_VERSION)?
160 .unwrap_or(0);
161
162 let events =
163 self.db
164 .get_session_events(session_id, branch_id, Some(watermark), batch_size)?;
165 if events.is_empty() {
166 return Ok(Vec::new());
167 }
168
169 let safe_views: Vec<SafeEventView> = events
170 .iter()
171 .map(|ev| SecurityMembrane::to_safe_view(ev, self.db.hmac_key()))
172 .collect();
173 let max_seq = safe_views.last().unwrap().sequence;
174
175 let mut extracted_candidates = Vec::new();
176
177 for ev in &safe_views {
178 if !ev.extraction_allowed {
179 continue;
180 }
181
182 if let Some(content) = &ev.safe_content {
183 // Rule-based heuristic extraction for sovereign runtime facts & user preferences
184 let text = content.trim();
185
186 // Pattern 1: User operational preferences (T0Direct)
187 // "I prefer X", "prefer using X", "my preferred X is Y"
188 if text.to_lowercase().contains("prefer") || text.to_lowercase().contains("use ") {
189 if let Some(cand) = Self::extract_preference(session_id, branch_id, ev, text) {
190 if let Ok(inserted) = self.db.insert_memory_candidate(&cand) {
191 extracted_candidates.push(inserted);
192 }
193 }
194 }
195
196 // Pattern 2: Learned technical procedure or discovery (T2Verified if tool evidence)
197 if ev.event_type == "tool_result" || ev.event_type == "agent_action" {
198 if let Some(cand) =
199 Self::extract_technical_fact(session_id, branch_id, ev, text)
200 {
201 if let Ok(inserted) = self.db.insert_memory_candidate(&cand) {
202 extracted_candidates.push(inserted);
203 }
204 }
205 }
206 }
207 }
208
209 // Advance extractor watermark
210 self.db.set_watermark(
211 session_id,
212 "extractor",
213 EXTRACTOR_PROCESSOR_VERSION,
214 max_seq,
215 )?;
216
217 Ok(extracted_candidates)
218 }
219
220 fn extract_preference(
221 session_id: &str,
222 branch_id: &str,
223 ev: &SafeEventView,
224 text: &str,
225 ) -> Option<CandidateWriteInput> {
226 let lower = text.to_lowercase();
227 if lower.contains("prefer rust") || lower.contains("use rust") {
228 Some(CandidateWriteInput {
229 id: None,
230 space: "atlas-memory".to_string(),
231 session_id: session_id.to_string(),
232 branch_id: branch_id.to_string(),
233 memory_type: "workflow_preference".to_string(),
234 subject: "user".to_string(),
235 predicate: "preferred_language".to_string(),
236 object_value: serde_json::json!("Rust"),
237 scope: "global".to_string(),
238 confidence: 0.95,
239 verification_tier: Some(VerificationTier::T0Direct),
240 extractor_version: EXTRACTOR_PROCESSOR_VERSION.to_string(),
241 evidence_ids: vec![ev.event_id.clone()],
242 })
243 } else if lower.contains("prefer concise") || lower.contains("concise responses") {
244 Some(CandidateWriteInput {
245 id: None,
246 space: "atlas-memory".to_string(),
247 session_id: session_id.to_string(),
248 branch_id: branch_id.to_string(),
249 memory_type: "workflow_preference".to_string(),
250 subject: "user".to_string(),
251 predicate: "response_style".to_string(),
252 object_value: serde_json::json!("concise"),
253 scope: "global".to_string(),
254 confidence: 0.92,
255 verification_tier: Some(VerificationTier::T0Direct),
256 extractor_version: EXTRACTOR_PROCESSOR_VERSION.to_string(),
257 evidence_ids: vec![ev.event_id.clone()],
258 })
259 } else {
260 None
261 }
262 }
263
264 fn extract_technical_fact(
265 session_id: &str,
266 branch_id: &str,
267 ev: &SafeEventView,
268 text: &str,
269 ) -> Option<CandidateWriteInput> {
270 let lower = text.to_lowercase();
271 if lower.contains("wal") && lower.contains("sqlite") {
272 Some(CandidateWriteInput {
273 id: None,
274 space: "atlas-memory".to_string(),
275 session_id: session_id.to_string(),
276 branch_id: branch_id.to_string(),
277 memory_type: "learned_procedure".to_string(),
278 subject: "AIEN_Cortex".to_string(),
279 predicate: "storage_mode".to_string(),
280 object_value: serde_json::json!("SQLite_WAL"),
281 scope: "system".to_string(),
282 confidence: 0.98,
283 verification_tier: Some(VerificationTier::T2Verified),
284 extractor_version: EXTRACTOR_PROCESSOR_VERSION.to_string(),
285 evidence_ids: vec![ev.event_id.clone()],
286 })
287 } else {
288 None
289 }
290 }
291}
292
293pub const MAX_WORKER_BATCH: usize = 32;
294
295pub struct ProcessingScheduler {
296 summary_worker: SummaryWorker,
297 extraction_worker: ExtractionWorker,
298}
299
300impl ProcessingScheduler {
301 pub fn new(db: Arc<Database>) -> Self {
302 Self {
303 summary_worker: SummaryWorker::new(Arc::clone(&db)),
304 extraction_worker: ExtractionWorker::new(db),
305 }
306 }
307
308 /// Run one consolidation tick for a specific session branch.
309 pub fn process_session(
310 &self,
311 session_id: &str,
312 branch_id: &str,
313 ) -> Result<(Option<SessionSummary>, Vec<MemoryCandidate>), rusqlite::Error> {
314 let batch = MAX_WORKER_BATCH;
315 let summary = self
316 .summary_worker
317 .process_session_branch(session_id, branch_id, batch)?;
318 let candidates = self
319 .extraction_worker
320 .process_session_branch(session_id, branch_id, batch)?;
321 Ok((summary, candidates))
322 }
323}
324
325#[cfg(test)]
326mod tests {
327 use super::*;
328 use crate::models::{CreateSessionInput, SessionEventInput};
329
330 #[test]
331 fn test_summary_and_extraction_workers() {
332 let db = Arc::new(Database::open_in_memory().unwrap());
333 let session = db
334 .create_session(&CreateSessionInput {
335 id: Some("sess-worker-test".to_string()),
336 space: "atlas-memory".to_string(),
337 agent_id: Some("worker-test".to_string()),
338 world_id: None,
339 parent_session_id: None,
340 fork_event_id: None,
341 retention_class: "standard".to_string(),
342 metadata: serde_json::json!({}),
343 })
344 .unwrap();
345
346 // Append events
347 let evs = vec![
348 SessionEventInput {
349 id: Some("ev-101".to_string()),
350 branch_id: Some("main".to_string()),
351 parent_event_id: None,
352 event_type: "user_message".to_string(),
353 role: Some("user".to_string()),
354 content: Some("I prefer Rust for sovereign architecture.".to_string()),
355 payload: serde_json::json!({}),
356 sensitivity: None,
357 },
358 SessionEventInput {
359 id: Some("ev-102".to_string()),
360 branch_id: Some("main".to_string()),
361 parent_event_id: Some("ev-101".to_string()),
362 event_type: "tool_result".to_string(),
363 role: Some("tool".to_string()),
364 content: Some(
365 "Verified SQLite WAL mode active with sub-millisecond latency.".to_string(),
366 ),
367 payload: serde_json::json!({"status": "verified"}),
368 sensitivity: None,
369 },
370 ];
371 db.batch_append_events(&session.id, "main", &evs).unwrap();
372
373 // Run scheduler
374 let scheduler = ProcessingScheduler::new(Arc::clone(&db));
375 let (summary, candidates) = scheduler.process_session(&session.id, "main").unwrap();
376
377 assert!(summary.is_some());
378 let s = summary.unwrap();
379 assert_eq!(s.level, 0);
380 assert_eq!(s.start_seq, 1);
381 assert_eq!(s.end_seq, 2);
382 assert!(s.summary_text.contains("prefer Rust"));
383
384 assert_eq!(candidates.len(), 2);
385 assert_eq!(candidates[0].subject, "user");
386 assert_eq!(candidates[0].predicate, "preferred_language");
387 assert_eq!(candidates[0].verification_tier, VerificationTier::T0Direct);
388
389 assert_eq!(candidates[1].subject, "AIEN_Cortex");
390 assert_eq!(candidates[1].predicate, "storage_mode");
391 assert_eq!(
392 candidates[1].verification_tier,
393 VerificationTier::T2Verified
394 );
395
396 // Verify watermarks were updated
397 let s_wm = db
398 .get_watermark(&session.id, "summary", SUMMARY_PROCESSOR_VERSION)
399 .unwrap();
400 assert_eq!(s_wm, Some(2));
401 let e_wm = db
402 .get_watermark(&session.id, "extractor", EXTRACTOR_PROCESSOR_VERSION)
403 .unwrap();
404 assert_eq!(e_wm, Some(2));
405 }
406}