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-aegis / tests / phase_3_to_5_integration.rs

383 lines · 14490 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//! AIENOS Phases 3–5 Full Architecture Integration Verification Suite.
17//!
18//! Validates:
19//! 1. AgentStateAbi reboot survival and state reconstruction (§9).
20//! 2. Cortex epistemic grounding and hallucination loop rejection (§11).
21//! 3. AEGIS deterministic effect brokering and operator authorization boundaries (§13, §5).
22//! 4. C1 Copy-On-Write Prefix Tree with zero memory duplication across 10 branches (§10, §28).
23//! 5. Native System Store and Recovery Core deterministic rollback and WAL truncation (ADR 0003, ADR 0006).
24
25use aienos_aegis::{
26 AegisError, AegisEvaluator, CapabilityGraph, CapabilityScope, EffectBroker, EffectIntent,
27 JSpaceWorld, OperatorGrant,
28};
29use aienos_agent_state::{AgentStateAbi, AgentStateManager, ComputeState, LogicalAgentId};
30use aienos_c1_tree::{C1PrefixTree, PAGE_CAPACITY_TOKENS};
31use aienos_cortex::{CortexError, CortexStore};
32use aienos_kernel::recovery::{BootSlot, SlotManager, WalRecovery};
33use aienos_kernel::store::SystemStore;
34use std::collections::BTreeMap;
35
36#[test]
37fn test_full_agent_epistemic_capability_and_c1_lifecycle() {
38 // ------------------------------------------------------------------------
39 // 1. PHASE 3: PERSISTENT AGENT STATE & CORTEX EPISTEMIC MEMORY
40 // ------------------------------------------------------------------------
41 let state_manager = AgentStateManager::new(1);
42 let agent_id = LogicalAgentId::from_seed("sovereign-aien-genesis");
43 let root_branch = state_manager.register_agent(agent_id, 1000);
44
45 let mut cortex = CortexStore::new();
46
47 // Ingest DirectObservation from hardware MMIO
48 let obs = cortex.record_observation(
49 "NVIDIA DGX Spark GB10 accelerator initialized at BAR0 0x10000000",
50 "bare_metal_probe",
51 b"hw_status:ready",
52 1001,
53 );
54
55 // Ingest grounded Inference
56 let inf = cortex
57 .record_inference(
58 "C1 engine can bind to physical page frames without host OS",
59 "model_cortex_core",
60 vec![obs.id],
61 0.98,
62 1002,
63 )
64 .expect("Inference must ground cleanly in observation");
65
66 // Attempt ungrounded hallucination -> must be strictly rejected
67 let hallucination = cortex.record_inference(
68 "Cloud licensing server responded with OK",
69 "hallucinating_agent",
70 vec![], // No ground truth!
71 0.5,
72 1003,
73 );
74 assert!(
75 matches!(hallucination, Err(CortexError::UngroundedAssertion(_))),
76 "Ungrounded assertions must be rejected by Cortex"
77 );
78
79 // Attempt mixed-parent hallucination (one observation + one ungrounded claim) -> must fail!
80 let bogus_claim = aienos_cortex::EpistemicRecord::new(
81 aienos_cortex::EpistemicStatus::Inference,
82 "Bogus premise",
83 "bad_agent",
84 &[],
85 1003,
86 0.5,
87 None,
88 vec![],
89 );
90 // Inject directly to simulate adversarial storage
91 let bogus_id = bogus_claim.id;
92 // cortex doesn't expose insert_record publicly outside crate, so test via ungrounded parent id
93 let mixed_hallucination = cortex.record_inference(
94 "Mixed inference",
95 "bad_agent",
96 vec![obs.id, bogus_id],
97 0.5,
98 1004,
99 );
100 assert!(
101 matches!(
102 mixed_hallucination,
103 Err(CortexError::RecordNotFound(_)) | Err(CortexError::UngroundedAssertion(_))
104 ),
105 "Mixed parent with unverified parent must be rejected"
106 );
107
108 // Record verified fact
109 let fact = cortex
110 .record_verified_fact(
111 "Kernel SHA-256 matches sovereign boot manifest",
112 "crypto_audit",
113 "sha256_verifier",
114 b"manifest_sig",
115 vec![obs.id, inf.id],
116 1005,
117 )
118 .expect("Verified fact must succeed");
119
120 // Attach epistemic refs to agent branch
121 state_manager
122 .add_epistemic_ref(root_branch, fact.id)
123 .expect("Attach epistemic ref");
124
125 // Append 500 prompt tokens into agent token history
126 let prompt_tokens: Vec<u32> = (1..=500).collect();
127 state_manager
128 .append_tokens(root_branch, &prompt_tokens)
129 .expect("Append tokens");
130
131 // ------------------------------------------------------------------------
132 // 2. PHASE 4: C1 COPY-ON-WRITE PREFIX TREE (§10, §28)
133 // ------------------------------------------------------------------------
134 let mut c1 = C1PrefixTree::new();
135 c1.create_root_branch(root_branch, &prompt_tokens)
136 .expect("Create C1 root branch");
137
138 let root_pages = c1.pool().allocated_page_count();
139 let expected_pages = 500_usize.div_ceil(PAGE_CAPACITY_TOKENS);
140 assert_eq!(root_pages, expected_pages);
141
142 // Fork into 10 exploratory branches
143 let mut child_branches = Vec::new();
144 for _ in 0..10 {
145 let child_branch = state_manager
146 .fork_branch(root_branch)
147 .expect("Fork agent branch");
148 c1.fork_branch(root_branch, child_branch)
149 .expect("Fork C1 branch");
150 child_branches.push(child_branch);
151 }
152
153 // VERIFY ZERO MEMORY DUPLICATION:
154 // Physical pages allocated must remain EXACTLY identical
155 assert_eq!(
156 c1.pool().allocated_page_count(),
157 root_pages,
158 "C1 fork must allocate 0 additional physical pages"
159 );
160
161 // Deduplication / sharing metrics
162 let metrics = c1.memory_metrics();
163 assert!(metrics.sharing_ratio > 1.0);
164 assert_eq!(metrics.total_virtual_tokens, 500 * 11);
165
166 // Reserve step capacity and append divergent tokens on branch 0
167 let reservation = c1
168 .reserve_step_capacity(child_branches[0], 10, 1005, 100)
169 .expect("Reserve step capacity");
170 assert_eq!(reservation.tokens_reserved, 10);
171
172 c1.append_tokens(child_branches[0], &[9001, 9002])
173 .expect("Append divergent tokens");
174 let b0_tokens = c1.get_tokens(child_branches[0]).expect("Get tokens");
175 assert_eq!(b0_tokens.len(), 502);
176 assert_eq!(b0_tokens[500], 9001);
177
178 // ------------------------------------------------------------------------
179 // 3. PHASE 4: AEGIS CAPABILITY GRAPH & EFFECT BROKER
180 // ------------------------------------------------------------------------
181 let master_secret = [0x55u8; 32];
182 let operator_secret = [0x77u8; 32];
183 let mut aegis_graph = CapabilityGraph::new(master_secret);
184 let aegis_evaluator = AegisEvaluator::new(operator_secret);
185 let mut broker = EffectBroker::new(aegis_evaluator);
186 broker.register_handler("fs.write", |_| Ok("mock file write".to_string()));
187
188 // Issue root filesystem capability to agent
189 let cap_id = [0x33u8; 16];
190 aegis_graph.issue_root_token(
191 cap_id,
192 agent_id,
193 CapabilityScope::Filesystem {
194 path_prefix: "/kernel/data".to_string(),
195 read_only: false,
196 },
197 5,
198 5000,
199 );
200
201 // Case A: the broker owns a World delta and routes the write into it.
202 let world_id = [0x99u8; 16];
203 let world = JSpaceWorld::new(world_id, None);
204 broker.register_world(world).expect("Register World delta");
205
206 let mut rev_params = BTreeMap::new();
207 rev_params.insert("path".to_string(), "/kernel/data/scratch.log".to_string());
208 rev_params.insert("content".to_string(), "temp_state".to_string());
209 let reversible_intent = EffectIntent::new(
210 agent_id,
211 "fs.write",
212 rev_params,
213 cap_id,
214 true, // is_reversible
215 Some(world_id),
216 );
217
218 let rev_decision = broker.dispatch(&reversible_intent, &aegis_graph, None, 1006);
219 assert!(rev_decision.is_ok());
220 assert_eq!(
221 broker
222 .world(&world_id)
223 .unwrap()
224 .read_file("/kernel/data/scratch.log", |_| None),
225 Some(b"temp_state".to_vec())
226 );
227
228 // Case B: Boundary-crossing irreversible effect without Operator Grant -> REJECTED
229 let mut irrev_params = BTreeMap::new();
230 irrev_params.insert(
231 "path".to_string(),
232 "/kernel/data/production.img".to_string(),
233 );
234 let irreversible_intent = EffectIntent::new(
235 agent_id,
236 "fs.write",
237 irrev_params,
238 cap_id,
239 false, // irreversible!
240 None, // outside sandbox
241 );
242
243 let unapproved_res = broker.dispatch(&irreversible_intent, &aegis_graph, None, 1007);
244 assert!(
245 matches!(unapproved_res, Err(AegisError::MissingOperatorGrant)),
246 "Irreversible intent must be blocked by AEGIS without operator grant"
247 );
248
249 // Case C: Provide authentic cryptographic Operator Grant -> APPROVED
250 let grant = OperatorGrant::issue(
251 irreversible_intent.id,
252 "operator_drake",
253 &operator_secret,
254 1008,
255 );
256
257 let approved_res = broker.dispatch(&irreversible_intent, &aegis_graph, Some(&grant), 1008);
258 assert!(
259 approved_res.is_ok(),
260 "Irreversible intent with valid operator grant must succeed"
261 );
262
263 // Case D: Cascading Revocation of root token immediately invalidates downstream intents
264 let sub_agent = LogicalAgentId::from_seed("delegated_worker");
265 let child_cap_id = [0x44u8; 16];
266 let child_cap = aegis_graph
267 .derive_child_token(
268 cap_id,
269 child_cap_id,
270 sub_agent,
271 CapabilityScope::Filesystem {
272 path_prefix: "/kernel/data".to_string(),
273 read_only: true,
274 },
275 1009,
276 )
277 .expect("Derive child capability");
278 assert!(aegis_graph.validate_token(&child_cap, 1009).is_ok());
279
280 aegis_graph.revoke(cap_id);
281 assert!(
282 matches!(
283 aegis_graph.validate_token(&child_cap, 1010),
284 Err(AegisError::TokenRevoked)
285 ),
286 "Cascading revocation must invalidate child token"
287 );
288
289 // ------------------------------------------------------------------------
290 // 4. SOFT REBOOT & DETERMINISTIC RECONSTRUCTION (§9, ADR 0006)
291 // ------------------------------------------------------------------------
292 let checkpoint_bytes = state_manager
293 .export_checkpoint(agent_id)
294 .expect("Export checkpoint");
295
296 // Simulate power cycle: new kernel boot incarnation 2
297 let mut rebooted_manager = AgentStateManager::restore_from_checkpoint(&checkpoint_bytes, 2)
298 .expect("Restore state across reboot");
299
300 let restored_root = rebooted_manager
301 .get_branch(&root_branch)
302 .expect("Root branch exists");
303 assert_eq!(restored_root.agent_id, agent_id);
304 assert_eq!(restored_root.token_history.len(), 500);
305
306 // Physical state is evicted post-reboot
307 let inc = rebooted_manager
308 .get_incarnation(&root_branch)
309 .expect("Incarnation exists");
310 assert_eq!(inc.incarnation_id, 2);
311 assert_eq!(inc.physical_state.compute_state, ComputeState::Evicted);
312
313 // Resume and reconstruct physical KV state
314 let _seq = rebooted_manager
315 .resume(root_branch)
316 .expect("Resume execution slot");
317 rebooted_manager
318 .reconstruct_physical(root_branch)
319 .expect("Reconstruct physical state");
320
321 let inc_reconstructed = rebooted_manager
322 .get_incarnation(&root_branch)
323 .expect("Reconstructed incarnation");
324 assert_eq!(
325 inc_reconstructed.physical_state.compute_state,
326 ComputeState::Decoding
327 );
328 assert_eq!(inc_reconstructed.physical_state.allocated_tokens_in_kv, 500);
329
330 // Cleanly remove exploratory branches from C1 tree without leaks
331 for child in child_branches {
332 c1.remove_branch(child).expect("Remove child branch");
333 }
334 assert_eq!(c1.pool().allocated_page_count(), root_pages);
335
336 // ------------------------------------------------------------------------
337 // 5. NATIVE SYSTEM STORE & RECOVERY CORE (ADR 0003, ADR 0006)
338 // ------------------------------------------------------------------------
339 let mut sys_store = SystemStore::<32768>::new();
340 let boot_bundle = b"AIENOS_BOOT_BUNDLE_v1:kernel=verified,model=llama-3.2-1b,hash=0x8899aabb";
341 let extent_desc = sys_store
342 .write_extent(boot_bundle)
343 .expect("Write boot bundle extent to native store");
344 let retrieved_bundle = sys_store
345 .read_extent(&extent_desc)
346 .expect("Read extent back");
347 assert_eq!(retrieved_bundle, boot_bundle);
348
349 // SliceStore verification on caller-provided buffer (no stack allocation)
350 let mut slice_buf = [0u8; 1024];
351 let mut slice_store = aienos_kernel::store::SliceStore::new(&mut slice_buf);
352 let slice_desc = slice_store
353 .write_extent(b"cortex_checkpoint_record_v1")
354 .expect("Write slice extent");
355 assert_eq!(
356 slice_store.read_extent(&slice_desc),
357 Some(&b"cortex_checkpoint_record_v1"[..])
358 );
359
360 // Deterministic A/B Slot Manager verification
361 let mut slot_mgr = SlotManager::new();
362 assert_eq!(slot_mgr.active_slot, BootSlot::SlotA);
363 slot_mgr.record_boot_attempt();
364 slot_mgr.record_boot_attempt();
365 // 3rd failed attempt triggers automatic rollback to SlotB
366 assert!(slot_mgr.record_boot_attempt());
367 assert_eq!(slot_mgr.active_slot, BootSlot::SlotB);
368
369 // WAL Truncation verification
370 let mut wal_buffer = [0u8; 256];
371 let mut wal_len = 0;
372 wal_len += WalRecovery::encode_entry(b"op_1: mount store", &mut wal_buffer[wal_len..]);
373 wal_len += WalRecovery::encode_entry(b"op_2: load cortex", &mut wal_buffer[wal_len..]);
374 let valid_prefix_len = wal_len;
375 // Append corrupted entry
376 wal_len += WalRecovery::encode_entry(b"op_3: partial write", &mut wal_buffer[wal_len..]);
377 wal_buffer[valid_prefix_len + 10] ^= 0xEE; // Corrupt record 3
378
379 let (valid_entries, truncated_bytes) =
380 WalRecovery::recover_and_truncate(&wal_buffer[..wal_len]);
381 assert_eq!(valid_entries, 2);
382 assert_eq!(truncated_bytes, valid_prefix_len);
383}