interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / aienos-cortex / src / store.rs

478 lines · 15640 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
16//! Cortex Epistemic Store engine managing the verifiable knowledge graph.
17
18use crate::record::EpistemicRecord;
19use crate::status::EpistemicStatus;
20use crate::verification::{verify_grounding, CortexError};
21use aienos_kernel::crypto::sha256;
22use serde::{Deserialize, Serialize};
23use std::collections::HashMap;
24
25/// Epistemic Journal Envelope with cryptographic SHA-256 seal.
26#[derive(Clone, Debug, Serialize, Deserialize)]
27pub struct JournalEnvelope {
28 pub records: Vec<EpistemicRecord>,
29 pub seal: [u8; 32],
30}
31
32/// Persistent Epistemic Knowledge Store.
33#[derive(Default)]
34pub struct CortexStore {
35 records: HashMap<[u8; 16], EpistemicRecord>,
36 status_index: HashMap<EpistemicStatus, Vec<[u8; 16]>>,
37}
38
39impl CortexStore {
40 /// Initialize a new empty Cortex store.
41 pub fn new() -> Self {
42 Self::default()
43 }
44
45 /// Record a Direct Observation (hardware sensor, file read, physical input).
46 pub fn record_observation(
47 &mut self,
48 statement: impl Into<String>,
49 provenance_source: impl Into<String>,
50 raw_evidence: &[u8],
51 created_at_utc: u64,
52 ) -> EpistemicRecord {
53 let record = EpistemicRecord::new(
54 EpistemicStatus::DirectObservation,
55 statement,
56 provenance_source,
57 raw_evidence,
58 created_at_utc,
59 1.0,
60 None,
61 Vec::new(),
62 );
63 self.insert_record(record.clone());
64 record
65 }
66
67 /// Record a Mathematically or Cryptographically Verified Fact.
68 pub fn record_verified_fact(
69 &mut self,
70 statement: impl Into<String>,
71 provenance_source: impl Into<String>,
72 verifier_tool: &str,
73 proof_payload: &[u8],
74 causal_parents: Vec<[u8; 16]>,
75 created_at_utc: u64,
76 ) -> Result<EpistemicRecord, CortexError> {
77 let record = EpistemicRecord::new(
78 EpistemicStatus::VerifiedFact,
79 statement,
80 provenance_source,
81 proof_payload,
82 created_at_utc,
83 1.0,
84 Some(verifier_tool.to_string()),
85 causal_parents,
86 );
87 self.insert_record(record.clone());
88 Ok(record)
89 }
90
91 /// Record an Operator Decision (canonical directive from human operator).
92 pub fn record_operator_decision(
93 &mut self,
94 statement: impl Into<String>,
95 operator_signature: &str,
96 created_at_utc: u64,
97 ) -> EpistemicRecord {
98 let record = EpistemicRecord::new(
99 EpistemicStatus::OperatorDecision,
100 statement,
101 format!("operator:{}", operator_signature),
102 operator_signature.as_bytes(),
103 created_at_utc,
104 1.0,
105 Some(operator_signature.to_string()),
106 Vec::new(),
107 );
108 self.insert_record(record.clone());
109 record
110 }
111
112 /// Record an Inference deduced by a model.
113 ///
114 /// Invariant: Must strictly ground in DirectObservation, VerifiedFact, or OperatorDecision.
115 /// Rejects ungrounded model hallucinations.
116 pub fn record_inference(
117 &mut self,
118 statement: impl Into<String>,
119 model_name: impl Into<String>,
120 causal_parents: Vec<[u8; 16]>,
121 confidence: f32,
122 created_at_utc: u64,
123 ) -> Result<EpistemicRecord, CortexError> {
124 let record = EpistemicRecord::new(
125 EpistemicStatus::Inference,
126 statement,
127 model_name,
128 &[],
129 created_at_utc,
130 confidence,
131 None,
132 causal_parents,
133 );
134
135 // Strictly verify grounding in verified facts or observations
136 verify_grounding(&record, &|id| self.records.get(id))?;
137
138 self.insert_record(record.clone());
139 Ok(record)
140 }
141
142 /// Record a tentative Hypothesis.
143 pub fn record_hypothesis(
144 &mut self,
145 statement: impl Into<String>,
146 agent_source: impl Into<String>,
147 causal_parents: Vec<[u8; 16]>,
148 created_at_utc: u64,
149 ) -> Result<EpistemicRecord, CortexError> {
150 let record = EpistemicRecord::new(
151 EpistemicStatus::Hypothesis,
152 statement,
153 agent_source,
154 &[],
155 created_at_utc,
156 0.5,
157 None,
158 causal_parents,
159 );
160
161 // Verify grounding in valid parent records
162 verify_grounding(&record, &|id| self.records.get(id))?;
163
164 self.insert_record(record.clone());
165 Ok(record)
166 }
167
168 /// Flag a detected Contradiction between two existing epistemic records.
169 pub fn flag_contradiction(
170 &mut self,
171 record_a_id: [u8; 16],
172 record_b_id: [u8; 16],
173 reason: &str,
174 created_at_utc: u64,
175 ) -> Result<EpistemicRecord, CortexError> {
176 if !self.records.contains_key(&record_a_id) {
177 return Err(CortexError::RecordNotFound(record_a_id));
178 }
179 if !self.records.contains_key(&record_b_id) {
180 return Err(CortexError::RecordNotFound(record_b_id));
181 }
182
183 let record = EpistemicRecord::new(
184 EpistemicStatus::Contradiction,
185 format!("Contradiction detected: {}", reason),
186 "cortex_sentinel",
187 reason.as_bytes(),
188 created_at_utc,
189 1.0,
190 None,
191 vec![record_a_id, record_b_id],
192 );
193
194 self.insert_record(record.clone());
195 Ok(record)
196 }
197
198 /// Retrieve an individual record by ID.
199 pub fn get(&self, id: &[u8; 16]) -> Option<&EpistemicRecord> {
200 self.records.get(id)
201 }
202
203 /// Retrieve all records of a specific epistemic status.
204 pub fn find_by_status(&self, status: EpistemicStatus) -> Vec<&EpistemicRecord> {
205 self.status_index
206 .get(&status)
207 .map(|ids| ids.iter().filter_map(|id| self.records.get(id)).collect())
208 .unwrap_or_default()
209 }
210
211 /// Total records in store.
212 pub fn len(&self) -> usize {
213 self.records.len()
214 }
215
216 /// Check if store is empty.
217 pub fn is_empty(&self) -> bool {
218 self.records.is_empty()
219 }
220
221 fn insert_record(&mut self, record: EpistemicRecord) {
222 let id = record.id;
223 let status = record.status;
224 self.status_index.entry(status).or_default().push(id);
225 self.records.insert(id, record);
226 }
227
228 /// Export durable journal with SHA-256 integrity seal.
229 pub fn export_journal(&self) -> Result<Vec<u8>, CortexError> {
230 let mut list: Vec<EpistemicRecord> = self.records.values().cloned().collect();
231 // Deterministic sort by timestamp, then id
232 list.sort_by(|a, b| {
233 a.created_at_utc
234 .cmp(&b.created_at_utc)
235 .then_with(|| a.id.cmp(&b.id))
236 });
237
238 let serialized =
239 serde_json::to_vec(&list).map_err(|e| CortexError::CorruptedJournal(e.to_string()))?;
240 let seal = sha256::hash(&serialized);
241
242 let envelope = JournalEnvelope {
243 records: list,
244 seal,
245 };
246
247 serde_json::to_vec(&envelope).map_err(|e| CortexError::CorruptedJournal(e.to_string()))
248 }
249
250 /// Import journal across reboot, verifying cryptographic seal and rebuilding indexes.
251 pub fn import_journal(&mut self, journal_data: &[u8]) -> Result<usize, CortexError> {
252 let envelope: JournalEnvelope = serde_json::from_slice(journal_data)
253 .map_err(|e| CortexError::CorruptedJournal(e.to_string()))?;
254
255 let serialized = serde_json::to_vec(&envelope.records)
256 .map_err(|e| CortexError::CorruptedJournal(e.to_string()))?;
257 let computed_seal = sha256::hash(&serialized);
258
259 if envelope.seal != computed_seal {
260 return Err(CortexError::IntegrityChecksumMismatch);
261 }
262
263 let count = envelope.records.len();
264 for record in envelope.records {
265 self.insert_record(record);
266 }
267
268 Ok(count)
269 }
270}
271
272#[cfg(test)]
273mod tests {
274 use super::*;
275
276 #[test]
277 fn test_epistemic_grounding_and_hallucination_rejection() {
278 let mut cortex = CortexStore::new();
279
280 // 1. Record raw hardware observation
281 let obs = cortex.record_observation(
282 "UART0 base physical address is 0x09000000",
283 "device_tree",
284 b"phys_uart0_reg",
285 100,
286 );
287
288 // 2. Valid inference derived from observation
289 let inf = cortex
290 .record_inference(
291 "Driver can safely bind to UART0 MMIO",
292 "llama3-spark",
293 vec![obs.id],
294 0.95,
295 101,
296 )
297 .expect("Valid grounded inference");
298 assert_eq!(inf.status, EpistemicStatus::Inference);
299
300 // Deep grounded inference: inf2 -> inf -> obs
301 let inf2 = cortex
302 .record_inference(
303 "Early console can initialize without Linux driver",
304 "llama3-spark",
305 vec![inf.id],
306 0.90,
307 102,
308 )
309 .expect("Valid deep grounded inference");
310 assert_eq!(inf2.status, EpistemicStatus::Inference);
311
312 // 3. Hallucination test: attempt ungrounded inference (no parents)
313 let hallucination_empty = cortex.record_inference(
314 "The system has 1024 GB10 GPUs connected",
315 "speculative_model",
316 vec![],
317 0.99,
318 103,
319 );
320 assert!(matches!(
321 hallucination_empty,
322 Err(CortexError::UngroundedAssertion(_))
323 ));
324
325 // 4. Hallucination test: circular inference with no ground truth
326 let mut circular_rec_a = EpistemicRecord::new(
327 EpistemicStatus::Inference,
328 "Claim A is true because Claim B is true",
329 "model_hallucination",
330 &[],
331 104,
332 0.8,
333 None,
334 vec![], // filled below
335 );
336 let circular_rec_b = EpistemicRecord::new(
337 EpistemicStatus::Inference,
338 "Claim B is true because Claim A is true",
339 "model_hallucination",
340 &[],
341 104,
342 0.8,
343 None,
344 vec![circular_rec_a.id],
345 );
346 circular_rec_a.causal_parents = vec![circular_rec_b.id];
347
348 // If we inject circular records manually into store, verify_grounding must detect cycle
349 cortex.insert_record(circular_rec_a.clone());
350 cortex.insert_record(circular_rec_b.clone());
351
352 let res_a = verify_grounding(&circular_rec_a, &|id| cortex.get(id));
353 assert!(matches!(
354 res_a,
355 Err(CortexError::CircularDependencyDetected(_))
356 ));
357
358 // 5. Hallucination test: references non-existent parent
359 let forged_id = [0xAAu8; 16];
360 let hallucination_forged = cortex.record_inference(
361 "Secret backdoors exist in kernel",
362 "adversarial_prompt",
363 vec![forged_id],
364 0.8,
365 105,
366 );
367 assert!(matches!(
368 hallucination_forged,
369 Err(CortexError::RecordNotFound(_))
370 ));
371
372 // 6. Mixed parent grounding rejection: one grounded observation + one ungrounded hallucination
373 // Must NOT allow the observation to mask the hallucinated parent!
374 let ungrounded_parent = EpistemicRecord::new(
375 EpistemicStatus::Inference,
376 "Fabricated premise with zero grounding",
377 "malicious_model",
378 &[],
379 106,
380 0.9,
381 None,
382 vec![], // No causal parents!
383 );
384 cortex.insert_record(ungrounded_parent.clone());
385
386 let mixed_inference = cortex.record_inference(
387 "Hybrid inference based on observation AND fabrication",
388 "hybrid_model",
389 vec![obs.id, ungrounded_parent.id],
390 0.85,
391 107,
392 );
393 assert!(
394 matches!(mixed_inference, Err(CortexError::UngroundedAssertion(_))),
395 "Inference containing even one ungrounded parent must be rejected"
396 );
397
398 // 7. Transitive grounding: Observation -> Hypothesis -> Inference
399 let hypo = cortex
400 .record_hypothesis(
401 "Hypothesis derived from valid observation",
402 "explorer_agent",
403 vec![obs.id],
404 108,
405 )
406 .expect("Hypothesis grounded in observation must succeed");
407
408 let transitive_inf = cortex
409 .record_inference(
410 "Inference deduced from verified hypothesis",
411 "reasoning_model",
412 vec![hypo.id],
413 0.95,
414 109,
415 )
416 .expect("Transitively grounded inference must succeed");
417 assert_eq!(transitive_inf.causal_parents, vec![hypo.id]);
418
419 // 8. Flag contradiction between opposing assertions
420 let contradiction = cortex
421 .flag_contradiction(
422 obs.id,
423 ungrounded_parent.id,
424 "Hardware sensor disagrees with fabricated premise",
425 110,
426 )
427 .expect("Flag contradiction");
428 assert_eq!(contradiction.status, EpistemicStatus::Contradiction);
429 }
430
431 #[test]
432 fn test_cortex_persistence_and_status_queries() {
433 let mut cortex = CortexStore::new();
434 let obs = cortex.record_observation("Boot completed at tick 42", "kernel_log", b"", 100);
435 let fact = cortex
436 .record_verified_fact(
437 "SHA256 test vector passes FIPS 180-4",
438 "test_suite",
439 "cargo_test",
440 b"proof",
441 vec![obs.id],
442 101,
443 )
444 .unwrap();
445
446 let op = cortex.record_operator_decision(
447 "Promote Phase 3 to canonical state",
448 "operator_ed25519_key",
449 102,
450 );
451
452 assert_eq!(
453 cortex
454 .find_by_status(EpistemicStatus::DirectObservation)
455 .len(),
456 1
457 );
458 assert_eq!(
459 cortex.find_by_status(EpistemicStatus::VerifiedFact).len(),
460 1
461 );
462 assert_eq!(
463 cortex
464 .find_by_status(EpistemicStatus::OperatorDecision)
465 .len(),
466 1
467 );
468
469 // Export and restore across simulated reboot
470 let journal = cortex.export_journal().expect("Export journal");
471 let mut restored = CortexStore::new();
472 let imported_count = restored.import_journal(&journal).expect("Import journal");
473 assert_eq!(imported_count, 3);
474 assert_eq!(restored.get(&obs.id).unwrap().statement, obs.statement);
475 assert_eq!(restored.get(&fact.id).unwrap().statement, fact.statement);
476 assert_eq!(restored.get(&op.id).unwrap().statement, op.statement);
477 }
478}