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 / verification.rs

133 lines · 4575 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//! Grounding verification and hallucination detection for Cortex Epistemic Store.
17
18use crate::record::EpistemicRecord;
19use core::fmt;
20use std::collections::HashSet;
21
22/// Errors arising during Cortex epistemic storage or verification.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub enum CortexError {
25 UngroundedAssertion(String),
26 CircularDependencyDetected(Vec<[u8; 16]>),
27 RecordNotFound([u8; 16]),
28 ContradictionDetected {
29 record_a: [u8; 16],
30 record_b: [u8; 16],
31 reason: String,
32 },
33 CorruptedJournal(String),
34 IntegrityChecksumMismatch,
35}
36
37impl fmt::Display for CortexError {
38 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39 match self {
40 Self::UngroundedAssertion(msg) => write!(f, "Ungrounded epistemic assertion: {}", msg),
41 Self::CircularDependencyDetected(cycle) => {
42 write!(
43 f,
44 "Circular epistemic dependency detected across {} records",
45 cycle.len()
46 )
47 }
48 Self::RecordNotFound(id) => write!(f, "Epistemic record not found: {:02x?}", id),
49 Self::ContradictionDetected {
50 record_a,
51 record_b,
52 reason,
53 } => write!(
54 f,
55 "Contradiction between {:02x?} and {:02x?}: {}",
56 record_a, record_b, reason
57 ),
58 Self::CorruptedJournal(msg) => write!(f, "Corrupted epistemic journal: {}", msg),
59 Self::IntegrityChecksumMismatch => write!(f, "Journal cryptographic checksum mismatch"),
60 }
61 }
62}
63
64/// Recursively verify that a record is strictly grounded in DirectObservation, VerifiedFact, or OperatorDecision.
65///
66/// Invariant: Every causal ancestry branch MUST terminate in an immutable ground truth.
67/// Rejects any assertion that relies even partially on ungrounded hypotheses or missing/circular evidence.
68pub fn verify_grounding<'a, F>(record: &EpistemicRecord, lookup: &F) -> Result<(), CortexError>
69where
70 F: Fn(&[u8; 16]) -> Option<&'a EpistemicRecord>,
71{
72 if record.status.is_ground_truth() {
73 return Ok(());
74 }
75
76 if record.causal_parents.is_empty() {
77 return Err(CortexError::UngroundedAssertion(format!(
78 "Assertion \"{}\" ({:?}) has no causal parent references",
79 record.statement, record.status
80 )));
81 }
82
83 let mut grounded_cache = HashSet::new();
84 let mut path = vec![record.id];
85
86 fn check_node<'a, F>(
87 current_id: &[u8; 16],
88 lookup: &F,
89 grounded_cache: &mut HashSet<[u8; 16]>,
90 path: &mut Vec<[u8; 16]>,
91 ) -> Result<(), CortexError>
92 where
93 F: Fn(&[u8; 16]) -> Option<&'a EpistemicRecord>,
94 {
95 if path.contains(current_id) {
96 path.push(*current_id);
97 return Err(CortexError::CircularDependencyDetected(path.clone()));
98 }
99
100 if grounded_cache.contains(current_id) {
101 return Ok(());
102 }
103
104 let current_rec = lookup(current_id).ok_or(CortexError::RecordNotFound(*current_id))?;
105
106 if current_rec.status.is_ground_truth() {
107 grounded_cache.insert(*current_id);
108 return Ok(());
109 }
110
111 if current_rec.causal_parents.is_empty() {
112 return Err(CortexError::UngroundedAssertion(format!(
113 "Assertion \"{}\" ({:?}) has no causal parent references",
114 current_rec.statement, current_rec.status
115 )));
116 }
117
118 path.push(*current_id);
119 for parent_id in &current_rec.causal_parents {
120 check_node(parent_id, lookup, grounded_cache, path)?;
121 }
122 path.pop();
123
124 grounded_cache.insert(*current_id);
125 Ok(())
126 }
127
128 for parent_id in &record.causal_parents {
129 check_node(parent_id, lookup, &mut grounded_cache, &mut path)?;
130 }
131
132 Ok(())
133}