aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
GitHub aien-dev/aienux#2 (code only)
Apply it
git checkout -b patch-7c16ea5a61934c19 b6ef95fa0d620f172c412daa9006bfa1fbe2f16e curl -fsSL https://interplane.io/drakestapleton/aienux/patches/7c16ea5a61934c19.patch | git am
Provenance
github-import 1
aien-dev/aienux
2
a1f77af659b592f7be8906aedc14ff0308bdd2be
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":2,"url":"https://github.com/aien-dev/aienux/pull/2","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:35:56Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..bc33e47f --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +/target/ +__pycache__/ +*.pyc +*.tmp +.claude/ +.agents/ diff --git a/CONTEXT.md b/CONTEXT.md new file mode 100644 index 00000000..f7116ac9 --- /dev/null +++ b/CONTEXT.md @@ -0,0 +1,95 @@ +# AIENOS Domain Model + +AIENOS is an agent-native, sovereign operating system wherein the persistent AIEN agent is the primary user interface and control plane, running directly on bare-metal hardware. + +## Language + +### Core Entities + +**Operator**: +The sovereign human user who owns the hardware, sets ultimate policy, and holds root authority over the system. +_Avoid_: User, admin, root, consumer + +**AIEN Agent**: +The persistent logical intelligence entity that acts as the primary interface, planner, and coordinator for the machine across reboots and hardware changes. +_Avoid_: Assistant, bot, chatbot, process + +**Logical Agent Identity**: +The immutable cryptographic and semantic identity (`LogicalAgentId`, lineage, token history, provenance) that persists across hardware swaps, crashes, and reboots. Created only by initial provisioning; boot, sleep, model reload, kernel restart, and migration resume it—they do not create it (Continuous-Existence Amendment). +_Avoid_: PID, session, instance, thread, recreated agent + +**Physical Execution State**: +The ephemeral, disposable hardware state (KV cache pages, GPU buffers, scheduler slots, registers) utilized to run inference. +_Avoid_: Agent identity, persistent state + +**Kernel**: +The minimal, deterministic, auditable software layer that schedules CPU, manages memory, services interrupts, and enforces capabilities without requiring an AI model. +_Avoid_: Core, microkernel, executive + +**Model**: +A replaceable, swappable intelligence component accessed via the Model ABI that proposes thought and action without possessing inherent authority. +_Avoid_: Operating system, AI, brain + +--- + +### Security & Authority + +**AEGIS**: +The deterministic policy evaluation and capability enforcement system that evaluates whether an agent's proposed action is permitted. +_Avoid_: Firewall, permission manager, sudo + +**Capability**: +An unforgeable token granting fine-grained authority to access a specific resource or effect. +_Avoid_: Privilege, role, access right + +**EffectIntent**: +A structured proposal emitted by the agent expressing a desire to perform an action on the physical machine, network, or data. +_Avoid_: Command, system call, RPC + +**EffectBroker**: +The deterministic mechanism that translates an AEGIS-authorized EffectIntent into real physical hardware, driver, or network effects. +_Avoid_: Dispatcher, driver wrapper + +--- + +### Epistemics & Execution + +**Cortex**: +The persistent, evidence-aware knowledge system that records facts, observations, and decisions with verifiable provenance. +_Avoid_: Vector database, memory store, cache + +**World**: +A sandboxed, reversible execution environment where the agent can mutate files, build code, run experiments, and evaluate decisions with instant rollback. +_Avoid_: Container, VM, workspace + +**Irreversible Boundary**: +Any state change, network transmission, or physical action that permanently alters data, leaves the local fabric, or cannot be rolled back via World discard. +_Avoid_: Write operation, side effect + +**C1 Copy-On-Write Tree**: +The branch-native prefix sharing architecture that shares common physical inference KV pages across divergent reasoning branches, allocating private pages only on divergence. +_Avoid_: Prefix cache, KV cache + +**Machine Capsule**: +A portable hardware description generated on a host system that defines all CPU, accelerator, storage, memory, and firmware characteristics required for AIENOS to reproduce native execution. +_Avoid_: Hardware profile, sysinfo + +--- + +### Storage, Recovery & Allocation + +**AIEN System Store**: +The native, minimal persistent storage layer organizing immutable content-addressed extents, append-only journals, and committed agent states without general-purpose POSIX filesystem overhead. +_Avoid_: Filesystem, disk image, partition table + +**Recovery Core**: +The deterministic, non-model operating environment providing local operator authentication, A/B slot verification, rollback, and raw hardware diagnostics without AI dependencies. +_Avoid_: Recovery mode, safe mode, rescue shell + +**Standing Capability**: +A pre-authorized capability grant enabling autonomous agent execution of specific external effects without interactive per-action confirmation. +_Avoid_: Permanent privilege, whitelist + +**Transactional KV Reservation**: +An atomic memory reservation acquired prior to scheduling a reasoning step to guarantee that worst-case private block divergence cannot exhaust physical memory mid-step. +_Avoid_: Dynamic allocation, malloc diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 00000000..c8a7ef88 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,143 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aienos-aegis" +version = "0.1.0" +dependencies = [ + "aienos-agent-state", + "aienos-c1-tree", + "aienos-cortex", + "aienos-kernel", + "serde", + "serde_json", +] + +[[package]] +name = "aienos-agent-state" +version = "0.1.0" +dependencies = [ + "aienos-kernel", + "serde", + "serde_json", +] + +[[package]] +name = "aienos-c1-tree" +version = "0.1.0" +dependencies = [ + "aienos-agent-state", + "aienos-kernel", + "serde", + "serde_json", +] + +[[package]] +name = "aienos-cortex" +version = "0.1.0" +dependencies = [ + "aienos-kernel", + "serde", + "serde_json", +] + +[[package]] +name = "aienos-kernel" +version = "0.1.0" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 00000000..e13fb942 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,25 @@ +[workspace] +resolver = "2" +members = [ + "crates/aienos-kernel", + "crates/aienos-agent-state", + "crates/aienos-cortex", + "crates/aienos-aegis", + "crates/aienos-c1-tree", +] + +[workspace.package] +version = "0.1.0" +edition = "2021" +authors = ["AIENOS Sovereign Contributors"] +license = "Apache-2.0 WITH LLVM-exception" +repository = "https://github.com/aien-dev/aienos" + +[workspace.dependencies] +aienos-kernel = { path = "crates/aienos-kernel" } +aienos-agent-state = { path = "crates/aienos-agent-state" } +aienos-cortex = { path = "crates/aienos-cortex" } +aienos-aegis = { path = "crates/aienos-aegis" } +aienos-c1-tree = { path = "crates/aienos-c1-tree" } +serde = { version = "1.0", default-features = false, features = ["derive", "alloc"] } +serde_json = { version = "1.0", default-features = false, features = ["alloc"] } diff --git a/README.md b/README.md index fe43d44e..ee52e13b 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,9 @@ > **Status: experimental / pre-alpha.** Nothing here boots yet. No support, stability, or compatibility promises. Expect breaking changes. -AIENOS is an operating system in which the AIEN agent is the primary interface. It is not a desktop OS with an assistant installed on top: you turn the machine on, the agent wakes up, knows the machine and your history, operates nearly everything inside it, and asks you only before crossing a boundary you have told it not to cross alone. +AIENOS is an agent-native operating system designed around continuous logical agent existence: the agent persists while models, kernels, inference state, power states, and physical machines change beneath it. You turn the machine on, the agent wakes up, knows the machine and your history, operates nearly everything inside it, and asks you only before crossing a boundary you have told it not to cross alone. + +AIEN is provisioned once. After that, boot, reboot, sleep, model reload, kernel restart, hardware failure, and migration are execution-state transitions—not agent creation events. The kernel stays small, deterministic, and non-intelligent. The model is never the kernel, and the agent is never the root of trust. @@ -24,11 +26,12 @@ Power on, AIENOS boots directly on the NVIDIA DGX Spark (no Linux host), the AIE ## Principles - **Sovereignty:** no outside organization is required to boot the machine, access your data, authenticate you, authorize the agent, build the trusted core, recover, change models, move hardware, or keep operating. +- **Continuous existence:** the agent is provisioned once; power and substrate changes reconstruct execution, they do not recreate identity. - **Open trusted base:** boot, kernel, memory management, scheduling, storage, cryptography, identity, AEGIS, capability enforcement, update verification, recovery, and provenance build from inspectable source with a reproducible toolchain. Opaque software may accelerate AIENOS; it may never be required to trust, build, boot, recover, or control it. - **Fastest thing possible:** close to the metal, measured, with evidence. - **Free inside reversible state; explicit authorization at irreversible boundaries.** -See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for the governing design. +See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for governing design, [docs/BLUEPRINT.md](docs/BLUEPRINT.md) for the 37-section blueprint, [docs/MILESTONES.md](docs/MILESTONES.md) for the phased milestone matrix, [docs/CONTINUOUS_EXISTENCE_AMENDMENT.md](docs/CONTINUOUS_EXISTENCE_AMENDMENT.md) for the continuous-existence amendment, and [docs/adr/README.md](docs/adr/README.md) for architectural decision records and technical specifications. ## License diff --git a/crates/aienos-aegis/Cargo.toml b/crates/aienos-aegis/Cargo.toml new file mode 100644 index 00000000..23d04e38 --- /dev/null +++ b/crates/aienos-aegis/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "aienos-aegis" +version.workspace = true +edition.workspace = true +authors.workspace = true +license.workspace = true +repository.workspace = true +description = "AIENOS Phase 4: AEGIS Capability Graph, Effect Intent Pipeline, and J-Space Worlds" + +[dependencies] +aienos-kernel = { workspace = true } +aienos-agent-state = { workspace = true } +aienos-cortex = { workspace = true } +serde = { workspace = true, features = ["derive", "alloc"] } +serde_json = { workspace = true, features = ["alloc"] } + +[dev-dependencies] +aienos-c1-tree = { workspace = true } diff --git a/crates/aienos-aegis/src/broker.rs b/crates/aienos-aegis/src/broker.rs new file mode 100644 index 00000000..10c002c5 --- /dev/null +++ b/crates/aienos-aegis/src/broker.rs @@ -0,0 +1,255 @@ +//! AEGIS Effect Broker: Dispatching approved intents to hardware and drivers (§5). + +use crate::capability::{AegisError, CapabilityGraph}; +use crate::effect::{EffectIntent, OperatorGrant}; +use crate::evaluator::{AegisDecision, AegisEvaluator}; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; + +/// Immutable audit record of an effect evaluation and execution attempt. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct EffectAuditRecord { + pub intent_id: [u8; 16], + pub action: String, + pub timestamp_utc: u64, + pub decision: AegisDecision, + pub executed: bool, + pub error: Option<String>, +} + +pub type EffectHandlerFn = Box<dyn Fn(&EffectIntent) -> Result<String, String> + Send + Sync>; + +/// Sovereign Effect Broker enforcing authorization before hardware execution. +pub struct EffectBroker { + evaluator: AegisEvaluator, + handlers: HashMap<String, EffectHandlerFn>, + audit_ledger: Vec<EffectAuditRecord>, +} + +impl EffectBroker { + /// Initialize Effect Broker with an evaluator. + pub fn new(evaluator: AegisEvaluator) -> Self { + Self { + evaluator, + handlers: HashMap::new(), + audit_ledger: Vec::new(), + } + } + + /// Register a native driver/subsystem effect handler. + pub fn register_handler<F>(&mut self, action_prefix: &str, handler: F) + where + F: Fn(&EffectIntent) -> Result<String, String> + Send + Sync + 'static, + { + self.handlers + .insert(action_prefix.to_string(), Box::new(handler)); + } + + /// Dispatch an effect intent through AEGIS authorization. + /// + /// Rejects any irreversible effect originating from an unapproved intent. + pub fn dispatch( + &mut self, + intent: &EffectIntent, + graph: &CapabilityGraph, + grant: Option<&OperatorGrant>, + now_utc: u64, + ) -> Result<String, AegisError> { + let decision = self.evaluator.evaluate(intent, graph, grant, now_utc); + + match &decision { + AegisDecision::Approved { .. } => { + // Prefer the most specific matching action prefix. + let handler = self + .handlers + .iter() + .filter(|(prefix, _)| intent.action.starts_with(prefix.as_str())) + .max_by_key(|(prefix, _)| prefix.len()) + .map(|(_, h)| h); + + let result = if let Some(h) = handler { + h(intent).map_err(AegisError::ExecutionFailed) + } else { + Err(AegisError::ExecutionFailed(format!( + "no handler registered for {}", + intent.action + ))) + }; + + let is_ok = result.is_ok(); + let err_msg = result.as_ref().err().map(|e| e.to_string()); + + self.audit_ledger.push(EffectAuditRecord { + intent_id: intent.id, + action: intent.action.clone(), + timestamp_utc: now_utc, + decision: decision.clone(), + executed: is_ok, + error: err_msg, + }); + + result + } + AegisDecision::RequiresOperatorApproval { reason, .. } => { + let err_reason = reason.clone(); + self.audit_ledger.push(EffectAuditRecord { + intent_id: intent.id, + action: intent.action.clone(), + timestamp_utc: now_utc, + decision, + executed: false, + error: Some(err_reason), + }); + Err(AegisError::MissingOperatorGrant) + } + AegisDecision::Rejected { reason } => { + let err_reason = reason.clone(); + self.audit_ledger.push(EffectAuditRecord { + intent_id: intent.id, + action: intent.action.clone(), + timestamp_utc: now_utc, + decision, + executed: false, + error: Some(err_reason.clone()), + }); + Err(AegisError::IrreversibleEffectDenied(err_reason)) + } + } + } + + /// Audit ledger of all effect attempts. + pub fn audit_ledger(&self) -> &[EffectAuditRecord] { + &self.audit_ledger + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::capability::CapabilityScope; + use aienos_agent_state::LogicalAgentId; + use std::collections::BTreeMap; + + #[test] + fn test_aegis_reversible_vs_irreversible_enforcement() { + let master_secret = [0x42u8; 32]; + let operator_secret = [0x99u8; 32]; + + let mut graph = CapabilityGraph::new(master_secret); + let agent = LogicalAgentId::from_seed("aegis-test-agent"); + + let fs_cap_id = [1u8; 16]; + graph.issue_root_token( + fs_cap_id, + agent, + CapabilityScope::Filesystem { + path_prefix: "/workspace".to_string(), + read_only: false, + }, + 3, + 2000, + ); + + let evaluator = AegisEvaluator::new(operator_secret); + let mut broker = EffectBroker::new(evaluator); + + // 1. REVERSIBLE: inside J-Space World -> Auto-Approved + let mut params = BTreeMap::new(); + params.insert("path".to_string(), "/workspace/test.txt".to_string()); + let world_id = Some([0xAAu8; 16]); + + let reversible_intent = EffectIntent::new( + agent, + "fs.write", + params.clone(), + fs_cap_id, + true, // is_reversible + world_id, + ); + + let missing_handler = broker.dispatch(&reversible_intent, &graph, None, 99); + assert!(matches!( + missing_handler, + Err(AegisError::ExecutionFailed(_)) + )); + assert!(!broker.audit_ledger()[0].executed); + broker.register_handler("fs.write", |_| Ok("mock file write".to_string())); + broker.register_handler("net.fetch", |_| Ok("mock network fetch".to_string())); + + let rev_result = broker.dispatch(&reversible_intent, &graph, None, 100); + assert!( + rev_result.is_ok(), + "Reversible intent inside world must succeed" + ); + + // 2. IRREVERSIBLE: outside world without Operator Grant -> REJECTED + let irreversible_intent = EffectIntent::new( + agent, + "fs.write", + params.clone(), + fs_cap_id, + false, // is_reversible == false + None, + ); + + let unapproved_res = broker.dispatch(&irreversible_intent, &graph, None, 101); + assert!( + matches!(unapproved_res, Err(AegisError::MissingOperatorGrant)), + "Irreversible intent without operator grant must be rejected" + ); + + // 3. IRREVERSIBLE with valid Operator Grant -> APPROVED + let grant = OperatorGrant::issue( + irreversible_intent.id, + "human_operator_1", + &operator_secret, + 102, + ); + + let approved_res = broker.dispatch(&irreversible_intent, &graph, Some(&grant), 102); + assert!( + approved_res.is_ok(), + "Irreversible intent with operator grant must succeed" + ); + + // 4. Verification that forged operator grant fails + let bad_secret = [0x00u8; 32]; + let forged_grant = + OperatorGrant::issue(irreversible_intent.id, "forged_operator", &bad_secret, 103); + let forged_res = broker.dispatch(&irreversible_intent, &graph, Some(&forged_grant), 103); + assert!( + forged_res.is_err(), + "Forged operator grant must be strictly rejected" + ); + + // 5. ADR 0004: Autonomous external outbound fetch via Standing Capability + let standing_cap_id = [2u8; 16]; + graph.issue_root_token( + standing_cap_id, + agent, + CapabilityScope::StandingFetch { + host: "api.sovereign.local".to_string(), + }, + 2, + 2000, + ); + + let mut fetch_params = BTreeMap::new(); + fetch_params.insert("host".to_string(), "api.sovereign.local".to_string()); + let fetch_intent = EffectIntent::new( + agent, + "net.fetch", + fetch_params, + standing_cap_id, + false, // external effect crossing boundary + None, + ); + + // Dispatches autonomously without requiring interactive human prompt + let fetch_res = broker.dispatch(&fetch_intent, &graph, None, 104); + assert!( + fetch_res.is_ok(), + "Standing capability autonomous fetch must be authorized" + ); + } +} diff --git a/crates/aienos-aegis/src/capability.rs b/crates/aienos-aegis/src/capability.rs new file mode 100644 index 00000000..a37e33e0 --- /dev/null +++ b/crates/aienos-aegis/src/capability.rs @@ -0,0 +1,429 @@ +//! Unforgeable capability tokens and the AEGIS Directed Acyclic Capability Graph (§13). + +use aienos_agent_state::LogicalAgentId; +use aienos_kernel::crypto::sha256; +use core::fmt; +use serde::{Deserialize, Serialize}; +use std::collections::{HashMap, HashSet}; + +/// Errors occurring in capability evaluation and graph operations. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum AegisError { + InvalidSignature, + TokenExpired, + TokenRevoked, + TokenNotFound([u8; 16]), + UnauthorizedAgent, + ScopeExceeded(String), + DelegationDepthExceeded, + IrreversibleEffectDenied(String), + MissingOperatorGrant, + ExecutionFailed(String), +} + +impl fmt::Display for AegisError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidSignature => write!(f, "Invalid capability cryptographic signature"), + Self::TokenExpired => write!(f, "Capability token has expired"), + Self::TokenRevoked => write!(f, "Capability token has been revoked"), + Self::TokenNotFound(id) => write!(f, "Capability token not found: {:02x?}", id), + Self::UnauthorizedAgent => { + write!(f, "Agent is not the authorized holder of capability") + } + Self::ScopeExceeded(msg) => { + write!(f, "Requested action exceeds capability scope: {}", msg) + } + Self::DelegationDepthExceeded => write!(f, "Maximum delegation depth exceeded"), + Self::IrreversibleEffectDenied(msg) => { + write!(f, "Irreversible effect denied by policy: {}", msg) + } + Self::MissingOperatorGrant => { + write!( + f, + "Irreversible effect requires explicit operator cryptographic grant" + ) + } + Self::ExecutionFailed(msg) => write!(f, "Effect execution failed: {}", msg), + } + } +} + +/// Scope definition for granular capability permissions. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum CapabilityScope { + Filesystem { + path_prefix: String, + read_only: bool, + }, + Network { + host: String, + port: u16, + }, + Model { + model_name: String, + max_tokens: u32, + }, + Device { + device_name: String, + read_only: bool, + }, + World { + max_depth: u32, + }, + /// Standing capability for autonomous external network fetches (ADR 0004). + StandingFetch { + host: String, + }, + SystemAdmin, + Custom { + namespace: String, + action: String, + }, +} + +impl CapabilityScope { + /// Check if child scope is an attenuation (equal or stricter subset) of self. + pub fn contains(&self, child: &CapabilityScope) -> bool { + match (self, child) { + (CapabilityScope::SystemAdmin, _) => true, + ( + CapabilityScope::StandingFetch { host: h_parent }, + CapabilityScope::StandingFetch { host: h_child }, + ) => h_parent == "*" || h_parent == h_child, + ( + CapabilityScope::Filesystem { + path_prefix: p_parent, + read_only: ro_parent, + }, + CapabilityScope::Filesystem { + path_prefix: p_child, + read_only: ro_child, + }, + ) => p_child.starts_with(p_parent) && (*ro_parent == *ro_child || *ro_child), + ( + CapabilityScope::Network { + host: h_parent, + port: p_parent, + }, + CapabilityScope::Network { + host: h_child, + port: p_child, + }, + ) => { + (h_parent == "*" || h_parent == h_child) && (*p_parent == 0 || p_parent == p_child) + } + ( + CapabilityScope::Model { + model_name: m_parent, + max_tokens: tok_parent, + }, + CapabilityScope::Model { + model_name: m_child, + max_tokens: tok_child, + }, + ) => (m_parent == "*" || m_parent == m_child) && tok_child <= tok_parent, + ( + CapabilityScope::World { + max_depth: d_parent, + }, + CapabilityScope::World { max_depth: d_child }, + ) => d_child <= d_parent, + ( + CapabilityScope::Custom { + namespace: ns_p, + action: act_p, + }, + CapabilityScope::Custom { + namespace: ns_c, + action: act_c, + }, + ) => ns_p == ns_c && (act_p == "*" || act_p == act_c), + _ => false, + } + } +} + +/// Unforgeable cryptographic capability token. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct CapabilityToken { + pub id: [u8; 16], + pub parent_id: Option<[u8; 16]>, + pub issuer: String, + pub holder: LogicalAgentId, + pub scope: CapabilityScope, + pub delegation_depth: u32, + pub valid_until_utc: u64, + pub signature: [u8; 32], +} + +impl CapabilityToken { + /// Compute HMAC-SHA256 signature over token payload. + #[allow(clippy::too_many_arguments)] + pub fn compute_signature( + secret: &[u8; 32], + id: &[u8; 16], + parent_id: Option<&[u8; 16]>, + issuer: &str, + holder: &LogicalAgentId, + scope: &CapabilityScope, + delegation_depth: u32, + valid_until_utc: u64, + ) -> [u8; 32] { + let mut hasher = sha256::Sha256::new(); + hasher.update(secret); + hasher.update(id); + if let Some(pid) = parent_id { + hasher.update(pid); + } else { + hasher.update(&[0u8; 16]); + } + hasher.update(issuer.as_bytes()); + hasher.update(holder.as_bytes()); + let scope_bytes = serde_json::to_vec(scope).unwrap_or_default(); + hasher.update(&scope_bytes); + hasher.update(&delegation_depth.to_be_bytes()); + hasher.update(&valid_until_utc.to_be_bytes()); + hasher.finalize() + } +} + +/// Directed Acyclic Capability Graph managing root authorities, delegations, and revocations. +pub struct CapabilityGraph { + master_secret: [u8; 32], + tokens: HashMap<[u8; 16], CapabilityToken>, + child_map: HashMap<[u8; 16], Vec<[u8; 16]>>, + revoked_tokens: HashSet<[u8; 16]>, +} + +impl CapabilityGraph { + /// Initialize capability graph with master kernel authority secret. + pub fn new(master_secret: [u8; 32]) -> Self { + Self { + master_secret, + tokens: HashMap::new(), + child_map: HashMap::new(), + revoked_tokens: HashSet::new(), + } + } + + /// Issue a root capability granted directly by the operator. + pub fn issue_root_token( + &mut self, + id: [u8; 16], + holder: LogicalAgentId, + scope: CapabilityScope, + delegation_depth: u32, + valid_until_utc: u64, + ) -> CapabilityToken { + let signature = CapabilityToken::compute_signature( + &self.master_secret, + &id, + None, + "root.authority", + &holder, + &scope, + delegation_depth, + valid_until_utc, + ); + + let token = CapabilityToken { + id, + parent_id: None, + issuer: "root.authority".to_string(), + holder, + scope, + delegation_depth, + valid_until_utc, + signature, + }; + + self.tokens.insert(id, token.clone()); + token + } + + /// Derive an attenuated child capability token. + pub fn derive_child_token( + &mut self, + parent_id: [u8; 16], + child_id: [u8; 16], + new_holder: LogicalAgentId, + child_scope: CapabilityScope, + now_utc: u64, + ) -> Result<CapabilityToken, AegisError> { + let parent = self.get_token(&parent_id)?; + self.validate_token(&parent, now_utc)?; + + if parent.delegation_depth == 0 { + return Err(AegisError::DelegationDepthExceeded); + } + + if !parent.scope.contains(&child_scope) { + return Err(AegisError::ScopeExceeded(format!( + "Child scope {:?} not contained in parent scope {:?}", + child_scope, parent.scope + ))); + } + + let delegation_depth = parent.delegation_depth - 1; + let valid_until_utc = parent.valid_until_utc; + + let signature = CapabilityToken::compute_signature( + &self.master_secret, + &child_id, + Some(&parent_id), + &format!("cap:{:02x?}", parent_id), + &new_holder, + &child_scope, + delegation_depth, + valid_until_utc, + ); + + let child = CapabilityToken { + id: child_id, + parent_id: Some(parent_id), + issuer: format!("cap:{:02x?}", parent_id), + holder: new_holder, + scope: child_scope, + delegation_depth, + valid_until_utc, + signature, + }; + + self.tokens.insert(child_id, child.clone()); + self.child_map.entry(parent_id).or_default().push(child_id); + + Ok(child) + } + + /// Revoke a capability token and all downstream delegated descendants. + pub fn revoke(&mut self, token_id: [u8; 16]) { + let mut queue = vec![token_id]; + while let Some(current) = queue.pop() { + self.revoked_tokens.insert(current); + if let Some(children) = self.child_map.get(¤t) { + for &child in children { + queue.push(child); + } + } + } + } + + /// Get token by ID. + pub fn get_token(&self, id: &[u8; 16]) -> Result<CapabilityToken, AegisError> { + self.tokens + .get(id) + .cloned() + .ok_or(AegisError::TokenNotFound(*id)) + } + + /// Cryptographically validate token authenticity, expiry, and revocation. + pub fn validate_token(&self, token: &CapabilityToken, now_utc: u64) -> Result<(), AegisError> { + if self.revoked_tokens.contains(&token.id) { + return Err(AegisError::TokenRevoked); + } + + // Cascading ancestor revocation check + let mut curr_parent = token.parent_id; + while let Some(pid) = curr_parent { + if self.revoked_tokens.contains(&pid) { + return Err(AegisError::TokenRevoked); + } + curr_parent = self.tokens.get(&pid).and_then(|p| p.parent_id); + } + + if now_utc > token.valid_until_utc { + return Err(AegisError::TokenExpired); + } + + let expected_sig = CapabilityToken::compute_signature( + &self.master_secret, + &token.id, + token.parent_id.as_ref(), + &token.issuer, + &token.holder, + &token.scope, + token.delegation_depth, + token.valid_until_utc, + ); + + if token.signature != expected_sig { + return Err(AegisError::InvalidSignature); + } + + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_capability_attenuation_and_cascading_revocation() { + let master_secret = [0x5Au8; 32]; + let mut graph = CapabilityGraph::new(master_secret); + let root_agent = LogicalAgentId::from_seed("root_agent"); + let sub_agent = LogicalAgentId::from_seed("sub_agent"); + + let root_id = [1u8; 16]; + let root_token = graph.issue_root_token( + root_id, + root_agent, + CapabilityScope::Filesystem { + path_prefix: "/workspace".to_string(), + read_only: false, + }, + 3, + 2000, + ); + assert!(graph.validate_token(&root_token, 100).is_ok()); + + // 1. Derive attenuated child token (read-only subset) + let child_id = [2u8; 16]; + let child_token = graph + .derive_child_token( + root_id, + child_id, + sub_agent, + CapabilityScope::Filesystem { + path_prefix: "/workspace/src".to_string(), + read_only: true, + }, + 101, + ) + .expect("Attenuated derivation must succeed"); + assert!(graph.validate_token(&child_token, 101).is_ok()); + + // 2. Scope expansion attempt must fail (trying to claim root path or rw) + let invalid_child_id = [3u8; 16]; + let expanded_res = graph.derive_child_token( + root_id, + invalid_child_id, + sub_agent, + CapabilityScope::Filesystem { + path_prefix: "/etc".to_string(), + read_only: false, + }, + 102, + ); + assert!(matches!(expanded_res, Err(AegisError::ScopeExceeded(_)))); + + // 3. Expiration check + assert!(matches!( + graph.validate_token(&child_token, 2001), + Err(AegisError::TokenExpired) + )); + + // 4. Cascading revocation: revoking root must invalidate child + graph.revoke(root_id); + assert!(matches!( + graph.validate_token(&root_token, 105), + Err(AegisError::TokenRevoked) + )); + assert!(matches!( + graph.validate_token(&child_token, 105), + Err(AegisError::TokenRevoked) + )); + } +} diff --git a/crates/aienos-aegis/src/effect.rs b/crates/aienos-aegis/src/effect.rs new file mode 100644 index 00000000..49286dea --- /dev/null +++ b/crates/aienos-aegis/src/effect.rs @@ -0,0 +1,102 @@ +//! Effect Intents and Operator Grants conforming to AEGIS (§5). + +use aienos_agent_state::LogicalAgentId; +use aienos_kernel::crypto::sha256; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +/// Effect Intent proposed by an agent reasoning loop. +/// +/// Intelligence proposes; deterministic authority disposes. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EffectIntent { + pub id: [u8; 16], + pub agent_id: LogicalAgentId, + pub action: String, + pub parameters: BTreeMap<String, String>, + pub claimed_capability_id: [u8; 16], + pub is_reversible: bool, + pub world_id: Option<[u8; 16]>, +} + +impl EffectIntent { + /// Create a new effect intent. + pub fn new( + agent_id: LogicalAgentId, + action: impl Into<String>, + parameters: BTreeMap<String, String>, + claimed_capability_id: [u8; 16], + is_reversible: bool, + world_id: Option<[u8; 16]>, + ) -> Self { + let action_str = action.into(); + let mut hasher = sha256::Sha256::new(); + hasher.update(agent_id.as_bytes()); + hasher.update(action_str.as_bytes()); + hasher.update(&claimed_capability_id); + hasher.update(&[is_reversible as u8]); + if let Some(wid) = &world_id { + hasher.update(wid); + } + for (k, v) in ¶meters { + hasher.update(k.as_bytes()); + hasher.update(v.as_bytes()); + } + let digest = hasher.finalize(); + let mut id = [0u8; 16]; + id.copy_from_slice(&digest[..16]); + + Self { + id, + agent_id, + action: action_str, + parameters, + claimed_capability_id, + is_reversible, + world_id, + } + } +} + +/// Explicit Operator Grant required for any irreversible action crossing boundaries. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct OperatorGrant { + pub intent_id: [u8; 16], + pub operator_id: String, + pub granted_at_utc: u64, + pub signature: [u8; 32], +} + +impl OperatorGrant { + /// Issue an operator grant. + pub fn issue( + intent_id: [u8; 16], + operator_id: &str, + operator_secret: &[u8; 32], + granted_at_utc: u64, + ) -> Self { + let mut hasher = sha256::Sha256::new(); + hasher.update(operator_secret); + hasher.update(&intent_id); + hasher.update(operator_id.as_bytes()); + hasher.update(&granted_at_utc.to_be_bytes()); + let signature = hasher.finalize(); + + Self { + intent_id, + operator_id: operator_id.to_string(), + granted_at_utc, + signature, + } + } + + /// Verify operator grant signature. + pub fn verify(&self, operator_secret: &[u8; 32]) -> bool { + let mut hasher = sha256::Sha256::new(); + hasher.update(operator_secret); + hasher.update(&self.intent_id); + hasher.update(self.operator_id.as_bytes()); + hasher.update(&self.granted_at_utc.to_be_bytes()); + hasher.finalize() == self.signature + } +} diff --git a/crates/aienos-aegis/src/evaluator.rs b/crates/aienos-aegis/src/evaluator.rs new file mode 100644 index 00000000..c2b28c1c --- /dev/null +++ b/crates/aienos-aegis/src/evaluator.rs @@ -0,0 +1,214 @@ +//! AEGIS Policy Evaluator: Enforcing cryptographic capabilities and reversibility invariants (§5). + +use crate::capability::{CapabilityGraph, CapabilityScope}; +use crate::effect::{EffectIntent, OperatorGrant}; +use serde::{Deserialize, Serialize}; + +/// Policy evaluation outcome emitted by AEGIS. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum AegisDecision { + Approved { reason: String }, + RequiresOperatorApproval { intent_id: [u8; 16], reason: String }, + Rejected { reason: String }, +} + +/// Deterministic AEGIS Evaluator. +/// +/// Intelligence proposes; deterministic authority disposes. The model cannot authorize itself. +pub struct AegisEvaluator { + operator_secret: [u8; 32], +} + +impl AegisEvaluator { + /// Create new AEGIS Evaluator bound to the operator's sovereign root secret. + pub fn new(operator_secret: [u8; 32]) -> Self { + Self { operator_secret } + } + + /// Evaluate an effect intent against the capability graph and reversibility policy. + pub fn evaluate( + &self, + intent: &EffectIntent, + graph: &CapabilityGraph, + grant: Option<&OperatorGrant>, + now_utc: u64, + ) -> AegisDecision { + // 1. Retrieve and cryptographically validate the claimed capability token + let token = match graph.get_token(&intent.claimed_capability_id) { + Ok(t) => t, + Err(e) => { + return AegisDecision::Rejected { + reason: e.to_string(), + } + } + }; + + if let Err(e) = graph.validate_token(&token, now_utc) { + return AegisDecision::Rejected { + reason: e.to_string(), + }; + } + + // 2. Validate token holder matches proposing agent + if token.holder != intent.agent_id { + return AegisDecision::Rejected { + reason: format!( + "Agent {} is not authorized holder of token {}", + intent.agent_id, token.holder + ), + }; + } + + // 3. Match capability scope against requested action + if !Self::scope_authorizes_action(&token.scope, &intent.action, &intent.parameters) { + return AegisDecision::Rejected { + reason: format!( + "Capability scope {:?} does not authorize action \"{}\"", + token.scope, intent.action + ), + }; + } + + // 4. Evaluate Reversibility & Standing Authority Policy (ADR 0004) + // Decouple Reversible from Authorized: + // - Free inside reversible state (J-Space World) -> Auto-Approved + // - Non-destructive autonomous reads/fetches authorized via Standing Capabilities -> Auto-Approved + // - Irreversible, destructive, or boundary operations -> Strictly require OperatorGrant + if intent.is_reversible && intent.world_id.is_some() { + return AegisDecision::Approved { + reason: "Reversible effect inside J-Space World auto-approved".to_string(), + }; + } + + let is_standing_fetch = matches!(token.scope, CapabilityScope::StandingFetch { .. }) + || (intent.action == "fs.read" || intent.action == "hardware.inspect"); + + if is_standing_fetch && !Self::is_high_impact_boundary(&intent.action) { + return AegisDecision::Approved { + reason: format!( + "Autonomous effect authorized via Standing Capability {:?}", + token.scope + ), + }; + } + + // Irreversible or high-impact effect: strictly requires valid OperatorGrant + if let Some(og) = grant { + if og.intent_id != intent.id { + return AegisDecision::Rejected { + reason: "Operator grant intent ID does not match proposed intent".to_string(), + }; + } + if !og.verify(&self.operator_secret) { + return AegisDecision::Rejected { + reason: "Cryptographic signature on operator grant is invalid".to_string(), + }; + } + AegisDecision::Approved { + reason: format!( + "Irreversible action approved by operator grant from {}", + og.operator_id + ), + } + } else { + AegisDecision::RequiresOperatorApproval { + intent_id: intent.id, + reason: format!( + "Irreversible action \"{}\" crosses boundary and requires explicit operator authorization", + intent.action + ), + } + } + } + + /// Check if action is high impact boundary requiring human operator grant. + pub fn is_high_impact_boundary(action: &str) -> bool { + matches!( + action, + "disk.format" + | "fs.delete" + | "fs.write" + | "git.publish" + | "code.publish" + | "kernel.replace" + | "system.install" + | "credential.modify" + | "finance.spend" + ) + } + + fn scope_authorizes_action( + scope: &CapabilityScope, + action: &str, + params: &std::collections::BTreeMap<String, String>, + ) -> bool { + match scope { + CapabilityScope::SystemAdmin => true, + CapabilityScope::Filesystem { + path_prefix, + read_only, + } => { + if action == "fs.read" { + if let Some(path) = params.get("path") { + path.starts_with(path_prefix) + } else { + false + } + } else if action == "fs.write" || action == "fs.delete" { + if *read_only { + false + } else if let Some(path) = params.get("path") { + path.starts_with(path_prefix) + } else { + false + } + } else { + false + } + } + CapabilityScope::StandingFetch { host } => { + if action == "net.fetch" || action == "net.read" { + let req_host = params.get("host").map(|s| s.as_str()).unwrap_or(""); + host == "*" || host == req_host + } else { + false + } + } + CapabilityScope::Network { host, port } => { + if action == "net.connect" || action == "net.send" { + let req_host = params.get("host").map(|s| s.as_str()).unwrap_or(""); + let req_port: u16 = + params.get("port").and_then(|p| p.parse().ok()).unwrap_or(0); + + (host == "*" || host == req_host) && (*port == 0 || *port == req_port) + } else { + false + } + } + CapabilityScope::Device { + device_name, + read_only, + } => { + if action.starts_with("device.") { + let req_dev = params.get("device").map(|s| s.as_str()).unwrap_or(""); + let is_write = action == "device.write"; + req_dev == device_name && (!is_write || !*read_only) + } else { + false + } + } + CapabilityScope::World { .. } => action.starts_with("world."), + CapabilityScope::Custom { + namespace, + action: act, + } => { + if let Some(suffix) = action.strip_prefix(&format!("{}.", namespace)) { + act == "*" || act == suffix + } else { + false + } + } + _ => false, + } + } +} diff --git a/crates/aienos-aegis/src/lib.rs b/crates/aienos-aegis/src/lib.rs new file mode 100644 index 00000000..143ff37d --- /dev/null +++ b/crates/aienos-aegis/src/lib.rs @@ -0,0 +1,16 @@ +//! AIENOS AEGIS: Capability Graph, Effect Intent Pipeline, and J-Space Worlds (§13, §5, §12). +//! +//! Enforces unforgeable capability tokens, copy-on-write transactional worlds, +//! and strict boundary policies: intelligence proposes; deterministic authority disposes. + +pub mod broker; +pub mod capability; +pub mod effect; +pub mod evaluator; +pub mod world; + +pub use broker::{EffectAuditRecord, EffectBroker}; +pub use capability::{AegisError, CapabilityGraph, CapabilityScope, CapabilityToken}; +pub use effect::{EffectIntent, OperatorGrant}; +pub use evaluator::{AegisDecision, AegisEvaluator}; +pub use world::{JSpaceWorld, WorldStatus}; diff --git a/crates/aienos-aegis/src/world.rs b/crates/aienos-aegis/src/world.rs new file mode 100644 index 00000000..d003ba05 --- /dev/null +++ b/crates/aienos-aegis/src/world.rs @@ -0,0 +1,78 @@ +//! J-Space Worlds: Transactional sandboxes with copy-on-write semantics (§12). + +use std::collections::{HashMap, HashSet}; + +/// State of a J-Space World transactional sandbox. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum WorldStatus { + Active, + RolledBack, + Promoted, +} + +/// J-Space World sandbox providing reversible copy-on-write environment. +pub struct JSpaceWorld { + pub world_id: [u8; 16], + pub parent_world_id: Option<[u8; 16]>, + pub delta_fs: HashMap<String, Vec<u8>>, + pub deleted_files: HashSet<String>, + pub status: WorldStatus, +} + +impl JSpaceWorld { + /// Instantiate a new isolated World sandbox. + pub fn new(world_id: [u8; 16], parent_world_id: Option<[u8; 16]>) -> Self { + Self { + world_id, + parent_world_id, + delta_fs: HashMap::new(), + deleted_files: HashSet::new(), + status: WorldStatus::Active, + } + } + + /// Read file content, checking delta layer first, falling back to base reader. + pub fn read_file<F>(&self, path: &str, base_reader: F) -> Option<Vec<u8>> + where + F: FnOnce(&str) -> Option<Vec<u8>>, + { + if self.deleted_files.contains(path) { + return None; + } + if let Some(content) = self.delta_fs.get(path) { + return Some(content.clone()); + } + base_reader(path) + } + + /// Write file to isolated copy-on-write delta layer. + pub fn write_file(&mut self, path: impl Into<String>, data: Vec<u8>) { + if self.status != WorldStatus::Active { + return; + } + let p = path.into(); + self.deleted_files.remove(&p); + self.delta_fs.insert(p, data); + } + + /// Mark a file deleted inside this world. + pub fn delete_file(&mut self, path: &str) { + if self.status != WorldStatus::Active { + return; + } + self.delta_fs.remove(path); + self.deleted_files.insert(path.to_string()); + } + + /// Instantaneous rollback via dropping all deltas. + pub fn rollback(&mut self) { + self.delta_fs.clear(); + self.deleted_files.clear(); + self.status = WorldStatus::RolledBack; + } + + /// Mark world as promoted. + pub fn mark_promoted(&mut self) { + self.status = WorldStatus::Promoted; + } +} diff --git a/crates/aienos-aegis/tests/phase_3_to_5_integration.rs b/crates/aienos-aegis/tests/phase_3_to_5_integration.rs new file mode 100644 index 00000000..602b3702 --- /dev/null +++ b/crates/aienos-aegis/tests/phase_3_to_5_integration.rs @@ -0,0 +1,363 @@ +//! AIENOS Phases 3–5 Full Architecture Integration Verification Suite. +//! +//! Validates: +//! 1. AgentStateAbi reboot survival and state reconstruction (§9). +//! 2. Cortex epistemic grounding and hallucination loop rejection (§11). +//! 3. AEGIS deterministic effect brokering and operator authorization boundaries (§13, §5). +//! 4. C1 Copy-On-Write Prefix Tree with zero memory duplication across 10 branches (§10, §28). +//! 5. Native System Store and Recovery Core deterministic rollback and WAL truncation (ADR 0003, ADR 0006). + +use aienos_aegis::{ + AegisError, AegisEvaluator, CapabilityGraph, CapabilityScope, EffectBroker, EffectIntent, + JSpaceWorld, OperatorGrant, +}; +use aienos_agent_state::{AgentStateAbi, AgentStateManager, ComputeState, LogicalAgentId}; +use aienos_c1_tree::{C1PrefixTree, PAGE_CAPACITY_TOKENS}; +use aienos_cortex::{CortexError, CortexStore}; +use aienos_kernel::recovery::{BootSlot, SlotManager, WalRecovery}; +use aienos_kernel::store::SystemStore; +use std::collections::BTreeMap; + +#[test] +fn test_full_agent_epistemic_capability_and_c1_lifecycle() { + // ------------------------------------------------------------------------ + // 1. PHASE 3: PERSISTENT AGENT STATE & CORTEX EPISTEMIC MEMORY + // ------------------------------------------------------------------------ + let state_manager = AgentStateManager::new(1); + let agent_id = LogicalAgentId::from_seed("sovereign-aien-genesis"); + let root_branch = state_manager.register_agent(agent_id, 1000); + + let mut cortex = CortexStore::new(); + + // Ingest DirectObservation from hardware MMIO + let obs = cortex.record_observation( + "NVIDIA DGX Spark GB10 accelerator initialized at BAR0 0x10000000", + "bare_metal_probe", + b"hw_status:ready", + 1001, + ); + + // Ingest grounded Inference + let inf = cortex + .record_inference( + "C1 engine can bind to physical page frames without host OS", + "model_cortex_core", + vec![obs.id], + 0.98, + 1002, + ) + .expect("Inference must ground cleanly in observation"); + + // Attempt ungrounded hallucination -> must be strictly rejected + let hallucination = cortex.record_inference( + "Cloud licensing server responded with OK", + "hallucinating_agent", + vec![], // No ground truth! + 0.5, + 1003, + ); + assert!( + matches!(hallucination, Err(CortexError::UngroundedAssertion(_))), + "Ungrounded assertions must be rejected by Cortex" + ); + + // Attempt mixed-parent hallucination (one observation + one ungrounded claim) -> must fail! + let bogus_claim = aienos_cortex::EpistemicRecord::new( + aienos_cortex::EpistemicStatus::Inference, + "Bogus premise", + "bad_agent", + &[], + 1003, + 0.5, + None, + vec![], + ); + // Inject directly to simulate adversarial storage + let bogus_id = bogus_claim.id; + // cortex doesn't expose insert_record publicly outside crate, so test via ungrounded parent id + let mixed_hallucination = cortex.record_inference( + "Mixed inference", + "bad_agent", + vec![obs.id, bogus_id], + 0.5, + 1004, + ); + assert!( + matches!( + mixed_hallucination, + Err(CortexError::RecordNotFound(_)) | Err(CortexError::UngroundedAssertion(_)) + ), + "Mixed parent with unverified parent must be rejected" + ); + + // Record verified fact + let fact = cortex + .record_verified_fact( + "Kernel SHA-256 matches sovereign boot manifest", + "crypto_audit", + "sha256_verifier", + b"manifest_sig", + vec![obs.id, inf.id], + 1005, + ) + .expect("Verified fact must succeed"); + + // Attach epistemic refs to agent branch + state_manager + .add_epistemic_ref(root_branch, fact.id) + .expect("Attach epistemic ref"); + + // Append 500 prompt tokens into agent token history + let prompt_tokens: Vec<u32> = (1..=500).collect(); + state_manager + .append_tokens(root_branch, &prompt_tokens) + .expect("Append tokens"); + + // ------------------------------------------------------------------------ + // 2. PHASE 4: C1 COPY-ON-WRITE PREFIX TREE (§10, §28) + // ------------------------------------------------------------------------ + let mut c1 = C1PrefixTree::new(); + c1.create_root_branch(root_branch, &prompt_tokens) + .expect("Create C1 root branch"); + + let root_pages = c1.pool().allocated_page_count(); + let expected_pages = 500_usize.div_ceil(PAGE_CAPACITY_TOKENS); + assert_eq!(root_pages, expected_pages); + + // Fork into 10 exploratory branches + let mut child_branches = Vec::new(); + for _ in 0..10 { + let child_branch = state_manager + .fork_branch(root_branch) + .expect("Fork agent branch"); + c1.fork_branch(root_branch, child_branch) + .expect("Fork C1 branch"); + child_branches.push(child_branch); + } + + // VERIFY ZERO MEMORY DUPLICATION: + // Physical pages allocated must remain EXACTLY identical + assert_eq!( + c1.pool().allocated_page_count(), + root_pages, + "C1 fork must allocate 0 additional physical pages" + ); + + // Deduplication / sharing metrics + let metrics = c1.memory_metrics(); + assert!(metrics.sharing_ratio > 1.0); + assert_eq!(metrics.total_virtual_tokens, 500 * 11); + + // Reserve step capacity and append divergent tokens on branch 0 + let reservation = c1 + .reserve_step_capacity(child_branches[0], 10, 1005, 100) + .expect("Reserve step capacity"); + assert_eq!(reservation.tokens_reserved, 10); + + c1.append_tokens(child_branches[0], &[9001, 9002]) + .expect("Append divergent tokens"); + let b0_tokens = c1.get_tokens(child_branches[0]).expect("Get tokens"); + assert_eq!(b0_tokens.len(), 502); + assert_eq!(b0_tokens[500], 9001); + + // ------------------------------------------------------------------------ + // 3. PHASE 4: AEGIS CAPABILITY GRAPH & EFFECT BROKER + // ------------------------------------------------------------------------ + let master_secret = [0x55u8; 32]; + let operator_secret = [0x77u8; 32]; + let mut aegis_graph = CapabilityGraph::new(master_secret); + let aegis_evaluator = AegisEvaluator::new(operator_secret); + let mut broker = EffectBroker::new(aegis_evaluator); + broker.register_handler("fs.write", |_| Ok("mock file write".to_string())); + + // Issue root filesystem capability to agent + let cap_id = [0x33u8; 16]; + aegis_graph.issue_root_token( + cap_id, + agent_id, + CapabilityScope::Filesystem { + path_prefix: "/kernel/data".to_string(), + read_only: false, + }, + 5, + 5000, + ); + + // Case A: Inside J-Space World (Reversible) -> Auto-Approved + let world_id = [0x99u8; 16]; + let mut world = JSpaceWorld::new(world_id, None); + world.write_file("/kernel/data/scratch.log", b"temp_state".to_vec()); + + let mut rev_params = BTreeMap::new(); + rev_params.insert("path".to_string(), "/kernel/data/scratch.log".to_string()); + let reversible_intent = EffectIntent::new( + agent_id, + "fs.write", + rev_params, + cap_id, + true, // is_reversible + Some(world_id), + ); + + let rev_decision = broker.dispatch(&reversible_intent, &aegis_graph, None, 1006); + assert!( + rev_decision.is_ok(), + "Reversible intent inside world must pass" + ); + + // Case B: Boundary-crossing irreversible effect without Operator Grant -> REJECTED + let mut irrev_params = BTreeMap::new(); + irrev_params.insert( + "path".to_string(), + "/kernel/data/production.img".to_string(), + ); + let irreversible_intent = EffectIntent::new( + agent_id, + "fs.write", + irrev_params, + cap_id, + false, // irreversible! + None, // outside sandbox + ); + + let unapproved_res = broker.dispatch(&irreversible_intent, &aegis_graph, None, 1007); + assert!( + matches!(unapproved_res, Err(AegisError::MissingOperatorGrant)), + "Irreversible intent must be blocked by AEGIS without operator grant" + ); + + // Case C: Provide authentic cryptographic Operator Grant -> APPROVED + let grant = OperatorGrant::issue( + irreversible_intent.id, + "operator_drake", + &operator_secret, + 1008, + ); + + let approved_res = broker.dispatch(&irreversible_intent, &aegis_graph, Some(&grant), 1008); + assert!( + approved_res.is_ok(), + "Irreversible intent with valid operator grant must succeed" + ); + + // Case D: Cascading Revocation of root token immediately invalidates downstream intents + let sub_agent = LogicalAgentId::from_seed("delegated_worker"); + let child_cap_id = [0x44u8; 16]; + let child_cap = aegis_graph + .derive_child_token( + cap_id, + child_cap_id, + sub_agent, + CapabilityScope::Filesystem { + path_prefix: "/kernel/data".to_string(), + read_only: true, + }, + 1009, + ) + .expect("Derive child capability"); + assert!(aegis_graph.validate_token(&child_cap, 1009).is_ok()); + + aegis_graph.revoke(cap_id); + assert!( + matches!( + aegis_graph.validate_token(&child_cap, 1010), + Err(AegisError::TokenRevoked) + ), + "Cascading revocation must invalidate child token" + ); + + // ------------------------------------------------------------------------ + // 4. SOFT REBOOT & DETERMINISTIC RECONSTRUCTION (§9, ADR 0006) + // ------------------------------------------------------------------------ + let checkpoint_bytes = state_manager + .export_checkpoint(agent_id) + .expect("Export checkpoint"); + + // Simulate power cycle: new kernel boot incarnation 2 + let mut rebooted_manager = AgentStateManager::restore_from_checkpoint(&checkpoint_bytes, 2) + .expect("Restore state across reboot"); + + let restored_root = rebooted_manager + .get_branch(&root_branch) + .expect("Root branch exists"); + assert_eq!(restored_root.agent_id, agent_id); + assert_eq!(restored_root.token_history.len(), 500); + + // Physical state is evicted post-reboot + let inc = rebooted_manager + .get_incarnation(&root_branch) + .expect("Incarnation exists"); + assert_eq!(inc.incarnation_id, 2); + assert_eq!(inc.physical_state.compute_state, ComputeState::Evicted); + + // Resume and reconstruct physical KV state + let _seq = rebooted_manager + .resume(root_branch) + .expect("Resume execution slot"); + rebooted_manager + .reconstruct_physical(root_branch) + .expect("Reconstruct physical state"); + + let inc_reconstructed = rebooted_manager + .get_incarnation(&root_branch) + .expect("Reconstructed incarnation"); + assert_eq!( + inc_reconstructed.physical_state.compute_state, + ComputeState::Decoding + ); + assert_eq!(inc_reconstructed.physical_state.allocated_tokens_in_kv, 500); + + // Cleanly remove exploratory branches from C1 tree without leaks + for child in child_branches { + c1.remove_branch(child).expect("Remove child branch"); + } + assert_eq!(c1.pool().allocated_page_count(), root_pages); + + // ------------------------------------------------------------------------ + // 5. NATIVE SYSTEM STORE & RECOVERY CORE (ADR 0003, ADR 0006) + // ------------------------------------------------------------------------ + let mut sys_store = SystemStore::<32768>::new(); + let boot_bundle = b"AIENOS_BOOT_BUNDLE_v1:kernel=verified,model=llama-3.2-1b,hash=0x8899aabb"; + let extent_desc = sys_store + .write_extent(boot_bundle) + .expect("Write boot bundle extent to native store"); + let retrieved_bundle = sys_store + .read_extent(&extent_desc) + .expect("Read extent back"); + assert_eq!(retrieved_bundle, boot_bundle); + + // SliceStore verification on caller-provided buffer (no stack allocation) + let mut slice_buf = [0u8; 1024]; + let mut slice_store = aienos_kernel::store::SliceStore::new(&mut slice_buf); + let slice_desc = slice_store + .write_extent(b"cortex_checkpoint_record_v1") + .expect("Write slice extent"); + assert_eq!( + slice_store.read_extent(&slice_desc), + Some(&b"cortex_checkpoint_record_v1"[..]) + ); + + // Deterministic A/B Slot Manager verification + let mut slot_mgr = SlotManager::new(); + assert_eq!(slot_mgr.active_slot, BootSlot::SlotA); + slot_mgr.record_boot_attempt(); + slot_mgr.record_boot_attempt(); + // 3rd failed attempt triggers automatic rollback to SlotB + assert!(slot_mgr.record_boot_attempt()); + assert_eq!(slot_mgr.active_slot, BootSlot::SlotB); + + // WAL Truncation verification + let mut wal_buffer = [0u8; 256]; + let mut wal_len = 0; + wal_len += WalRecovery::encode_entry(b"op_1: mount store", &mut wal_buffer[wal_len..]); + wal_len += WalRecovery::encode_entry(b"op_2: load cortex", &mut wal_buffer[wal_len..]); + let valid_prefix_len = wal_len; + // Append corrupted entry + wal_len += WalRecovery::encode_entry(b"op_3: partial write", &mut wal_buffer[wal_len..]); + wal_buffer[valid_prefix_len + 10] ^= 0xEE; // Corrupt record 3 + + let (valid_entries, truncated_bytes) = + WalRecovery::recover_and_truncate(&wal_buffer[..wal_len]); + assert_eq!(valid_entries, 2); + assert_eq!(truncated_bytes, valid_prefix_len); +} diff --git a/crates/aienos-agent-state/Cargo.toml b/crates/aienos-agent-state/Cargo.toml new file mode 100644 index 00000000..6fdcf3c3 --- /dev/null +++ b/crates/aienos-agent-state/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "aienos-agent-state" +version.workspace = true +edition.workspace = true +authors.workspace = true +license.workspace = true +repository.workspace = true +description = "AIENOS Phase 3: Persistent Agent State ABI and execution incarnation decoupling" + +[dependencies] +aienos-kernel = { workspace = true } +serde = { workspace = true, features = ["derive", "alloc"] } +serde_json = { workspace = true, features = ["alloc"] } diff --git a/crates/aienos-agent-state/src/abi.rs b/crates/aienos-agent-state/src/abi.rs new file mode 100644 index 00000000..17cf0e5d --- /dev/null +++ b/crates/aienos-agent-state/src/abi.rs @@ -0,0 +1,75 @@ +//! AIENOS Agent State ABI (§9). + +use crate::id::{LogicalAgentId, LogicalBranchId}; +use crate::incarnation::SequenceId; +use core::fmt; +use serde::{Deserialize, Serialize}; + +/// Checkpoint cryptographic integrity hash. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +pub struct CheckpointHash(pub [u8; 32]); + +impl fmt::Debug for CheckpointHash { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "CheckpointHash({:02x}{:02x}...)", self.0[0], self.0[1]) + } +} + +impl fmt::Display for CheckpointHash { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + for b in &self.0 { + write!(f, "{:02x}", b)?; + } + Ok(()) + } +} + +/// Errors occurring during Agent State operations. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum StateError { + AgentNotFound(LogicalAgentId), + BranchNotFound(LogicalBranchId), + ParentBranchNotFound(LogicalBranchId), + AlreadySuspended(LogicalBranchId), + NotSuspended(LogicalBranchId), + SerializationError(String), + DeserializationError(String), + ChecksumMismatch, + ReconstructionFailed(String), +} + +impl fmt::Display for StateError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::AgentNotFound(id) => write!(f, "Agent not found: {}", id), + Self::BranchNotFound(id) => write!(f, "Branch not found: {}", id), + Self::ParentBranchNotFound(id) => write!(f, "Parent branch not found: {}", id), + Self::AlreadySuspended(id) => write!(f, "Branch already suspended: {}", id), + Self::NotSuspended(id) => write!(f, "Branch not suspended: {}", id), + Self::SerializationError(msg) => write!(f, "Serialization error: {}", msg), + Self::DeserializationError(msg) => write!(f, "Deserialization error: {}", msg), + Self::ChecksumMismatch => write!(f, "Checkpoint checksum mismatch"), + Self::ReconstructionFailed(msg) => write!(f, "Physical reconstruction failed: {}", msg), + } + } +} + +/// The Agent State ABI (§9). +/// +/// Decouples persistent semantic identity from ephemeral execution incarnations. +pub trait AgentStateAbi { + /// Fork an existing logical branch into an isolated child branch. + fn fork_branch(&self, parent: LogicalBranchId) -> Result<LogicalBranchId, StateError>; + + /// Checkpoint logical agent state to durable storage. + fn checkpoint(&self, agent_id: LogicalAgentId) -> Result<CheckpointHash, StateError>; + + /// Suspend execution incarnation without mutating logical state. + fn suspend(&mut self, branch_id: LogicalBranchId) -> Result<(), StateError>; + + /// Resume execution, re-instantiating physical state via recompute or cache. + fn resume(&mut self, branch_id: LogicalBranchId) -> Result<SequenceId, StateError>; + + /// Reconstruct lost physical state from TokenHistory and EpistemicRefs. + fn reconstruct_physical(&mut self, branch_id: LogicalBranchId) -> Result<(), StateError>; +} diff --git a/crates/aienos-agent-state/src/history.rs b/crates/aienos-agent-state/src/history.rs new file mode 100644 index 00000000..4bafd73b --- /dev/null +++ b/crates/aienos-agent-state/src/history.rs @@ -0,0 +1,113 @@ +//! Append-only TokenHistory log with cryptographic rolling hash chains. + +use aienos_kernel::crypto::sha256; +use serde::{Deserialize, Serialize}; + +/// Record of an individual token and its cryptographic chain state. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct TokenRecord { + pub sequence_idx: u64, + pub token_id: u32, + pub token_hash: [u8; 32], +} + +/// Append-only log of token sequence IDs & hashes. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct TokenHistory { + records: Vec<TokenRecord>, + rolling_hash: [u8; 32], +} + +impl Default for TokenHistory { + fn default() -> Self { + Self::new() + } +} + +impl TokenHistory { + /// Initialize an empty token history with genesis rolling hash. + pub fn new() -> Self { + let genesis_hash = sha256::hash(b"AIENOS_TOKEN_GENESIS_v1"); + Self { + records: Vec::new(), + rolling_hash: genesis_hash, + } + } + + /// Number of tokens in history. + pub fn len(&self) -> usize { + self.records.len() + } + + /// Check if history is empty. + pub fn is_empty(&self) -> bool { + self.records.is_empty() + } + + /// Current cumulative rolling hash. + pub fn rolling_hash(&self) -> [u8; 32] { + self.rolling_hash + } + + /// Slice of all token records. + pub fn records(&self) -> &[TokenRecord] { + &self.records + } + + /// Extract raw token IDs. + pub fn tokens(&self) -> Vec<u32> { + self.records.iter().map(|r| r.token_id).collect() + } + + /// Append a single token to the history log, updating rolling cryptographic hash. + pub fn append(&mut self, token_id: u32) { + let seq = self.records.len() as u64; + let mut hasher = sha256::Sha256::new(); + hasher.update(&self.rolling_hash); + hasher.update(&seq.to_be_bytes()); + hasher.update(&token_id.to_be_bytes()); + let next_hash = hasher.finalize(); + + self.records.push(TokenRecord { + sequence_idx: seq, + token_id, + token_hash: next_hash, + }); + self.rolling_hash = next_hash; + } + + /// Append a batch of tokens sequentially. + pub fn append_tokens(&mut self, tokens: &[u32]) { + for &t in tokens { + self.append(t); + } + } + + /// Fork this token history into a new independent branch starting from this state. + pub fn fork(&self) -> Self { + self.clone() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_token_history_rolling_hash() { + let mut h1 = TokenHistory::new(); + h1.append_tokens(&[101, 202, 303]); + + let mut h2 = TokenHistory::new(); + h2.append_tokens(&[101, 202, 303]); + + assert_eq!(h1.len(), 3); + assert_eq!(h1.rolling_hash(), h2.rolling_hash()); + assert_eq!(h1.tokens(), vec![101, 202, 303]); + + // Appending different tokens must diverge hashes + let mut h3 = h1.fork(); + h3.append(404); + assert_ne!(h1.rolling_hash(), h3.rolling_hash()); + } +} diff --git a/crates/aienos-agent-state/src/id.rs b/crates/aienos-agent-state/src/id.rs new file mode 100644 index 00000000..4fcdc983 --- /dev/null +++ b/crates/aienos-agent-state/src/id.rs @@ -0,0 +1,125 @@ +//! Sovereign cryptographic identities for agents and reasoning branches. + +use aienos_kernel::crypto::sha256; +use core::fmt; +use serde::{Deserialize, Serialize}; + +/// Sovereign Logical Agent Identifier (32-byte cryptographic key or UUIDv7 digest). +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +pub struct LogicalAgentId(pub [u8; 32]); + +impl LogicalAgentId { + /// Construct a LogicalAgentId directly from 32 bytes. + pub const fn from_bytes(bytes: [u8; 32]) -> Self { + Self(bytes) + } + + /// Deterministically derive an agent ID from a canonical seed string. + pub fn from_seed(seed: &str) -> Self { + let prefix = b"AIENOS_AGENT_GENESIS_v1:"; + let seed_bytes = seed.as_bytes(); + let mut hasher = sha256::Sha256::new(); + hasher.update(prefix); + hasher.update(seed_bytes); + Self(hasher.finalize()) + } + + /// Return raw bytes. + pub const fn as_bytes(&self) -> &[u8; 32] { + &self.0 + } +} + +impl fmt::Debug for LogicalAgentId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "AgentId({}", &self.to_string()[..12])?; + write!(f, "...)") + } +} + +impl fmt::Display for LogicalAgentId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + for b in &self.0 { + write!(f, "{:02x}", b)?; + } + Ok(()) + } +} + +/// Deterministic Logical Branch Identifier derived from parent branch + branch index. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +pub struct LogicalBranchId(pub [u8; 32]); + +impl LogicalBranchId { + /// Construct directly from 32 bytes. + pub const fn from_bytes(bytes: [u8; 32]) -> Self { + Self(bytes) + } + + /// Create root branch for an agent. + pub fn root_branch(agent_id: LogicalAgentId) -> Self { + let mut hasher = sha256::Sha256::new(); + hasher.update(b"AIENOS_ROOT_BRANCH_v1:"); + hasher.update(agent_id.as_bytes()); + Self(hasher.finalize()) + } + + /// Deterministically derive a child branch ID from a parent branch ID and a child index. + pub fn derive(parent: LogicalBranchId, branch_index: u64) -> Self { + let mut hasher = sha256::Sha256::new(); + hasher.update(b"AIENOS_CHILD_BRANCH_v1:"); + hasher.update(&parent.0); + hasher.update(&branch_index.to_be_bytes()); + Self(hasher.finalize()) + } + + /// Return raw bytes. + pub const fn as_bytes(&self) -> &[u8; 32] { + &self.0 + } +} + +impl fmt::Debug for LogicalBranchId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "BranchId({}", &self.to_string()[..12])?; + write!(f, "...)") + } +} + +impl fmt::Display for LogicalBranchId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + for b in &self.0 { + write!(f, "{:02x}", b)?; + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_agent_id_determinism() { + let id1 = LogicalAgentId::from_seed("agent-alpha"); + let id2 = LogicalAgentId::from_seed("agent-alpha"); + let id3 = LogicalAgentId::from_seed("agent-beta"); + + assert_eq!(id1, id2); + assert_ne!(id1, id3); + assert_eq!(id1.to_string().len(), 64); + } + + #[test] + fn test_branch_id_derivation() { + let agent = LogicalAgentId::from_seed("spark-agent"); + let root = LogicalBranchId::root_branch(agent); + let child0 = LogicalBranchId::derive(root, 0); + let child1 = LogicalBranchId::derive(root, 1); + let child0_repeat = LogicalBranchId::derive(root, 0); + + assert_eq!(child0, child0_repeat); + assert_ne!(child0, child1); + assert_ne!(root, child0); + } +} diff --git a/crates/aienos-agent-state/src/incarnation.rs b/crates/aienos-agent-state/src/incarnation.rs new file mode 100644 index 00000000..655a418b --- /dev/null +++ b/crates/aienos-agent-state/src/incarnation.rs @@ -0,0 +1,112 @@ +//! Ephemeral execution incarnations and decoupled physical inference states. + +use crate::history::TokenHistory; +use crate::id::{LogicalAgentId, LogicalBranchId}; +use crate::lineage::{EpistemicRefs, Lineage}; +use serde::{Deserialize, Serialize}; + +/// Monotonic boot / process incarnation counter. +pub type IncarnationId = u64; + +/// Ephemeral scheduler slot identifier. +pub type SequenceId = u32; + +/// State of accelerator/hardware inference pipeline. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum ComputeState { + Idle, + Prefilling, + Decoding, + Suspended, + Evicted, +} + +/// Ephemeral physical inference allocation. +/// +/// Losing this state costs computation (recompute / cache reload), NEVER identity. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct PhysicalInferenceState { + pub kv_page_table_ref: Option<usize>, + pub accelerator_buffer_ref: Option<usize>, + pub compute_state: ComputeState, + pub allocated_tokens_in_kv: usize, +} + +impl Default for PhysicalInferenceState { + fn default() -> Self { + Self { + kv_page_table_ref: None, + accelerator_buffer_ref: None, + compute_state: ComputeState::Idle, + allocated_tokens_in_kv: 0, + } + } +} + +/// Ephemeral per-boot/process execution instance. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ExecutionIncarnation { + pub incarnation_id: IncarnationId, + pub sequence_id: SequenceId, + pub physical_state: PhysicalInferenceState, +} + +impl ExecutionIncarnation { + /// Create new active execution incarnation. + pub fn new(incarnation_id: IncarnationId, sequence_id: SequenceId) -> Self { + Self { + incarnation_id, + sequence_id, + physical_state: PhysicalInferenceState::default(), + } + } + + /// Mark incarnation as evicted (hardware resources reclaimed). + pub fn evict(&mut self) { + self.physical_state.kv_page_table_ref = None; + self.physical_state.accelerator_buffer_ref = None; + self.physical_state.allocated_tokens_in_kv = 0; + self.physical_state.compute_state = ComputeState::Evicted; + } +} + +/// Persistent Logical Branch entity holding complete semantic identity. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct LogicalBranch { + pub branch_id: LogicalBranchId, + pub parent_branch_id: Option<LogicalBranchId>, + pub agent_id: LogicalAgentId, + pub token_history: TokenHistory, + pub lineage: Lineage, + pub epistemic_refs: EpistemicRefs, + pub created_at_utc: u64, +} + +impl LogicalBranch { + /// Initialize a new root branch for an agent. + pub fn new_root(agent_id: LogicalAgentId, timestamp: u64) -> Self { + let branch_id = LogicalBranchId::root_branch(agent_id); + Self { + branch_id, + parent_branch_id: None, + agent_id, + token_history: TokenHistory::new(), + lineage: Lineage::new_root(agent_id), + epistemic_refs: EpistemicRefs::new(), + created_at_utc: timestamp, + } + } + + /// Fork this branch into a child branch, inheriting token history and extending lineage. + pub fn fork(&self, child_id: LogicalBranchId, timestamp: u64) -> Self { + Self { + branch_id: child_id, + parent_branch_id: Some(self.branch_id), + agent_id: self.agent_id, + token_history: self.token_history.fork(), + lineage: self.lineage.extend(child_id), + epistemic_refs: self.epistemic_refs.clone(), + created_at_utc: timestamp, + } + } +} diff --git a/crates/aienos-agent-state/src/lib.rs b/crates/aienos-agent-state/src/lib.rs new file mode 100644 index 00000000..fdf4290e --- /dev/null +++ b/crates/aienos-agent-state/src/lib.rs @@ -0,0 +1,23 @@ +//! AIENOS Agent State ABI & Execution Incarnation Substrate (§9). +//! +//! Provides sovereign logical agent identities, deterministic branch derivation, +//! append-only token history logs with rolling cryptographic hash chains, +//! and complete decoupling of persistent semantic identity from ephemeral +//! physical compute incarnations. + +pub mod abi; +pub mod history; +pub mod id; +pub mod incarnation; +pub mod lineage; +pub mod manager; + +pub use abi::{AgentStateAbi, CheckpointHash, StateError}; +pub use history::{TokenHistory, TokenRecord}; +pub use id::{LogicalAgentId, LogicalBranchId}; +pub use incarnation::{ + ComputeState, ExecutionIncarnation, IncarnationId, LogicalBranch, PhysicalInferenceState, + SequenceId, +}; +pub use lineage::{EpistemicRefs, Lineage}; +pub use manager::{AgentSnapshot, AgentStateManager, CheckpointEnvelope}; diff --git a/crates/aienos-agent-state/src/lineage.rs b/crates/aienos-agent-state/src/lineage.rs new file mode 100644 index 00000000..1942b1ae --- /dev/null +++ b/crates/aienos-agent-state/src/lineage.rs @@ -0,0 +1,104 @@ +//! Agent lineage provenance tracking and Cortex epistemic references. + +use crate::id::{LogicalAgentId, LogicalBranchId}; +use serde::{Deserialize, Serialize}; + +/// Provenance lineage tree path tracing back to Genesis root agent. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Lineage { + pub root_agent: LogicalAgentId, + pub ancestor_branches: Vec<LogicalBranchId>, + pub depth: usize, +} + +impl Lineage { + /// Create root lineage for an agent. + pub fn new_root(root_agent: LogicalAgentId) -> Self { + Self { + root_agent, + ancestor_branches: Vec::new(), + depth: 0, + } + } + + /// Extend lineage with a new descendant branch. + pub fn extend(&self, branch_id: LogicalBranchId) -> Self { + let mut ancestors = self.ancestor_branches.clone(); + ancestors.push(branch_id); + Self { + root_agent: self.root_agent, + ancestor_branches: ancestors, + depth: self.depth + 1, + } + } + + /// Check if this branch is in the lineage. + pub fn contains(&self, branch_id: &LogicalBranchId) -> bool { + self.ancestor_branches.contains(branch_id) + } +} + +/// Set of Cortex observation/fact record UUIDs referenced by a reasoning branch. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct EpistemicRefs { + record_ids: Vec<[u8; 16]>, +} + +impl EpistemicRefs { + /// Create empty epistemic references set. + pub fn new() -> Self { + Self { + record_ids: Vec::new(), + } + } + + /// Insert a Cortex record reference UUID. + pub fn insert(&mut self, record_id: [u8; 16]) { + if !self.record_ids.contains(&record_id) { + self.record_ids.push(record_id); + } + } + + /// Check if a Cortex record is referenced. + pub fn contains(&self, record_id: &[u8; 16]) -> bool { + self.record_ids.contains(record_id) + } + + /// Access all referenced record UUIDs. + pub fn records(&self) -> &[[u8; 16]] { + &self.record_ids + } + + /// Count of referenced epistemic records. + pub fn len(&self) -> usize { + self.record_ids.len() + } + + /// Check if empty. + pub fn is_empty(&self) -> bool { + self.record_ids.is_empty() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_lineage_extension() { + let agent = LogicalAgentId::from_seed("lineage-test"); + let root = Lineage::new_root(agent); + assert_eq!(root.depth, 0); + + let b1 = LogicalBranchId::derive(LogicalBranchId::root_branch(agent), 1); + let l1 = root.extend(b1); + assert_eq!(l1.depth, 1); + assert!(l1.contains(&b1)); + + let b2 = LogicalBranchId::derive(b1, 2); + let l2 = l1.extend(b2); + assert_eq!(l2.depth, 2); + assert!(l2.contains(&b1)); + assert!(l2.contains(&b2)); + } +} diff --git a/crates/aienos-agent-state/src/manager.rs b/crates/aienos-agent-state/src/manager.rs new file mode 100644 index 00000000..a2e9bf16 --- /dev/null +++ b/crates/aienos-agent-state/src/manager.rs @@ -0,0 +1,400 @@ +//! Concrete thread-safe AgentStateManager implementing AgentStateAbi. + +use crate::abi::{AgentStateAbi, CheckpointHash, StateError}; +use crate::id::{LogicalAgentId, LogicalBranchId}; +use crate::incarnation::{ComputeState, ExecutionIncarnation, LogicalBranch, SequenceId}; +use aienos_kernel::crypto::sha256; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::RwLock; + +/// Persistent snapshot of agent state for cross-boot serialization. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct AgentSnapshot { + pub agents: Vec<LogicalAgentId>, + pub branches: Vec<LogicalBranch>, + pub snapshot_incarnation: u64, +} + +/// Durable checkpoint container with cryptographic seal. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct CheckpointEnvelope { + pub hash: [u8; 32], + pub payload_json: String, +} + +struct InnerState { + agents: Vec<LogicalAgentId>, + branches: HashMap<LogicalBranchId, LogicalBranch>, + incarnations: HashMap<LogicalBranchId, ExecutionIncarnation>, + branch_child_counters: HashMap<LogicalBranchId, u64>, +} + +/// Thread-safe sovereign manager for logical agent states and execution incarnations. +pub struct AgentStateManager { + inner: RwLock<InnerState>, + current_incarnation_id: AtomicU64, + next_sequence_id: AtomicU32, +} + +impl Default for AgentStateManager { + fn default() -> Self { + Self::new(1) + } +} + +impl AgentStateManager { + /// Initialize a new manager with a specific boot incarnation ID. + pub fn new(incarnation_id: u64) -> Self { + Self { + inner: RwLock::new(InnerState { + agents: Vec::new(), + branches: HashMap::new(), + incarnations: HashMap::new(), + branch_child_counters: HashMap::new(), + }), + current_incarnation_id: AtomicU64::new(incarnation_id), + next_sequence_id: AtomicU32::new(1), + } + } + + /// Register a new agent and instantiate its root branch. + pub fn register_agent(&self, agent_id: LogicalAgentId, timestamp: u64) -> LogicalBranchId { + let mut inner = self.inner.write().unwrap(); + if !inner.agents.contains(&agent_id) { + inner.agents.push(agent_id); + } + + let root_branch = LogicalBranch::new_root(agent_id, timestamp); + let branch_id = root_branch.branch_id; + inner.branches.insert(branch_id, root_branch); + + let seq = self.next_sequence_id.fetch_add(1, Ordering::SeqCst); + let incarnation_id = self.current_incarnation_id.load(Ordering::SeqCst); + inner + .incarnations + .insert(branch_id, ExecutionIncarnation::new(incarnation_id, seq)); + + branch_id + } + + /// Append tokens to an existing branch's history. + pub fn append_tokens( + &self, + branch_id: LogicalBranchId, + tokens: &[u32], + ) -> Result<(), StateError> { + let mut inner = self.inner.write().unwrap(); + let history_len = { + let branch = inner + .branches + .get_mut(&branch_id) + .ok_or(StateError::BranchNotFound(branch_id))?; + branch.token_history.append_tokens(tokens); + branch.token_history.len() + }; + + if let Some(inc) = inner.incarnations.get_mut(&branch_id) { + if inc.physical_state.compute_state != ComputeState::Suspended + && inc.physical_state.compute_state != ComputeState::Evicted + { + inc.physical_state.allocated_tokens_in_kv = history_len; + inc.physical_state.compute_state = ComputeState::Decoding; + } + } + Ok(()) + } + + /// Attach a Cortex epistemic reference to a branch. + pub fn add_epistemic_ref( + &self, + branch_id: LogicalBranchId, + record_id: [u8; 16], + ) -> Result<(), StateError> { + let mut inner = self.inner.write().unwrap(); + let branch = inner + .branches + .get_mut(&branch_id) + .ok_or(StateError::BranchNotFound(branch_id))?; + branch.epistemic_refs.insert(record_id); + Ok(()) + } + + /// Retrieve branch details. + pub fn get_branch(&self, branch_id: &LogicalBranchId) -> Option<LogicalBranch> { + let inner = self.inner.read().unwrap(); + inner.branches.get(branch_id).cloned() + } + + /// Retrieve ephemeral incarnation details. + pub fn get_incarnation(&self, branch_id: &LogicalBranchId) -> Option<ExecutionIncarnation> { + let inner = self.inner.read().unwrap(); + inner.incarnations.get(branch_id).cloned() + } + + /// Export a durable checkpoint envelope with SHA-256 seal. + pub fn export_checkpoint(&self, agent_id: LogicalAgentId) -> Result<Vec<u8>, StateError> { + let inner = self.inner.read().unwrap(); + if !inner.agents.contains(&agent_id) { + return Err(StateError::AgentNotFound(agent_id)); + } + + let agent_branches: Vec<LogicalBranch> = inner + .branches + .values() + .filter(|b| b.agent_id == agent_id) + .cloned() + .collect(); + + let snapshot = AgentSnapshot { + agents: vec![agent_id], + branches: agent_branches, + snapshot_incarnation: self.current_incarnation_id.load(Ordering::SeqCst), + }; + + let json = serde_json::to_string(&snapshot) + .map_err(|e| StateError::SerializationError(e.to_string()))?; + let hash = sha256::hash(json.as_bytes()); + + let envelope = CheckpointEnvelope { + hash, + payload_json: json, + }; + + serde_json::to_vec(&envelope).map_err(|e| StateError::SerializationError(e.to_string())) + } + + /// Restore state from a durable checkpoint envelope across reboot. + /// + /// Verifies cryptographic checksum, restores all logical state, and + /// resets physical state to `Evicted` under a new monotonic boot incarnation. + pub fn restore_from_checkpoint( + checkpoint_data: &[u8], + new_incarnation_id: u64, + ) -> Result<Self, StateError> { + let envelope: CheckpointEnvelope = serde_json::from_slice(checkpoint_data) + .map_err(|e| StateError::DeserializationError(e.to_string()))?; + + let expected_hash = sha256::hash(envelope.payload_json.as_bytes()); + if envelope.hash != expected_hash { + return Err(StateError::ChecksumMismatch); + } + + let snapshot: AgentSnapshot = serde_json::from_str(&envelope.payload_json) + .map_err(|e| StateError::DeserializationError(e.to_string()))?; + + let manager = Self::new(new_incarnation_id); + { + let mut inner = manager.inner.write().unwrap(); + inner.agents = snapshot.agents; + for branch in snapshot.branches { + let branch_id = branch.branch_id; + inner.branches.insert(branch_id, branch); + + // Re-instantiate ephemeral incarnation with EVICTED physical state + let seq = manager.next_sequence_id.fetch_add(1, Ordering::SeqCst); + let mut inc = ExecutionIncarnation::new(new_incarnation_id, seq); + inc.evict(); + inner.incarnations.insert(branch_id, inc); + } + } + + Ok(manager) + } +} + +impl AgentStateAbi for AgentStateManager { + fn fork_branch(&self, parent: LogicalBranchId) -> Result<LogicalBranchId, StateError> { + let mut inner = self.inner.write().unwrap(); + let parent_branch = inner + .branches + .get(&parent) + .ok_or(StateError::ParentBranchNotFound(parent))? + .clone(); + + let counter = inner.branch_child_counters.entry(parent).or_insert(0); + let child_idx = *counter; + *counter += 1; + + let child_id = LogicalBranchId::derive(parent, child_idx); + let child_branch = parent_branch.fork(child_id, 1000 + child_idx); + + inner.branches.insert(child_id, child_branch); + + let seq = self.next_sequence_id.fetch_add(1, Ordering::SeqCst); + let incarnation_id = self.current_incarnation_id.load(Ordering::SeqCst); + inner + .incarnations + .insert(child_id, ExecutionIncarnation::new(incarnation_id, seq)); + + Ok(child_id) + } + + fn checkpoint(&self, agent_id: LogicalAgentId) -> Result<CheckpointHash, StateError> { + let bytes = self.export_checkpoint(agent_id)?; + let envelope: CheckpointEnvelope = serde_json::from_slice(&bytes) + .map_err(|e| StateError::SerializationError(e.to_string()))?; + Ok(CheckpointHash(envelope.hash)) + } + + fn suspend(&mut self, branch_id: LogicalBranchId) -> Result<(), StateError> { + let mut inner = self.inner.write().unwrap(); + if !inner.branches.contains_key(&branch_id) { + return Err(StateError::BranchNotFound(branch_id)); + } + let inc = inner + .incarnations + .get_mut(&branch_id) + .ok_or(StateError::BranchNotFound(branch_id))?; + + if inc.physical_state.compute_state == ComputeState::Suspended { + return Err(StateError::AlreadySuspended(branch_id)); + } + + inc.physical_state.compute_state = ComputeState::Suspended; + Ok(()) + } + + fn resume(&mut self, branch_id: LogicalBranchId) -> Result<SequenceId, StateError> { + let mut inner = self.inner.write().unwrap(); + if !inner.branches.contains_key(&branch_id) { + return Err(StateError::BranchNotFound(branch_id)); + } + + let seq = self.next_sequence_id.fetch_add(1, Ordering::SeqCst); + let inc = inner + .incarnations + .get_mut(&branch_id) + .ok_or(StateError::BranchNotFound(branch_id))?; + + inc.sequence_id = seq; + if inc.physical_state.compute_state == ComputeState::Suspended { + inc.physical_state.compute_state = ComputeState::Idle; + } + + Ok(seq) + } + + fn reconstruct_physical(&mut self, branch_id: LogicalBranchId) -> Result<(), StateError> { + let mut inner = self.inner.write().unwrap(); + let branch = inner + .branches + .get(&branch_id) + .ok_or(StateError::BranchNotFound(branch_id))? + .clone(); + + let inc = inner + .incarnations + .get_mut(&branch_id) + .ok_or(StateError::BranchNotFound(branch_id))?; + + // Reconstruct physical inference state deterministically from TokenHistory + inc.physical_state.allocated_tokens_in_kv = branch.token_history.len(); + inc.physical_state.kv_page_table_ref = Some(0xDEAD_0000 + branch.token_history.len()); + inc.physical_state.compute_state = ComputeState::Decoding; + + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_checkpoint_reboot_and_reconstruction() { + let manager = AgentStateManager::new(1); + let agent_id = LogicalAgentId::from_seed("aienos-sovereign-agent"); + let root_branch = manager.register_agent(agent_id, 100); + + // Append 50 tokens + let tokens: Vec<u32> = (1..=50).collect(); + manager.append_tokens(root_branch, &tokens).unwrap(); + + // Fork branch + let child_branch = manager.fork_branch(root_branch).unwrap(); + manager.append_tokens(child_branch, &[51, 52]).unwrap(); + + // Add epistemic ref + let ref_id = [7u8; 16]; + manager.add_epistemic_ref(child_branch, ref_id).unwrap(); + + // Checkpoint agent + let checkpoint_bytes = manager.export_checkpoint(agent_id).unwrap(); + let CheckpointHash(hash) = manager.checkpoint(agent_id).unwrap(); + assert_ne!(hash, [0u8; 32]); + + // SIMULATE SOFT REBOOT: Host powers down, new manager boots with incarnation 2 + let mut rebooted_manager = + AgentStateManager::restore_from_checkpoint(&checkpoint_bytes, 2).unwrap(); + + // Verify logical identity intact + let restored_root = rebooted_manager.get_branch(&root_branch).unwrap(); + assert_eq!(restored_root.agent_id, agent_id); + assert_eq!(restored_root.token_history.len(), 50); + + let restored_child = rebooted_manager.get_branch(&child_branch).unwrap(); + assert_eq!(restored_child.parent_branch_id, Some(root_branch)); + assert_eq!(restored_child.token_history.len(), 52); + assert!(restored_child.epistemic_refs.contains(&ref_id)); + + // Physical state is evicted post-reboot + let inc = rebooted_manager.get_incarnation(&child_branch).unwrap(); + assert_eq!(inc.incarnation_id, 2); + assert_eq!(inc.physical_state.compute_state, ComputeState::Evicted); + assert_eq!(inc.physical_state.allocated_tokens_in_kv, 0); + + // Resume and reconstruct physical inference state + let new_seq = rebooted_manager.resume(child_branch).unwrap(); + assert!(new_seq > 0); + + rebooted_manager.reconstruct_physical(child_branch).unwrap(); + let inc_reconstructed = rebooted_manager.get_incarnation(&child_branch).unwrap(); + assert_eq!( + inc_reconstructed.physical_state.compute_state, + ComputeState::Decoding + ); + assert_eq!(inc_reconstructed.physical_state.allocated_tokens_in_kv, 52); + assert!(inc_reconstructed.physical_state.kv_page_table_ref.is_some()); + } + + #[test] + fn test_suspend_resume_lifecycle_and_tamper_rejection() { + let mut manager = AgentStateManager::new(1); + let agent_id = LogicalAgentId::from_seed("suspend-test-agent"); + let branch = manager.register_agent(agent_id, 100); + + // Suspend branch + manager.suspend(branch).expect("Suspend active branch"); + let inc = manager.get_incarnation(&branch).unwrap(); + assert_eq!(inc.physical_state.compute_state, ComputeState::Suspended); + + // Suspending already suspended branch must fail + assert!(matches!( + manager.suspend(branch), + Err(StateError::AlreadySuspended(_)) + )); + + // Resume branch returns new sequence ID and transitions to Idle + let seq = manager.resume(branch).expect("Resume branch"); + assert!(seq > 0); + let inc_resumed = manager.get_incarnation(&branch).unwrap(); + assert_eq!(inc_resumed.physical_state.compute_state, ComputeState::Idle); + + // Tamper detection on checkpoint restore + let mut valid_checkpoint = manager.export_checkpoint(agent_id).unwrap(); + // Corrupt one byte in payload JSON + let last_idx = valid_checkpoint.len() - 5; + valid_checkpoint[last_idx] ^= 0x55; + + let restore_result = AgentStateManager::restore_from_checkpoint(&valid_checkpoint, 2); + assert!( + matches!( + restore_result, + Err(StateError::ChecksumMismatch) | Err(StateError::DeserializationError(_)) + ), + "Corrupted checkpoint must be detected and rejected" + ); + } +} diff --git a/crates/aienos-c1-tree/Cargo.toml b/crates/aienos-c1-tree/Cargo.toml new file mode 100644 index 00000000..59fd9da9 --- /dev/null +++ b/crates/aienos-c1-tree/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "aienos-c1-tree" +version.workspace = true +edition.workspace = true +authors.workspace = true +license.workspace = true +repository.workspace = true +description = "AIENOS Phase 4: C1 Copy-On-Write Prefix Tree with physical KV page sharing (hardware-accelerated in Phase 5)" + +[dependencies] +aienos-kernel = { workspace = true } +aienos-agent-state = { workspace = true } +serde = { workspace = true, features = ["derive", "alloc"] } +serde_json = { workspace = true, features = ["alloc"] } diff --git a/crates/aienos-c1-tree/src/lib.rs b/crates/aienos-c1-tree/src/lib.rs new file mode 100644 index 00000000..860b51a1 --- /dev/null +++ b/crates/aienos-c1-tree/src/lib.rs @@ -0,0 +1,14 @@ +//! AIENOS C1 Copy-On-Write Prefix Tree (§10, §28). +//! +//! Provides zero-duplication prefix sharing across reasoning branches, +//! deterministic Copy-On-Write divergence, and complete eviction independence. + +pub mod metrics; +pub mod page; +pub mod pool; +pub mod tree; + +pub use metrics::C1MemoryMetrics; +pub use page::{PageId, PhysicalKvPage, PAGE_CAPACITY_TOKENS, PAGE_KV_BYTES}; +pub use pool::PhysicalPagePool; +pub use tree::{BranchDescriptor, C1Error, C1PrefixTree, ReservationReceipt}; diff --git a/crates/aienos-c1-tree/src/metrics.rs b/crates/aienos-c1-tree/src/metrics.rs new file mode 100644 index 00000000..6148e5a6 --- /dev/null +++ b/crates/aienos-c1-tree/src/metrics.rs @@ -0,0 +1,13 @@ +//! Memory metrics for C1 Copy-On-Write Prefix Tree verification. + +use serde::{Deserialize, Serialize}; + +/// Performance and memory metrics proving sub-linear scaling and zero-copy branching. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct C1MemoryMetrics { + pub physical_pages_allocated: usize, + pub physical_memory_bytes: usize, + pub total_virtual_tokens: usize, + pub total_unique_physical_tokens: usize, + pub sharing_ratio: f64, +} diff --git a/crates/aienos-c1-tree/src/page.rs b/crates/aienos-c1-tree/src/page.rs new file mode 100644 index 00000000..021ea3bd --- /dev/null +++ b/crates/aienos-c1-tree/src/page.rs @@ -0,0 +1,108 @@ +//! Physical KV Page representation for C1 Copy-On-Write memory engine (§10, §28). + +use aienos_kernel::crypto::sha256; +use core::fmt; +use serde::{Deserialize, Serialize}; + +/// Number of tokens stored per physical KV page frame. +pub const PAGE_CAPACITY_TOKENS: usize = 64; + +/// Simulated embedding / KV tensor bytes per token slot (e.g. 128 f32 elements = 512 bytes). +pub const KV_ELEMENTS_PER_TOKEN: usize = 128; +pub const PAGE_KV_BYTES: usize = PAGE_CAPACITY_TOKENS * KV_ELEMENTS_PER_TOKEN * 4; + +/// Physical KV Page frame identifier. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +pub struct PageId(pub u64); + +impl fmt::Debug for PageId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "PageId(0x{:08x})", self.0) + } +} + +impl fmt::Display for PageId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "0x{:08x}", self.0) + } +} + +/// Physical Key-Value Page holding prefix cache on bare-metal accelerator memory. +#[derive(Clone, Debug, PartialEq)] +pub struct PhysicalKvPage { + pub page_id: PageId, + pub tokens: [u32; PAGE_CAPACITY_TOKENS], + pub len: usize, + pub ref_count: usize, + pub kv_cache: Vec<f32>, + pub checksum: [u8; 32], +} + +impl PhysicalKvPage { + /// Allocate an empty physical page frame. + pub fn new(page_id: PageId) -> Self { + Self { + page_id, + tokens: [0u32; PAGE_CAPACITY_TOKENS], + len: 0, + ref_count: 1, + kv_cache: vec![0.0; PAGE_CAPACITY_TOKENS * KV_ELEMENTS_PER_TOKEN], + checksum: [0u8; 32], + } + } + + /// Check if page has reached its maximum token capacity. + pub fn is_full(&self) -> bool { + self.len >= PAGE_CAPACITY_TOKENS + } + + /// Explicit block ownership (ADR 0005): shared immutable block. + pub fn is_shared(&self) -> bool { + self.ref_count > 1 + } + + /// Explicit block ownership (ADR 0005): private mutable block. + pub fn is_private(&self) -> bool { + self.ref_count == 1 + } + + /// Append a token and update its physical KV cache slot and cryptographic checksum. + pub fn append(&mut self, token_id: u32) -> bool { + if self.is_full() { + return false; + } + + let idx = self.len; + self.tokens[idx] = token_id; + + // Deterministically synthesize KV cache slot from token ID + let base = idx * KV_ELEMENTS_PER_TOKEN; + for i in 0..KV_ELEMENTS_PER_TOKEN { + self.kv_cache[base + i] = ((token_id as f32) * 0.01) + (i as f32 * 0.001); + } + + self.len += 1; + self.recompute_checksum(); + true + } + + /// Recompute SHA-256 checksum over page tokens and physical KV data. + pub fn recompute_checksum(&mut self) { + let mut hasher = sha256::Sha256::new(); + hasher.update(&self.page_id.0.to_be_bytes()); + for i in 0..self.len { + hasher.update(&self.tokens[i].to_be_bytes()); + } + self.checksum = hasher.finalize(); + } + + /// Verify cryptographic integrity of physical KV page against SHA-256 checksum. + pub fn verify_checksum(&self) -> bool { + let mut hasher = sha256::Sha256::new(); + hasher.update(&self.page_id.0.to_be_bytes()); + for i in 0..self.len { + hasher.update(&self.tokens[i].to_be_bytes()); + } + hasher.finalize() == self.checksum + } +} diff --git a/crates/aienos-c1-tree/src/pool.rs b/crates/aienos-c1-tree/src/pool.rs new file mode 100644 index 00000000..ecfbcd38 --- /dev/null +++ b/crates/aienos-c1-tree/src/pool.rs @@ -0,0 +1,85 @@ +//! Physical page pool managing accelerator memory allocation and reference counting. + +use crate::page::{PageId, PhysicalKvPage, PAGE_KV_BYTES}; +use std::collections::HashMap; + +/// Pool managing physical KV pages with atomic reference tracking. +#[derive(Default)] +pub struct PhysicalPagePool { + pages: HashMap<PageId, PhysicalKvPage>, + next_id: u64, +} + +impl PhysicalPagePool { + /// Initialize an empty physical page pool. + pub fn new() -> Self { + Self { + pages: HashMap::new(), + next_id: 1, + } + } + + /// Allocate a new physical KV page. + pub fn allocate(&mut self) -> PageId { + let id = PageId(self.next_id); + self.next_id += 1; + self.pages.insert(id, PhysicalKvPage::new(id)); + id + } + + /// Reference an existing page by ID. + pub fn get(&self, id: PageId) -> Option<&PhysicalKvPage> { + self.pages.get(&id) + } + + /// Mutable reference to an existing page by ID. + pub fn get_mut(&mut self, id: PageId) -> Option<&mut PhysicalKvPage> { + self.pages.get_mut(&id) + } + + /// Increment reference count when sharing a page across branches. + pub fn retain(&mut self, id: PageId) { + if let Some(p) = self.pages.get_mut(&id) { + p.ref_count += 1; + } + } + + /// Decrement reference count. If count reaches 0, free page frame immediately. + pub fn release(&mut self, id: PageId) { + if let Some(p) = self.pages.get_mut(&id) { + p.ref_count = p.ref_count.saturating_sub(1); + if p.ref_count == 0 { + self.pages.remove(&id); + } + } + } + + /// Perform Copy-On-Write: clone page contents into a new private frame, + /// decrementing the shared parent's ref_count. + pub fn clone_on_write(&mut self, source_id: PageId) -> PageId { + let new_id = PageId(self.next_id); + self.next_id += 1; + + let mut new_page = PhysicalKvPage::new(new_id); + if let Some(source) = self.pages.get(&source_id) { + new_page.tokens = source.tokens; + new_page.len = source.len; + new_page.kv_cache = source.kv_cache.clone(); + new_page.recompute_checksum(); + } + + self.release(source_id); + self.pages.insert(new_id, new_page); + new_id + } + + /// Total active physical pages currently residing in accelerator memory. + pub fn allocated_page_count(&self) -> usize { + self.pages.len() + } + + /// Total physical bytes occupied by active KV pages. + pub fn physical_memory_bytes(&self) -> usize { + self.pages.len() * PAGE_KV_BYTES + } +} diff --git a/crates/aienos-c1-tree/src/tree.rs b/crates/aienos-c1-tree/src/tree.rs new file mode 100644 index 00000000..19bece6a --- /dev/null +++ b/crates/aienos-c1-tree/src/tree.rs @@ -0,0 +1,501 @@ +//! C1 Copy-On-Write Prefix Tree engine (§10, §28). + +use crate::metrics::C1MemoryMetrics; +use crate::page::{PageId, PAGE_CAPACITY_TOKENS}; +use crate::pool::PhysicalPagePool; +use aienos_agent_state::LogicalBranchId; +use core::fmt; +use std::collections::HashMap; + +/// Errors occurring during C1 prefix tree operations. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum C1Error { + BranchNotFound(LogicalBranchId), + BranchEvicted(LogicalBranchId), + BranchAlreadyExists(LogicalBranchId), + CorruptedPage(PageId), + ReservationQuotaExceeded { requested: usize, available: usize }, +} + +impl fmt::Display for C1Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::BranchNotFound(b) => write!(f, "C1 branch not found: {}", b), + Self::BranchEvicted(b) => { + write!(f, "C1 branch physical KV is currently evicted: {}", b) + } + Self::BranchAlreadyExists(b) => write!(f, "C1 branch already exists: {}", b), + Self::CorruptedPage(p) => write!(f, "Physical KV page corrupted: {}", p), + Self::ReservationQuotaExceeded { + requested, + available, + } => write!( + f, + "KV reservation quota exceeded: requested {} pages, available {}", + requested, available + ), + } + } +} + +/// Transactional KV step reservation receipt (ADR 0005). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ReservationReceipt { + pub branch_id: LogicalBranchId, + pub tokens_reserved: usize, + pub pages_reserved: usize, + pub reservation_tick: u64, +} + +/// Descriptor tracking physical KV page table bindings for a reasoning branch. +#[derive(Clone, Debug)] +pub struct BranchDescriptor { + pub branch_id: LogicalBranchId, + pub page_ids: Vec<PageId>, + pub total_tokens: usize, + pub evicted: bool, +} + +/// The C1 Prefix Tree: Bare-metal copy-on-write KV engine for agent branching. +#[derive(Default)] +pub struct C1PrefixTree { + pool: PhysicalPagePool, + branches: HashMap<LogicalBranchId, BranchDescriptor>, +} + +impl C1PrefixTree { + /// Initialize an empty C1 prefix tree. + pub fn new() -> Self { + Self::default() + } + + /// Access underlying physical page pool. + pub fn pool(&self) -> &PhysicalPagePool { + &self.pool + } + + /// Initialize a new root reasoning branch populated with a prompt token sequence. + pub fn create_root_branch( + &mut self, + branch_id: LogicalBranchId, + prompt_tokens: &[u32], + ) -> Result<(), C1Error> { + if self.branches.contains_key(&branch_id) { + return Err(C1Error::BranchAlreadyExists(branch_id)); + } + + let mut desc = BranchDescriptor { + branch_id, + page_ids: Vec::new(), + total_tokens: 0, + evicted: false, + }; + + for &tok in prompt_tokens { + Self::append_single_token(&mut self.pool, &mut desc, tok)?; + } + + self.branches.insert(branch_id, desc); + Ok(()) + } + + /// Fork an existing reasoning branch with ZERO memory duplication (§10). + /// + /// The child branch points directly to the parent's physical KV pages. + /// Memory overhead of fork = 0 bytes! + pub fn fork_branch( + &mut self, + parent_id: LogicalBranchId, + child_id: LogicalBranchId, + ) -> Result<(), C1Error> { + let parent = self + .branches + .get(&parent_id) + .ok_or(C1Error::BranchNotFound(parent_id))? + .clone(); + + if parent.evicted { + return Err(C1Error::BranchEvicted(parent_id)); + } + + if self.branches.contains_key(&child_id) { + return Err(C1Error::BranchAlreadyExists(child_id)); + } + + // Increment reference count on all shared physical pages + for &pid in &parent.page_ids { + self.pool.retain(pid); + } + + let child = BranchDescriptor { + branch_id: child_id, + page_ids: parent.page_ids.clone(), + total_tokens: parent.total_tokens, + evicted: false, + }; + + self.branches.insert(child_id, child); + Ok(()) + } + + /// Explicit transactional KV reservation prior to step admission (ADR 0005). + pub fn reserve_step_capacity( + &self, + branch_id: LogicalBranchId, + num_tokens: usize, + tick: u64, + max_pool_pages: usize, + ) -> Result<ReservationReceipt, C1Error> { + let desc = self + .branches + .get(&branch_id) + .ok_or(C1Error::BranchNotFound(branch_id))?; + + if desc.evicted { + return Err(C1Error::BranchEvicted(branch_id)); + } + + let needed_pages = num_tokens.div_ceil(PAGE_CAPACITY_TOKENS); + let current_allocated = self.pool.allocated_page_count(); + if current_allocated + needed_pages > max_pool_pages { + return Err(C1Error::ReservationQuotaExceeded { + requested: needed_pages, + available: max_pool_pages.saturating_sub(current_allocated), + }); + } + + Ok(ReservationReceipt { + branch_id, + tokens_reserved: num_tokens, + pages_reserved: needed_pages, + reservation_tick: tick, + }) + } + + /// Append tokens to an active reasoning branch, triggering Copy-On-Write only upon divergence. + pub fn append_tokens( + &mut self, + branch_id: LogicalBranchId, + tokens: &[u32], + ) -> Result<(), C1Error> { + let mut desc = self + .branches + .get(&branch_id) + .ok_or(C1Error::BranchNotFound(branch_id))? + .clone(); + + if desc.evicted { + return Err(C1Error::BranchEvicted(branch_id)); + } + + for &tok in tokens { + Self::append_single_token(&mut self.pool, &mut desc, tok)?; + } + + self.branches.insert(branch_id, desc); + Ok(()) + } + + fn append_single_token( + pool: &mut PhysicalPagePool, + desc: &mut BranchDescriptor, + token_id: u32, + ) -> Result<(), C1Error> { + if desc.page_ids.is_empty() { + let pid = pool.allocate(); + let page = pool.get_mut(pid).unwrap(); + page.append(token_id); + desc.page_ids.push(pid); + desc.total_tokens += 1; + return Ok(()); + } + + let last_pid = *desc.page_ids.last().unwrap(); + let page = pool.get(last_pid).ok_or(C1Error::CorruptedPage(last_pid))?; + if !page.verify_checksum() { + return Err(C1Error::CorruptedPage(last_pid)); + } + + if !page.is_full() { + if page.ref_count == 1 { + // Exclusive ownership: append directly + let page_mut = pool.get_mut(last_pid).unwrap(); + page_mut.append(token_id); + } else { + // Shared page: perform Copy-On-Write! + let new_pid = pool.clone_on_write(last_pid); + let page_mut = pool.get_mut(new_pid).unwrap(); + page_mut.append(token_id); + // Replace last page with private page in this branch + let last_idx = desc.page_ids.len() - 1; + desc.page_ids[last_idx] = new_pid; + } + } else { + // Last page is full: allocate a brand new page + let new_pid = pool.allocate(); + let page_mut = pool.get_mut(new_pid).unwrap(); + page_mut.append(token_id); + desc.page_ids.push(new_pid); + } + + desc.total_tokens += 1; + Ok(()) + } + + /// Retrieve complete token sequence for a branch. + pub fn get_tokens(&self, branch_id: LogicalBranchId) -> Result<Vec<u32>, C1Error> { + let desc = self + .branches + .get(&branch_id) + .ok_or(C1Error::BranchNotFound(branch_id))?; + + if desc.evicted { + return Err(C1Error::BranchEvicted(branch_id)); + } + + let mut out = Vec::with_capacity(desc.total_tokens); + for &pid in &desc.page_ids { + let page = self.pool.get(pid).ok_or(C1Error::CorruptedPage(pid))?; + if !page.verify_checksum() { + return Err(C1Error::CorruptedPage(pid)); + } + for i in 0..page.len { + out.push(page.tokens[i]); + } + } + Ok(out) + } + + /// Evict physical KV pages for a branch to simulate memory reclamation. + pub fn evict_branch(&mut self, branch_id: LogicalBranchId) -> Result<(), C1Error> { + let desc = self + .branches + .get_mut(&branch_id) + .ok_or(C1Error::BranchNotFound(branch_id))?; + + if desc.evicted { + return Ok(()); + } + + for &pid in &desc.page_ids { + self.pool.release(pid); + } + desc.page_ids.clear(); + desc.evicted = true; + Ok(()) + } + + /// Remove and deallocate an exploratory or completed reasoning branch, releasing all its pages. + pub fn remove_branch(&mut self, branch_id: LogicalBranchId) -> Result<(), C1Error> { + let desc = self + .branches + .remove(&branch_id) + .ok_or(C1Error::BranchNotFound(branch_id))?; + + if !desc.evicted { + for &pid in &desc.page_ids { + self.pool.release(pid); + } + } + Ok(()) + } + + /// Reconstruct physical KV pages deterministically from token sequence. + /// Re-allocates pages cleanly without leaking existing physical frames. + pub fn reconstruct_branch( + &mut self, + branch_id: LogicalBranchId, + tokens: &[u32], + ) -> Result<(), C1Error> { + let desc = self + .branches + .get_mut(&branch_id) + .ok_or(C1Error::BranchNotFound(branch_id))?; + + if !desc.evicted { + for &pid in &desc.page_ids { + self.pool.release(pid); + } + } + + desc.page_ids.clear(); + desc.total_tokens = 0; + desc.evicted = false; + + for &tok in tokens { + Self::append_single_token(&mut self.pool, desc, tok)?; + } + + Ok(()) + } + + /// Compute memory and sharing metrics across all branches. + pub fn memory_metrics(&self) -> C1MemoryMetrics { + let physical_pages = self.pool.allocated_page_count(); + let physical_bytes = self.pool.physical_memory_bytes(); + let total_virtual_tokens: usize = self.branches.values().map(|b| b.total_tokens).sum(); + let total_unique_physical_tokens: usize = physical_pages * PAGE_CAPACITY_TOKENS; + + let sharing_ratio = if total_unique_physical_tokens > 0 { + total_virtual_tokens as f64 / total_unique_physical_tokens as f64 + } else { + 1.0 + }; + + C1MemoryMetrics { + physical_pages_allocated: physical_pages, + physical_memory_bytes: physical_bytes, + total_virtual_tokens, + total_unique_physical_tokens, + sharing_ratio, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use aienos_agent_state::{LogicalAgentId, LogicalBranchId}; + use std::sync::{Arc, Mutex}; + use std::thread; + + #[test] + fn test_zero_memory_increase_on_10k_tokens_fork() { + let mut tree = C1PrefixTree::new(); + let agent = LogicalAgentId::from_seed("c1-cow-test"); + let root_branch = LogicalBranchId::root_branch(agent); + + // 1. Create a 10,000-token prompt + let prompt_tokens: Vec<u32> = (0..10_000).map(|i| 1000 + (i % 50000)).collect(); + tree.create_root_branch(root_branch, &prompt_tokens) + .unwrap(); + + let initial_pages = tree.pool().allocated_page_count(); + let initial_bytes = tree.pool().physical_memory_bytes(); + assert_eq!(initial_pages, 10_000_usize.div_ceil(PAGE_CAPACITY_TOKENS)); + + // 2. Fork into 10 concurrent exploratory branches + let mut child_branches = Vec::new(); + for i in 0..10 { + let child = LogicalBranchId::derive(root_branch, i); + tree.fork_branch(root_branch, child).unwrap(); + child_branches.push(child); + } + + // ACCEPTANCE CRITERIA VERIFICATION: + // Demonstrates ZERO memory increase when branching a 10,000-token prefix across 10 concurrent exploratory branches! + let post_fork_pages = tree.pool().allocated_page_count(); + let post_fork_bytes = tree.pool().physical_memory_bytes(); + assert_eq!( + initial_pages, post_fork_pages, + "Physical pages allocated must NOT increase upon branching" + ); + assert_eq!( + initial_bytes, post_fork_bytes, + "Physical memory bytes must NOT increase upon branching (ZERO overhead)" + ); + + // 3. Verify deterministic divergence upon appending tokens + for (i, &child) in child_branches.iter().enumerate() { + tree.append_tokens(child, &[9999 + i as u32]).unwrap(); + let tokens = tree.get_tokens(child).unwrap(); + assert_eq!(tokens.len(), 10_001); + assert_eq!(tokens[10_000], 9999 + i as u32); + } + + // After appending 1 divergent token each, only private pages allocated for divergent step + let post_divergence_pages = tree.pool().allocated_page_count(); + assert_eq!(post_divergence_pages, initial_pages + 10); + } + + #[test] + fn test_transactional_kv_reservation() { + let mut tree = C1PrefixTree::new(); + let agent = LogicalAgentId::from_seed("reservation-test"); + let root = LogicalBranchId::root_branch(agent); + tree.create_root_branch(root, &[1, 2, 3]).unwrap(); + + // Limit pool to 10 pages total + let receipt = tree.reserve_step_capacity(root, 64, 42, 10).unwrap(); + assert_eq!(receipt.pages_reserved, 1); + assert_eq!(receipt.tokens_reserved, 64); + + // Try reserving more pages than available in quota + let overflow = tree.reserve_step_capacity(root, 1000, 43, 10); + assert!(matches!( + overflow, + Err(C1Error::ReservationQuotaExceeded { .. }) + )); + } + + #[test] + fn test_reconstruct_branch_no_page_leak() { + let mut tree = C1PrefixTree::new(); + let agent = LogicalAgentId::from_seed("reconstruct-leak-test"); + let root = LogicalBranchId::root_branch(agent); + tree.create_root_branch(root, &[10, 20, 30]).unwrap(); + let initial_pages = tree.pool().allocated_page_count(); + assert_eq!(initial_pages, 1); + + // Reconstructing an active branch must release previous pages and allocate clean ones without leak + tree.reconstruct_branch(root, &[10, 20, 30]).unwrap(); + assert_eq!(tree.pool().allocated_page_count(), initial_pages); + + // Remove branch should release all pages back to 0 + tree.remove_branch(root).unwrap(); + assert_eq!(tree.pool().allocated_page_count(), 0); + } + + #[test] + fn test_concurrent_multithreaded_branching_and_reservations() { + let tree = Arc::new(Mutex::new(C1PrefixTree::new())); + let agent = LogicalAgentId::from_seed("concurrent-c1-agent"); + let root = LogicalBranchId::root_branch(agent); + + { + let mut t = tree.lock().unwrap(); + let prompt: Vec<u32> = (0..128).collect(); + t.create_root_branch(root, &prompt).unwrap(); + } + + let mut handles = Vec::new(); + for worker_id in 0..8 { + let tree_clone = Arc::clone(&tree); + let handle = thread::spawn(move || { + let child = LogicalBranchId::derive(root, worker_id); + { + let mut t = tree_clone.lock().unwrap(); + t.fork_branch(root, child).unwrap(); + } + + // Reserve capacity + { + let t = tree_clone.lock().unwrap(); + let res = t + .reserve_step_capacity(child, 16, 100 + worker_id, 1000) + .unwrap(); + assert_eq!(res.tokens_reserved, 16); + } + + // Append divergent tokens + { + let mut t = tree_clone.lock().unwrap(); + t.append_tokens(child, &[5000 + worker_id as u32]).unwrap(); + let tokens = t.get_tokens(child).unwrap(); + assert_eq!(tokens.len(), 129); + assert_eq!(tokens[128], 5000 + worker_id as u32); + } + }); + handles.push(handle); + } + + for h in handles { + h.join().unwrap(); + } + + let t = tree.lock().unwrap(); + let metrics = t.memory_metrics(); + assert_eq!(metrics.total_virtual_tokens, 128 + 8 * 129); + assert!(metrics.sharing_ratio > 1.0); + } +} diff --git a/crates/aienos-cortex/Cargo.toml b/crates/aienos-cortex/Cargo.toml new file mode 100644 index 00000000..f4b1ddda --- /dev/null +++ b/crates/aienos-cortex/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "aienos-cortex" +version.workspace = true +edition.workspace = true +authors.workspace = true +license.workspace = true +repository.workspace = true +description = "AIENOS Phase 3: Cortex Epistemic Store with verifiable provenance" + +[dependencies] +aienos-kernel = { workspace = true } +serde = { workspace = true, features = ["derive", "alloc"] } +serde_json = { workspace = true, features = ["alloc"] } diff --git a/crates/aienos-cortex/src/lib.rs b/crates/aienos-cortex/src/lib.rs new file mode 100644 index 00000000..d2fa6549 --- /dev/null +++ b/crates/aienos-cortex/src/lib.rs @@ -0,0 +1,15 @@ +//! AIENOS Cortex Epistemic Store (§11). +//! +//! Preserves durable epistemic memory with verifiable provenance: +//! DirectObservation, VerifiedFact, Inference, Hypothesis, Contradiction, OperatorDecision. +//! Rejects ungrounded model hallucinations and circular assertions. + +pub mod record; +pub mod status; +pub mod store; +pub mod verification; + +pub use record::EpistemicRecord; +pub use status::EpistemicStatus; +pub use store::{CortexStore, JournalEnvelope}; +pub use verification::{verify_grounding, CortexError}; diff --git a/crates/aienos-cortex/src/record.rs b/crates/aienos-cortex/src/record.rs new file mode 100644 index 00000000..886c8eb0 --- /dev/null +++ b/crates/aienos-cortex/src/record.rs @@ -0,0 +1,96 @@ +//! Epistemic records capturing knowledge with immutable provenance and evidence hashes. + +use crate::status::EpistemicStatus; +use aienos_kernel::crypto::sha256; +use core::fmt; +use serde::{Deserialize, Serialize}; + +/// Epistemic Record preserving knowledge with verifiable provenance. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct EpistemicRecord { + pub id: [u8; 16], + pub status: EpistemicStatus, + pub statement: String, + pub provenance_source: String, + pub evidence_hash: [u8; 32], + pub created_at_utc: u64, + pub confidence: f32, + pub verified_by: Option<String>, + pub causal_parents: Vec<[u8; 16]>, +} + +impl EpistemicRecord { + /// Create a new record with calculated deterministic evidence hash. + #[allow(clippy::too_many_arguments)] + pub fn new( + status: EpistemicStatus, + statement: impl Into<String>, + provenance_source: impl Into<String>, + evidence_payload: &[u8], + created_at_utc: u64, + confidence: f32, + verified_by: Option<String>, + causal_parents: Vec<[u8; 16]>, + ) -> Self { + let stmt = statement.into(); + let prov = provenance_source.into(); + + // Calculate cryptographic evidence hash: SHA-256(status || statement || provenance || payload) + let mut hasher = sha256::Sha256::new(); + hasher.update(&[status as u8]); + hasher.update(stmt.as_bytes()); + hasher.update(prov.as_bytes()); + hasher.update(evidence_payload); + for parent in &causal_parents { + hasher.update(parent); + } + let evidence_hash = hasher.finalize(); + + // Deterministic ID derived from evidence hash + timestamp + let mut id_hasher = sha256::Sha256::new(); + id_hasher.update(&evidence_hash); + id_hasher.update(&created_at_utc.to_be_bytes()); + let full_id = id_hasher.finalize(); + let mut id = [0u8; 16]; + id.copy_from_slice(&full_id[..16]); + + Self { + id, + status, + statement: stmt, + provenance_source: prov, + evidence_hash, + created_at_utc, + confidence: confidence.clamp(0.0, 1.0), + verified_by, + causal_parents, + } + } + + /// Hex-formatted string of record ID. + pub fn id_hex(&self) -> String { + self.id.iter().map(|b| format!("{:02x}", b)).collect() + } + + /// Hex-formatted string of evidence hash. + pub fn hash_hex(&self) -> String { + self.evidence_hash + .iter() + .map(|b| format!("{:02x}", b)) + .collect() + } +} + +impl fmt::Display for EpistemicRecord { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "[{:?}] ({}) \"{}\" (conf: {:.2}, prov: {})", + self.status, + &self.id_hex()[..8], + self.statement, + self.confidence, + self.provenance_source + ) + } +} diff --git a/crates/aienos-cortex/src/status.rs b/crates/aienos-cortex/src/status.rs new file mode 100644 index 00000000..145cb137 --- /dev/null +++ b/crates/aienos-cortex/src/status.rs @@ -0,0 +1,36 @@ +//! Epistemic status classifications conforming to AIENOS Blueprint §11 and Specs §2.3. + +use serde::{Deserialize, Serialize}; + +/// Epistemic status distinctions preserving provenance and preventing self-reinforcing hallucination. +#[repr(u8)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +pub enum EpistemicStatus { + /// Raw sensor, hardware register, or direct file input (ground truth). + DirectObservation = 1, + /// Mathematically, cryptographically, or deterministically verified fact. + VerifiedFact = 2, + /// Model deduction derived from observations or verified facts. + Inference = 3, + /// Tentative exploratory branch awaiting validation. + Hypothesis = 4, + /// Detected epistemic conflict between opposing assertions. + Contradiction = 5, + /// Canonical directive originating directly from the human operator. + OperatorDecision = 6, +} + +impl EpistemicStatus { + /// Check if this status constitutes an immutable grounding root. + pub fn is_ground_truth(&self) -> bool { + matches!( + self, + Self::DirectObservation | Self::VerifiedFact | Self::OperatorDecision + ) + } + + /// Check if this record is a derived or tentative assertion requiring grounding. + pub fn requires_grounding(&self) -> bool { + matches!(self, Self::Inference | Self::Hypothesis) + } +} diff --git a/crates/aienos-cortex/src/store.rs b/crates/aienos-cortex/src/store.rs new file mode 100644 index 00000000..fe760238 --- /dev/null +++ b/crates/aienos-cortex/src/store.rs @@ -0,0 +1,463 @@ +//! Cortex Epistemic Store engine managing the verifiable knowledge graph. + +use crate::record::EpistemicRecord; +use crate::status::EpistemicStatus; +use crate::verification::{verify_grounding, CortexError}; +use aienos_kernel::crypto::sha256; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; + +/// Epistemic Journal Envelope with cryptographic SHA-256 seal. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct JournalEnvelope { + pub records: Vec<EpistemicRecord>, + pub seal: [u8; 32], +} + +/// Persistent Epistemic Knowledge Store. +#[derive(Default)] +pub struct CortexStore { + records: HashMap<[u8; 16], EpistemicRecord>, + status_index: HashMap<EpistemicStatus, Vec<[u8; 16]>>, +} + +impl CortexStore { + /// Initialize a new empty Cortex store. + pub fn new() -> Self { + Self::default() + } + + /// Record a Direct Observation (hardware sensor, file read, physical input). + pub fn record_observation( + &mut self, + statement: impl Into<String>, + provenance_source: impl Into<String>, + raw_evidence: &[u8], + created_at_utc: u64, + ) -> EpistemicRecord { + let record = EpistemicRecord::new( + EpistemicStatus::DirectObservation, + statement, + provenance_source, + raw_evidence, + created_at_utc, + 1.0, + None, + Vec::new(), + ); + self.insert_record(record.clone()); + record + } + + /// Record a Mathematically or Cryptographically Verified Fact. + pub fn record_verified_fact( + &mut self, + statement: impl Into<String>, + provenance_source: impl Into<String>, + verifier_tool: &str, + proof_payload: &[u8], + causal_parents: Vec<[u8; 16]>, + created_at_utc: u64, + ) -> Result<EpistemicRecord, CortexError> { + let record = EpistemicRecord::new( + EpistemicStatus::VerifiedFact, + statement, + provenance_source, + proof_payload, + created_at_utc, + 1.0, + Some(verifier_tool.to_string()), + causal_parents, + ); + self.insert_record(record.clone()); + Ok(record) + } + + /// Record an Operator Decision (canonical directive from human operator). + pub fn record_operator_decision( + &mut self, + statement: impl Into<String>, + operator_signature: &str, + created_at_utc: u64, + ) -> EpistemicRecord { + let record = EpistemicRecord::new( + EpistemicStatus::OperatorDecision, + statement, + format!("operator:{}", operator_signature), + operator_signature.as_bytes(), + created_at_utc, + 1.0, + Some(operator_signature.to_string()), + Vec::new(), + ); + self.insert_record(record.clone()); + record + } + + /// Record an Inference deduced by a model. + /// + /// Invariant: Must strictly ground in DirectObservation, VerifiedFact, or OperatorDecision. + /// Rejects ungrounded model hallucinations. + pub fn record_inference( + &mut self, + statement: impl Into<String>, + model_name: impl Into<String>, + causal_parents: Vec<[u8; 16]>, + confidence: f32, + created_at_utc: u64, + ) -> Result<EpistemicRecord, CortexError> { + let record = EpistemicRecord::new( + EpistemicStatus::Inference, + statement, + model_name, + &[], + created_at_utc, + confidence, + None, + causal_parents, + ); + + // Strictly verify grounding in verified facts or observations + verify_grounding(&record, &|id| self.records.get(id))?; + + self.insert_record(record.clone()); + Ok(record) + } + + /// Record a tentative Hypothesis. + pub fn record_hypothesis( + &mut self, + statement: impl Into<String>, + agent_source: impl Into<String>, + causal_parents: Vec<[u8; 16]>, + created_at_utc: u64, + ) -> Result<EpistemicRecord, CortexError> { + let record = EpistemicRecord::new( + EpistemicStatus::Hypothesis, + statement, + agent_source, + &[], + created_at_utc, + 0.5, + None, + causal_parents, + ); + + // Verify grounding in valid parent records + verify_grounding(&record, &|id| self.records.get(id))?; + + self.insert_record(record.clone()); + Ok(record) + } + + /// Flag a detected Contradiction between two existing epistemic records. + pub fn flag_contradiction( + &mut self, + record_a_id: [u8; 16], + record_b_id: [u8; 16], + reason: &str, + created_at_utc: u64, + ) -> Result<EpistemicRecord, CortexError> { + if !self.records.contains_key(&record_a_id) { + return Err(CortexError::RecordNotFound(record_a_id)); + } + if !self.records.contains_key(&record_b_id) { + return Err(CortexError::RecordNotFound(record_b_id)); + } + + let record = EpistemicRecord::new( + EpistemicStatus::Contradiction, + format!("Contradiction detected: {}", reason), + "cortex_sentinel", + reason.as_bytes(), + created_at_utc, + 1.0, + None, + vec![record_a_id, record_b_id], + ); + + self.insert_record(record.clone()); + Ok(record) + } + + /// Retrieve an individual record by ID. + pub fn get(&self, id: &[u8; 16]) -> Option<&EpistemicRecord> { + self.records.get(id) + } + + /// Retrieve all records of a specific epistemic status. + pub fn find_by_status(&self, status: EpistemicStatus) -> Vec<&EpistemicRecord> { + self.status_index + .get(&status) + .map(|ids| ids.iter().filter_map(|id| self.records.get(id)).collect()) + .unwrap_or_default() + } + + /// Total records in store. + pub fn len(&self) -> usize { + self.records.len() + } + + /// Check if store is empty. + pub fn is_empty(&self) -> bool { + self.records.is_empty() + } + + fn insert_record(&mut self, record: EpistemicRecord) { + let id = record.id; + let status = record.status; + self.status_index.entry(status).or_default().push(id); + self.records.insert(id, record); + } + + /// Export durable journal with SHA-256 integrity seal. + pub fn export_journal(&self) -> Result<Vec<u8>, CortexError> { + let mut list: Vec<EpistemicRecord> = self.records.values().cloned().collect(); + // Deterministic sort by timestamp, then id + list.sort_by(|a, b| { + a.created_at_utc + .cmp(&b.created_at_utc) + .then_with(|| a.id.cmp(&b.id)) + }); + + let serialized = + serde_json::to_vec(&list).map_err(|e| CortexError::CorruptedJournal(e.to_string()))?; + let seal = sha256::hash(&serialized); + + let envelope = JournalEnvelope { + records: list, + seal, + }; + + serde_json::to_vec(&envelope).map_err(|e| CortexError::CorruptedJournal(e.to_string())) + } + + /// Import journal across reboot, verifying cryptographic seal and rebuilding indexes. + pub fn import_journal(&mut self, journal_data: &[u8]) -> Result<usize, CortexError> { + let envelope: JournalEnvelope = serde_json::from_slice(journal_data) + .map_err(|e| CortexError::CorruptedJournal(e.to_string()))?; + + let serialized = serde_json::to_vec(&envelope.records) + .map_err(|e| CortexError::CorruptedJournal(e.to_string()))?; + let computed_seal = sha256::hash(&serialized); + + if envelope.seal != computed_seal { + return Err(CortexError::IntegrityChecksumMismatch); + } + + let count = envelope.records.len(); + for record in envelope.records { + self.insert_record(record); + } + + Ok(count) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_epistemic_grounding_and_hallucination_rejection() { + let mut cortex = CortexStore::new(); + + // 1. Record raw hardware observation + let obs = cortex.record_observation( + "UART0 base physical address is 0x09000000", + "device_tree", + b"phys_uart0_reg", + 100, + ); + + // 2. Valid inference derived from observation + let inf = cortex + .record_inference( + "Driver can safely bind to UART0 MMIO", + "llama3-spark", + vec![obs.id], + 0.95, + 101, + ) + .expect("Valid grounded inference"); + assert_eq!(inf.status, EpistemicStatus::Inference); + + // Deep grounded inference: inf2 -> inf -> obs + let inf2 = cortex + .record_inference( + "Early console can initialize without Linux driver", + "llama3-spark", + vec![inf.id], + 0.90, + 102, + ) + .expect("Valid deep grounded inference"); + assert_eq!(inf2.status, EpistemicStatus::Inference); + + // 3. Hallucination test: attempt ungrounded inference (no parents) + let hallucination_empty = cortex.record_inference( + "The system has 1024 GB10 GPUs connected", + "speculative_model", + vec![], + 0.99, + 103, + ); + assert!(matches!( + hallucination_empty, + Err(CortexError::UngroundedAssertion(_)) + )); + + // 4. Hallucination test: circular inference with no ground truth + let mut circular_rec_a = EpistemicRecord::new( + EpistemicStatus::Inference, + "Claim A is true because Claim B is true", + "model_hallucination", + &[], + 104, + 0.8, + None, + vec![], // filled below + ); + let circular_rec_b = EpistemicRecord::new( + EpistemicStatus::Inference, + "Claim B is true because Claim A is true", + "model_hallucination", + &[], + 104, + 0.8, + None, + vec![circular_rec_a.id], + ); + circular_rec_a.causal_parents = vec![circular_rec_b.id]; + + // If we inject circular records manually into store, verify_grounding must detect cycle + cortex.insert_record(circular_rec_a.clone()); + cortex.insert_record(circular_rec_b.clone()); + + let res_a = verify_grounding(&circular_rec_a, &|id| cortex.get(id)); + assert!(matches!( + res_a, + Err(CortexError::CircularDependencyDetected(_)) + )); + + // 5. Hallucination test: references non-existent parent + let forged_id = [0xAAu8; 16]; + let hallucination_forged = cortex.record_inference( + "Secret backdoors exist in kernel", + "adversarial_prompt", + vec![forged_id], + 0.8, + 105, + ); + assert!(matches!( + hallucination_forged, + Err(CortexError::RecordNotFound(_)) + )); + + // 6. Mixed parent grounding rejection: one grounded observation + one ungrounded hallucination + // Must NOT allow the observation to mask the hallucinated parent! + let ungrounded_parent = EpistemicRecord::new( + EpistemicStatus::Inference, + "Fabricated premise with zero grounding", + "malicious_model", + &[], + 106, + 0.9, + None, + vec![], // No causal parents! + ); + cortex.insert_record(ungrounded_parent.clone()); + + let mixed_inference = cortex.record_inference( + "Hybrid inference based on observation AND fabrication", + "hybrid_model", + vec![obs.id, ungrounded_parent.id], + 0.85, + 107, + ); + assert!( + matches!(mixed_inference, Err(CortexError::UngroundedAssertion(_))), + "Inference containing even one ungrounded parent must be rejected" + ); + + // 7. Transitive grounding: Observation -> Hypothesis -> Inference + let hypo = cortex + .record_hypothesis( + "Hypothesis derived from valid observation", + "explorer_agent", + vec![obs.id], + 108, + ) + .expect("Hypothesis grounded in observation must succeed"); + + let transitive_inf = cortex + .record_inference( + "Inference deduced from verified hypothesis", + "reasoning_model", + vec![hypo.id], + 0.95, + 109, + ) + .expect("Transitively grounded inference must succeed"); + assert_eq!(transitive_inf.causal_parents, vec![hypo.id]); + + // 8. Flag contradiction between opposing assertions + let contradiction = cortex + .flag_contradiction( + obs.id, + ungrounded_parent.id, + "Hardware sensor disagrees with fabricated premise", + 110, + ) + .expect("Flag contradiction"); + assert_eq!(contradiction.status, EpistemicStatus::Contradiction); + } + + #[test] + fn test_cortex_persistence_and_status_queries() { + let mut cortex = CortexStore::new(); + let obs = cortex.record_observation("Boot completed at tick 42", "kernel_log", b"", 100); + let fact = cortex + .record_verified_fact( + "SHA256 test vector passes FIPS 180-4", + "test_suite", + "cargo_test", + b"proof", + vec![obs.id], + 101, + ) + .unwrap(); + + let op = cortex.record_operator_decision( + "Promote Phase 3 to canonical state", + "operator_ed25519_key", + 102, + ); + + assert_eq!( + cortex + .find_by_status(EpistemicStatus::DirectObservation) + .len(), + 1 + ); + assert_eq!( + cortex.find_by_status(EpistemicStatus::VerifiedFact).len(), + 1 + ); + assert_eq!( + cortex + .find_by_status(EpistemicStatus::OperatorDecision) + .len(), + 1 + ); + + // Export and restore across simulated reboot + let journal = cortex.export_journal().expect("Export journal"); + let mut restored = CortexStore::new(); + let imported_count = restored.import_journal(&journal).expect("Import journal"); + assert_eq!(imported_count, 3); + assert_eq!(restored.get(&obs.id).unwrap().statement, obs.statement); + assert_eq!(restored.get(&fact.id).unwrap().statement, fact.statement); + assert_eq!(restored.get(&op.id).unwrap().statement, op.statement); + } +} diff --git a/crates/aienos-cortex/src/verification.rs b/crates/aienos-cortex/src/verification.rs new file mode 100644 index 00000000..d1186243 --- /dev/null +++ b/crates/aienos-cortex/src/verification.rs @@ -0,0 +1,118 @@ +//! Grounding verification and hallucination detection for Cortex Epistemic Store. + +use crate::record::EpistemicRecord; +use core::fmt; +use std::collections::HashSet; + +/// Errors arising during Cortex epistemic storage or verification. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CortexError { + UngroundedAssertion(String), + CircularDependencyDetected(Vec<[u8; 16]>), + RecordNotFound([u8; 16]), + ContradictionDetected { + record_a: [u8; 16], + record_b: [u8; 16], + reason: String, + }, + CorruptedJournal(String), + IntegrityChecksumMismatch, +} + +impl fmt::Display for CortexError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::UngroundedAssertion(msg) => write!(f, "Ungrounded epistemic assertion: {}", msg), + Self::CircularDependencyDetected(cycle) => { + write!( + f, + "Circular epistemic dependency detected across {} records", + cycle.len() + ) + } + Self::RecordNotFound(id) => write!(f, "Epistemic record not found: {:02x?}", id), + Self::ContradictionDetected { + record_a, + record_b, + reason, + } => write!( + f, + "Contradiction between {:02x?} and {:02x?}: {}", + record_a, record_b, reason + ), + Self::CorruptedJournal(msg) => write!(f, "Corrupted epistemic journal: {}", msg), + Self::IntegrityChecksumMismatch => write!(f, "Journal cryptographic checksum mismatch"), + } + } +} + +/// Recursively verify that a record is strictly grounded in DirectObservation, VerifiedFact, or OperatorDecision. +/// +/// Invariant: Every causal ancestry branch MUST terminate in an immutable ground truth. +/// Rejects any assertion that relies even partially on ungrounded hypotheses or missing/circular evidence. +pub fn verify_grounding<'a, F>(record: &EpistemicRecord, lookup: &F) -> Result<(), CortexError> +where + F: Fn(&[u8; 16]) -> Option<&'a EpistemicRecord>, +{ + if record.status.is_ground_truth() { + return Ok(()); + } + + if record.causal_parents.is_empty() { + return Err(CortexError::UngroundedAssertion(format!( + "Assertion \"{}\" ({:?}) has no causal parent references", + record.statement, record.status + ))); + } + + let mut grounded_cache = HashSet::new(); + let mut path = vec![record.id]; + + fn check_node<'a, F>( + current_id: &[u8; 16], + lookup: &F, + grounded_cache: &mut HashSet<[u8; 16]>, + path: &mut Vec<[u8; 16]>, + ) -> Result<(), CortexError> + where + F: Fn(&[u8; 16]) -> Option<&'a EpistemicRecord>, + { + if path.contains(current_id) { + path.push(*current_id); + return Err(CortexError::CircularDependencyDetected(path.clone())); + } + + if grounded_cache.contains(current_id) { + return Ok(()); + } + + let current_rec = lookup(current_id).ok_or(CortexError::RecordNotFound(*current_id))?; + + if current_rec.status.is_ground_truth() { + grounded_cache.insert(*current_id); + return Ok(()); + } + + if current_rec.causal_parents.is_empty() { + return Err(CortexError::UngroundedAssertion(format!( + "Assertion \"{}\" ({:?}) has no causal parent references", + current_rec.statement, current_rec.status + ))); + } + + path.push(*current_id); + for parent_id in ¤t_rec.causal_parents { + check_node(parent_id, lookup, grounded_cache, path)?; + } + path.pop(); + + grounded_cache.insert(*current_id); + Ok(()) + } + + for parent_id in &record.causal_parents { + check_node(parent_id, lookup, &mut grounded_cache, &mut path)?; + } + + Ok(()) +} diff --git a/crates/aienos-kernel/Cargo.toml b/crates/aienos-kernel/Cargo.toml new file mode 100644 index 00000000..cf717d70 --- /dev/null +++ b/crates/aienos-kernel/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "aienos-kernel" +version.workspace = true +edition.workspace = true +authors.workspace = true +license.workspace = true +repository.workspace = true +description = "AIENOS bare-metal no_std kernel substrate for aarch64" + +[features] +default = ["std"] +std = [] + +[dependencies] diff --git a/crates/aienos-kernel/src/arch/aarch64.rs b/crates/aienos-kernel/src/arch/aarch64.rs new file mode 100644 index 00000000..981229de --- /dev/null +++ b/crates/aienos-kernel/src/arch/aarch64.rs @@ -0,0 +1,237 @@ +//! AArch64 bare-metal architecture primitives, MMIO, and UART for AIENOS. + +use core::marker::PhantomData; +use core::ptr::{read_volatile, write_volatile}; + +/// Memory-Mapped I/O Register abstraction for safe volatile access. +#[repr(transparent)] +pub struct MmioReg<T> { + addr: usize, + _marker: PhantomData<T>, +} + +impl<T: Copy> MmioReg<T> { + /// Create a new MMIO register accessor at the given physical/virtual address. + pub const fn new(addr: usize) -> Self { + Self { + addr, + _marker: PhantomData, + } + } + + /// Read volatile from MMIO register. + pub fn read(&self) -> T { + unsafe { read_volatile(self.addr as *const T) } + } + + /// Write volatile to MMIO register. + pub fn write(&self, value: T) { + unsafe { write_volatile(self.addr as *mut T, value) } + } +} + +/// AArch64 Exception Level query. +/// Returns 0 for EL0, 1 for EL1, 2 for EL2, 3 for EL3. +#[inline(always)] +pub fn current_el() -> u8 { + #[cfg(target_arch = "aarch64")] + { + let el: u64; + unsafe { + core::arch::asm!( + "mrs {0}, CurrentEL", + out(reg) el, + options(nomem, nostack) + ); + } + ((el >> 2) & 0x03) as u8 + } + #[cfg(not(target_arch = "aarch64"))] + { + 1 // Default mock EL1 for non-aarch64 hosts + } +} + +/// Data Memory Barrier (DMB). +#[inline(always)] +pub fn dmb() { + #[cfg(target_arch = "aarch64")] + unsafe { + core::arch::asm!("dmb sy", options(nostack)); + } +} + +/// Data Synchronization Barrier (DSB). +#[inline(always)] +pub fn dsb() { + #[cfg(target_arch = "aarch64")] + unsafe { + core::arch::asm!("dsb sy", options(nostack)); + } +} + +/// Instruction Synchronization Barrier (ISB). +#[inline(always)] +pub fn isb() { + #[cfg(target_arch = "aarch64")] + unsafe { + core::arch::asm!("isb", options(nostack)); + } +} + +/// Disable interrupts (set DAIF flags). +#[inline(always)] +pub fn disable_interrupts() { + #[cfg(target_arch = "aarch64")] + unsafe { + core::arch::asm!("msr daifset, #2", options(nomem, nostack)); + } +} + +/// Enable interrupts (clear DAIF flags). +#[inline(always)] +pub fn enable_interrupts() { + #[cfg(target_arch = "aarch64")] + unsafe { + core::arch::asm!("msr daifclr, #2", options(nomem, nostack)); + } +} + +/// Check if interrupts are enabled (I bit in DAIF). +#[inline(always)] +pub fn are_interrupts_enabled() -> bool { + #[cfg(target_arch = "aarch64")] + { + let daif: u64; + unsafe { + core::arch::asm!("mrs {0}, daif", out(reg) daif, options(nomem, nostack)); + } + (daif & (1 << 7)) == 0 + } + #[cfg(not(target_arch = "aarch64"))] + { + true + } +} + +/// Wait For Interrupt (WFI) instruction - places core into low-power sleep until interrupt. +#[inline(always)] +pub fn wfi() { + #[cfg(target_arch = "aarch64")] + unsafe { + core::arch::asm!("wfi", options(nomem, nostack)); + } + #[cfg(not(target_arch = "aarch64"))] + core::hint::spin_loop(); +} + +/// Wait For Event (WFE) instruction. +#[inline(always)] +pub fn wfe() { + #[cfg(target_arch = "aarch64")] + unsafe { + core::arch::asm!("wfe", options(nomem, nostack)); + } + #[cfg(not(target_arch = "aarch64"))] + core::hint::spin_loop(); +} + +/// Send Event (SEV) instruction. +#[inline(always)] +pub fn sev() { + #[cfg(target_arch = "aarch64")] + unsafe { + core::arch::asm!("sev", options(nomem, nostack)); + } +} + +/// Deterministic bare-metal halt loop: disables interrupts and sleeps in WFI. +pub fn halt() -> ! { + disable_interrupts(); + loop { + wfi(); + } +} + +/// Reference MMIO base address for PL011 UART on NVIDIA DGX Spark (Cortex-X925). +pub const SPARK_PL011_UART_BASE: usize = 0x16A0_0000; + +/// Reference MMIO base address for PL011 UART on QEMU AArch64 Virt machine. +pub const QEMU_VIRT_PL011_UART_BASE: usize = 0x0900_0000; + +/// Standard PL011 UART register offsets. +pub mod pl011_regs { + pub const UARTDR: usize = 0x00; + pub const UARTFR: usize = 0x18; + pub const UARTIBRD: usize = 0x24; + pub const UARTFBRD: usize = 0x28; + pub const UARTLCR_H: usize = 0x2C; + pub const UARTCR: usize = 0x30; + pub const UARTIMSC: usize = 0x38; + + pub const FR_BUSY: u32 = 1 << 3; + pub const FR_TXFF: u32 = 1 << 5; + pub const FR_RXFE: u32 = 1 << 4; +} + +/// Early boot UART driver for AArch64 bare-metal console output. +pub struct EarlyUart { + base_addr: usize, +} + +impl EarlyUart { + /// Create a new EarlyUart driver instance at the specified MMIO base address. + pub const fn new(base_addr: usize) -> Self { + Self { base_addr } + } + + /// Read raw register. + fn reg(&self, offset: usize) -> MmioReg<u32> { + MmioReg::new(self.base_addr + offset) + } + + /// Send a single byte through UART transmit FIFO. + pub fn write_byte(&self, b: u8) { + let fr = self.reg(pl011_regs::UARTFR); + let dr = self.reg(pl011_regs::UARTDR); + + // Wait until transmit FIFO has space (TXFF == 0) + while (fr.read() & pl011_regs::FR_TXFF) != 0 { + core::hint::spin_loop(); + } + + dr.write(b as u32); + } + + /// Transmit a UTF-8 string through UART. + pub fn write_str(&self, s: &str) { + for b in s.bytes() { + if b == b'\n' { + self.write_byte(b'\r'); + } + self.write_byte(b); + } + } + + /// Attempt to read a single byte from UART receive FIFO without blocking. + /// Returns None if receive FIFO is empty (RXFE == 1). + pub fn try_read_byte(&self) -> Option<u8> { + let fr = self.reg(pl011_regs::UARTFR); + if (fr.read() & pl011_regs::FR_RXFE) != 0 { + None + } else { + let dr = self.reg(pl011_regs::UARTDR); + Some((dr.read() & 0xFF) as u8) + } + } + + /// Read a single byte from UART, blocking until data arrives. + pub fn read_byte(&self) -> u8 { + loop { + if let Some(b) = self.try_read_byte() { + return b; + } + core::hint::spin_loop(); + } + } +} diff --git a/crates/aienos-kernel/src/arch/mod.rs b/crates/aienos-kernel/src/arch/mod.rs new file mode 100644 index 00000000..1f550c2e --- /dev/null +++ b/crates/aienos-kernel/src/arch/mod.rs @@ -0,0 +1,5 @@ +//! Architecture-specific abstractions for AIENOS bare-metal substrate. + +pub mod aarch64; + +pub use aarch64::*; diff --git a/crates/aienos-kernel/src/boot.rs b/crates/aienos-kernel/src/boot.rs new file mode 100644 index 00000000..d9c03f33 --- /dev/null +++ b/crates/aienos-kernel/src/boot.rs @@ -0,0 +1,71 @@ +//! AIENOS Bare-Metal Boot Spine (§Step 2 of Systems Integration Sequence). +//! +//! Provides the canonical reset vector / UEFI entry point `_start`, +//! the unadorned console banner, and the structured BootReceipt definition. + +use crate::arch::aarch64::{ + current_el, disable_interrupts, dsb, halt, isb, EarlyUart, SPARK_PL011_UART_BASE, +}; + +/// Deterministic, immutable boot receipt emitted by the native boot spine. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct BootReceipt { + pub boot_epoch: u64, + pub arch_magic: u32, // 0xAA64_0001 + pub exception_level: u8, + pub entry_status: u8, // 0 = Clean Entry + pub exit_status: u8, // 0 = Clean Halt + pub memory_detected_kb: u64, + pub kernel_sha256_prefix: [u8; 8], +} + +impl BootReceipt { + pub const ARCH_AARCH64: u32 = 0xAA64_0001; + + pub const fn new(epoch: u64, el: u8, mem_kb: u64, hash_prefix: [u8; 8]) -> Self { + Self { + boot_epoch: epoch, + arch_magic: Self::ARCH_AARCH64, + exception_level: el, + entry_status: 0, + exit_status: 0, + memory_detected_kb: mem_kb, + kernel_sha256_prefix: hash_prefix, + } + } +} + +/// Early kernel boot initialization executed directly from UEFI or reset vector. +pub fn early_kernel_init() -> ! { + // 1. Disable maskable interrupts + disable_interrupts(); + + // 2. Memory and instruction synchronization barriers + dsb(); + isb(); + + // 3. Early console UART output on DGX Spark MMIO (0x16A00000) + // Strictly unadorned console telemetry per Gate 2 specification + let uart = EarlyUart::new(SPARK_PL011_UART_BASE); + uart.write_str("\r\nAIENOS\r\n"); + uart.write_str("arch: aarch64\r\n"); + uart.write_str("boot: native\r\n"); + + let el = current_el(); + uart.write_str("exception_level: EL"); + uart.write_byte(b'0' + el); + uart.write_str("\r\n"); + + uart.write_str("kernel: alive\r\n"); + uart.write_str("halt: clean\r\n"); + + // 4. Deterministic non-model halt loop + halt(); +} + +/// Canonical bare-metal entry point when compiling for `#![no_std]` targets. +#[cfg(all(not(feature = "std"), not(test)))] +#[no_mangle] +pub unsafe extern "C" fn _start() -> ! { + early_kernel_init(); +} diff --git a/crates/aienos-kernel/src/crypto/mod.rs b/crates/aienos-kernel/src/crypto/mod.rs new file mode 100644 index 00000000..bedf892d --- /dev/null +++ b/crates/aienos-kernel/src/crypto/mod.rs @@ -0,0 +1,5 @@ +//! Sovereign cryptographic primitives for AIENOS. + +pub mod sha256; + +pub use sha256::{hash, Digest, Sha256}; diff --git a/crates/aienos-kernel/src/crypto/sha256.rs b/crates/aienos-kernel/src/crypto/sha256.rs new file mode 100644 index 00000000..12a3e3e9 --- /dev/null +++ b/crates/aienos-kernel/src/crypto/sha256.rs @@ -0,0 +1,219 @@ +//! Pure-Rust, sovereign SHA-256 implementation conforming to FIPS 180-4. +//! +//! Fully deterministic and zero-dependency, safe for bare-metal `#![no_std]`. + +/// 32-byte digest returned by SHA-256. +pub type Digest = [u8; 32]; + +const K: [u32; 64] = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, +]; + +/// SHA-256 state machine. +#[derive(Clone, Debug)] +pub struct Sha256 { + state: [u32; 8], + buffer: [u8; 64], + buf_len: usize, + total_len_bytes: u64, +} + +impl Default for Sha256 { + fn default() -> Self { + Self::new() + } +} + +impl Sha256 { + /// Initialize a new SHA-256 state with FIPS 180-4 standard IV. + pub const fn new() -> Self { + Self { + state: [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, + 0x5be0cd19, + ], + buffer: [0u8; 64], + buf_len: 0, + total_len_bytes: 0, + } + } + + /// Ingest a slice of bytes into the hasher. + pub fn update(&mut self, data: &[u8]) { + self.total_len_bytes = self.total_len_bytes.wrapping_add(data.len() as u64); + let mut offset = 0; + + // Fill remaining buffer if not empty + if self.buf_len > 0 { + let to_copy = core::cmp::min(64 - self.buf_len, data.len()); + self.buffer[self.buf_len..self.buf_len + to_copy].copy_from_slice(&data[..to_copy]); + self.buf_len += to_copy; + offset += to_copy; + + if self.buf_len == 64 { + let block = self.buffer; + Self::process_block(&mut self.state, &block); + self.buf_len = 0; + } + } + + // Process full 64-byte chunks + while offset + 64 <= data.len() { + let mut block = [0u8; 64]; + block.copy_from_slice(&data[offset..offset + 64]); + Self::process_block(&mut self.state, &block); + offset += 64; + } + + // Buffer remaining bytes + if offset < data.len() { + let rem = data.len() - offset; + self.buffer[..rem].copy_from_slice(&data[offset..]); + self.buf_len = rem; + } + } + + /// Finalize hash calculation and return the 32-byte digest. + pub fn finalize(mut self) -> Digest { + let bit_len = self.total_len_bytes.wrapping_mul(8); + + // Append 0x80 byte + self.buffer[self.buf_len] = 0x80; + self.buf_len += 1; + + // If buffer len > 56, pad with zeros, process block, then pad next block + if self.buf_len > 56 { + for b in &mut self.buffer[self.buf_len..64] { + *b = 0; + } + let block = self.buffer; + Self::process_block(&mut self.state, &block); + self.buffer = [0u8; 64]; + self.buf_len = 0; + } + + // Pad with zeros up to byte 56 + for b in &mut self.buffer[self.buf_len..56] { + *b = 0; + } + + // Append bit length as 64-bit big endian integer + self.buffer[56..64].copy_from_slice(&bit_len.to_be_bytes()); + let block = self.buffer; + Self::process_block(&mut self.state, &block); + + let mut out = [0u8; 32]; + for (i, word) in self.state.iter().enumerate() { + out[i * 4..(i + 1) * 4].copy_from_slice(&word.to_be_bytes()); + } + out + } + + fn process_block(state: &mut [u32; 8], block: &[u8; 64]) { + let mut w = [0u32; 64]; + for i in 0..16 { + w[i] = u32::from_be_bytes([ + block[i * 4], + block[i * 4 + 1], + block[i * 4 + 2], + block[i * 4 + 3], + ]); + } + + for i in 16..64 { + let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3); + let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10); + w[i] = w[i - 16] + .wrapping_add(s0) + .wrapping_add(w[i - 7]) + .wrapping_add(s1); + } + + let mut a = state[0]; + let mut b = state[1]; + let mut c = state[2]; + let mut d = state[3]; + let mut e = state[4]; + let mut f = state[5]; + let mut g = state[6]; + let mut h = state[7]; + + for i in 0..64 { + let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25); + let ch = (e & f) ^ ((!e) & g); + let temp1 = h + .wrapping_add(s1) + .wrapping_add(ch) + .wrapping_add(K[i]) + .wrapping_add(w[i]); + let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22); + let maj = (a & b) ^ (a & c) ^ (b & c); + let temp2 = s0.wrapping_add(maj); + + h = g; + g = f; + f = e; + e = d.wrapping_add(temp1); + d = c; + c = b; + b = a; + a = temp1.wrapping_add(temp2); + } + + state[0] = state[0].wrapping_add(a); + state[1] = state[1].wrapping_add(b); + state[2] = state[2].wrapping_add(c); + state[3] = state[3].wrapping_add(d); + state[4] = state[4].wrapping_add(e); + state[5] = state[5].wrapping_add(f); + state[6] = state[6].wrapping_add(g); + state[7] = state[7].wrapping_add(h); + } +} + +/// Compute the SHA-256 digest of arbitrary byte data. +pub fn hash(data: &[u8]) -> Digest { + let mut hasher = Sha256::new(); + hasher.update(data); + hasher.finalize() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_sha256_empty() { + // e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 + let res = hash(b""); + assert_eq!( + res, + [ + 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, + 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, + 0x78, 0x52, 0xb8, 0x55, + ] + ); + } + + #[test] + fn test_sha256_abc() { + // ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad + let res = hash(b"abc"); + assert_eq!( + res, + [ + 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, + 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, + 0xf2, 0x00, 0x15, 0xad, + ] + ); + } +} diff --git a/crates/aienos-kernel/src/lib.rs b/crates/aienos-kernel/src/lib.rs new file mode 100644 index 00000000..7714e819 --- /dev/null +++ b/crates/aienos-kernel/src/lib.rs @@ -0,0 +1,23 @@ +//! AIENOS Bare-Metal Kernel Substrate for AArch64 (DGX Spark). +//! +//! Provides minimal, sovereign, deterministic primitives: +//! - AArch64 MMIO, UART, and exception-level access +//! - Physical memory addressing and bitmap frame allocation +//! - Pure-Rust cryptographic hashing (SHA-256) +//! - Bare-metal synchronization (`SpinLock`) + +#![cfg_attr(not(feature = "std"), no_std)] + +pub mod arch; +pub mod boot; +pub mod crypto; +pub mod mem; +pub mod recovery; +pub mod store; +pub mod sync; + +#[cfg(all(not(feature = "std"), not(test)))] +#[panic_handler] +fn panic(_info: &core::panic::PanicInfo) -> ! { + arch::aarch64::halt(); +} diff --git a/crates/aienos-kernel/src/mem/frame_allocator.rs b/crates/aienos-kernel/src/mem/frame_allocator.rs new file mode 100644 index 00000000..34342d6b --- /dev/null +++ b/crates/aienos-kernel/src/mem/frame_allocator.rs @@ -0,0 +1,229 @@ +//! Deterministic physical memory and frame allocator primitives for AIENOS. + +/// Physical Page Size on AArch64 (4 KiB standard). +pub const PAGE_SIZE: usize = 4096; + +/// Physical address wrapper. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[repr(transparent)] +pub struct PhysAddr(pub usize); + +impl PhysAddr { + #[inline(always)] + pub const fn new(addr: usize) -> Self { + Self(addr) + } + + #[inline(always)] + pub const fn as_usize(self) -> usize { + self.0 + } + + #[inline(always)] + pub const fn is_page_aligned(self) -> bool { + self.0.is_multiple_of(PAGE_SIZE) + } + + #[inline(always)] + pub const fn align_up(self) -> Self { + Self((self.0 + PAGE_SIZE - 1) & !(PAGE_SIZE - 1)) + } + + #[inline(always)] + pub const fn align_down(self) -> Self { + Self(self.0 & !(PAGE_SIZE - 1)) + } + + #[inline(always)] + pub const fn offset(self, bytes: usize) -> Self { + Self(self.0 + bytes) + } +} + +/// Virtual address wrapper. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[repr(transparent)] +pub struct VirtAddr(pub usize); + +impl VirtAddr { + #[inline(always)] + pub const fn new(addr: usize) -> Self { + Self(addr) + } + + #[inline(always)] + pub const fn as_usize(self) -> usize { + self.0 + } + + #[inline(always)] + pub const fn is_page_aligned(self) -> bool { + self.0.is_multiple_of(PAGE_SIZE) + } +} + +/// Represents a single physical page frame. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Frame { + pub index: usize, +} + +impl Frame { + #[inline(always)] + pub const fn from_index(index: usize) -> Self { + Self { index } + } + + #[inline(always)] + pub const fn start_address(self, base: PhysAddr) -> PhysAddr { + PhysAddr(base.0 + self.index * PAGE_SIZE) + } +} + +/// Fixed-size bitmap frame allocator for deterministic bare-metal memory tracking. +/// +/// `FRAMES` is the total number of managed 4 KiB frames. +/// `WORDS` = `(FRAMES + 63) / 64`. +pub struct BitmapFrameAllocator<const WORDS: usize> { + base_addr: PhysAddr, + total_frames: usize, + bitmap: [u64; WORDS], + allocated_count: usize, +} + +impl<const WORDS: usize> BitmapFrameAllocator<WORDS> { + /// Initialize a new frame allocator for a physical memory region. + pub const fn new(base_addr: PhysAddr, total_frames: usize) -> Self { + Self { + base_addr, + total_frames, + bitmap: [0u64; WORDS], + allocated_count: 0, + } + } + + /// Total managed physical frames. + pub const fn total_frames(&self) -> usize { + self.total_frames + } + + /// Number of allocated frames. + pub const fn allocated_count(&self) -> usize { + self.allocated_count + } + + /// Number of free frames remaining. + pub const fn free_count(&self) -> usize { + self.total_frames.saturating_sub(self.allocated_count) + } + + /// Allocate a single physical frame. + pub fn allocate_frame(&mut self) -> Option<PhysAddr> { + for (word_idx, word) in self.bitmap.iter_mut().enumerate() { + if *word != !0u64 { + let bit_idx = word.trailing_ones() as usize; + let frame_idx = word_idx * 64 + bit_idx; + if frame_idx < self.total_frames { + *word |= 1u64 << bit_idx; + self.allocated_count += 1; + return Some(PhysAddr(self.base_addr.0 + frame_idx * PAGE_SIZE)); + } + } + } + None + } + + /// Free a previously allocated physical frame. + pub fn deallocate_frame(&mut self, addr: PhysAddr) -> bool { + if addr.0 < self.base_addr.0 { + return false; + } + let offset = addr.0 - self.base_addr.0; + let frame_idx = offset / PAGE_SIZE; + if frame_idx >= self.total_frames { + return false; + } + + let word_idx = frame_idx / 64; + let bit_idx = frame_idx % 64; + + if (self.bitmap[word_idx] & (1u64 << bit_idx)) != 0 { + self.bitmap[word_idx] &= !(1u64 << bit_idx); + self.allocated_count = self.allocated_count.saturating_sub(1); + true + } else { + false + } + } + + /// Allocate contiguous physical frames. + pub fn allocate_contiguous(&mut self, count: usize) -> Option<PhysAddr> { + if count == 0 || count > self.free_count() { + return None; + } + + let mut run_start = 0; + let mut current_run = 0; + + for i in 0..self.total_frames { + let word_idx = i / 64; + let bit_idx = i % 64; + let is_set = (self.bitmap[word_idx] & (1u64 << bit_idx)) != 0; + + if !is_set { + if current_run == 0 { + run_start = i; + } + current_run += 1; + if current_run == count { + // Mark run as allocated + for f in run_start..run_start + count { + let w = f / 64; + let b = f % 64; + self.bitmap[w] |= 1u64 << b; + } + self.allocated_count += count; + return Some(PhysAddr(self.base_addr.0 + run_start * PAGE_SIZE)); + } + } else { + current_run = 0; + } + } + + None + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_allocator_basic() { + let mut alloc = BitmapFrameAllocator::<4>::new(PhysAddr(0x1000_0000), 256); + assert_eq!(alloc.total_frames(), 256); + assert_eq!(alloc.free_count(), 256); + + let f0 = alloc.allocate_frame().expect("Alloc f0"); + assert_eq!(f0, PhysAddr(0x1000_0000)); + assert_eq!(alloc.allocated_count(), 1); + + let f1 = alloc.allocate_frame().expect("Alloc f1"); + assert_eq!(f1, PhysAddr(0x1000_1000)); + + assert!(alloc.deallocate_frame(f0)); + assert_eq!(alloc.allocated_count(), 1); + + // Re-allocation should pick reused f0 + let f0_reused = alloc.allocate_frame().expect("Realloc f0"); + assert_eq!(f0_reused, PhysAddr(0x1000_0000)); + } + + #[test] + fn test_alloc_contiguous() { + let mut alloc = BitmapFrameAllocator::<2>::new(PhysAddr(0x2000_0000), 128); + let block = alloc.allocate_contiguous(4).expect("Contiguous 4 frames"); + assert_eq!(block, PhysAddr(0x2000_0000)); + assert_eq!(alloc.allocated_count(), 4); + } +} diff --git a/crates/aienos-kernel/src/mem/mod.rs b/crates/aienos-kernel/src/mem/mod.rs new file mode 100644 index 00000000..e8953815 --- /dev/null +++ b/crates/aienos-kernel/src/mem/mod.rs @@ -0,0 +1,5 @@ +//! Physical memory management primitives for AIENOS kernel. + +pub mod frame_allocator; + +pub use frame_allocator::{BitmapFrameAllocator, Frame, PhysAddr, VirtAddr, PAGE_SIZE}; diff --git a/crates/aienos-kernel/src/recovery.rs b/crates/aienos-kernel/src/recovery.rs new file mode 100644 index 00000000..7750d7cb --- /dev/null +++ b/crates/aienos-kernel/src/recovery.rs @@ -0,0 +1,271 @@ +//! AIENOS Deterministic Recovery Core (ADR 0006). +//! +//! A non-model, deterministic subsystem for: +//! - Offline local operator credential authentication +//! - Transactional A/B boot slot rollback +//! - Deterministic WAL truncation upon corruption without AI dependencies + +use crate::crypto::sha256; + +/// Boot slot identifier for transactional updates. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BootSlot { + SlotA, + SlotB, +} + +impl BootSlot { + /// Return the alternate slot. + pub fn alternate(self) -> Self { + match self { + Self::SlotA => Self::SlotB, + Self::SlotB => Self::SlotA, + } + } +} + +/// Operational state of a boot slot. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SlotHealth { + Unverified, + ConfirmedGood, + FailedRollback, +} + +/// Transactional A/B slot manager for deterministic kernel rollback. +#[derive(Clone, Debug)] +pub struct SlotManager { + pub active_slot: BootSlot, + pub slot_a_health: SlotHealth, + pub slot_b_health: SlotHealth, + pub boot_attempts: u32, + pub max_boot_attempts: u32, +} + +impl SlotManager { + /// Initialize with SlotA as primary confirmed good. + pub fn new() -> Self { + Self { + active_slot: BootSlot::SlotA, + slot_a_health: SlotHealth::ConfirmedGood, + slot_b_health: SlotHealth::Unverified, + boot_attempts: 0, + max_boot_attempts: 3, + } + } + + /// Mark active slot as confirmed good after reaching health milestone. + pub fn mark_milestone_healthy(&mut self) { + self.boot_attempts = 0; + match self.active_slot { + BootSlot::SlotA => self.slot_a_health = SlotHealth::ConfirmedGood, + BootSlot::SlotB => self.slot_b_health = SlotHealth::ConfirmedGood, + } + } + + /// Record a failed boot attempt; triggers deterministic rollback if threshold exceeded. + pub fn record_boot_attempt(&mut self) -> bool { + self.boot_attempts += 1; + if self.boot_attempts >= self.max_boot_attempts { + // Trigger automatic rollback to alternate slot + match self.active_slot { + BootSlot::SlotA => self.slot_a_health = SlotHealth::FailedRollback, + BootSlot::SlotB => self.slot_b_health = SlotHealth::FailedRollback, + } + self.active_slot = self.active_slot.alternate(); + self.boot_attempts = 0; + true // Rolled back + } else { + false + } + } +} + +impl Default for SlotManager { + fn default() -> Self { + Self::new() + } +} + +/// Offline local operator credential verifier without network or model dependencies. +/// +/// Invariant (ADR 0006): Offline authentication must use Argon2id key derivation for human +/// passphrases before challenge-response (or hardware/FIDO keys); do not use bare SHA-256 +/// for password verification. Fast hashing over human passwords is strictly prohibited to +/// resist offline brute-force and dictionary attacks. +pub struct OperatorAuth; + +impl OperatorAuth { + /// Verify an operator authorization token against a high-entropy root key / derived credential. + /// + /// The `derived_key_hash` must represent either a hardware-sealed key (e.g. FIDO/YubiKey) + /// or a high-entropy root key derived from a human passphrase via Argon2id. + /// Bare SHA-256 password verification is strictly prohibited. + pub fn verify_offline_credentials( + derived_key_hash: &[u8; 32], + challenge: &[u8; 32], + signature: &[u8; 32], + ) -> bool { + let mut hasher = sha256::Sha256::new(); + hasher.update(derived_key_hash); + hasher.update(challenge); + let expected = hasher.finalize(); + &expected == signature + } +} + +/// Deterministic Write-Ahead Log frame recovery with truncation on corruption. +pub struct WalRecovery; + +impl WalRecovery { + /// Scan a serialized binary WAL log, validating per-record checksums. + /// + /// If corruption is encountered, deterministically truncates the log + /// at the last valid record boundary, preserving all uncorrupted history. + pub fn recover_and_truncate(raw_wal: &[u8]) -> (usize, usize) { + let mut offset = 0; + let mut valid_records = 0; + + while offset + 36 <= raw_wal.len() { + let record_len = u32::from_be_bytes([ + raw_wal[offset], + raw_wal[offset + 1], + raw_wal[offset + 2], + raw_wal[offset + 3], + ]) as usize; + + let expected_checksum = &raw_wal[offset + 4..offset + 36]; + let payload_start = offset + 36; + let payload_end = match payload_start.checked_add(record_len) { + Some(end) => end, + None => break, // Overflow in record length header: stop at valid boundary + }; + + if payload_end > raw_wal.len() { + // Incomplete or truncated record: stop at last valid boundary + break; + } + + let actual_checksum = sha256::hash(&raw_wal[payload_start..payload_end]); + if actual_checksum != expected_checksum { + // Corrupted record detected: halt and truncate log here + break; + } + + valid_records += 1; + offset = payload_end; + } + + let truncated_valid_bytes = offset; + (valid_records, truncated_valid_bytes) + } + + /// Helper to format a single WAL entry with 4-byte length and 32-byte SHA-256 checksum. + pub fn encode_entry(payload: &[u8], buf: &mut [u8]) -> usize { + let len = payload.len() as u32; + let checksum = sha256::hash(payload); + + let total_len = 36 + payload.len(); + if buf.len() < total_len { + return 0; + } + + buf[0..4].copy_from_slice(&len.to_be_bytes()); + buf[4..36].copy_from_slice(&checksum); + buf[36..total_len].copy_from_slice(payload); + total_len + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_slot_rollback_on_failure() { + let mut mgr = SlotManager::new(); + assert_eq!(mgr.active_slot, BootSlot::SlotA); + + assert!(!mgr.record_boot_attempt()); + assert!(!mgr.record_boot_attempt()); + // 3rd attempt triggers rollback + assert!(mgr.record_boot_attempt()); + assert_eq!(mgr.active_slot, BootSlot::SlotB); + assert_eq!(mgr.slot_a_health, SlotHealth::FailedRollback); + + // SlotB reaches health milestone + mgr.mark_milestone_healthy(); + assert_eq!(mgr.slot_b_health, SlotHealth::ConfirmedGood); + } + + #[test] + fn test_wal_truncation_on_corruption() { + let mut buffer = [0u8; 512]; + let mut offset = 0; + + // Entry 1: 10 bytes + let e1 = b"boot_start"; + let n1 = WalRecovery::encode_entry(e1, &mut buffer[offset..]); + offset += n1; + + // Entry 2: 12 bytes + let e2 = b"cortex_mount"; + let n2 = WalRecovery::encode_entry(e2, &mut buffer[offset..]); + offset += n2; + + // Verify clean log + let (valid_count, valid_bytes) = WalRecovery::recover_and_truncate(&buffer[..offset]); + assert_eq!(valid_count, 2); + assert_eq!(valid_bytes, offset); + + // Entry 3: Corrupt byte in payload + let e3 = b"corrupted_entry_here"; + let n3 = WalRecovery::encode_entry(e3, &mut buffer[offset..]); + // Corrupt one byte of e3's payload + buffer[offset + 40] ^= 0xFF; + let total_with_corrupt = offset + n3; + + // Recovery should reject entry 3 and truncate cleanly back to 2 valid entries! + let (recovered_count, recovered_bytes) = + WalRecovery::recover_and_truncate(&buffer[..total_with_corrupt]); + assert_eq!(recovered_count, 2); + assert_eq!(recovered_bytes, offset); + } + + #[test] + fn test_wal_zero_length_entry_and_overflow_protection() { + let mut buffer = [0u8; 256]; + let mut offset = 0; + + // 1. Encode valid zero-length entry + let n0 = WalRecovery::encode_entry(b"", &mut buffer[offset..]); + assert_eq!(n0, 36); + offset += n0; + + // 2. Encode normal entry + let n1 = WalRecovery::encode_entry(b"checkpoint", &mut buffer[offset..]); + offset += n1; + + let (valid_count, valid_bytes) = WalRecovery::recover_and_truncate(&buffer[..offset]); + assert_eq!(valid_count, 2); + assert_eq!(valid_bytes, offset); + + // 3. Craft malicious length header (u32::MAX) that could cause integer overflow + let mut malicious_buf = [0u8; 100]; + malicious_buf[0..4].copy_from_slice(&u32::MAX.to_be_bytes()); + malicious_buf[4..36].copy_from_slice(&[0xAAu8; 32]); + let (mal_count, mal_bytes) = WalRecovery::recover_and_truncate(&malicious_buf); + assert_eq!(mal_count, 0); + assert_eq!(mal_bytes, 0); + + // 4. Incomplete header (< 36 bytes) + let (inc_count, inc_bytes) = WalRecovery::recover_and_truncate(&[1, 2, 3, 4, 5]); + assert_eq!(inc_count, 0); + assert_eq!(inc_bytes, 0); + + // 5. Empty slice + let (empty_count, empty_bytes) = WalRecovery::recover_and_truncate(&[]); + assert_eq!(empty_count, 0); + assert_eq!(empty_bytes, 0); + } +} diff --git a/crates/aienos-kernel/src/store.rs b/crates/aienos-kernel/src/store.rs new file mode 100644 index 00000000..deffbef2 --- /dev/null +++ b/crates/aienos-kernel/src/store.rs @@ -0,0 +1,189 @@ +//! Host-tested implementation of ADR 0003 storage semantics. +//! +//! Note: This module provides a host-tested implementation of ADR 0003 storage semantics, +//! not yet native AIENOS storage on bare-metal block devices. +//! +//! Content-addressed extents (`model/<hash>`, `cortex/wal`, `agent/<id>`) +//! rather than a general-purpose POSIX filesystem. + +use crate::crypto::sha256; + +/// An immutable content-addressed storage extent. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ExtentDescriptor { + pub hash: [u8; 32], + pub offset: usize, + pub length: usize, +} + +/// Fixed-buffer Sovereign System Store for bare-metal `#![no_std]` substrate. +pub struct SystemStore<const CAPACITY: usize> { + storage: [u8; CAPACITY], + allocated: usize, +} + +impl<const CAPACITY: usize> Default for SystemStore<CAPACITY> { + fn default() -> Self { + Self::new() + } +} + +impl<const CAPACITY: usize> SystemStore<CAPACITY> { + /// Create a new sovereign system store over a fixed buffer. + pub const fn new() -> Self { + Self { + storage: [0u8; CAPACITY], + allocated: 0, + } + } + + /// Write an immutable content-addressed extent into store. + pub fn write_extent(&mut self, payload: &[u8]) -> Option<ExtentDescriptor> { + let new_allocated = self.allocated.checked_add(payload.len())?; + if new_allocated > CAPACITY { + return None; + } + + let hash = sha256::hash(payload); + let offset = self.allocated; + let length = payload.len(); + + self.storage[offset..new_allocated].copy_from_slice(payload); + self.allocated = new_allocated; + + Some(ExtentDescriptor { + hash, + offset, + length, + }) + } + + /// Read an extent and verify its cryptographic integrity. + pub fn read_extent<'a>(&'a self, desc: &ExtentDescriptor) -> Option<&'a [u8]> { + let extent_end = desc.offset.checked_add(desc.length)?; + if extent_end > self.allocated { + return None; + } + + let slice = &self.storage[desc.offset..extent_end]; + let actual_hash = sha256::hash(slice); + if actual_hash != desc.hash { + return None; // Integrity violation + } + + Some(slice) + } + + /// Total bytes currently stored. + pub const fn allocated_bytes(&self) -> usize { + self.allocated + } + + /// Total capacity. + pub const fn capacity(&self) -> usize { + CAPACITY + } +} + +/// Slice-backed Sovereign System Store operating over caller-allocated memory +/// (e.g. static memory frame, DMA region, or heap buffer) without stack allocation risk. +pub struct SliceStore<'a> { + storage: &'a mut [u8], + allocated: usize, +} + +impl<'a> SliceStore<'a> { + /// Create a new store backed by an existing memory slice. + pub fn new(storage: &'a mut [u8]) -> Self { + Self { + storage, + allocated: 0, + } + } + + /// Write an immutable content-addressed extent into the memory slice. + pub fn write_extent(&mut self, payload: &[u8]) -> Option<ExtentDescriptor> { + let new_allocated = self.allocated.checked_add(payload.len())?; + if new_allocated > self.storage.len() { + return None; + } + + let hash = sha256::hash(payload); + let offset = self.allocated; + let length = payload.len(); + + self.storage[offset..new_allocated].copy_from_slice(payload); + self.allocated = new_allocated; + + Some(ExtentDescriptor { + hash, + offset, + length, + }) + } + + /// Read an extent and verify its cryptographic integrity. + pub fn read_extent(&self, desc: &ExtentDescriptor) -> Option<&[u8]> { + let extent_end = desc.offset.checked_add(desc.length)?; + if extent_end > self.allocated { + return None; + } + + let slice = &self.storage[desc.offset..extent_end]; + let actual_hash = sha256::hash(slice); + if actual_hash != desc.hash { + return None; // Integrity violation + } + + Some(slice) + } + + /// Total bytes allocated so far. + pub fn allocated_bytes(&self) -> usize { + self.allocated + } + + /// Total available capacity. + pub fn capacity(&self) -> usize { + self.storage.len() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_content_addressed_extent_storage() { + let mut store = SystemStore::<4096>::new(); + + let model_header = b"AIENOS_MODEL_METADATA_v1:llama-3.2-1b"; + let desc = store.write_extent(model_header).expect("Write extent"); + + let read_back = store.read_extent(&desc).expect("Read extent"); + assert_eq!(read_back, model_header); + + // Verify tamper detection + let mut corrupted_desc = desc; + corrupted_desc.hash[0] ^= 0xFF; + assert!(store.read_extent(&corrupted_desc).is_none()); + } + + #[test] + fn test_slice_store_operations_and_boundaries() { + let mut mem = [0u8; 1024]; + let mut store = SliceStore::new(&mut mem); + + let data1 = b"cortex_snapshot_data_001"; + let desc1 = store.write_extent(data1).expect("Write data1"); + assert_eq!(store.read_extent(&desc1), Some(&data1[..])); + + // Capacity overflow check + let huge_data = [0x55u8; 2048]; + assert!(store.write_extent(&huge_data).is_none()); + + // Zero-length extent + let empty_desc = store.write_extent(b"").expect("Write empty extent"); + assert_eq!(store.read_extent(&empty_desc), Some(&b""[..])); + } +} diff --git a/crates/aienos-kernel/src/sync/mod.rs b/crates/aienos-kernel/src/sync/mod.rs new file mode 100644 index 00000000..f34027f7 --- /dev/null +++ b/crates/aienos-kernel/src/sync/mod.rs @@ -0,0 +1,5 @@ +//! Sovereign synchronization primitives for bare-metal substrate. + +pub mod spinlock; + +pub use spinlock::{SpinLock, SpinLockGuard}; diff --git a/crates/aienos-kernel/src/sync/spinlock.rs b/crates/aienos-kernel/src/sync/spinlock.rs new file mode 100644 index 00000000..ceb06cbc --- /dev/null +++ b/crates/aienos-kernel/src/sync/spinlock.rs @@ -0,0 +1,98 @@ +//! Sovereign SpinLock for bare-metal `#![no_std]` concurrency. + +use core::cell::UnsafeCell; +use core::ops::{Deref, DerefMut}; +use core::sync::atomic::{AtomicBool, Ordering}; + +/// A simple, sovereign spinlock for bare-metal concurrency. +pub struct SpinLock<T> { + locked: AtomicBool, + data: UnsafeCell<T>, +} + +unsafe impl<T: Send> Sync for SpinLock<T> {} +unsafe impl<T: Send> Send for SpinLock<T> {} + +impl<T> SpinLock<T> { + /// Create a new SpinLock protecting `data`. + pub const fn new(data: T) -> Self { + Self { + locked: AtomicBool::new(false), + data: UnsafeCell::new(data), + } + } + + /// Acquire the spinlock, spinning until available. + pub fn lock(&self) -> SpinLockGuard<'_, T> { + while self.locked.swap(true, Ordering::Acquire) { + while self.locked.load(Ordering::Relaxed) { + core::hint::spin_loop(); + } + } + SpinLockGuard { lock: self } + } + + /// Try to acquire the spinlock without blocking. + pub fn try_lock(&self) -> Option<SpinLockGuard<'_, T>> { + if !self.locked.swap(true, Ordering::Acquire) { + Some(SpinLockGuard { lock: self }) + } else { + None + } + } +} + +/// RAII guard for `SpinLock`. +pub struct SpinLockGuard<'a, T> { + lock: &'a SpinLock<T>, +} + +impl<'a, T> Deref for SpinLockGuard<'a, T> { + type Target = T; + fn deref(&self) -> &Self::Target { + unsafe { &*self.lock.data.get() } + } +} + +impl<'a, T> DerefMut for SpinLockGuard<'a, T> { + fn deref_mut(&mut self) -> &mut Self::Target { + unsafe { &mut *self.lock.data.get() } + } +} + +impl<'a, T> Drop for SpinLockGuard<'a, T> { + fn drop(&mut self) { + self.lock.locked.store(false, Ordering::Release); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_spinlock_basic() { + let lock = SpinLock::new(42); + { + let mut guard = lock.lock(); + assert_eq!(*guard, 42); + *guard += 1; + } + { + let guard = lock.lock(); + assert_eq!(*guard, 43); + } + } + + #[test] + fn test_spinlock_try_lock() { + let lock = SpinLock::new(100); + let guard1 = lock.try_lock(); + assert!(guard1.is_some()); + let guard2 = lock.try_lock(); + assert!(guard2.is_none()); + drop(guard1); + let guard3 = lock.try_lock(); + assert!(guard3.is_some()); + } +} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 945db9e9..9188e057 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -2,11 +2,23 @@ Status: confirmed by the operator on 2026-09-23. Changes to anything in this document that the operator listed as fundamental (see "Authority and escalation") require the operator's approval. +For complete architectural specifications, execution milestones, and decision records, see: +- [AIENOS Final Architectural Blueprint](BLUEPRINT.md) (Complete 37-section architectural foundation) +- [AIENOS Architectural Milestones Matrix](MILESTONES.md) (8-phase execution roadmap, invariants, and contracts) +- [AIENOS Technical Specification & Contracts (Phases 3–5)](PHASE_3_TO_5_SPECIFICATION.md) (Agent State ABI, Cortex, AEGIS & Worlds, and C1 CoW Prefix Tree) +- [AIENOS Systems Integration Sequence & Epistemic Calibration](SYSTEMS_INTEGRATION_SEQUENCE.md) (10-step empirical verification sequence and host vs. native qualification) +- [AIENOS Continuous-Existence Amendment](CONTINUOUS_EXISTENCE_AMENDMENT.md) (Governing lifecycle amendment: provisioning-once, power states, state classes, gate acceptance criteria) +- [Architectural Decision Records](adr/README.md) (Accepted architectural decisions: [ADR 0001](adr/0001-native-boot-milestone-and-linux-island.md), [ADR 0002](adr/0002-incumbent-os-as-migration-environment.md), [ADR 0003](adr/0003-bootstrap-firmware-handoff-and-minimal-object-store.md), [ADR 0004](adr/0004-reversibility-definition-and-network-effect-boundary.md), [ADR 0005](adr/0005-unified-memory-c1-cow-and-reservation-accounting.md), [ADR 0006](adr/0006-deterministic-recovery-core-and-offline-operator-authority.md), [ADR 0007](adr/0007-continuous-existence-provisioning-once.md)) + ## 1. What AIENOS is -AIENOS is the operating system. The resident AIEN agent is its primary user interface, coordinator, and policy-aware control plane. Graphical interfaces are projections of agent state that the agent can construct and change on request; there is no fixed desktop. +**AIENOS is an agent-native operating system designed around continuous logical agent existence: the agent persists while models, kernels, inference state, power states, and physical machines change beneath it.** + +The resident AIEN agent is its primary user interface, coordinator, and policy-aware control plane. Graphical interfaces are projections of agent state that the agent can construct and change on request; there is no fixed desktop. + +AIEN is provisioned once. After that, boot, reboot, sleep, model reload, kernel restart, hardware failure, and migration are execution-state transitions—not agent creation events ([Continuous-Existence Amendment](CONTINUOUS_EXISTENCE_AMENDMENT.md), [ADR 0007](adr/0007-continuous-existence-provisioning-once.md)). Cold boot initializes hardware; it does not create AIEN. -The model is never the kernel. The kernel is small, deterministic, auditable, and must function with no model loaded. It schedules CPU time, manages memory, services interrupts, mounts storage, enforces capability boundaries, restores a known World, authenticates the operator, recovers networking, kills processes, rolls back updates, and boots into recovery. +The model is never the kernel. The kernel is small, deterministic, auditable, and must function with no model loaded. It schedules CPU time, manages memory, services interrupts, mounts storage, enforces capability boundaries, restores a known World, authenticates the operator, recovers networking, kills processes, rolls back updates, and boots into recovery. The kernel operates deterministically without an AI model; recovery is governed by the deterministic Recovery Core ([ADR 0006](adr/0006-deterministic-recovery-core-and-offline-operator-authority.md)). The agent is the operating interface, not the root of trust: @@ -38,6 +50,7 @@ You - **Personal data is OS state:** Person, Conversation, Message, Document, Photo, Video, Project, Repository, CalendarEvent, Device, CredentialRef, Task, World, Memory. - **Personal Fabric:** a given computer is Machine N, not "the AIEN computer." Hardware and vendor details are capabilities, not identities. - **Models are replaceable components** behind a Model ABI: locally stored, no cloud or provider account required. The model proposes thought and action; it does not define truth, authority, policy, identity, storage, or the OS. +- **Unified memory and explicit block accounting:** Hardware unified addressability (NVLink-C2C) is managed via explicit block ownership, distinct subsystem memory budgets, and copy-on-write prefix trees ([ADR 0005](adr/0005-unified-memory-c1-cow-and-reservation-accounting.md)). ## 3. Sovereignty and the trusted base @@ -53,6 +66,8 @@ Accepted exception: silicon that physically requires vendor-signed firmware (for **Host operating systems:** Windows, macOS, and Linux are bootstrap and migration environments, not the target runtime. **AIENOS may learn from the host, but it must not require the host to survive** ([ADR 0002](adr/0002-incumbent-os-as-migration-environment.md)). +**Persistent storage:** Persistent storage avoids POSIX filesystem complexity in favor of the native AIEN System Store with content-addressed model extents and append-only journals ([ADR 0003](adr/0003-bootstrap-firmware-handoff-and-minimal-object-store.md)). + ## 4. Security - **Boot trust:** Secure Boot off during early development. Before daily use: firmware verifies the operator's key, the operator's key verifies AIENOS boot artifacts, AIENOS verifies kernel and runtime components. An offline recovery key and recovery media are designed before enforcement. @@ -65,7 +80,7 @@ Free inside reversible state; explicit authorization at irreversible boundaries. Autonomous by default: read local files, search Cortex, run inference, inspect hardware and system state, run tests and diagnostics, create temporary files and Worlds, make rollback-safe changes inside a reversible World, change ordinary agent preferences. -Operator approval required: permanent deletion, overwriting important data, external email or messages, publishing code, spending money, credential changes, exporting private information, contacting untrusted machines, installing privileged components, boot or security policy changes, changing AEGIS, replacing the kernel, promoting RSI-generated system changes. +Operator approval required: permanent deletion, overwriting important data, external email or messages, publishing code, spending money, credential changes, exporting private information, contacting untrusted machines, installing privileged components, boot or security policy changes, changing AEGIS, replacing the kernel, promoting RSI-generated system changes. All outbound network traffic, external device state, and telemetry are external effects requiring AEGIS capability evaluation, even when read-only ([ADR 0004](adr/0004-reversibility-definition-and-network-effect-boundary.md)). Self-improvement may tune scheduler, allocator, KV, caching, UI, routing, network, kernel implementation, placement, and power policy only out of band, through evaluation, canary, signing, and promotion gates, never by rewriting the running kernel. @@ -85,7 +100,9 @@ The first agent's job is running, understanding, diagnosing, repairing, and impr Every stage boots and does something real. -Steps 2 and 3 are the primary milestone (native AIENOS boot with CPU inference). A minimal-Linux image booting straight into `aien-init` exists only as Benchmark Config B and the temporary GPU compatibility island, and it is never a prerequisite for the native path. Configs A (Ubuntu reference), B (minimal-Linux island), and C (native AIENOS) run the same frozen workload and report boot-to-ready, ready-to-model, TTFT, throughput, idle and available memory, jitter, power, and branch cost separately ([ADR 0001](adr/0001-native-boot-milestone-and-linux-island.md)). +Steps 2 and 3 are the primary milestone (native AIENOS boot with CPU inference). A minimal-Linux image booting straight into `aien-init` exists only as Benchmark Config B and the temporary GPU compatibility island, and it is never a prerequisite for the native path. + +Configs A (Ubuntu reference), B (minimal-Linux island), and C (native AIENOS) run the same frozen workload and report boot-to-ready, ready-to-model, TTFT, throughput, idle and available memory, jitter, power, and branch cost separately, plus continuous-existence lifecycle metrics (wake-to-continuation and reconstruction latencies) per the [Continuous-Existence Amendment](CONTINUOUS_EXISTENCE_AMENDMENT.md) ([ADR 0001](adr/0001-native-boot-milestone-and-linux-island.md), [ADR 0007](adr/0007-continuous-existence-provisioning-once.md)). Native capability migration order: Runtime, Cortex, AEGIS, World/J-Space, Capability Graph, local inference, storage, networking, operator interface, developer tools, mail, cockpit, others. Nothing is rebuilt merely because it exists today. @@ -106,3 +123,5 @@ Milestone reports show what was built, what passed, what failed, what changed, t ## 10. The persistent thing The persistent thing is AIEN itself. Hardware is replaceable beneath it. Models, interfaces, tools, and Machines are replaceable around it. If a company disappears tomorrow, the long-term target is that AIENOS continues to boot and remains the operator's. + +**Strengthened ([Continuous-Existence Amendment §21](CONTINUOUS_EXISTENCE_AMENDMENT.md), [ADR 0007](adr/0007-continuous-existence-provisioning-once.md)):** AIEN is the persistent logical entity. Hardware, kernels, models, runtime processes, inference caches, interfaces, and Machines are replaceable execution substrates. Sleep changes residency. Reboot changes execution substrate. Failure triggers reconstruction. None of these events inherently terminates logical identity. diff --git a/docs/BLUEPRINT.md b/docs/BLUEPRINT.md new file mode 100644 index 00000000..3455233a --- /dev/null +++ b/docs/BLUEPRINT.md @@ -0,0 +1,1609 @@ +# AIENOS — Final Architectural Blueprint + +## 1. The final vision + +AIENOS is an agent-native operating system. + +The end state is a machine where the user presses the power button and AIEN wakes up directly. + +Not: + +Windows → AIEN application. + +Not: + +macOS → AIEN application. + +Not: + +Ubuntu → desktop → containers → Python → HTTP server → AIEN. + +The target is: + +```text +Power + ↓ +Firmware + ↓ +AIEN Boot Trust + ↓ +AIENOS + ↓ +Hardware + ↕ +AIEN Runtime + ↕ +Persistent AIEN Agent + ↓ +User +``` + +AIEN itself is the persistent thing. + +The physical computer can change. + +The model can change. + +The GPU can change. + +The user interface can change. + +Individual implementations can change. + +But the agent's identity, state, memory, authority, history, evidence and relationship to the operator survive those changes. + +The computer is no longer organized around applications. + +It is organized around: + +```text +identity +state +memory +capabilities +effects +hardware +models +Worlds +evidence +``` + +The model is an intelligence component inside the system. + +It is not the operating system. + +It is not the root of trust. + +It is not the authority that decides what it is allowed to do. + +--- + +# 2. The central architectural principle + +AIENOS separates four things that conventional AI systems usually blur together: + +```text +WHO AM I? + ↓ +Persistent logical agent identity + +WHAT DO I KNOW? + ↓ +Cortex / evidence-aware memory + +WHAT AM I ALLOWED TO DO? + ↓ +AEGIS / capabilities / effect authorization + +WHERE AM I CURRENTLY EXECUTING? + ↓ +Physical compute, inference state, memory and hardware +``` + +Those must remain separable. + +The foundational rule remains: + +> Losing physical inference state should cost computation, not identity. + +A GPU crash must not create a new agent. + +Evicting KV memory must not create a new agent. + +Changing models must not create a new agent. + +Rebooting the computer must not create a new agent. + +Moving to another machine must eventually not create a new agent. + +Physical execution is replaceable. + +Logical identity is persistent. + +--- + +# 3. Final system architecture + +The target stack is approximately: + +```text +┌────────────────────────────────────────────┐ +│ OPERATOR │ +└─────────────────────┬──────────────────────┘ + │ +┌─────────────────────▼──────────────────────┐ +│ AIEN AGENT │ +│ │ +│ reasoning • planning • interface • routing │ +└──────────┬───────────┬───────────┬─────────┘ + │ │ │ + ▼ ▼ ▼ + J-Space Cortex Capability + Worlds Memory Graph + │ │ │ + └───────────┼───────────┘ + ▼ +┌────────────────────────────────────────────┐ +│ AEGIS │ +│ │ +│ policy • authorization • provenance │ +│ effect approval • capability enforcement │ +└─────────────────────┬──────────────────────┘ + │ + ▼ +┌────────────────────────────────────────────┐ +│ EFFECT BROKER │ +│ │ +│ converts authorized intent into real │ +│ effects on machines, networks and data │ +└─────────────────────┬──────────────────────┘ + │ +┌─────────────────────▼──────────────────────┐ +│ AIEN NEURAL RUNTIME │ +│ │ +│ Model ABI │ +│ Agent State ABI │ +│ inference scheduler │ +│ physical COW state │ +│ placement / compute │ +│ tools and skills │ +│ storage services │ +│ network services │ +└─────────────────────┬──────────────────────┘ + │ +┌─────────────────────▼──────────────────────┐ +│ AIENOS KERNEL │ +│ │ +│ scheduling │ +│ memory │ +│ IPC / capabilities │ +│ interrupts │ +│ storage │ +│ networking │ +│ device access │ +│ isolation │ +│ recovery │ +└─────────────────────┬──────────────────────┘ + │ +┌─────────────────────▼──────────────────────┐ +│ HARDWARE │ +│ CPU • GPU/NPU • RAM • disks • network • IO │ +└────────────────────────────────────────────┘ +``` + +The exact implementation of every box may change. + +The separation between the boxes should not. + +--- + +# 4. What is fixed versus what the engineering agent may decide + +The engineering agent should have substantial autonomy. + +It may choose: + +* algorithms; +* data structures; +* crate boundaries; +* internal APIs; +* schedulers; +* allocator designs; +* boot mechanisms; +* storage implementations; +* driver strategies; +* build tooling; +* testing machinery; +* optimization techniques; +* assembly versus Rust versus another appropriate open technology; +* whether a component should initially be replaced, wrapped, emulated or rewritten; +* the fastest technically sound path to the milestone. + +The agent should not be forced to implement something merely because we previously imagined one implementation. + +The architecture is defined by behavior and boundaries, not by arbitrary code layout. + +What is not free to drift is the destination. + +AIENOS must remain independently bootable. + +The agent cannot become the root of trust. + +Native AIENOS cannot require Windows, macOS or Linux to survive. + +The trusted core cannot require a proprietary cloud service, licensing server or opaque compiler/runtime to boot, recover or control the machine. + +Compatibility infrastructure cannot quietly become the permanent native architecture. + +Operator authority cannot be silently broadened. + +Persistent identity cannot be reduced to a running process ID. + +Correctness cannot be sacrificed merely because an implementation benchmarks faster. + +Everything else is engineering territory. + +--- + +# 5. Boot and trust architecture + +Eventually: + +```text +Firmware + ↓ +operator-controlled boot trust + ↓ +verified AIENOS boot artifact + ↓ +verified kernel + ↓ +verified system services + ↓ +verified AIEN Runtime + ↓ +persistent AIEN state +``` + +The operating principle is: + +> The agent cannot authorize itself. + +The model may propose: + +> Send this email. + +But the actual path is: + +```text +Model proposes action + ↓ +EffectIntent + ↓ +AEGIS + ↓ +capability + policy evaluation + ↓ +Effect Broker + ↓ +driver / network / storage + ↓ +real-world effect +``` + +The intelligence that proposes an action is therefore separated from the deterministic mechanism deciding whether the action may occur. + +That separation is fundamental. + +--- + +# 6. The AIENOS kernel + +The kernel should remain small relative to the whole AIEN system. + +It does not need to reason. + +It needs to be extremely dependable. + +At maturity it owns things such as: + +```text +CPU scheduling +memory management +interrupts +timers +IPC +capability enforcement +device access +storage +networking +isolation +process/service lifecycle +recovery +``` + +The model must not be necessary to: + +* boot; +* mount storage; +* recover data; +* diagnose basic failures; +* authenticate the operator; +* repair the system; +* roll back an update; +* kill a malfunctioning service. + +AIENOS must remain a functioning computer even if no model loads. + +--- + +# 7. Hardware sovereignty + +The long-term target is direct ownership of the important hardware path. + +Conceptually: + +```text +AIEN Runtime + ↓ +AIENOS native interfaces + ↓ +hardware +``` + +rather than: + +```text +AIEN + ↓ +desktop application + ↓ +framework + ↓ +IPC + ↓ +host service + ↓ +general-purpose OS stack + ↓ +driver stack + ↓ +hardware +``` + +But this does not mean rewriting everything simply for ideological reasons. + +The engineering agent should optimize toward the native path where it provides actual value. + +The objective is: + +```text +fewer copies +fewer boundaries +less serialization +less unnecessary scheduling +predictable latency +persistent model residency +direct memory management +direct accelerator state +direct storage paths +direct network paths +lower overhead +higher agent density +``` + +The project measures each of these instead of assuming bare metal is automatically faster. + +--- + +# 8. Compatibility islands + +During the transition, AIENOS is allowed to use compatibility islands. + +For example: + +```text + AIENOS + │ + ┌──────────┴──────────┐ + │ │ +native capability compatibility island + │ │ + ▼ ▼ + hardware Linux/vendor stack +``` + +An island can temporarily provide: + +* GPU access; +* legacy applications; +* unsupported hardware; +* specialized vendor functionality. + +It can even be faster than the native implementation temporarily. + +That is acceptable. + +What matters is: + +> The island is not AIENOS's foundation. + +Removing it must not make the native system impossible to build, boot, recover or control. + +Over time: + +```text +Era I +large compatibility island +small native system + +Era II +rough parity + +Era III +mostly native +small legacy island + +End state +islands exist only where useful +``` + +--- + +# 9. Agent State ABI + +This may become one of AIEN's most important contributions. + +An agent should have logical state that is separate from whatever runtime instance happens to execute it. + +The hierarchy becomes roughly: + +```text +LogicalAgentId + │ + ├── LogicalBranchId + │ + ├── TokenHistory + │ + ├── memory references + │ + ├── capability state + │ + ├── lineage + │ + └── evidence/provenance + │ + ▼ +Execution incarnation + │ + ▼ +SequenceId + │ + ▼ +physical inference state + │ + ├── KV pages + ├── accelerator buffers + └── temporary compute +``` + +A branch can: + +```text +fork +run +suspend +resume +evict +reconstruct +crash +restart +``` + +without silently changing semantic identity. + +Eventually: + +```text +fork(agent_state) +checkpoint(agent_state) +suspend(agent_state) +resume(agent_state) +migrate(agent_state) +destroy(agent_state) +``` + +become well-defined system operations. + +--- + +# 10. Copy-on-write agent computation + +AIEN's branch model should allow many reasoning branches to share their common physical inference prefix. + +Instead of: + +```text +100 agents +× +same 100K-token prefix +``` + +AIEN aims toward: + +```text +one physical prefix + ↓ + ┌──────┼──────┬──────┐ + ↓ ↓ ↓ ↓ +B1 B2 B3 ... +``` + +Only divergent state becomes private. + +This potentially affects: + +* coding-agent swarms; +* planning; +* search; +* hypothesis exploration; +* best-of-N inference; +* simulation; +* research agents; +* long-context reasoning. + +C1 exists to prove this behaves correctly before AIEN makes strong performance claims around it. + +--- + +# 11. Cortex + +Cortex is the persistent knowledge system. + +Its job is not merely to store embeddings. + +It should maintain distinctions such as: + +```text +observation +verified fact +source +inference +hypothesis +contradiction +decision +episodic memory +canonical state +``` + +The system should understand not just: + +> What do I remember? + +but: + +> Why do I believe this? + +That avoids a failure mode where model-generated speculation gets stored, later retrieved as apparent fact, and recursively reinforces itself. + +Cortex becomes durable epistemic state. + +--- + +# 12. Worlds / J-Space + +AIEN needs a place where it can act freely without constantly asking permission. + +The basic operating principle is: + +> Free inside reversible state. Approval at irreversible boundaries. + +A World is a reversible execution/state environment. + +Inside one, AIEN can: + +* modify code; +* restructure files; +* run tests; +* experiment; +* build artifacts; +* simulate decisions; +* change temporary configuration; +* create branches; +* evaluate alternative solutions. + +Only when something needs to cross from reversible state into the real world does the Effect system become involved. + +For example: + +```text +World + ↓ +AIEN modifies repository + ↓ +tests pass + ↓ +AIEN proposes publish + ↓ +EffectIntent: push code externally + ↓ +AEGIS + ↓ +operator policy/approval + ↓ +Git operation +``` + +This allows considerable autonomy without making autonomy equivalent to unlimited authority. + +--- + +# 13. Capability Graph + +Traditional operating systems organize software around programs. + +AIENOS should increasingly organize functionality around capabilities. + +Examples: + +```text +filesystem.read +filesystem.write + +mail.read +mail.send + +calendar.read +calendar.schedule + +code.build +code.test +code.publish + +network.connect + +image.edit + +model.run + +device.camera + +hardware.inspect +``` + +Applications may still exist. + +But an application does not own the underlying capability or data. + +The agent can compose capabilities dynamically. + +That is how the computer stops being a collection of application silos and becomes an environment the agent can operate coherently. + +--- + +# 14. Model ABI + +Models are replaceable intelligence engines. + +AIENOS should eventually be able to say: + +```text +load model A + +replace with model B + +run specialist model C for coding + +run smaller model D for routing +``` + +without redefining the identity of the agent. + +The Model ABI should separate: + +```text +model weights +tokenizer +execution backend +inference state +sampling +logical agent state +``` + +No model provider should become equivalent to AIEN itself. + +--- + +# 15. Phase 1 — Freeze reality + +Before replacing anything, freeze the working Spark system. + +This is Config A. + +```text +Ubuntu + ↓ +current AIEN stack + ↓ +current NVIDIA path + ↓ +DGX Spark +``` + +The goal is not optimization. + +The goal is reproducibility. + +Capture: + +* hardware identity; +* firmware; +* current OS; +* source commits; +* build configuration; +* model hashes; +* tokenizer; +* libraries; +* execution environment; +* workloads; +* correctness evidence; +* recovery procedure; +* performance distributions. + +Produce a verified reference bundle. + +After this phase we can answer: + +> What exactly did native AIENOS replace? + +without relying on memory or marketing. + +--- + +# 16. Phase 2 — Native AIENOS boot + +Now the actual operating system begins. + +Objective: + +> Power on the DGX Spark and boot AIENOS itself. + +Minimum milestone: + +```text +Firmware + ↓ +AIENOS boot + ↓ +AIENOS kernel + ↓ +CPU initialized + ↓ +memory available + ↓ +interrupts/timers operating + ↓ +console available + ↓ +storage available + ↓ +recovery available +``` + +No agent required yet. + +No GPU required yet. + +No elaborate UI required. + +No networking required to claim this milestone. + +The proof is brutally simple: + +> The machine boots AIENOS without Linux being the host. + +--- + +# 17. Phase 3 — The agent wakes up + +Once the native machine substrate works: + +```text +AIENOS boots + ↓ +AIEN Runtime starts + ↓ +local model loads + ↓ +AIEN Agent starts + ↓ +operator can communicate with it + ↓ +Cortex persists + ↓ +reboot + ↓ +same logical AIEN resumes +``` + +CPU inference is sufficient. + +The objective isn't speed yet. + +The objective is continuity. + +The first native AIEN should primarily understand and operate AIENOS itself. + +Its earliest job is: + +```text +observe machine +diagnose machine +inspect itself +run tests +read logs +repair reversible failures +help develop AIENOS +``` + +General assistant capabilities are secondary during this stage. + +--- + +# 18. Phase 4 — Native system intelligence + +Now make the agent genuinely useful as the operating interface. + +Bring in: + +```text +Cortex +Agent State +AEGIS +Effect Broker +Capability Graph +Worlds +system introspection +storage capabilities +local tools +developer capabilities +``` + +The operator should increasingly be able to interact with the system through intent: + +> Show me what's consuming memory. + +> Fix this build. + +> Find why networking stopped. + +> Create a new development World. + +> Roll back the last system update. + +AIEN translates intent into capabilities rather than requiring the user to manually navigate traditional programs. + +--- + +# 19. Phase 5 — Native hardware acceleration + +Only after native AIENOS itself exists do we aggressively optimize. + +AIENOS progressively takes ownership of hot paths: + +```text +accelerator +storage +network +memory +scheduler +inference +``` + +The engineering agent is free to find the fastest correct solution. + +The requirement is that the resulting native path remains sovereign according to the trusted-base rules. + +Compatibility GPU paths can remain beside it while the native accelerator path matures. + +The important competition becomes: + +```text +A — Ubuntu reference +B — minimal Linux / compatibility island +C — native AIENOS +``` + +Run the same workloads. + +Compare separately: + +```text +boot → agent ready + +agent ready → model ready + +TTFT + +steady-state throughput + +memory availability + +scheduler jitter + +power + +branch creation + +branch physical memory cost + +restore time + +agent density +``` + +No single synthetic “speed score.” + +--- + +# 20. Phase 6 — Migration system + +Once AIENOS can survive independently, adoption becomes important. + +The existing OS becomes an installer. + +On Windows/macOS/Linux: + +```text +AIEN bootstrap + ↓ +inspect machine + ↓ +Machine Capsule + ↓ +determine AIENOS support + ↓ +prepare native installation + ↓ +preserve user state + ↓ +install separate boot target + ↓ +validate + ↓ +Restart into AIEN +``` + +The host is scaffolding. + +It is not the destination. + +The core migration rule: + +> AIENOS may learn from the host, but it must not require the host to survive. + +--- + +# 21. Machine Capsule + +A host-side AIEN installation should learn enough about a machine to create a portable description of it. + +Conceptually: + +```text +MachineCapsule +├── firmware +├── CPU +├── accelerator +├── memory +├── storage +├── network +├── display +├── audio +├── USB +├── Bluetooth +├── input +├── known drivers +├── user state +├── critical applications +└── compatibility requirements +``` + +The Machine Capsule is not itself a driver implementation. + +It describes what AIENOS needs to reproduce. + +The engineering agent may then determine the best path for supporting that machine. + +--- + +# 22. Reversible installation + +AIENOS should initially install beside the existing OS. + +Conceptually: + +```text +Disk +│ +├── incumbent OS +│ +├── AIENOS +└── recovery +``` + +The system validates: + +```text +boot +storage +display +input +network where available +model loading +AIEN state +Cortex +recovery +``` + +before encouraging broader migration. + +If AIENOS fails: + +> Boot the old system. + +This dramatically lowers adoption risk. + +--- + +# 23. Progressive escape from the incumbent OS + +At first, users may still rely on old software. + +That's acceptable. + +The progression is: + +```text +Stage 1 +AIEN lives inside host. + +Stage 2 +AIENOS dual-boots. + +Stage 3 +AIENOS becomes primary. + +Stage 4 +Legacy host is used only for a few applications. + +Stage 5 +Legacy capabilities run through compatibility islands. + +Stage 6 +Old OS becomes an archive/recovery image. + +Stage 7 +Old OS can be removed if the operator chooses. +``` + +The project does not force migration. + +It makes migration increasingly unnecessary to resist. + +--- + +# 24. Phase 7 — Multi-hardware AIENOS + +Once Spark proves the architecture, expand outward. + +Do not hard-code the system conceptually around NVIDIA DGX Spark. + +Spark is the reference machine, not AIEN's identity. + +Port AIENOS to additional targets based on engineering value and available resources. + +Examples could eventually include: + +```text +desktop x86 +ARM systems +AMD accelerator systems +Apple hardware where practical +embedded systems +future AI appliances +``` + +Every platform implements the same higher-level AIEN contracts. + +Hardware becomes a replaceable substrate. + +--- + +# 25. Phase 8 — Personal Fabric + +Eventually one AIEN may span several machines. + +For example: + +```text + AIEN + │ + ┌────────────┼────────────┐ + │ │ │ + Spark Laptop Phone + │ │ │ + GPU display sensors + compute keyboard mobile +``` + +Machines become resources belonging to the operator's AIEN environment. + +AIEN can determine: + +> This computation belongs on Machine A. + +> This interface belongs on Machine B. + +> These files remain physically on Machine C. + +> This model should migrate to the workstation. + +The identity remains above the machines. + +--- + +# 26. Eventually: state mobility + +A mature system should be able to: + +```text +run branch on machine A + ↓ +suspend + ↓ +move logical state + ↓ +reconstruct required physical state + ↓ +resume on machine B +``` + +Physical KV state need not necessarily migrate byte-for-byte. + +The system may decide recomputation is cheaper. + +Again: + +> Physical state is optimization. + +> Logical state is identity. + +--- + +# 27. Evidence architecture + +Every major AIENOS technical claim should be backed by a reproducible evidence bundle. + +That means: + +```text +source commit +machine identity +build identity +model identity +config +workload +raw measurements +correctness result +environment +verifier +artifact hashes +``` + +No screenshot-as-proof culture. + +No benchmark number detached from the command that generated it. + +No “verified” because the program happened not to crash. + +Claims should be predefined. + +Evidence earns claims. + +Evidence does not earn adjectives. + +--- + +# 28. C1's role + +C1 remains foundational. + +Before AIENOS uses branch-native inference as a major architectural advantage, C1 establishes that: + +```text +identity survives +branches isolate correctly +COW is physically real +recomputation is equivalent +memory conserves correctly +resources are reclaimed +parents survive child behavior +state continuity survives resource events +``` + +AIENOS can inherit those semantics. + +It should not create weaker OS-specific versions. + +--- + +# 29. Development model for the autonomous engineering agent + +The engineering agent receives: + +```text +CURRENT STATE ++ +NEXT MILESTONE ++ +ARCHITECTURAL INVARIANTS ++ +ACCEPTANCE TESTS +``` + +Then it is free to solve the engineering problem. + +It should be allowed to: + +```text +research +prototype +rewrite +benchmark +discard approaches +change internal implementation +write new tools +run experiments +optimize +refactor +``` + +without repeatedly asking which exact function to create. + +The operator is not the implementation router. + +The operator owns the architecture. + +The agent owns engineering execution. + +Escalation happens when the agent discovers that success appears to require changing something fundamental, such as: + +```text +trust model +operator authority +persistent identity semantics +security boundary +irreversible data format +native-vs-compatibility boundary +sovereignty requirement +licensing +recovery guarantees +external protocol contract +major architecture +``` + +Otherwise: + +> Solve it. + +--- + +# 30. Failure should change implementation, not the goal + +Suppose native storage approach A doesn't work. + +The agent tries B. + +Suppose B is slow. + +Try C. + +Suppose the planned scheduler architecture turns out to be wrong. + +Replace it. + +Suppose Rust isn't appropriate for a tiny low-level section. + +Use something appropriate. + +The blueprint should not trap the project inside guesses made before the evidence existed. + +The destination is fixed. + +The route evolves. + +--- + +# 31. “Fastest wins” properly defined + +The rule is not: + +> fastest benchmark result wins regardless of everything else. + +It is: + +> Among implementations that satisfy correctness, security, sovereignty and the required contract, the fastest measured implementation wins. + +Conceptually: + +```text +Correct? + no → reject + +Secure enough? + no → reject + +Sovereignty contract? + no → compatibility-only + +Passes interface/invariant tests? + no → reject + +Remaining candidates + ↓ +measure + ↓ +fastest wins +``` + +--- + +# 32. Self-improvement + +Eventually AIEN should help improve AIENOS. + +But it must not mutate its trusted foundation arbitrarily while running. + +The model may: + +```text +discover optimization + ↓ +create experimental World + ↓ +modify implementation + ↓ +build + ↓ +run correctness suite + ↓ +benchmark + ↓ +compare evidence + ↓ +produce candidate +``` + +Promotion remains controlled: + +```text +candidate + ↓ +evaluation + ↓ +security checks + ↓ +signing + ↓ +deployment + ↓ +rollback available +``` + +AIEN may improve itself. + +AIEN does not simply declare its own rewrite trustworthy. + +--- + +# 33. What the finished system feels like + +The user presses power. + +AIENOS verifies itself. + +The resident agent wakes. + +The machine already knows: + +```text +who the operator is +who the agent is +what hardware exists +what capabilities exist +what state existed before shutdown +what projects are active +what memories are trusted +what permissions have been granted +what branches are suspended +what models are available +``` + +The user doesn't need to open an application to begin computing. + +They interact with AIEN. + +If they need something visual, AIEN creates an interface. + +If they need code built, AIEN invokes build capabilities. + +If they need mail sent, AIEN invokes mail capabilities. + +If they need a simulation, AIEN creates a World. + +If more reasoning is useful, AIEN forks state. + +If hardware state disappears, AIEN reconstructs it. + +If another machine is better suited, AIEN eventually moves work there. + +The operating system becomes the substrate of the agent rather than the collection of applications the user manually coordinates. + +--- + +# 34. The adoption proposition + +The message isn't: + +> Throw away your computer and install an experimental OS. + +It becomes: + +> Let AIEN learn the machine you already own. + +Then: + +> Let AIEN build a native environment for it. + +Then: + +> Restart into AIEN. + +Then eventually: + +> The old operating system is no longer necessary. + +The host exists to help AIEN escape the host. + +--- + +# 35. The strategic endpoint + +The largest possible outcome is not merely an AIEN-branded operating system. + +It is the establishment of a different abstraction for personal computing: + +```text +old model: + +user + ↓ +applications + ↓ +operating system + ↓ +hardware + + +AIEN model: + +operator + ↓ +persistent intelligent agent + ↓ +capabilities + Worlds + memory + authority + ↓ +AIENOS + ↓ +hardware +``` + +And underneath the agent: + +```text +logical identity ≠ physical execution +knowledge ≠ speculation +intelligence ≠ authority +compatibility ≠ architecture +performance ≠ correctness +model ≠ agent +machine ≠ identity +``` + +Those separations are the real architecture. + +--- + +# 36. The master execution sequence + +The overall journey is: + +```text +CURRENT AIEN + ↓ +PHASE 1 +Freeze Linux/Spark reference + ↓ +PHASE 2 +Native AIENOS boots + ↓ +PHASE 3 +Persistent AIEN wakes natively + ↓ +PHASE 4 +Cortex + AEGIS + Worlds + capabilities + ↓ +PHASE 5 +Native high-performance hardware paths + ↓ +PHASE 6 +Host-to-AIENOS migration compiler + ↓ +PHASE 7 +Additional hardware + ↓ +PHASE 8 +Personal multi-machine fabric + ↓ +MATURE AIENOS +Persistent sovereign agent-native computing +``` + +The phases may overlap when engineering reality makes that useful. + +Their order expresses dependency, not bureaucracy. + +The engineering agent may discover a better path. + +It should take it if the architectural invariants and milestone proofs remain intact. + +--- + +# 37. Final definition of success + +AIENOS has achieved its core vision when all of these statements are true: + +The machine can boot without Windows, macOS or Linux acting as its host. + +AIENOS can recover without an AI model. + +The AIEN agent survives reboot as the same logical entity. + +Cortex survives and preserves evidence/provenance semantics. + +The model can be replaced without replacing AIEN. + +Agent inference state can be branched, suspended, reclaimed and reconstructed without changing logical identity. + +The agent operates the machine through explicit capabilities. + +Irreversible effects cross enforceable authorization boundaries. + +The operator can recover from AIEN failure. + +No outside company is required for ordinary continued operation. + +Important native hardware paths are directly controlled by AIENOS. + +Compatibility layers are optional rather than foundational. + +The system can prove its important performance and correctness claims. + +The user can move to another supported machine without the idea of “their AIEN” being tied permanently to the old hardware. + +And the ordinary experience becomes: + +> Power on the machine. AIEN wakes up. + +That is the final vision. diff --git a/docs/CONTINUOUS_EXISTENCE_AMENDMENT.md b/docs/CONTINUOUS_EXISTENCE_AMENDMENT.md new file mode 100644 index 00000000..0ed6f28f --- /dev/null +++ b/docs/CONTINUOUS_EXISTENCE_AMENDMENT.md @@ -0,0 +1,1005 @@ +# AIENOS Continuous-Existence Amendment + +**Status:** Operator-approved governing amendment (2026-09-23) +**Authority:** Operator Directive +**Scope:** Lifecycle semantics and acceptance criteria across the locked 10-gate Systems-Integration Sequence +**Related:** [SYSTEMS_INTEGRATION_SEQUENCE.md](SYSTEMS_INTEGRATION_SEQUENCE.md), [ARCHITECTURE.md §1, §10](ARCHITECTURE.md), [ADR 0007](adr/0007-continuous-existence-provisioning-once.md), [ADR 0005](adr/0005-unified-memory-c1-cow-and-reservation-accounting.md), [ADR 0006](adr/0006-deterministic-recovery-core-and-offline-operator-authority.md) + +This amendment does not add a new conceptual layer and does not change the locked 10-gate Systems-Integration Sequence. + +It changes the lifecycle semantics and acceptance criteria applied across those gates. + +The key architectural change is: + +> **AIEN is provisioned once. After that, boot, reboot, sleep, model reload, kernel restart, hardware failure, and migration are execution-state transitions—not agent creation events.** + +--- + +## 1. Governing invariant: AIEN exists continuously + +AIENOS is designed around **continuous logical agent existence**. + +The resident AIEN agent is not defined by: + +- a running process; +- a loaded model; +- a KV cache; +- RAM contents; +- a kernel instance; +- a boot session; +- a particular physical machine. + +Those are execution substrates. + +AIEN's durable identity is logical and persistent. + +The governing rule is: + +> **AIEN is provisioned once. Physical execution may stop, migrate, sleep, fail, restart, or be reconstructed without implicitly creating a new agent.** + +Therefore: + +> **Cold boot initializes hardware. It does not create AIEN.** + +And: + +> **Loss of physical execution state may increase reconstruction cost, but must not by itself terminate logical identity.** + +This generalizes the existing C1 rule: + +> **Losing KV costs computation, not identity.** + +into the system-wide rule: + +> **Losing physical execution state costs recovery or computation, not identity.** + +--- + +## 2. Provisioning is different from boot + +AIENOS must distinguish **initial provisioning** from all later starts. + +### Initial provisioning + +Only the initial creation of an AIEN identity may create a new durable `LogicalAgentId`. + +Conceptually: + +```text +unprovisioned AIENOS + ↓ +operator explicitly provisions AIEN + ↓ +LogicalAgentId created + ↓ +durable agent root committed + ↓ +AIEN exists +``` + +After this point, that identity is persistent. + +### Every later machine start + +```text +power / reset / wake + ↓ +hardware initialization + ↓ +locate durable AIEN root + ↓ +verify committed state + ↓ +restore execution environment + ↓ +resume existing LogicalAgentId +``` + +A normal boot path must never silently generate a replacement `LogicalAgentId`. + +If the persistent identity cannot be verified: + +```text +DO NOT CREATE A REPLACEMENT AGENT + ↓ +enter deterministic Recovery Core +``` + +The operator then chooses whether to restore, import, recover, or explicitly provision a new identity. + +--- + +## 3. AIENOS lifecycle model + +The normal lifecycle is not: + +```text +BOOT + ↓ +RUN + ↓ +SHUTDOWN +``` + +It is: + +```text + AIEN + │ + ┌───────────┼───────────┐ + │ │ │ + AWAKE QUIET SLEEP + │ │ │ + └───────────┼───────────┘ + │ + DEEP SLEEP + │ + COLD RECOVERY + only when needed +``` + +These names define semantic states, not mandatory implementation mechanisms. + +The engineering agent may choose the most efficient implementation. + +--- + +## 4. Power-state semantics + +### AWAKE + +Full interactive operation. + +Likely resources: + +- CPU execution; +- required memory; +- active inference; +- required accelerator resources; +- operator interface; +- active capabilities; +- live Worlds. + +No special restoration required. + +### QUIET + +AIEN remains actively executing, but unused resources may be reduced or powered down. + +Examples: + +- display off; +- unused accelerator regions released; +- unnecessary devices suspended; +- background work reduced; +- model retained where useful. + +Logical state is unchanged. + +### SLEEP + +Execution is substantially suspended while sufficient volatile state remains available for rapid continuation. + +The implementation may retain: + +- RAM; +- selected inference state; +- model residency; +- scheduler structures; +- selected device state. + +Wake should normally continue from preserved physical state. + +### DEEP SLEEP + +AIEN's logical state remains durable while expensive volatile execution state may be discarded. + +The system must preserve everything required to reconstruct the same logical agent. + +Physical resources such as: + +- KV pages; +- accelerator buffers; +- model residency; +- caches; +- temporary allocations; + +may be discarded. + +Wake reconstructs whatever physical state is missing. + +### COLD RECOVERY + +Used when useful volatile state does not survive, including: + +- complete power removal; +- kernel failure; +- hardware reset; +- severe corruption; +- machine replacement. + +AIENOS initializes the execution substrate, locates the latest valid durable AIEN state, verifies it, and reconstructs execution. + +Cold recovery is not agent creation. + +--- + +## 5. State classes + +Every important AIEN state object must be classified according to whether it defines identity or is merely an execution optimization. + +### Class A — durable semantic state + +Loss changes who AIEN is, what it knows, what it has committed to, or what it is doing. + +This state must survive according to the persistence contract. + +Examples include: + +```text +LogicalAgentId +LogicalBranchId +canonical TokenHistory / branch history +branch lineage +Cortex committed state +provenance +World manifests +durable tasks +capability grants +operator policy +accepted decisions +conversation history where committed +effect history +execution lineage metadata +RNG coordinates required for deterministic continuation +persistent configuration +``` + +Class A must never depend solely on volatile memory. + +### Class B — reconstructible physical state + +Loss costs time or computation but does not change logical identity. + +Examples: + +```text +KV cache +accelerator buffers +compiled execution caches +temporary tensor residency +model pages cached in RAM +scheduler caches +prefix-cache materializations +derived indexes +``` + +Class B may be retained when economically useful. + +It may be discarded under pressure or deep sleep. + +It must be reconstructible from Class A state plus immutable artifacts. + +### Class C — ephemeral scratch state + +State with no semantic requirement to survive. + +Examples: + +```text +temporary buffers +intermediate activations +scratch allocations +temporary benchmark structures +uncommitted speculative work +``` + +Class C may disappear at any time consistent with transaction semantics. + +--- + +## 6. Commit-before-observation rule + +AIENOS must not rely on periodic "memory saves" as the primary continuity mechanism. + +Durable semantic state should be committed transactionally as the system operates. + +The governing principle is: + +> **A state transition that future AIEN behavior depends upon must cross its required durability boundary before AIEN treats that transition as committed.** + +For externally visible semantic events, prefer: + +```text +compute/propose transition + ↓ +commit required logical state + ↓ +make transition externally visible +``` + +Examples include: + +- accepted conversation turns; +- committed Cortex updates; +- durable branch creation; +- durable task-state changes; +- accepted external effects; +- important operator decisions. + +This does **not** require every neural activation or intermediate tensor to be persisted. + +Transient model computation remains transient. + +The persistent layer records semantic continuity, not every electrical detail of execution. + +--- + +## 7. Wake is reconstruction, not revival + +A wake event should follow this abstract decision tree: + +```text +wake event + ↓ +validate logical AIEN root + ↓ +what physical state survived? + │ + ├── sufficient state survives + │ ↓ + │ resume + │ + └── physical state missing + ↓ + reconstruct from durable state + ↓ + resume +``` + +The operator-facing result should be the same logical AIEN regardless of which path occurred. + +The user should not need to know whether AIENOS: + +- resumed RAM; +- rebuilt KV; +- reloaded model weights; +- replayed a journal; +- reconstructed branches; +- restarted the kernel; +- moved to another machine. + +Those are substrate concerns. + +--- + +## 8. Model lifecycle + +The model is not AIEN's identity. + +Therefore: + +```text +AIEN + ↓ +Model A +``` + +may become: + +```text +AIEN + ↓ +Model B +``` + +without creating another logical agent. + +Likewise: + +```text +model unload +model reload +model corruption +model replacement +backend replacement +``` + +are execution events. + +The durable AIEN state survives them. + +Model corruption must prevent the corrupted model from loading. + +It must not force creation of a new agent. + +--- + +## 9. Kernel lifecycle + +The kernel is also not AIEN's identity. + +A maintenance restart may be: + +```text +AIEN logical state committed + ↓ +kernel stops + ↓ +new kernel starts + ↓ +durable state verified + ↓ +same AIEN continues +``` + +The same principle applies to kernel upgrades and A/B slot changes. + +The Recovery Core verifies and restores the execution environment. + +It does not invent a replacement AIEN. + +--- + +## 10. Hardware lifecycle + +Ultimately a physical machine is also not AIEN's identity. + +Long-term: + +```text +Machine A fails + ↓ +durable AIEN state survives + ↓ +Machine B obtains authorized state + ↓ +required physical execution state reconstructed + ↓ +same LogicalAgentId continues +``` + +Hardware migration is therefore an extension of the same continuity semantics used for sleep and reboot. + +This capability need not exist during the initial Spark milestones, but no early architecture should make it impossible. + +--- + +## 11. Deterministic wake path + +The earliest wake path must remain deterministic. + +A neural model is not required to decide how the computer wakes. + +The deterministic system is responsible for: + +```text +wake event detection +hardware restoration +integrity verification +persistent-state discovery +journal recovery +execution-state classification +reconstruction launch +recovery fallback +``` + +Only once a valid execution environment exists does the neural runtime resume. + +AIEN may later optimize its sleep and wake policy. + +It may not become necessary to recover from its own absence. + +--- + +## 12. Power management objective + +AIENOS should optimize for **continuous existence with minimum necessary resource residency**, not repeated full startup. + +The scheduler/power manager may determine that a given period requires only: + +```text +timer +storage +network +crypto +``` + +without waking: + +```text +display +GPU +large model +interactive interface +``` + +Likewise an event requiring reasoning may progressively wake additional capabilities. + +Conceptually: + +```text +event + ↓ +determine required capability set + ↓ +wake minimum required hardware/runtime + ↓ +perform work + ↓ +return unnecessary resources to lower-power state +``` + +This is an optimization policy. + +The architecture does not prescribe the exact power-management mechanism. + +--- + +## 13. Ordinary operator semantics + +The normal operator vocabulary should eventually favor: + +- **Wake** +- **Sleep** +- **Deep Sleep** +- **Restart Runtime** +- **Restart Kernel** +- **Power Off** + +rather than treating shutdown/boot as the normal lifecycle. + +`Power Off` remains available because the operator owns the machine. + +It is an exceptional physical-state transition, not logical agent deletion. + +--- + +## 14. Planned power-off + +Before an intentional complete power-off, AIENOS should attempt to establish a clean continuity point: + +```text +stop accepting new semantic work + ↓ +commit pending durable state + ↓ +commit Cortex/WAL state + ↓ +record branch/task continuation information + ↓ +write continuity receipt/checkpoint + ↓ +verify persistent state + ↓ +power off +``` + +On the next cold start: + +```text +hardware bootstrap + ↓ +verify continuity state + ↓ +same LogicalAgentId + ↓ +reconstruct execution +``` + +--- + +## 15. Unexpected power loss + +AIENOS must assume power can disappear without warning. + +Therefore continuity cannot depend exclusively on orderly shutdown. + +Recovery uses: + +```text +last valid checkpoint ++ +durable WAL / journals ++ +immutable object manifests ++ +integrity hashes +``` + +Any uncommitted tail is discarded according to its subsystem's recovery rules. + +Externally committed state must never depend on an uncommitted volatile-only transition. + +--- + +## 16. Changes to the locked Systems-Integration Sequence + +The ten gates remain unchanged. + +Continuous-existence requirements are inserted into their acceptance criteria. + +The gate-by-gate amendments are binding and are mirrored in [SYSTEMS_INTEGRATION_SEQUENCE.md](SYSTEMS_INTEGRATION_SEQUENCE.md) §2. + +### Gate 1 — Config A Reference Freeze + +No structural change. + +Add baseline measurements for: + +- existing host cold-start behavior; +- model reload time; +- current state-restoration behavior where measurable. + +Config A remains the historical comparison. + +### Gate 2 — Native Boot Spine + +Purpose remains native execution from firmware. + +Gate 2 does **not** prove persistent AIEN continuity yet. + +Its semantics are now explicitly: + +> The boot spine initializes the physical machine. It does not define or create an AIEN identity. + +No `LogicalAgentId` should be minted merely because Gate 2 code starts. + +### Gate 3 — Integrate `aienos-kernel` + +Kernel lifecycle structures must not assume that kernel lifetime equals agent lifetime. + +Interfaces introduced here should allow durable logical state to outlive: + +- kernel restart; +- scheduler reconstruction; +- allocator reconstruction. + +No persistent agent identifier may be derived solely from volatile kernel identifiers. + +### Gate 4 — Native Storage Bring-Up + +Gate 4 becomes the first major continuity foundation. + +The AIEN System Store must be capable of persistently representing at least: + +```text +provisioned LogicalAgentId / agent root +committed logical state +Cortex checkpoints/WAL foundation +branch/state manifests +immutable artifact references +continuity metadata +``` + +Gate 4 qualification should prove that committed semantic data survives native storage round trips. + +No model is required. + +### Gate 5 — Recovery Core + +Add the following mandatory test. + +#### Identity-loss refusal + +Corrupt or remove the active execution environment while leaving a valid durable AIEN identity. + +Recovery must: + +1. locate the valid durable identity; +2. authenticate the operator; +3. restore or select the valid system state; +4. preserve the same `LogicalAgentId`. + +If no valid durable AIEN identity can be recovered: + +> Recovery must stop and ask the operator. + +It must **not** silently create a new identity. + +### Gate 6 — Agent State + Cortex + +This becomes the first empirical qualification of **continuous AIEN existence**. + +Mandatory scenario: + +```text +native AIENOS + ↓ +provision/restore AIEN + ↓ +LogicalAgentId = X + ↓ +create Cortex state +create branch/task state +commit conversation/state + ↓ +full power cycle + ↓ +cold native AIENOS start + ↓ +recover state + ↓ +LogicalAgentId = X +``` + +The proof must demonstrate: + +- same durable `LogicalAgentId`; +- preserved committed Cortex state; +- preserved branch lineage; +- preserved durable task/state metadata; +- uncommitted state handled according to WAL rules; +- no hidden creation of a replacement identity. + +Only after this passes may the project claim: + +> **AIEN logical identity survives a real Spark power cycle.** + +### Gate 7 — Inference Bring-Up + +Add the following qualification: + +```text +AIEN identity X + ↓ +model loads + ↓ +conversation continues + ↓ +model unload/reboot/reload + ↓ +same AIEN identity X + ↓ +conversation/state continuity preserved +``` + +The model must be demonstrably replaceable/reloadable beneath the same logical agent. + +This gate proves: + +> **Inference execution can disappear and return without redefining AIEN.** + +### Gate 8 — AEGIS & J-Space Worlds + +Durable authorization semantics must survive sleep/recovery correctly. + +Persist what must persist. + +Do not persist temporary authority that was explicitly scoped to a single volatile session unless its policy says otherwise. + +A wake/restart must never accidentally broaden capability authority. + +### Gate 9 — C1 Physical Tree + +Connect C1 directly to lifecycle semantics. + +Mandatory cases should eventually include: + +```text +live branch + ↓ +physical KV discarded + ↓ +logical branch preserved + ↓ +KV reconstructed + ↓ +equivalence passes +``` + +and: + +```text +branch committed + ↓ +deep-sleep simulation + ↓ +all physical KV gone + ↓ +logical state restored + ↓ +branch reconstruction + ↓ +same LogicalBranchId +``` + +This empirically connects: + +> Losing KV costs computation, not identity. + +to the native OS lifecycle. + +### Gate 10 — Native Hardware Acceleration + +Acceleration must not weaken continuity. + +GPU/accelerator state is Class B reconstructible physical state unless explicitly proven otherwise. + +Native acceleration should optimize: + +- warm wake; +- model residency; +- branch residency; +- KV preservation; +- state reconstruction; + +but AIEN's identity may never become dependent on preserving accelerator state. + +--- + +## 17. Benchmark changes + +The existing Config A/B/C comparison remains. + +Add lifecycle metrics rather than replacing the existing boot metrics. + +Measure separately: + +```text +cold hardware bootstrap → kernel ready +cold recovery → AIEN logical state restored +AIEN restored → model ready +wake from sleep → interactive +wake from deep sleep → interactive +model reconstruction latency +branch reconstruction latency +Cortex recovery latency +energy consumed while sleeping +idle residency cost +``` + +This prevents "boot time" from hiding fundamentally different paths. + +Eventually the most important user-facing metric should become: + +> **wake-to-continuation latency** + +rather than merely boot-to-shell. + +--- + +## 18. Continuity receipts + +Important lifecycle transitions should produce verifiable continuity evidence. + +A continuity receipt may record: + +```text +LogicalAgentId +previous committed state digest +new committed state digest +Cortex checkpoint/WAL position +branch-lineage digest +execution fingerprint +machine identity +transition type +transition epoch +reconstruction mode +integrity result +``` + +Transition types may include: + +```text +sleep +wake +deep_sleep +cold_recovery +runtime_restart +kernel_restart +model_replace +machine_migration +``` + +The exact schema may evolve. + +The requirement is that continuity claims become auditable rather than inferred. + +--- + +## 19. Failure semantics + +AIENOS must fail toward preservation. + +If the system cannot prove that a recovered logical state belongs to the existing AIEN: + +```text +STOP + ↓ +Recovery Core + ↓ +operator decision +``` + +Never: + +```text +state uncertain + ↓ +generate new agent automatically + ↓ +pretend continuity +``` + +False continuity is worse than refusing to continue. + +--- + +## 20. Engineering-agent freedom + +This amendment defines semantics, not implementation. + +The engineering agent remains free to determine: + +- low-power mechanisms; +- checkpoint strategy; +- memory residency strategy; +- wake implementation; +- firmware interaction; +- hardware power states; +- storage layout; +- serialization; +- reconstruction algorithms; +- device restoration; +- scheduling; +- cache persistence; +- model-residency policies. + +The acceptance requirement is behavioral: + +> **The same durable AIEN must emerge on the other side of the transition whenever valid committed state exists.** + +--- + +## 21. Revised persistent-thing rule + +The existing architecture statement: + +> The persistent thing is AIEN itself. + +is strengthened to: + +> **AIEN is the persistent logical entity. Hardware, kernels, models, runtime processes, inference caches, interfaces, and Machines are replaceable execution substrates. Sleep changes residency. Reboot changes execution substrate. Failure triggers reconstruction. None of these events inherently terminates logical identity.** + +--- + +## 22. Final lifecycle objective + +The desired mature experience is: + +```text +operator presses power / wake + ↓ +machine restores required substrate + ↓ +AIEN continues +``` + +not: + +```text +operator powers machine + ↓ +system constructs a new assistant + ↓ +loads old memories into it +``` + +The distinction is architectural. + +The target is therefore: + +> **Power on the machine: AIEN wakes.** + +not: + +> **Power on the machine: AIEN is recreated.** + +--- + +## 23. Project definition amendment + +The one-line definition of the project is amended to: + +> **AIENOS is an agent-native operating system designed around continuous logical agent existence: the agent persists while models, kernels, inference state, power states, and physical machines change beneath it.** diff --git a/docs/MILESTONES.md b/docs/MILESTONES.md new file mode 100644 index 00000000..eab941e5 --- /dev/null +++ b/docs/MILESTONES.md @@ -0,0 +1,391 @@ +# AIENOS Architectural Milestones Matrix & Execution Plan + +**Status:** Confirmed Architectural Specification +**Version:** 1.0.0 +**Governing Documents:** +- [AIENOS Governing Architecture](ARCHITECTURE.md) +- [AIENOS Final Architectural Blueprint (37 Sections)](BLUEPRINT.md) +- [AIENOS Technical Specification & Contracts (Phases 3–5)](PHASE_3_TO_5_SPECIFICATION.md) +- [AIENOS Systems Integration Sequence & Epistemic Calibration](SYSTEMS_INTEGRATION_SEQUENCE.md) +- [AIENOS Continuous-Existence Amendment](CONTINUOUS_EXISTENCE_AMENDMENT.md) (Operator-approved governing amendment: lifecycle semantics binding on all phases and the 10-gate sequence; gate order unchanged) +- [Architectural Decision Records (ADRs) Index](adr/README.md): + - [ADR 0001: Native Boot Milestone & Linux Island](adr/0001-native-boot-milestone-and-linux-island.md) + - [ADR 0002: Incumbent OS as Migration Environment](adr/0002-incumbent-os-as-migration-environment.md) + - [ADR 0003: Bootstrap Firmware Handoff & Minimal Object Store](adr/0003-bootstrap-firmware-handoff-and-minimal-object-store.md) + - [ADR 0004: Reversibility Definition & Network Effect Boundary](adr/0004-reversibility-definition-and-network-effect-boundary.md) + - [ADR 0005: Unified Memory C1 CoW & Reservation Accounting](adr/0005-unified-memory-c1-cow-and-reservation-accounting.md) + - [ADR 0006: Deterministic Recovery Core & Offline Operator Authority](adr/0006-deterministic-recovery-core-and-offline-operator-authority.md) + - [ADR 0007: Continuous Existence & Provisioning-Once](adr/0007-continuous-existence-provisioning-once.md) + +> **Foundational Mandate to the Engineering Agent:** +> *“You own the route; this document owns the destination.”* + +--- + +## 1. Master Phased Execution Framework + +The AIENOS master execution sequence progresses across eight distinct phases. The order expresses architectural dependency, not administrative bureaucracy. Each phase establishes sovereign deliverables, enforceable invariants, objective acceptance tests, and explicit escalation triggers. + +```text +PHASE 1: Freeze Reality (Config A Ubuntu Reference Baseline) + ↓ +PHASE 2: Native AIENOS Boot (Minimal Bare-Metal Substrate) + ↓ +PHASE 3: The Agent Wakes Up (Persistent Agent & Early Memory) + ↓ +PHASE 4: Native System Intelligence (Capability Graph & AEGIS) + ↓ +PHASE 5: Native Hardware Acceleration (Sovereignty & A/B/C Competition) + ↓ +PHASE 6: Migration System (Machine Capsule & Reversible Install) + ↓ +PHASE 7: Multi-Hardware AIENOS (BSP Expansion Beyond DGX Spark) + ↓ +PHASE 8: Personal Fabric (Distributed Nodes & State Mobility) + ↓ +MATURE AIENOS: Sovereign Agent-Native Personal Computing +``` + +--- + +## 2. Core Architectural Invariants Governing All Phases + +Every implementation artifact must preserve these eleven foundational invariants: + +1. **Model is Never the Kernel (Blueprint §6, ARCHITECTURE.md §1, ADR 0006):** Kernel schedules CPU, manages memory, services interrupts, mounts storage, authenticates the operator with offline credentials, and executes deterministic recovery with zero AI models loaded. +2. **Separation of Authority and Proposal (Blueprint §5, ARCHITECTURE.md §1, ADR 0004):** The agent cannot authorize itself. Irreversible actions and external effects strictly flow: `Model Proposal -> EffectIntent -> AEGIS Policy -> Effect Broker -> Driver`. +3. **Identity vs. Execution Separation & C1 Branch Isolation (Blueprint §2, §28, ADR 0005):** Losing physical inference state (GPU crash, bus reset, KV cache eviction, process restart) costs computation, never logical identity. Physical KV blocks are managed via explicit block tables and reservations; child branch memory corruption can never leak into parent state; logical token lineage survives indefinitely. +4. **Sovereign Trusted Base (Blueprint §4, ARCHITECTURE.md §3, ADR 0006):** Boot, kernel, memory management, scheduler, storage core, cryptography, recovery core, and AEGIS build from inspectable open-source code with zero mandatory proprietary or cloud dependencies. +5. **Compatibility as Island, Not Foundation (Blueprint §8, ADR 0001):** Compatibility layers (e.g. minimal Linux GPU island / Config B) are temporary acceleration mechanisms. Native Config C must never depend on Config B artifacts, CUDA userspace, or Linux kernel modules; removing Config B leaves native AIENOS fully buildable, bootable, and recoverable. +6. **Reversible Autonomy & Explicit Effect Boundary (Blueprint §12, ARCHITECTURE.md §5, ADR 0004):** Agent is fully autonomous inside reversible Worlds where state changes remain under AIENOS transactional control. All outbound network traffic, telemetry, and uncheckpointed device state changes cross into AEGIS as external effects requiring explicit capability authorization, even when read-only. +7. **Capability-Centric Computing (Blueprint §13, ARCHITECTURE.md §2):** Functionality is organized into composable capabilities (`filesystem.read`, `mail.send`, `code.build`). Applications do not own underlying capabilities or personal data; personal data is native OS state. +8. **Replaceable Model Intelligence (Blueprint §14):** The Model ABI decouples weights, tokenizers, backends, and sampling from agent identity. Changing models does not redefine agent identity. +9. **Constrained "Fastest Wins" (Blueprint §31, ADR 0001):** Among implementations satisfying correctness, security, sovereignty, and interface contracts, the fastest measured implementation wins. Speed never overrides sovereignty. +10. **Controlled Self-Improvement (Blueprint §32, ARCHITECTURE.md §5):** Recursive self-improvement occurs strictly out-of-band in isolated Worlds via candidate evaluation, signing, and canary deployment; the agent never mutates the running kernel in-place. +11. **Continuous Existence / Provisioning-Once (Continuous-Existence Amendment, ADR 0007):** AIEN is provisioned once; boot, reboot, sleep, model reload, kernel restart, hardware failure, and migration are execution-state transitions—not agent creation events. Cold boot initializes hardware and must never silently mint a replacement `LogicalAgentId`. Losing physical execution state costs recovery or computation, not identity. + +--- + +## 3. Autonomous Engineering Protocol & Escalation Triggers + +Engineering agents operate autonomously within milestone boundaries (Blueprint §4, §29, §30): +- **Autonomous Authority:** Agents freely select data structures, crate layouts, memory allocators, scheduling algorithms, low-level assembly routines, build scripts, and optimization passes. +- **Goal Immutability:** If an implementation approach fails, the agent iterates or replaces the implementation (Blueprint §30); the destination milestone and architectural invariants remain fixed. +- **The 15 Mandatory Escalation Triggers (Requiring Immediate Operator Signoff):** + 1. Alteration of the root of trust, Secure Boot policy, or cryptographic boot verification chain. + 2. Broadening of agent, service, or operator authority, autonomous expansion of capability grants, elevation of synthetic process privileges, removal of AEGIS policy gates, or bypass of the Effect Broker without explicit operator cryptographic authorization. + 3. Modification of persistent identity semantics or the Agent State ABI hierarchy. + 4. Weakening of security boundaries, memory isolation, or J-Space World containment. + 5. Introduction of irreversible data formats into Cortex or persistent storage. + 6. Permitting compatibility infrastructure (e.g. Linux or proprietary CUDA) to become a mandatory prerequisite for native AIENOS build, boot, or recovery (ADR 0001). + 7. Introducing closed-source proprietary binaries, external cloud licensing, or opaque compiler toolchains into the trusted base. + 8. Removing or disabling recovery media, fallback boot targets, or system rollback guarantees. + 9. Alteration of externally visible protocol commitments or API contracts. + 10. Structural modifications to the 7-layer architecture stack. + 11. Retaining firmware/UEFI runtime storage services beyond boot handoff, or introducing general-purpose POSIX filesystem dependencies (e.g. ext4, btrfs) instead of the native minimal persistent object store (ADR 0003). + 12. Bypassing AEGIS capability evaluation for outbound network traffic, external telemetry, or uncheckpointed device effects under the pretext of 'reversible' execution within a World (ADR 0004). + 13. Unstructured or untracked physical KV memory allocation, admitting multi-branch inference steps without transactional KV block reservations, or violating C1 CoW block refcounting rules (ADR 0005). + 14. Introducing AI model inference, cloud identity, or network dependencies into the Recovery Core, health milestone verification, A/B slot rollback, or WAL corruption repair (ADR 0006). + 15. Silently creating a replacement `LogicalAgentId` on boot, wake, recovery, or migration when durable identity state is missing or unverifiable; treating cold boot, sleep, model reload, kernel restart, or hardware failure as agent-creation events (Continuous-Existence Amendment, ADR 0007). + +--- + +## 4. Detailed Phase Specifications + +### Phase 1: Freeze Reality (Config A Reference Baseline) +- **Blueprint Sections Mapped:** §15 (Phase 1 Freeze reality), §21 (Machine Capsule), §27 (Evidence Architecture). +- **Secondary Sections:** §1 (Vision), §4 (Engineering Boundaries), §36 (Execution Sequence). +- **Governing ADRs:** [ADR 0001](adr/0001-native-boot-milestone-and-linux-island.md) (defines Config A as the frozen Ubuntu reference baseline), [ADR 0002](adr/0002-incumbent-os-as-migration-environment.md) (host inspection generates Machine Capsule without host runtime dependencies). +- **Mission:** Freeze the operational DGX Spark / Linux reference baseline (`Config A`) before writing native code, establishing an auditable, reproducible ground truth for all performance and sovereignty claims. +- **Deliverables & Artifacts:** + - `scripts/freeze_reality.sh`: Non-destructive host inspection script capturing hardware identity, firmware, kernel parameters, runtime libraries, and workspace commit digests. + - `evidence/config_a_reference_bundle.json`: Verifiable reference bundle containing the complete 15-component Section 21 Machine Capsule. + - `schemas/machine_capsule.schema.json`: Formal JSON schema enforcing Section 21 specification. + - `scripts/verify_evidence.sh`: Automated schema and cryptographic SHA-256 validation script. +- **Architectural Invariants:** + - Non-destructive execution: zero writes outside `evidence/`; no modifications to host disks, boot entries, NVRAM, or EFI partitions. + - 100% empirical truth: no hardware descriptors may be mocked, synthesized, or assumed. + - Self-contained verifiability: verifiable with standard open-source tools (`jq`, `sha256sum`). +- **Acceptance Criteria:** + - `bash scripts/freeze_reality.sh` exits with return code `0`. + - `evidence/config_a_reference_bundle.json` exists, is valid JSON, and contains non-empty sections for all 15 Machine Capsule components. + - `bash scripts/verify_evidence.sh evidence/config_a_reference_bundle.json` exits with return code `0`, confirming schema validity and SHA-256 self-consistency. +- **Escalation Triggers:** + - Hardware inspection requiring destructive host actions or privileged modifications. + - Any unreadable, inaccessible, or non-verifiable hardware descriptor required by the Blueprint Section 21 Machine Capsule specification (no descriptors may be mocked, synthesized, or assumed). + - Any write operation or modification to host storage, partition tables, EFI boot entries, or host NVRAM during evidence capture. + +--- + +### Phase 2: Native AIENOS Boot (Minimal Bare-Metal Substrate) +- **Blueprint Sections Mapped:** §6 (The AIENOS Kernel), §16 (Phase 2 Native AIENOS boot). +- **Secondary Sections:** §4 (Sovereignty Boundaries), §5 (Boot & Trust Substrate), §7 (Hardware Ownership), §27 (Evidence Architecture). +- **Governing ADRs:** [ADR 0001](adr/0001-native-boot-milestone-and-linux-island.md) (mandates native AIENOS boot on bare-metal ARM64 as primary milestone; minimal Linux wrappers prohibited as native substrate), [ADR 0003](adr/0003-bootstrap-firmware-handoff-and-minimal-object-store.md) (firmware loads boot bundle; storage services are bootstrap only), [ADR 0006](adr/0006-deterministic-recovery-core-and-offline-operator-authority.md) (deterministic non-model Recovery Core and raw panic crash records). +- **Mission:** Power on the DGX Spark and boot the sovereign `no_std` AIENOS kernel targeting 64-bit ARM (`aarch64`) directly on bare metal without Linux hosting the system. +- **Deliverables & Artifacts:** + - `crates/aienos-kernel/Cargo.toml`: Standalone `no_std`, `no_main` bare-metal kernel crate targeting `aarch64-unknown-none`. + - `crates/aienos-kernel/linker.ld`: Sovereign ARM64 linker script enforcing clean segment separation (`.text`, `.rodata`, `.data`, `.bss`, `.stack`) and deterministic entry point `_start`. + - `crates/aienos-kernel/src/main.rs`: Bare-metal CPU initialization, early stack setup, and boot flow. + - `crates/aienos-kernel/src/drivers/uart.rs`: MMIO serial console driver targeting the physical Tegra/16550 UART at MMIO base `0x16A00000` (stride 4, 32-bit width, 921600 baud). + - `crates/aienos-kernel/src/panic.rs`: Sovereign panic handler emitting deterministic telemetry to UART and executing an infinite `wfi` halt loop. + - `scripts/verify_all.sh`: End-to-end verification script compiling the kernel and verifying evidence. + - `evidence/build_and_test_evidence.log`: Verifiable compilation and test execution log. +- **Architectural Invariants:** + - Model is Never the Kernel (Blueprint §6): Boot, memory initialization, interrupt setup, and panic handling proceed with zero AI models loaded. + - Sovereign Toolchain (Blueprint §4): Zero dependencies on Linux standard library (`std`), glibc, musl, or Linux syscalls. + - Deterministic Panic: Panic handler must disable interrupts (`daifset`) and halt CPU without external runtime shims. +- **Acceptance Criteria:** + - `cargo check --target aarch64-unknown-none` within `crates/aienos-kernel` exits with status `0` and zero warnings. + - `cargo build --target aarch64-unknown-none --release` produces valid bare-metal ELF binary. + - Linker layout inspection verifies that `_start` is at the expected entry address and segments do not overlap. + - Serial driver writes ASCII telemetry to MMIO register base `0x16A00000`. +- **Escalation Triggers:** + - Any compilation requirement introducing dependencies on Linux libc, POSIX headers, or host kernel modules. + - Firmware incompatibility requiring proprietary binary shims to achieve early CPU control. + - Any modification, deletion, or tampering with host disk partitions, the physical EFI system partition (`/boot/efi`), host bootloaders, or firmware NVRAM bootloader variables (`efibootmgr`, `/sys/firmware/efi/efivars`, `BootOrder`, `BootNext`) outside the repository workspace without prior operator cryptographic authorization. + - Retaining UEFI/firmware runtime storage services as an AIENOS runtime dependency beyond the initial immutable boot bundle handoff (violating ADR 0003). + - Introducing AI model or external network dependencies into early kernel panic handling or recovery console routines (violating ADR 0006). + +--- + +### Phase 3: The Agent Wakes Up (Persistent Agent & Early Memory) +- **Blueprint Sections Mapped:** §2 (Central Architectural Principle), §11 (Cortex), §14 (Model ABI), §17 (Phase 3 The agent wakes up). +- **Secondary Sections:** §5 (Boot Trust), §9 (Agent State ABI), §33 (UX Feel). +- **Governing ADRs:** [ADR 0003](adr/0003-bootstrap-firmware-handoff-and-minimal-object-store.md) (minimal persistent object store for model extents and Cortex WAL), [ADR 0007](adr/0007-continuous-existence-provisioning-once.md) (continuous existence; provisioning is not boot). +- **Technical Specification:** [Phase 3 Technical Specification](PHASE_3_TO_5_SPECIFICATION.md#2-phase-3-the-persistent-agent-wakes-up) (Agent State ABI & Cortex Epistemic Store). +- **Mission:** Initialize the AIEN Neural Runtime on the native kernel, load a local CPU inference model, wake the persistent resident AIEN agent, and verify that Cortex persists epistemic memory across reboots. +- **Deliverables & Artifacts:** + - `crates/aienos-agent-state/`: Foundational Persistent Agent State ABI managing sovereign `LogicalAgentId` and execution incarnation decoupling (`ExecutionIncarnation`). + - `crates/aienos-runtime/`: Native neural runtime executive operating directly on kernel substrate. + - `crates/aienos-model-abi/`: Model ABI implementation abstracting weights, tokenizers, and execution backends from agent identity. + - `crates/aienos-cortex/`: Early durable Cortex storage engine supporting write-ahead epistemic logging on NVMe storage. + - Local CPU inference backend executing quantized language model (e.g. Llama-3.2-1B / Qwen). + - Native console dialogue interface enabling direct operator-agent interaction. + - `evidence/phase3_reboot_persistence_receipt.json`: Verifiable proof of state retention across soft reboot. +- **Architectural Invariants:** + - Identity vs Execution Separation (Blueprint §2): Restarting the model, clearing KV cache, or rebooting the machine must not create a new agent identity. + - Provisioning-Once (Continuous-Existence Amendment, ADR 0007): Only initial provisioning may mint a durable `LogicalAgentId`; every later start resumes that identity or stops in Recovery Core. + - Self-Diagnostic Focus (Blueprint §17): The first agent's primary duty is observing, diagnosing, and repairing AIENOS itself; general conversational features are secondary. + - Model Replaceability (Blueprint §14): Changing model weights or backend leaves agent identity and Cortex history intact. +- **Acceptance Criteria:** + - Machine boots natively -> Runtime starts -> Local model weights load into RAM -> Agent prompts operator on console within 10 seconds. + - Operator issues diagnostic command via console; agent queries kernel tables and returns factual response. + - System executes reboot; agent wakes, loads previous session context from Cortex, and acknowledges continuity. + - Full power cycle: same durable `LogicalAgentId`, committed Cortex/branch/task state restored, uncommitted tails handled by WAL rules, no silent replacement identity (Gate 6 continuous-existence proof). + - Model unload/reload (or model swap) under the same `LogicalAgentId` preserves conversation and durable state continuity (Gate 7). +- **Escalation Triggers:** + - Failure of agent identity continuity across system reboot. + - Any boot, wake, recovery, or migration path that silently creates a replacement `LogicalAgentId` instead of restoring or refusing (ADR 0007). + - Model weights or runtime demanding network connection or cloud licensing servers to execute. + - Memory corruption during CPU weight ingestion that forces fallback to Linux userspace. + +--- + +### Phase 4: Native System Intelligence (Capability Graph & System Control) +- **Blueprint Sections Mapped:** §3 (Final System Architecture), §5 (Boot & Trust / AEGIS), §9 (Agent State ABI), §10 (Copy-on-Write Prefix Sharing), §12 (Worlds / J-Space), §13 (Capability Graph), §18 (Phase 4 Native system intelligence), §28 (C1 Invariant Foundation), §32 (Self-Improvement). +- **Secondary Sections:** §11 (Cortex Deep Tiering), §35 (Strategic Endpoint). +- **Mission:** Transform the resident agent into the primary system interface and coordinator via dynamic Capability Graph composition. Enforce AEGIS policy control and J-Space reversible execution Worlds. Formalize the Agent State ABI and C1 Copy-on-Write prefix sharing. +- **Deliverables & Artifacts:** + - `crates/aienos-aegis/`: AEGIS capability authorization engine enforcing deterministic security policies. + - `crates/aienos-broker/`: Effect Broker translating validated `EffectIntent` into concrete device/storage/network actions. + - `crates/aienos-capabilities/`: Capability Graph registry managing dynamic capability composition. + - `crates/aienos-jspace/`: Reversible World sandbox subsystem with snapshotting, checkpointing, and instant rollback. + - `crates/aienos-state/`: Agent State ABI managing `LogicalAgentId`, `LogicalBranchId`, and physical `SequenceId`. + - `crates/aienos-c1/`: C1 verification suite proving branch isolation, memory conservation, and parent survival. +- **Architectural Invariants:** + - Agent Cannot Authorize Itself (Blueprint §5): Every irreversible system action flows `EffectIntent -> AEGIS -> Effect Broker`. + - Reversible Autonomy (Blueprint §12): Total freedom inside reversible Worlds; strict cryptographic approval at irreversible boundaries. + - Mathematical Branch Isolation (Blueprint §28): Reasoning branches share physical prefix pages; child branch memory corruption can never leak into parent state. +- **Acceptance Criteria:** + - Agent processes natural language operator intent ("find memory leak") by generating an isolated World, running diagnostics, and proposing a safe resolution diff. + - AEGIS policy interceptor denies an unauthorized `EffectIntent` (e.g. disk write to reserved partition) with an auditable cryptographic receipt. + - C1 benchmark runs 100 concurrent reasoning branches sharing a 100K token prefix; memory consumption scales sub-linearly with zero state cross-contamination. + - Failed build experiment inside a World rolls back cleanly with zero modified bytes on the root filesystem. +- **Escalation Triggers:** + - Any architectural bypass where an agent executes an external effect without passing through AEGIS. + - Silent broadening of operator permissions or capability grant escalation. + - State leak across reasoning branches violating the C1 invariant. + +--- + +### Phase 5: Native Hardware Acceleration (GPU/NVLink Ownership & A/B/C Competition) +- **Blueprint Sections Mapped:** §7 (Hardware Sovereignty), §8 (Compatibility Islands), §19 (Phase 5 Native hardware acceleration), §31 ("Fastest Wins" Properly Defined). +- **Secondary Sections:** §10 (CoW Prefix Sharing), §27 (Evidence Architecture). +- **Governing ADR:** [ADR 0001](adr/0001-native-boot-milestone-and-linux-island.md) (defines 3-way configuration competition Config A vs B vs C; Config B must never become prerequisite for Config C; defines 9-11 benchmark metrics and scoped 'fastest wins'). +- **Mission:** Progressively transition hot hardware paths (accelerator, NVLink-C2C, NVMe storage, network) to native AIENOS ownership. Execute the standardized A/B/C benchmark competition across Config A (Ubuntu baseline), Config B (Minimal Linux compatibility island), and Config C (Native AIENOS bare-metal substrate) measuring the original performance metrics plus continuous-existence lifecycle metrics (wake-to-continuation and reconstruction latencies). +- **Deliverables & Artifacts:** + - `crates/aienos-accel/`: Native GPU/NPU memory management and execution driver for NVIDIA Blackwell GB10 over NVLink-C2C. + - `crates/aienos-nvme/`: Direct high-performance NVMe driver bypassing general-purpose VFS layers. + - `crates/aienos-net/`: Native network driver (Realtek RTL8127 2.5GbE). + - `scripts/benchmark_abc.sh`: Non-interactive benchmark suite executing identical prompt/model envelopes across Configs A, B, and C. + - `evidence/benchmark_abc_receipt.json`: Standardized evaluation receipt documenting comparative performance and lifecycle metrics. +- **Architectural Invariants:** + - Sovereignty Precedes Speed (Blueprint §31, ADR 0001): "Fastest wins" applies ONLY among implementations satisfying correctness, security, and sovereignty contracts. + - Compatibility Island Isolation (Blueprint §8, ADR 0001): Config B is a temporary control experiment and Era II island; removing it must leave Config C fully operational. + - Zero Closed Blobs in Trusted Base: Native accelerator interfaces must not introduce proprietary, uninspected userspace binaries into the core kernel address space. + - Accelerator State Is Class B (Continuous-Existence Amendment, ADR 0007): GPU/accelerator residency is reconstructible physical state; identity never depends on preserving it. +- **Acceptance Criteria:** + - Standardized benchmark executes across Config A, Config B, and Config C measuring: + 1. Cold boot to agent ready (ms) + 2. Agent ready to model ready (ms) + 3. TTFT (Time to First Token, ms) + 4. Steady-state throughput (tokens/s) + 5. Idle physical memory footprint (MB) + 6. Available workload memory (MB) + 7. Scheduler jitter (µs) + 8. Power consumption (W) + 9. Branch creation latency (µs) + 10. Branch physical memory cost (KB) + 11. State restore time (ms) + 12. Wake-to-continuation latency (ms; Continuous-Existence Amendment lifecycle metric) + 13. Cold recovery → AIEN logical state restored (ms) + 14. Model reconstruction latency (ms) + 15. Branch reconstruction latency (ms) + 16. Cortex recovery latency (ms) + - Config C demonstrates measurable latency, jitter, or memory density improvements over Config A while maintaining 100% test pass rates. +- **Escalation Triggers:** + - Proposal to declare Config B (Linux island) as the permanent architecture. + - Introduction of proprietary closed runtime blobs that cannot be isolated into an optional island. + - Benchmark regression where native paths fail correctness or safety requirements in pursuit of throughput. + +--- + +### Phase 6: Migration System (Machine Capsule, Dual-Boot & Reversible Install) +- **Blueprint Sections Mapped:** §20 (Phase 6 Migration system), §21 (Machine Capsule), §22 (Reversible installation), §23 (Progressive escape from incumbent OS), §34 (The adoption proposition), ADR 0002. +- **Secondary Sections:** §4 (Sovereignty Boundaries), §5 (Boot Trust). +- **Governing ADR:** [ADR 0002](adr/0002-incumbent-os-as-migration-environment.md) (governs progressive escape from incumbent OS; AIENOS may learn from host but must not require host to survive). +- **Mission:** Deploy host-side bootstrap tools on incumbent operating systems (Windows, macOS, Linux). Scaffolding inventories the machine, generates a Section 21 Machine Capsule, installs AIENOS with reversible dual-boot, and guides the operator through the 7-stage progressive escape lifecycle. +- **Deliverables & Artifacts:** + - `tools/aienos-installer/`: Host-side inspection and partition setup CLI. + - Machine Capsule compiler validating host hardware against AIENOS BSP requirements. + - Reversible EFI dual-boot installer configuring side-by-side boot entries without overwriting host bootloaders. + - Automated watchdog recovery harness reverting to the incumbent OS if native boot fails. + - Adoption lifecycle tracker managing progression across Stages 1 through 7. +- **Architectural Invariants:** + - Host as Scaffolding (Blueprint §20, ADR 0002): AIENOS may learn from the host, but must never require the host to survive once installed. + - Reversible Installation (Blueprint §22): The incumbent OS bootloader, partition table, and user data remain intact and bootable at all times. + - Non-Coercive Migration (Blueprint §23): AIENOS never forces host removal; the operator retains full sovereignty over migration stages. +- **Acceptance Criteria:** + - Installer runs non-destructively on host OS; outputs valid Section 21 Machine Capsule. + - Dual-boot partition carved and formatted; EFI boot entry registered with watchdog counter. + - Test boot into AIENOS verifies kernel, storage, input, and model loading. + - Simulated kernel panic during boot triggers watchdog reset into incumbent OS bootloader. +- **Escalation Triggers:** + - Incompatible host disk layout (e.g. unsupported software RAID or locked bootloader) that cannot be safely partitioned. + - Host inspection identifying proprietary peripherals lacking open documentation or safe compatibility fallback. + - Accidental modification or corruption of host OS partitions. + +--- + +### Phase 7: Multi-Hardware AIENOS (BSP Expansion Beyond DGX Spark) +- **Blueprint Sections Mapped:** §7 (Hardware Sovereignty), §21 (Machine Capsule), §24 (Phase 7 Multi-hardware AIENOS). +- **Secondary Sections:** §2 (Identity Separation), §14 (Model ABI). +- **Mission:** Decouple AIENOS from DGX Spark hardware assumptions. Generalize kernel and runtime abstractions into a formal Hardware Abstraction Layer (HAL) and Board Support Packages (BSPs) for desktop x86_64, generic ARM64, AMD accelerators, and Apple silicon. +- **Deliverables & Artifacts:** + - `crates/aienos-hal/`: Hardware Abstraction Layer defining standard CPU, MMU, interrupt, timer, and DMA interfaces. + - `crates/bsp-dgx-spark/`: Reference BSP for NVIDIA Grace Blackwell P4242 board. + - `crates/bsp-x86_64/`: Standard PC / ACPI Board Support Package. + - `crates/bsp-arm64-generic/`: Generic ARM64 Board Support Package. + - Cross-architecture automated emulation test harness (QEMU x86_64 and QEMU aarch64). + - Platform portability receipts (`evidence/platform_matrix_receipt.json`). +- **Architectural Invariants:** + - Hardware Independence (Blueprint §24): Spark is a reference machine, not AIEN's identity. Core kernel logic, AEGIS, Cortex, and Agent State ABI are strictly platform-agnostic. + - Uniform Contract Enforcement: All supported platforms must guarantee identical behavioral semantics for capability execution, branch isolation, and memory persistence. +- **Acceptance Criteria:** + - `cargo test --workspace` passes across both `aarch64` and `x86_64` targets. + - Automated QEMU test boots AIENOS on both `x86_64` and `aarch64`, initializing serial consoles, memory maps, and panic handlers. + - Agent state exported from DGX Spark loads and resumes execution on an x86_64 target under identical invariant proofs. +- **Escalation Triggers:** + - Platform-specific workarounds that leak architecture-dependent behavior into higher-level runtime or agent crates. + - Introduction of proprietary binary firmware blobs into the core HAL without open-source fallbacks. + +--- + +### Phase 8: Personal Fabric (Distributed Nodes & State Mobility) +- **Blueprint Sections Mapped:** §1 (The Final Vision), §25 (Phase 8 Personal Fabric), §26 (State Mobility), §33 (What the Finished System Feels Like), §35 (The Strategic Endpoint), §37 (Final Definition of Success). +- **Secondary Sections:** §2 (Central Principle), §9 (Agent State ABI), §27 (Evidence Architecture). +- **Mission:** Expand AIEN into a personal distributed fabric where a single logical AIEN identity spans multiple physical machines (DGX Spark compute + laptop display/keyboard + mobile sensors). Implement state mobility (`migrate(agent_state)`) allowing execution branches to move across physical nodes with dynamic KV reconstruction. Fully satisfy all 15 Blueprint Section 37 final success criteria. +- **Deliverables & Artifacts:** + - `crates/aienos-fabric/`: Sovereign peer-to-peer fabric protocol for inter-node capability discovery, state synchronization, and RPC. + - State Mobility Engine: Native implementation of `migrate(agent_state)` with on-demand physical KV reconstruction. + - Heterogeneous compute scheduler placing model inference on accelerator nodes and UI projection on client devices. + - Autonomous local fallback daemon ensuring disconnected nodes remain functional. + - Blueprint Section 37 Master Verification Suite (`tests/section_37_audit.rs`). + - `evidence/phase8_final_success_receipt.json`: Signed verification receipt certifying full realization of the AIENOS vision. +- **Architectural Invariants:** + - Identity Above Machines (Blueprint §25): The agent's identity exists above physical machines; computers are replaceable compute and I/O resources. + - State Mobility Invariant (Blueprint §26): Logical state migrates; physical state is reconstructed or lazily synchronized; migration preserves continuous identity. + - Partition Sovereignty: Node disconnection must never freeze local core operating capabilities; nodes fall back to autonomous local mode. +- **Acceptance Criteria:** + - Two independent physical nodes establish encrypted P2P fabric connection and merge capability graphs. + - Active reasoning branch is suspended on Node A, transmitted across the fabric, and resumed on Node B with identical context within 2000 ms. + - Section 37 Master Audit passes 100% of all 15 final criteria. +- **Escalation Triggers:** + - Network protocol introducing centralized cloud coordination or external third-party identity providers. + - Split-brain network partition resulting in permanent divergent agent identities without automatic reconciliation. + +--- + +## 5. Master 37-Section Blueprint Traceability Matrix + +| # | Section Title | Primary Phase | Key Deliverables | Enforced Invariants | Verification Gate | +|---|---|---|---|---|---| +| **1** | The final vision | Phase 8 | `docs/MILESTONES.md`, Boot flow | Identity survives hardware/model changes | Direct power-on boot into AIEN | +| **2** | Central architectural principle | Phase 3 | `crates/aienos-state/`, Cortex | State loss costs compute, not identity | Identity persists across soft reboot | +| **3** | Final system architecture | Phase 4 | 7-layer stack in `crates/` | Strict layer boundary separation | End-to-end intent execution crossing layers | +| **4** | Fixed vs decision space | Phase 2 | Cargo workspace, sovereign crates | Zero cloud or proprietary dependencies | Builds with open toolchains | +| **5** | Boot and trust architecture | Phase 2 | Secure Boot hooks, AEGIS engine | Agent cannot authorize itself | Unauthorized intent rejected | +| **6** | The AIENOS kernel | Phase 2 | `aienos-kernel`, `linker.ld` | Model is never the kernel | Boots without model loaded | +| **7** | Hardware sovereignty | Phase 5 | `crates/aienos-accel/`, NVMe | Direct hot-path hardware ownership | Native MMIO/DMA without host OS | +| **8** | Compatibility islands | Phase 5 | Config B (`minimal-linux-island`) | Island is not the foundation | Boots with Config B deleted | +| **9** | Agent State ABI | Phase 4 | `crates/aienos-state/` | Logical state decoupled from physical KV | Branch fork/suspend/resume unit tests | +| **10** | Copy-on-write agent computation | Phase 4 | `crates/aienos-c1/`, CoW allocator | Read-only prefix KV page sharing | Sub-linear memory scaling across branches | +| **11** | Cortex | Phase 3 | `crates/aienos-cortex/`, NVMe log | Epistemic distinctions preserved | Cortex persistence survives reboot | +| **12** | Worlds / J-Space | Phase 4 | `crates/aienos-jspace/`, Worlds | Reversible inside; approval at boundary | Rollback discards diff with zero leak | +| **13** | Capability Graph | Phase 4 | `crates/aienos-capabilities/` | Capabilities replace applications | Intent executes via capability composition | +| **14** | Model ABI | Phase 3 | `crates/aienos-model-abi/` | Models are replaceable components | Model swap leaves identity intact | +| **15** | Phase 1 — Freeze reality | Phase 1 | `freeze_reality.sh`, bundle JSON | Non-destructive read-only capture | Script exits 0; schema validates | +| **16** | Phase 2 — Native AIENOS boot | Phase 2 | `aienos-kernel`, UART driver | Boots bare metal without Linux host | Cargo build exits 0; emits banner | +| **17** | Phase 3 — The agent wakes up | Phase 3 | Runtime, CPU model, console loop | Agent wakes natively; Cortex persists | Console dialogue; persists post-reboot | +| **18** | Phase 4 — Native intelligence | Phase 4 | AEGIS, Broker, Capabilities, Worlds | Natural language operating control | Intent diagnostics pass in sandbox | +| **19** | Phase 5 — Hardware acceleration | Phase 5 | Native GB10 driver, benchmark suite | Constrained "fastest wins"; accelerator state is Class B | Performance + lifecycle benchmark report emitted | +| **20** | Phase 6 — Migration system | Phase 6 | `tools/aienos-installer/` | Host OS is scaffolding | Dual-boot installed from host OS | +| **21** | Machine Capsule | Phase 1 | Machine Capsule schema & parser | 15-component hardware descriptor | Schema validation passes on bundle | +| **22** | Reversible installation | Phase 6 | Dual-boot partitioner, watchdog | Host OS remains bootable | Watchdog resets to host on panic | +| **23** | Progressive escape from host | Phase 6 | 7-stage migration state machine | Voluntary adoption progression | Progression across Stages 1–7 verified | +| **24** | Phase 7 — Multi-hardware | Phase 7 | `aienos-hal`, x86_64/ARM64 BSPs | Hardware is replaceable substrate | Tests pass on both x86_64 and aarch64 | +| **25** | Phase 8 — Personal Fabric | Phase 8 | `crates/aienos-fabric/`, P2P sync | Single identity across machines | P2P capability mesh links nodes | +| **26** | Eventually: state mobility | Phase 8 | `migrate(agent_state)` engine | State moves; physical KV recomputed | Reasoning branch migrates Node A to B | +| **27** | Evidence architecture | Phase 1 | Verification scripts, SHA receipts | Evidence earns claims | Cryptographically signed receipts | +| **28** | C1's role | Phase 4 | `crates/aienos-c1/` formal suite | Proof of branch isolation & CoW | Formal C1 stress tests pass | +| **29** | Autonomous engineering model | Phase 1–8 | Dispatch logs, `progress.md` | Autonomous between milestone gates | Iterations pass without micromanagement | +| **30** | Failure changes route not goal | Phase 1–8 | Engineering logs, alternative algos | Destination milestone is immutable | Alternate algorithm passes gate | +| **31** | "Fastest wins" properly defined | Phase 5 | Benchmark selection filter | Correctness & sovereignty first | Faster candidate rejected if unsovereign | +| **32** | Self-improvement | Phase 4 | World canary evaluation pipeline | Out-of-band evaluation; no live patch | Canary test rejects flawed patch | +| **33** | Finished system feel | Phase 8 | Dynamic UI projection engine | Power on → AIEN wakes | Cold boot wakes interactive agent | +| **34** | The adoption proposition | Phase 6 | Host discovery onboarding flow | Non-coercive adoption | Native boot target prepared safely | +| **35** | The strategic endpoint | Phase 8 | Complete architectural runtime | Operator → Agent → Capabilities → AIENOS | Total agent-native computing realized | +| **36** | Master execution sequence | Phase 1–8 | Milestone dependency DAG | Phased dependency ordering | Exit criteria verified before unlock | +| **37** | Final definition of success | Phase 8 | Master Audit Suite | All 15 criteria verified true | 15/15 binary conditions passing | + +--- + +## 6. Master Success Criteria (Blueprint Section 37) Verification Matrix + +| # | Blueprint Section 37 Success Condition | Verifying Phase | Implementing Artifact / Crate | Objective Verification Test Method | +|---|---|---|---|---| +| **1** | The machine can boot without Windows, macOS or Linux acting as its host. | Phase 2 | `crates/aienos-kernel` (`_start`) | Power-on boot test into native bare-metal ELF on DGX Spark; kernel emits UART banner. | +| **2** | AIENOS can recover without an AI model. | Phase 2 | `crates/aienos-kernel` (`recovery.rs`) | Boot into recovery mode with zero model files on storage; mount storage and execute diagnostic shell. | +| **3** | The AIEN agent survives reboot as the same logical entity. | Phase 3 | `crates/aienos-runtime`, `cortex` | Soft reboot during active conversation; agent wakes and verifies prior interaction history. | +| **4** | Cortex survives and preserves evidence/provenance semantics. | Phase 3 | `crates/aienos-cortex` | Write epistemic graph with observations and facts; power cycle; query Cortex and verify hashes. | +| **5** | The model can be replaced without replacing AIEN. | Phase 3 | `crates/aienos-model-abi` | Swap underlying model weights from Model A to Model B; verify agent identity and history remain intact. | +| **6** | Agent inference state can be branched, suspended, reclaimed and reconstructed without changing logical identity. | Phase 4 | `crates/aienos-state`, `crates/aienos-c1` | Create 5 reasoning branches; suspend 3; evict physical KV; resume; verify identity and recomputed context. | +| **7** | The agent operates the machine through explicit capabilities. | Phase 4 | `crates/aienos-capabilities` | Natural language intent translated into `CapabilityCall` (`fs.read`, `system.inspect`) without app silos. | +| **8** | Irreversible effects cross enforceable authorization boundaries. | Phase 4 | `crates/aienos-aegis`, `broker` | Attempt disk partition format; verify AEGIS blocks execution pending operator cryptographic grant. | +| **9** | The operator can recover from AIEN failure. | Phase 3 | Kernel fallback console & recovery media | Kill runtime process; kernel falls back to deterministic low-level recovery console. | +| **10** | No outside company is required for ordinary continued operation. | Phase 2 | Sovereign build chain & local model | Disconnect physical network cable; execute complete boot, inference, storage, and agent loop. | +| **11** | Important native hardware paths are directly controlled by AIENOS. | Phase 5 | `crates/aienos-accel`, `nvme`, `net` | Direct MMIO register access to GB10 accelerator and NVMe block devices without host drivers. | +| **12** | Compatibility layers are optional rather than foundational. | Phase 5 | Benchmark Config B isolation | Delete Config B Linux compatibility image; confirm native AIENOS boots, executes, and recovers. | +| **13** | The system can prove its important performance and correctness claims. | Phase 1 | `scripts/verify_evidence.sh` | Every benchmark and test emits cryptographically signed JSON evidence receipts into `evidence/`. | +| **14** | The user can move to another supported machine without their AIEN being permanently tied to old hardware. | Phase 7 | `crates/aienos-fabric`, `aienos-hal` | Export agent state from DGX Spark; import and resume on x86_64 host under identical identity. | +| **15** | Ordinary experience: Power on the machine. AIEN wakes up. | Phase 8 | Complete integrated AIENOS | Cold power button press leads directly to interactive AIEN agent greeting without intermediate desktop. | diff --git a/docs/PHASE_3_TO_5_SPECIFICATION.md b/docs/PHASE_3_TO_5_SPECIFICATION.md new file mode 100644 index 00000000..30814447 --- /dev/null +++ b/docs/PHASE_3_TO_5_SPECIFICATION.md @@ -0,0 +1,229 @@ +# AIENOS: Technical Specification & Contracts (Phases 3 – 5) + +> **Status:** Architecture Blueprint Extension +> **Target:** Native Agent Wakeup, Epistemic Memory, Capability Enforcement, and C1 Branch-Native Compute +> **Authority:** AIENOS Final Architectural Blueprint §§ 9–14, 17–19, 28 + +--- + +## 1. Overview & Phased Roadmap + +This specification establishes the formal data structures, interface boundaries, and invariant contracts for the three evolutionary phases succeeding Native Bare-Metal Boot (Phase 2): + +```text +Phase 2 (Substrate) Phase 3 (Continuity) Phase 4 (Intelligence) Phase 5 (Sovereignty) +┌─────────────────┐ ┌─────────────────────┐ ┌─────────────────────┐ ┌─────────────────────┐ +│ AIENOS Kernel │ ───► │ Persistent Agent │──► │ AEGIS & J-Worlds │ ──► │ Direct GB10 Path │ +│ no_std aarch64 │ │ Agent State ABI │ │ Capability Graph │ │ Hardware C1 VMM │ +│ UART / MMIO │ │ Cortex Epistemic │ │ C1 Prefix Tree (§28)│ │ A/B/C Benchmarks │ +└─────────────────┘ └─────────────────────┘ └─────────────────────┘ └─────────────────────┘ +``` + +--- + +## 2. Phase 3: The Persistent Agent Wakes Up + +### 2.1 The Agent State ABI (§9) + +The foundational principle dictates: **Losing physical inference state costs computation, not identity.** +The Agent State ABI separates persistent semantic identity from ephemeral execution incarnations. + +```text +LogicalAgentId (UUID v7 / Ed25519 public key) + │ + ├── LogicalBranchId (Deterministic UUID / SHA-256 derivation) + │ ├── ParentBranchId: Option<LogicalBranchId> + │ ├── TokenHistory: Append-only log of token sequence IDs & hashes + │ ├── Lineage: Tree path from root Genesis Agent + │ └── EpistemicRefs: Set of Cortex observation/fact UUIDs + │ + ▼ +Execution Incarnation (Ephemeral per boot/process) + │ + ├── IncarnationId: u64 (Monotonic boot counter) + ├── SequenceId: u32 (Scheduler slot) + └── PhysicalInferenceState: + ├── KVPageTableRef: Option<PhysicalPageTablePtr> + ├── AcceleratorBufferRef: Option<BufferHandle> + └── ComputeState: Idle | Prefilling | Decoding | Suspended | Evicted +``` + +#### Core ABI Operations +```rust +pub trait AgentStateAbi { + /// Fork an existing logical branch into an isolated child branch + fn fork_branch(&self, parent: LogicalBranchId) -> Result<LogicalBranchId, StateError>; + + /// Checkpoint logical agent state to durable storage + fn checkpoint(&self, agent_id: LogicalAgentId) -> Result<CheckpointHash, StateError>; + + /// Suspend execution incarnation without mutating logical state + fn suspend(&mut self, branch_id: LogicalBranchId) -> Result<(), StateError>; + + /// Resume execution, re-instantiating physical state via recompute or cache + fn resume(&mut self, branch_id: LogicalBranchId) -> Result<SequenceId, StateError>; + + /// Reconstruct lost physical state from TokenHistory and EpistemicRefs + fn reconstruct_physical(&mut self, branch_id: LogicalBranchId) -> Result<(), StateError>; +} +``` + +### 2.2 Model ABI (§14) + +Models are swappable intelligence components, not the operating system or root of trust. + +```rust +pub trait ModelAbi { + type Token; + type Logits; + + /// Query static architecture metadata + fn metadata(&self) -> ModelMetadata; + + /// Initialize prompt prefill context + fn prefill(&mut self, tokens: &[Self::Token], state: &mut PhysicalInferenceState) -> Result<(), ModelError>; + + /// Decode the next token step + fn step(&mut self, state: &mut PhysicalInferenceState) -> Result<Self::Logits, ModelError>; + + /// Tokenize text to internal token IDs + fn tokenize(&self, text: &str) -> Vec<Self::Token>; + + /// Detokenize IDs back to UTF-8 + fn detokenize(&self, tokens: &[Self::Token]) -> String; +} +``` + +### 2.3 Cortex Epistemic Store (§11) + +Cortex preserves knowledge with verifiable provenance, preventing self-reinforcing hallucination. + +```rust +#[repr(u8)] +pub enum EpistemicStatus { + DirectObservation = 1, // Raw sensor / hardware / file input + VerifiedFact = 2, // Mathematically / cryptographically proven + Inference = 3, // Model deduction from observations + Hypothesis = 4, // Tentative exploration branch + Contradiction = 5, // Detected epistemic conflict + OperatorDecision = 6, // Canonical directive from operator +} + +pub struct EpistemicRecord { + pub id: Uuid, + pub status: EpistemicStatus, + pub statement: String, + pub provenance_source: String, + pub evidence_hash: [u8; 32], + pub created_at_utc: u64, + pub confidence: f32, + pub verified_by: Option<String>, +} +``` + +--- + +## 3. Phase 4: Native System Intelligence (AEGIS, Worlds & Capabilities) + +### 3.1 The Capability Graph (§13) + +Traditional process permissions are replaced with unforgeable capability tokens arranged in a directed acyclic capability graph. + +```text +root.authority (Operator) + │ + ├── cap::filesystem [scope: /projects, mode: rw] + ├── cap::network [scope: local-fabric, port: 8080] + ├── cap::model [model: Llama-3.2-1B, max_tokens: 4096] + ├── cap::device [device: MMIO_UART, access: read_write] + └── cap::world [action: create, max_depth: 4] +``` + +### 3.2 AEGIS Effect Intent Pipeline (§5) + +Intelligence proposes; deterministic authority disposes. The model cannot authorize itself. + +```text +AIEN Reasoning Loop + │ + ▼ (Proposes action) + EffectIntent { + action: "publish_code", + parameters: { repo: "aienos-repo", commit: "..." }, + claimed_capability: "cap::git::publish" + } + │ + ▼ + AEGIS Evaluator + ├── 1. Cryptographic validation of capability token + ├── 2. Verification of operator policy (Is action reversible?) + │ ├── Reversible (Inside World) ──► Auto-Approve + │ └── Irreversible (External) ──► Solicit Operator Approval + │ + ▼ (Approved) + EffectBroker + │ (Dispatches to native device / driver) + ▼ + Hardware / Network / Disk Effect +``` + +### 3.3 J-Space Worlds (§12) + +A World is an isolated, transactional sandbox with copy-on-write semantics: +- Modifications to files, memory, and runtime state are isolated to a delta layer. +- Rollback is instantaneous via pointer drop. +- Promotion to canonical state requires an explicit `PromoteWorldIntent` verified by AEGIS. + +--- + +## 4. Phase 5: Native Hardware Acceleration & Hardware-Bound C1 Compute + +### 4.1 Hardware-Accelerated C1 Copy-On-Write Engine (§10, §19, §28) +> *Note:* The algorithmic C1 Copy-On-Write prefix tree data structure and §28 invariants are established in Phase 4 (`crates/aienos-c1-tree`); Phase 5 binds physical KV page frames directly to the NVIDIA Blackwell GB10 accelerator over NVLink-C2C. + +Instead of replicating common prefix KV states across $N$ parallel reasoning branches, AIENOS maintains a shared physical prefix tree: + +```text +Root Prefix: System Prompt + Codebase Context (100K Tokens) +Physical Address: [Page 0x1000 .. 0x4000] (RefCount: 3) + │ + ┌───────────┼───────────┐ + ▼ ▼ ▼ + Branch 1 Branch 2 Branch 3 + (Plan A) (Plan B) (Plan C) + [Private] [Private] [Private] + Page 0x5000 Page 0x6000 Page 0x7000 +``` + +#### Invariant Matrix: +1. **Zero Duplication**: Shared prompt tokens map to identical physical KV pages. +2. **Deterministic Divergence**: Allocation of private pages occurs strictly upon divergent token generation. +3. **Eviction Independence**: Children preserve semantic identity even if physical KV pages are evicted to RAM or disk; reconstruction re-executes deterministically from the last checkpoint. + +### 4.2 Hardware Sovereignty: 3-Way Benchmark Suite (§19) + +Performance is measured systematically across three configurations: +- **Config A**: Reference baseline on Ubuntu 24.04 LTS (frozen in Phase 1). +- **Config B**: Minimal Linux compatibility island. +- **Config C**: Native AIENOS bare-metal substrate. + +```text +Benchmark Metrics: +1. Power-On to Agent Ready (ms) +2. Agent Ready to Model Inference Ready (ms) +3. Time-to-First-Token (TTFT) across 1K, 16K, 128K context +4. Sustained Token Generation (tokens/sec) +5. Branch Fork Overhead (microseconds to branch 100K context) +6. Scheduler Jitter (microseconds at 99.9th percentile) +7. Physical Memory Overhead per Concurrent Agent Branch (MiB) +``` + +--- + +## 5. Verification & Acceptance Criteria for Next Phases + +- [ ] `AgentStateAbi` supports deterministic serialization and deserialization across reboot. +- [ ] Epistemic store detects and rejects ungrounded self-reinforcing assertions. +- [ ] AEGIS sandbox rejects any irreversible effect originating from an unapproved intent. +- [ ] C1 COW tree demonstrates zero memory increase when branching a 10,000-token prefix across 10 concurrent exploratory branches. +- [ ] Machine-readable evidence logs accompany all measured performance claims. diff --git a/docs/SYSTEMS_INTEGRATION_SEQUENCE.md b/docs/SYSTEMS_INTEGRATION_SEQUENCE.md new file mode 100644 index 00000000..631978ca --- /dev/null +++ b/docs/SYSTEMS_INTEGRATION_SEQUENCE.md @@ -0,0 +1,122 @@ +# AIENOS Systems Integration Sequence & Epistemic Calibration + +> **Status:** Governing Integration Framework +> **Authority:** Operator Directive (2026-09-23) +> **Amendment:** [Continuous-Existence Amendment](CONTINUOUS_EXISTENCE_AMENDMENT.md) ([ADR 0007](adr/0007-continuous-existence-provisioning-once.md)) — binding on all gate acceptance criteria; **gate order unchanged** +> **Stage Transition:** Architecture-Definition → Systems-Integration +> **Core Mandate:** *“You own the route; this document owns the destination.”* + +--- + +## 1. Epistemic Calibration & Precision of Claims + +To preserve intellectual integrity across all public documentation, benchmark claims, and engineering reports, the following strict distinctions are enforced: + +1. **Host-Tested vs. Native-Qualified**: + - The modular crates (`aienos-kernel`, `aienos-agent-state`, `aienos-cortex`, `aienos-aegis`, `aienos-c1-tree`) currently have **phase-targeted crates implemented and host-tested**. + - Host unit tests (`cargo test`) demonstrate component logic on Linux userspace; they **do not** claim that those phases are completed on bare metal. + - Phases 1 through 8 are marked complete only when their invariants survive execution under real AIENOS boot, hardware resets, and native storage on the DGX Spark. + +2. **Prefix Sharing Claims**: + - “Zero-memory prefix sharing” specifically means **zero duplicated physical KV tensor payload** for the shared token prefix. + - It does not mean zero bytes allocated anywhere: branch metadata, block tables, reference counters, logical branch IDs, and scheduler bookkeeping consume structured RAM. + +3. **Identity Survival Claims**: + - “Logical identity survives indefinitely” is an **architectural invariant and contract**, not an empirical claim, until crash/reboot/storage-corruption test harnesses actually verify it across the full native stack. + - Per the [Continuous-Existence Amendment](CONTINUOUS_EXISTENCE_AMENDMENT.md): AIEN is provisioned once; boot, reboot, sleep, model reload, kernel restart, hardware failure, and migration are execution-state transitions—not agent creation events. Empirical claims still require the gate proofs below. + +4. **Provisioning vs. Boot**: + - Only initial provisioning may create a durable `LogicalAgentId`. + - Normal boot locates, verifies, and resumes an existing identity, or stops in the Recovery Core. It never silently mints a replacement. + +--- + +## 2. The 10-Step Systems Integration Sequence + +The engineering question is no longer *“What should AIENOS be?”* +It is: *“Can these independently correct pieces survive contact with one another, real firmware, real storage, real resets, and real hardware while preserving the frozen invariants?”* + +```text +Config A Freeze (Linux / DGX Spark reference baseline) + │ + ▼ +Native Boot Spine (firmware -> AIENOS boot artifact -> CPU/mem/UART/halt) + │ + ▼ +aienos-kernel Native Integration (physical MMIO, frame allocator, spinlocks) + │ + ▼ +Native Storage Bring-up (ADR 0003: minimal object store, WAL + model extents) + │ + ▼ +Recovery Core Verification (ADR 0006: deliberate failure, offline auth, no model) + │ + ▼ +Agent State + Cortex Integration (Real Phase 3: persistent identity across reboot) + │ + ▼ +Inference Bring-up (Local CPU GGUF inference, operator dialogue) + │ + ▼ +AEGIS & J-Space Worlds Integration (fail-closed network, standing capabilities) + │ + ▼ +C1 Physical Tree Integration (actual KV state, partial-block forks, reservations) + │ + ▼ +Native Hardware Acceleration (Direct GB10 MMIO, Config B/C 3-way benchmarking) +``` + +### Detailed Sequence & Acceptance Gates + +Continuous-existence clauses below come from the [Continuous-Existence Amendment](CONTINUOUS_EXISTENCE_AMENDMENT.md) and are binding without reordering gates. + +#### Step 1: Finish Config A Freeze +Capture the working Linux/NVIDIA reference baseline on the DGX Spark into `evidence/config_a_reference_bundle.json` with cryptographic digests (SHA-256), hardware identity, firmware versions, model hashes, baseline TTFT/throughput, and verified recovery procedures. + +**Continuous existence:** No structural change. Also baseline host cold-start behavior, model reload time, and measurable state-restoration behavior. Config A remains the historical comparison. + +#### Step 2: Create the Native Boot Spine +Make the DGX Spark reach AIENOS code directly from UEFI firmware (`_start` / `efi_main`). The milestone requires that AIENOS owns CPU execution, initial physical memory, timer/interrupt setup, early UART console output (`0x16A00000`), and a deterministic panic/halt loop (`wfi`). + +**Continuous existence:** The boot spine initializes the physical machine. It does not define or create an AIEN identity. No `LogicalAgentId` is minted merely because Gate 2 code starts. + +#### Step 3: Integrate `aienos-kernel` on Real Hardware +Transition the frame allocator, spinlocks, and SHA-256 hashing from host-compiled tests into the native bare-metal execution environment. + +**Continuous existence:** Kernel lifetime must not equal agent lifetime. Interfaces must allow durable logical state to outlive kernel restart, scheduler reconstruction, and allocator reconstruction. No persistent agent identifier may derive solely from volatile kernel identifiers. + +#### Step 4: Bring Up Native Storage (ADR 0003) +Implement the minimal native storage machinery necessary to discover partitions, read immutable content-addressed model extents (`model/<hash>`), read/write committed Cortex checkpoints, and safely replay/truncate the WAL. No POSIX filesystem required. + +**Continuous existence:** First major continuity foundation. The AIEN System Store must persistently represent at least: provisioned `LogicalAgentId` / agent root, committed logical state, Cortex checkpoints/WAL foundation, branch/state manifests, immutable artifact references, and continuity metadata. Qualification proves committed semantic data survives native storage round trips. No model required. + +#### Step 5: Prove Recovery Core Before the Model (ADR 0006) +Before any AI model boots autonomously, deliberately inject a fault (corrupt model extent, corrupt uncommitted WAL tail). Prove the operator can enter Recovery Core, authenticate with offline credentials, inspect the raw system record, and roll back to a known-good slot with zero model involvement. + +**Continuous existence — identity-loss refusal (mandatory):** Corrupt or remove the active execution environment while leaving a valid durable AIEN identity. Recovery must (1) locate the valid durable identity, (2) authenticate the operator, (3) restore or select the valid system state, and (4) preserve the same `LogicalAgentId`. If no valid durable AIEN identity can be recovered, Recovery must stop and ask the operator. It must not silently create a new identity. + +#### Step 6: Integrate Agent State + Cortex (The Real Phase 3 Gate) +Boot the system, create/modify logical agent state, persist it to the native object store, power cycle the machine, reconstruct the state, and prove that the exact same `LogicalAgentId` and causal branch lineage return. + +**Continuous existence — first empirical qualification:** `LogicalAgentId = X` → create Cortex/branch/task state → commit → full power cycle → cold native start → recover → same `LogicalAgentId = X`. Proof must show preserved committed Cortex state, branch lineage, durable task metadata, WAL handling of uncommitted tails, and no hidden replacement identity. Only after this passes: *AIEN logical identity survives a real Spark power cycle.* + +#### Step 7: Load Inference +Bring up local quantized CPU inference (e.g. 1B parameter GGUF). The acceptance condition is continuity: power on → native AIENOS → persistent agent → local model → console dialogue → reboot → continuity. + +**Continuous existence:** Identity X → model loads → conversation continues → model unload/reboot/reload → same identity X → conversation/state continuity preserved. The model must be replaceable/reloadable beneath the same logical agent. Proves inference execution can disappear and return without redefining AIEN. + +#### Step 8: Integrate AEGIS and Worlds +Execute the agent inside a transactional J-Space World. Verify that all outbound network attempts (DNS, TCP, TLS) fail closed unless covered by an explicit pre-authorized Standing Capability. Verify that discarding a World completely reverts file deltas. + +**Continuous existence:** Durable authorization semantics must survive sleep/recovery. Persist what must persist; do not persist temporary authority scoped to a single volatile session unless policy says otherwise. A wake/restart must never accidentally broaden capability authority. + +#### Step 9: Integrate the C1 Physical Tree +Connect the C1 Copy-On-Write tree to live inference KV state. Enforce transactional reservations before step admission, verify that a 10,000-token shared prefix allocates zero duplicate KV pages across child branches, and verify recomputation equivalence on memory pressure. + +**Continuous existence:** Mandatory cases include live branch → physical KV discarded → logical branch preserved → KV reconstructed → equivalence passes; and branch committed → deep-sleep simulation → all physical KV gone → logical state restored → reconstruction → same `LogicalBranchId`. Empirically binds *losing KV costs computation, not identity* to the native OS lifecycle. + +#### Step 10: Pursue Native Hardware Acceleration +With native correctness mathematically proven, introduce direct MMIO accelerator paths to the NVIDIA GB10, measuring performance against Config A (Ubuntu reference) and Config B (minimal Linux compatibility island). + +**Continuous existence:** Accelerator state is Class B reconstructible physical state unless explicitly proven otherwise. Optimize warm wake, model/branch residency, KV preservation, and state reconstruction—never make identity depend on preserving accelerator state. Lifecycle metrics (wake-to-continuation, reconstruction latencies) join the Config A/B/C report without replacing boot metrics. diff --git a/docs/adr/0003-bootstrap-firmware-handoff-and-minimal-object-store.md b/docs/adr/0003-bootstrap-firmware-handoff-and-minimal-object-store.md new file mode 100644 index 00000000..5d689e8c --- /dev/null +++ b/docs/adr/0003-bootstrap-firmware-handoff-and-minimal-object-store.md @@ -0,0 +1,21 @@ +# ADR 0003: Bootstrap Firmware Handoff and Minimal Persistent Object Store + +Status: accepted by the operator, 2026-09-23. +Governing: [ARCHITECTURE.md §3](../ARCHITECTURE.md), [BLUEPRINT.md §5, §15, §17](../BLUEPRINT.md), [ADR 0001](0001-native-boot-milestone-and-linux-island.md), [MILESTONES.md Phase 2, 3](../MILESTONES.md). +Specification: [PHASE_3_TO_5_SPECIFICATION.md §2](../PHASE_3_TO_5_SPECIFICATION.md#2-phase-3-the-persistent-agent-wakes-up). + +## Context + +Firmware (UEFI) services provide early machine initialization and hardware discovery. However, relying on UEFI runtime services creates a permanent foreign dependency on platform firmware code of unknown provenance, quality, and security posture. Similarly, general-purpose POSIX filesystems (ext4, btrfs, ZFS) introduce massive metadata overhead, journal complexity, and foreign driver dependencies into the trusted computing base. + +## Decision + +Firmware (UEFI) loads the immutable AIENOS boot bundle into memory; firmware storage services are strictly bootstrap machinery and never part of the permanent runtime. Persistent AIEN state (model weights, Cortex database, agent state) is loaded only after AIENOS owns a native block device path. + +Rather than implementing a complex general-purpose POSIX filesystem (e.g. ext4, btrfs), Phase 3 introduces a minimal, native persistent object store designed around immutable content-addressed extents (`model/<hash>`), journaled append-only state (`cortex/` WAL + checkpoints), and committed agent branches. + +## Consequences + +- Firmware handoff is one-way: once the native kernel initializes CPU and memory, firmware runtime calls are terminated. +- AIENOS boot does not depend on host partition schemes or complex POSIX filesystems. +- Persistent state is stored in content-addressed extents and append-only WAL streams, guaranteeing deterministic verification and crash recovery. diff --git a/docs/adr/0004-reversibility-definition-and-network-effect-boundary.md b/docs/adr/0004-reversibility-definition-and-network-effect-boundary.md new file mode 100644 index 00000000..d84e2aef --- /dev/null +++ b/docs/adr/0004-reversibility-definition-and-network-effect-boundary.md @@ -0,0 +1,23 @@ +# ADR 0004: Reversibility Definition and Network Effect Boundary + +Status: accepted by the operator, 2026-09-23. +Governing: [ARCHITECTURE.md §5](../ARCHITECTURE.md), [BLUEPRINT.md §5, §12, §13](../BLUEPRINT.md), [MILESTONES.md Phase 4](../MILESTONES.md). +Specification: [PHASE_3_TO_5_SPECIFICATION.md §3](../PHASE_3_TO_5_SPECIFICATION.md#3-phase-4-native-system-intelligence-aegis-worlds-capabilities). + +## Context + +Agent autonomy requires sandbox environments ("Worlds" / J-Space) where speculative reasoning, exploratory code execution, and intermediate computations can be evaluated safely. If effects inside a World cannot be rolled back, speculative execution risks leaking or corrupting persistent state. Outbound network traffic, DNS requests, and external device mutations leave irreversible traces in the external world. + +## Decision + +An action inside a World is reversible if and only if every externally observable state change caused by the action remains under AIENOS's transactional control, such that prior observable state can be restored without external cooperation. + +Because outbound network packets, telemetry, and external device state leave permanent externally observable artifacts (DNS logs, server connection logs, metadata disclosure), all outbound network access is classified as an external effect (`EffectIntent`) crossing into AEGIS, even when read-only. + +Reversibility and authorization are decoupled: agents may execute network fetches autonomously via pre-authorized standing capabilities, but network traffic never bypasses AEGIS capability evaluation under the guise of being "reversible research." + +## Consequences + +- Reversible execution is strictly confined to local transactional boundaries (memory and snapshot-capable local storage). +- Outbound network requests and hardware device state mutations are never classified as reversible; they require AEGIS policy evaluation and capability authorization. +- Agents cannot evade capability gates by labeling external communication as speculative or exploratory. diff --git a/docs/adr/0005-unified-memory-c1-cow-and-reservation-accounting.md b/docs/adr/0005-unified-memory-c1-cow-and-reservation-accounting.md new file mode 100644 index 00000000..e4187ea9 --- /dev/null +++ b/docs/adr/0005-unified-memory-c1-cow-and-reservation-accounting.md @@ -0,0 +1,23 @@ +# ADR 0005: Unified Memory C1 Copy-On-Write and Reservation Accounting + +Status: accepted by the operator, 2026-09-23. +Governing: [ARCHITECTURE.md §2, §7](../ARCHITECTURE.md), [BLUEPRINT.md §9, §10, §28](../BLUEPRINT.md), [MILESTONES.md Phase 4, 5](../MILESTONES.md). +Specification: [PHASE_3_TO_5_SPECIFICATION.md §4](../PHASE_3_TO_5_SPECIFICATION.md#4-phase-5-native-hardware-acceleration-hardware-bound-c1-compute). + +## Context + +On architectures with unified physical memory between CPU and GPU (such as NVLink-C2C on NVIDIA DGX Spark), address spaces are physically unified. Without explicit ownership and strict accounting, multi-branch agent reasoning can exhaust memory mid-step, corrupt shared KV cache prefixes, or allow memory churn across speculative branches to starve core system processes. + +## Decision + +Hardware unified addressability (NVLink-C2C on DGX Spark) does not mean unstructured ownership: AIENOS explicitly owns, tracks, and accounts for every physical inference KV block with distinct memory budgets (System, Model, KV Pool, Agent State, Cortex). + +Branches hold block tables mapping to shared physical prefix blocks (`refcount > 1`, immutable) and private blocks (`refcount == 1`). Multi-branch divergence is managed via transactional KV reservations prior to step admission to prevent out-of-memory mid-step corruption. + +Under memory pressure, physical state is reclaimed according to a value-preserving hierarchy (completed private state -> suspended private suffixes -> suspended shared prefix leases -> reconstructible state); logical agent identity and token lineage survive indefinitely while physical state is reconstructed from canonical history if evicted. + +## Consequences + +- Prefix sharing achieves sublinear physical memory scaling across concurrent reasoning branches. +- Physical memory exhaustion causes transactional admission denial or graceful eviction, never corrupted state or lost agent identity. +- Explicit refcounting prevents child branch mutations from corrupting parent or sibling KV state. diff --git a/docs/adr/0006-deterministic-recovery-core-and-offline-operator-authority.md b/docs/adr/0006-deterministic-recovery-core-and-offline-operator-authority.md new file mode 100644 index 00000000..08a13d93 --- /dev/null +++ b/docs/adr/0006-deterministic-recovery-core-and-offline-operator-authority.md @@ -0,0 +1,23 @@ +# ADR 0006: Deterministic Recovery Core and Offline Operator Authority + +Status: accepted by the operator, 2026-09-23. +Governing: [ARCHITECTURE.md §1, §4, §6](../ARCHITECTURE.md), [BLUEPRINT.md §5, §6, §33](../BLUEPRINT.md), [MILESTONES.md Phase 2, 6](../MILESTONES.md). +Sequence: [SYSTEMS_INTEGRATION_SEQUENCE.md Step 5](../SYSTEMS_INTEGRATION_SEQUENCE.md#step-5-prove-recovery-core-before-the-model-adr-0006). + +## Context + +If an operating system relies on an AI model or remote cloud network services to diagnose panics, verify boot health, authenticate operators, or repair corrupted persistent journals, any model hallucination, weight corruption, or network outage could render the machine permanently unbootable and irrecoverable. + +## Decision + +AIENOS incorporates an autonomous, deterministic Recovery Core operating completely outside the model, neural runtime, and network dependency chain. + +Root authority and authentication are entirely local (supporting offline physical credentials such as hardware/FIDO keys or local human passphrase key derivation via Argon2id before challenge-response, with zero reliance on cloud identity or AI verification; bare SHA-256 for password verification is strictly prohibited). + +System updates employ transactional A/B slot switching with deterministic kernel health milestone verification rather than subjective model assertions. Kernel panics capture deterministic crash records to dedicated raw storage, model weights are verified against cryptographic content hashes, and Cortex corruption is resolved via WAL truncation to the last valid committed record without requiring semantic model understanding. + +## Consequences + +- Machine survival and operator access never depend on model availability, inference correctness, or network connectivity. +- Corrupted WAL or model files are deterministically recovered or rolled back to verified states. +- System updates are atomic and safely reversible via hardware-backed A/B slots. diff --git a/docs/adr/0007-continuous-existence-provisioning-once.md b/docs/adr/0007-continuous-existence-provisioning-once.md new file mode 100644 index 00000000..f96beace --- /dev/null +++ b/docs/adr/0007-continuous-existence-provisioning-once.md @@ -0,0 +1,26 @@ +# ADR 0007: Continuous Existence and Provisioning-Once + +Status: accepted by the operator, 2026-09-23. +Governing: [ARCHITECTURE.md §1, §10](../ARCHITECTURE.md), [BLUEPRINT.md §2, §9, §17, §33](../BLUEPRINT.md), [MILESTONES.md Phase 3, 6, 8](../MILESTONES.md). +Sequence: [SYSTEMS_INTEGRATION_SEQUENCE.md Steps 1–10](../SYSTEMS_INTEGRATION_SEQUENCE.md) (acceptance criteria amended; gate order unchanged). +Full text: [CONTINUOUS_EXISTENCE_AMENDMENT.md](../CONTINUOUS_EXISTENCE_AMENDMENT.md). + +## Context + +Boot, reboot, sleep, model reload, kernel restart, hardware failure, and migration were at risk of being treated as agent-creation events. That would make logical identity depend on execution substrates (process, model, KV, RAM, kernel, boot session, machine) and would weaken the C1 rule that physical loss costs computation, not identity. + +## Decision + +AIEN is provisioned once. After initial provisioning creates the durable `LogicalAgentId` and agent root, every later machine start is an execution-state transition that must locate, verify, and resume that identity—or stop in the deterministic Recovery Core. Cold boot initializes hardware; it does not create AIEN. + +State is classified Class A (durable semantic), Class B (reconstructible physical), or Class C (ephemeral scratch). Commit-before-observation binds externally visible semantic transitions. Wake is reconstruction, not revival. Model, kernel, and hardware lifecycle events never implicitly mint a replacement identity. + +The locked 10-gate Systems-Integration Sequence keeps its order. Continuous-existence acceptance criteria are inserted into Gates 1–10 as specified in the amendment. Failure semantics fail toward preservation: uncertain continuity never auto-creates a new agent. + +## Consequences + +- Cold boot, sleep, deep sleep, cold recovery, runtime/kernel restart, model replace, and migration are lifecycle transitions with auditable continuity receipts—not agent creation. +- Gate 4 becomes the first durable continuity foundation; Gate 6 is the first empirical power-cycle identity proof; Gate 7 proves model replaceability under one identity. +- Recovery Core must refuse silent identity replacement when durable state cannot be verified (extends ADR 0006). +- C1 physical discard/reconstruct cases (extends ADR 0005) bind to native lifecycle semantics. +- Lifecycle metrics (wake-to-continuation, reconstruction latencies) join Config A/B/C benchmarks without replacing boot metrics. diff --git a/docs/adr/README.md b/docs/adr/README.md new file mode 100644 index 00000000..4b48c284 --- /dev/null +++ b/docs/adr/README.md @@ -0,0 +1,48 @@ +# Architectural Decision Records (ADRs) & Specifications + +This directory documents the key architectural decisions and formal technical specifications for AIENOS. Each record captures the context, decision, invariants, consequences, and operator approval. + +## 1. Master Index of Architectural Decision Records + +| ADR | Title | Status | Date | Primary Cross-References | +|---|---|---|---|---| +| [ADR 0001](0001-native-boot-milestone-and-linux-island.md) | Native boot with CPU inference stays the next milestone; minimal Linux is only Benchmark Config B | Accepted | 2026-09-23 | [`ARCHITECTURE.md` §3, §7](../ARCHITECTURE.md); [`BLUEPRINT.md` §8, §15, §16, §19, §31](../BLUEPRINT.md); [`MILESTONES.md` Phase 1, 2, 5](../MILESTONES.md) | +| [ADR 0002](0002-incumbent-os-as-migration-environment.md) | Incumbent operating systems are bootstrap and migration environments | Accepted | 2026-09-23 | [`ARCHITECTURE.md` §3](../ARCHITECTURE.md); [`BLUEPRINT.md` §20, §21, §22, §23, §34](../BLUEPRINT.md); [`MILESTONES.md` Phase 1, 6](../MILESTONES.md) | +| [ADR 0003](0003-bootstrap-firmware-handoff-and-minimal-object-store.md) | Bootstrap Firmware Handoff and Minimal Persistent Object Store | Accepted | 2026-09-23 | [`ARCHITECTURE.md` §3](../ARCHITECTURE.md); [`BLUEPRINT.md` §5, §15, §17](../BLUEPRINT.md); [`MILESTONES.md` Phase 2, 3](../MILESTONES.md); [`PHASE_3_TO_5_SPECIFICATION.md` §2](../PHASE_3_TO_5_SPECIFICATION.md#2-phase-3-the-persistent-agent-wakes-up); [ADR 0001](0001-native-boot-milestone-and-linux-island.md) | +| [ADR 0004](0004-reversibility-definition-and-network-effect-boundary.md) | Reversibility Definition and Network Effect Boundary | Accepted | 2026-09-23 | [`ARCHITECTURE.md` §5](../ARCHITECTURE.md); [`BLUEPRINT.md` §5, §12, §13](../BLUEPRINT.md); [`MILESTONES.md` Phase 4](../MILESTONES.md); [`PHASE_3_TO_5_SPECIFICATION.md` §3](../PHASE_3_TO_5_SPECIFICATION.md#3-phase-4-native-system-intelligence-aegis-worlds-capabilities) | +| [ADR 0005](0005-unified-memory-c1-cow-and-reservation-accounting.md) | Unified Memory C1 Copy-On-Write and Reservation Accounting | Accepted | 2026-09-23 | [`ARCHITECTURE.md` §2, §7](../ARCHITECTURE.md); [`BLUEPRINT.md` §9, §10, §28](../BLUEPRINT.md); [`MILESTONES.md` Phase 4, 5](../MILESTONES.md); [`PHASE_3_TO_5_SPECIFICATION.md` §4](../PHASE_3_TO_5_SPECIFICATION.md#4-phase-5-native-hardware-acceleration--hardware-bound-c1-compute) | +| [ADR 0006](0006-deterministic-recovery-core-and-offline-operator-authority.md) | Deterministic Recovery Core and Offline Operator Authority | Accepted | 2026-09-23 | [`ARCHITECTURE.md` §1, §4, §6](../ARCHITECTURE.md); [`BLUEPRINT.md` §5, §6, §33](../BLUEPRINT.md); [`MILESTONES.md` Phase 2, 6](../MILESTONES.md); [`SYSTEMS_INTEGRATION_SEQUENCE.md` §2.5](../SYSTEMS_INTEGRATION_SEQUENCE.md#step-5-prove-recovery-core-before-the-model-adr-0006) | +| [ADR 0007](0007-continuous-existence-provisioning-once.md) | Continuous Existence and Provisioning-Once | Accepted | 2026-09-23 | [`CONTINUOUS_EXISTENCE_AMENDMENT.md`](../CONTINUOUS_EXISTENCE_AMENDMENT.md); [`ARCHITECTURE.md` §1, §10](../ARCHITECTURE.md); [`SYSTEMS_INTEGRATION_SEQUENCE.md` Steps 1–10](../SYSTEMS_INTEGRATION_SEQUENCE.md); [`MILESTONES.md` Phase 3, 6, 8](../MILESTONES.md); [ADR 0005](0005-unified-memory-c1-cow-and-reservation-accounting.md); [ADR 0006](0006-deterministic-recovery-core-and-offline-operator-authority.md) | + +--- + +## 2. Architectural Specifications & Integration Frameworks + +In addition to discrete decision records, AIENOS maintains formal technical specifications and execution sequences that govern phased implementation: + +| Document | Scope | Status | Authority | Target Phases | +|---|---|---|---|---| +| [AIENOS Technical Specification & Contracts (Phases 3 – 5)](../PHASE_3_TO_5_SPECIFICATION.md) | Agent State ABI, Model ABI, Cortex Epistemic Store, AEGIS Effect Intent Pipeline, J-Space Worlds, and C1 CoW Prefix Tree | Confirmed Specification | Blueprint §§ 9–14, 17–19, 28 | Phases 3, 4, 5 | +| [AIENOS Systems Integration Sequence & Epistemic Calibration](../SYSTEMS_INTEGRATION_SEQUENCE.md) | 10-step empirical hardware integration sequence, epistemic claim precision, and host-tested vs. native-qualified gates | Governing Framework | Operator Directive (2026-09-23) | Phases 1 – 8 | +| [AIENOS Continuous-Existence Amendment](../CONTINUOUS_EXISTENCE_AMENDMENT.md) | Provisioning-once lifecycle, power states, state classes A/B/C, continuous-existence acceptance criteria for Gates 1–10 | Operator-Approved Governing Amendment | Operator Directive (2026-09-23); ADR 0007 | All Phases | +| [AIENOS Final Architectural Blueprint](../BLUEPRINT.md) | Complete 37-section architectural foundation, core principles, and final success definitions | Immutable Foundation | Operator Directive | All Phases | +| [AIENOS Architectural Milestones Matrix](../MILESTONES.md) | 8-phase execution roadmap, deliverables, invariant contracts, and escalation triggers | Confirmed Specification | Blueprint §36 | Phases 1 – 8 | +| [AIENOS Governing Architecture](../ARCHITECTURE.md) | High-level system overview, stack, trusted base, agent authority, security, and roadmap | Confirmed Architecture | Operator Directive | All Phases | + +--- + +## 3. Operator Invariant Freeze Summary (2026-09-23) + +The operator confirmed immutable architectural invariants in ADR 0003–0007: + +1. **ADR 0003 (Firmware Handoff & AIEN System Store)**: Firmware loads the immutable boot bundle only. Firmware services are bootstrap machinery, never a runtime dependency. Phase 3 introduces a minimal native AIEN System Store (immutable content-addressed extents `model/<hash>`, Cortex WAL + checkpoints, agent branches) rather than a general-purpose POSIX filesystem. +2. **ADR 0004 (Reversibility & AEGIS Egress Boundary)**: Reversibility requires that all observable state changes remain under AIENOS transactional control. Outbound network packets, telemetry, and external device state are external effects (`EffectIntent`) crossing into AEGIS even when read-only. Reversibility and authorization are decoupled via Standing Capabilities; network access never bypasses AEGIS under the guise of "reversible research." +3. **ADR 0005 (Unified Memory & C1 Block Accounting)**: Unified memory (NVLink-C2C) requires explicit block ownership across System, Model, KV Pool, Agent State, and Cortex budgets. C1 CoW prefix tree uses shared immutable blocks (`refcount > 1`) and private blocks (`refcount == 1`). Multi-branch divergence mandates transactional KV reservations prior to step admission to prevent mid-step OOM corruption. Logical identity survives; physical state is expendable. +4. **ADR 0006 (Recovery Core & Offline Authority)**: Recovery Core is an autonomous, deterministic subsystem operating completely outside the model, neural runtime, and network stack. Root authority and authentication are strictly local (offline physical credentials/passphrase). System updates use transactional A/B slot switching with deterministic kernel health milestone verification. Kernel panics write deterministic crash records to raw storage, and Cortex corruption is resolved via WAL truncation without semantic AI dependencies. +5. **ADR 0007 (Continuous Existence & Provisioning-Once)**: AIEN is provisioned once. Boot, reboot, sleep, model reload, kernel restart, hardware failure, and migration are execution-state transitions—not agent creation events. Cold boot initializes hardware and never silently mints a replacement `LogicalAgentId`. Uncertain identity fails toward Recovery Core and operator decision, never toward false continuity. Gate order (1–10) is unchanged; continuous-existence acceptance criteria bind every gate. + +--- + +## 4. Governance + +ADRs reflect decisions confirmed by the operator. Changes to the core decisions, invariants, or specifications documented here require operator escalation and approval per [`docs/ARCHITECTURE.md` §9](../ARCHITECTURE.md). diff --git a/evidence/config_a_reference_bundle.json b/evidence/config_a_reference_bundle.json new file mode 100644 index 00000000..94f387fa --- /dev/null +++ b/evidence/config_a_reference_bundle.json @@ -0,0 +1,340 @@ +{ + "schema_version": "2.0.0", + "generated_at_utc": "2026-09-23T23:10:08.215161+00:00", + "config_identity": { + "host": "spark-b87b", + "kernel": "7.0.0-1019-nvidia", + "architecture": "aarch64", + "os_distribution": "Ubuntu 24.04.5 LTS", + "kernel_command_line": "BOOT_IMAGE=/boot/vmlinuz-7.0.0-1019-nvidia root=UUID=d27bfd26-ff30-400e-9eca-9cdf73de9406 ro init_on_alloc=0 iommu.passthrough=0 console=tty0 plymouth.ignore-serial-consoles plymouth.use-simpledrm earlycon=uart,mmio32,0x16A00000 console=tty0 console=ttyS0,921600 crashkernel=1G-:0M quiet splash initcall_blacklist=tegra234_cbb_init pci=pcie_bus_safe vt.handoff=7" + }, + "machine_capsule": { + "firmware": { + "uefi_present": true, + "platform_bits": "64" + }, + "cpu": { + "models": [ + "0xd85", + "0xd87" + ], + "cores": 20, + "architecture": "aarch64" + }, + "accelerator": [ + { + "model": "NVIDIA GB10", + "driver_version": "580.173.02", + "pci_bus_id": "0000000F:01:00.0" + } + ], + "memory": { + "total_kb": 127598748, + "swap_kb": 0 + }, + "storage": { + "root_available_bytes": 1868129050624, + "block_devices": { + "blockdevices": [ + { + "name": "loop0", + "type": "loop", + "size": "4K", + "model": null, + "mountpoints": [ + "/snap/bare/5" + ] + }, + { + "name": "loop1", + "type": "loop", + "size": "69M", + "model": null, + "mountpoints": [ + "/snap/core22/2438" + ] + }, + { + "name": "loop2", + "type": "loop", + "size": "69M", + "model": null, + "mountpoints": [ + "/snap/core22/2956" + ] + }, + { + "name": "loop3", + "type": "loop", + "size": "61.8M", + "model": null, + "mountpoints": [ + "/snap/core24/2125" + ] + }, + { + "name": "loop4", + "type": "loop", + "size": "61.9M", + "model": null, + "mountpoints": [ + "/snap/core24/1644" + ] + }, + { + "name": "loop6", + "type": "loop", + "size": "10.2M", + "model": null, + "mountpoints": [ + "/snap/firmware-updater/168" + ] + }, + { + "name": "loop7", + "type": "loop", + "size": "503.1M", + "model": null, + "mountpoints": [ + "/snap/gnome-42-2204/264" + ] + }, + { + "name": "loop8", + "type": "loop", + "size": "15.6M", + "model": null, + "mountpoints": [ + "/snap/firmware-updater/227" + ] + }, + { + "name": "loop9", + "type": "loop", + "size": "188.2M", + "model": null, + "mountpoints": [ + "/snap/mesa-2404/1836" + ] + }, + { + "name": "loop10", + "type": "loop", + "size": "552.9M", + "model": null, + "mountpoints": [ + "/snap/gnome-46-2404/154" + ] + }, + { + "name": "loop11", + "type": "loop", + "size": "91.7M", + "model": null, + "mountpoints": [ + "/snap/gtk-common-themes/1535" + ] + }, + { + "name": "loop12", + "type": "loop", + "size": "12.2M", + "model": null, + "mountpoints": [ + "/snap/snap-store/1217" + ] + }, + { + "name": "loop13", + "type": "loop", + "size": "249.8M", + "model": null, + "mountpoints": [ + "/snap/firefox/8968" + ] + }, + { + "name": "loop14", + "type": "loop", + "size": "43.4M", + "model": null, + "mountpoints": [ + "/snap/snapd/27709" + ] + }, + { + "name": "loop15", + "type": "loop", + "size": "43.5M", + "model": null, + "mountpoints": [ + "/snap/snapd/27740" + ] + }, + { + "name": "loop16", + "type": "loop", + "size": "552K", + "model": null, + "mountpoints": [ + "/snap/snapd-desktop-integration/316" + ] + }, + { + "name": "loop17", + "type": "loop", + "size": "804K", + "model": null, + "mountpoints": [ + "/snap/snapd-desktop-integration/396" + ] + }, + { + "name": "loop18", + "type": "loop", + "size": "249.7M", + "model": null, + "mountpoints": [ + "/snap/firefox/8926" + ] + }, + { + "name": "loop19", + "type": "loop", + "size": "214.7M", + "model": null, + "mountpoints": [ + "/snap/thunderbird/1256" + ] + }, + { + "name": "loop20", + "type": "loop", + "size": "215.2M", + "model": null, + "mountpoints": [ + "/snap/thunderbird/1261" + ] + }, + { + "name": "loop21", + "type": "loop", + "size": "73.7M", + "model": null, + "mountpoints": [ + "/snap/snap-store/1420" + ] + }, + { + "name": "loop22", + "type": "loop", + "size": "561.1M", + "model": null, + "mountpoints": [ + "/snap/gnome-46-2404/169" + ] + }, + { + "name": "nvme0n1", + "type": "disk", + "size": "3.7T", + "model": "SAMSUNG MZALC4T0HBL1-00B07", + "mountpoints": [ + null + ], + "children": [ + { + "name": "nvme0n1p1", + "type": "part", + "size": "298M", + "model": null, + "mountpoints": [ + "/boot/efi" + ] + }, + { + "name": "nvme0n1p2", + "type": "part", + "size": "3.7T", + "model": null, + "mountpoints": [ + "/" + ] + } + ] + } + ] + } + } + }, + "toolchains": { + "rustc": "rustc 1.98.1 (48a229cea 2026-09-01)", + "cargo": "cargo 1.98.1 (797e8a9bc 2026-08-05)", + "python": "3.12.3", + "cuda_compiler_release": "13.0" + }, + "baseline_model": { + "path": "/home/drakestapleton/models/aien-mail/Llama-3.2-1B-Instruct-Q4_K_M.gguf", + "size_bytes": 807694368, + "sha256": "3f5a22426976ab26cfe84dba63c1d08391717abb1af893e10f1b2968d862dcc1" + }, + "workspace_repositories": [ + { + "name": "aienos-repo", + "commit": "f6350b548cccc53ec03825021112be75c2b30667", + "branch": "feat/aienos-m1-integration", + "dirty": true + }, + { + "name": "aegis-runtime", + "commit": "e8eed5aac8612c1b846284c09d58e798e382c11b", + "branch": "fix/rust-simd-oracle", + "dirty": false + }, + { + "name": "aien-sovereign-core", + "commit": "c83eb5b2f96b3d0a36fcb5092fcf0d66af5dd0d0", + "branch": "docs/readme-restructure", + "dirty": true + }, + { + "name": "spark-sentinel", + "commit": "f5a8546016cbb31982ace7fda91ace3ce7f335e6", + "branch": "main", + "dirty": false + } + ], + "reference_workload": { + "endpoint": "http://127.0.0.1:18094/v1", + "model": "unsloth/Llama-3.2-1B-Instruct", + "prompt": "Reply with one word: ready", + "samples": [ + { + "index": 0, + "ttft_ms": 85.445, + "total_ms": 99.962, + "output_tokens": 2, + "output_tokens_per_second": 20.008 + }, + { + "index": 1, + "ttft_ms": 86.248, + "total_ms": 102.887, + "output_tokens": 2, + "output_tokens_per_second": 19.439 + }, + { + "index": 2, + "ttft_ms": 84.974, + "total_ms": 103.17, + "output_tokens": 2, + "output_tokens_per_second": 19.385 + } + ] + }, + "recovery_procedure": { + "status": "documented_only", + "native_boot_rollback_tested": false + }, + "bundle_checksum_sha256": "d642a2724e9b27ca480883d14a00e6c2ab80d7c605b75ced457f6cafbdff78f1" +} diff --git a/scripts/capture_config_a.py b/scripts/capture_config_a.py new file mode 100755 index 00000000..61a72cba --- /dev/null +++ b/scripts/capture_config_a.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python3 +"""Read-only Config A hardware capture and local streaming inference probe.""" + +import datetime +import hashlib +import json +import os +from pathlib import Path +import platform +import re +import subprocess +import time +import urllib.request + +ROOT = Path(__file__).resolve().parents[1] +MODEL = Path(os.environ.get("AIENOS_BASELINE_MODEL", "/home/drakestapleton/models/aien-mail/Llama-3.2-1B-Instruct-Q4_K_M.gguf")) +ENDPOINT = os.environ.get("AIENOS_REFERENCE_ENDPOINT", "http://127.0.0.1:18094/v1") + + +def command(*args): + try: + return subprocess.run(args, check=True, capture_output=True, text=True, timeout=15).stdout.strip() + except (OSError, subprocess.SubprocessError): + return None + + +def file_hash(path): + digest = hashlib.sha256() + with path.open("rb") as source: + for block in iter(lambda: source.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def memory(): + result = {} + for line in Path("/proc/meminfo").read_text().splitlines(): + key, _, value = line.partition(":") + if key in ("MemTotal", "SwapTotal"): + result[key] = int(value.strip().split()[0]) + return result + + +def gpu(): + raw = command("nvidia-smi", "--query-gpu=name,driver_version,pci.bus_id", "--format=csv,noheader") + if not raw: + return None + return [dict(zip(("model", "driver_version", "pci_bus_id"), + (part.strip() for part in row.split(",", 2)))) for row in raw.splitlines()] + + +def repositories(): + result = [] + for name in ("aienos-repo", "aegis-runtime", "aien-sovereign-core", "spark-sentinel"): + path = ROOT.parent / name + if not (path / ".git").exists(): + continue + status = command("git", "-C", str(path), "status", "--porcelain") + result.append({"name": name, + "commit": command("git", "-C", str(path), "rev-parse", "HEAD"), + "branch": command("git", "-C", str(path), "branch", "--show-current"), + "dirty": None if status is None else bool(status)}) + return result + + +def request(url, payload=None): + body = None if payload is None else json.dumps(payload).encode() + return urllib.request.urlopen(urllib.request.Request( + url, data=body, headers={"Content-Type": "application/json"}), timeout=30) + + +def workload(): + try: + with request(ENDPOINT + "/models") as response: + model = json.load(response)["data"][0]["id"] + except (OSError, ValueError, KeyError, IndexError) as error: + return {"endpoint": ENDPOINT, "error": str(error), "samples": []} + prompt = "Reply with one word: ready" + samples = [] + for index in range(3): + payload = {"model": model, "messages": [{"role": "user", "content": prompt}], + "temperature": 0, "max_tokens": 32, "stream": True, + "stream_options": {"include_usage": True}} + started = time.monotonic_ns() + first = None + usage = None + try: + with request(ENDPOINT + "/chat/completions", payload) as response: + for line in response: + if not line.startswith(b"data: ") or line.strip() == b"data: [DONE]": + continue + chunk = json.loads(line[6:]) + usage = chunk.get("usage") or usage + if first is None and any(c.get("delta", {}).get("content") for c in chunk.get("choices", [])): + first = time.monotonic_ns() + finished = time.monotonic_ns() + tokens = usage.get("completion_tokens") if usage else None + samples.append({"index": index, "ttft_ms": None if first is None else round((first-started)/1e6, 3), + "total_ms": round((finished-started)/1e6, 3), "output_tokens": tokens, + "output_tokens_per_second": None if not tokens else round(tokens/((finished-started)/1e9), 3)}) + except (OSError, ValueError) as error: + samples.append({"index": index, "error": str(error)}) + return {"endpoint": ENDPOINT, "model": model, "prompt": prompt, "samples": samples} + + +def main(): + if not MODEL.is_file(): + raise SystemExit(f"Baseline model does not exist: {MODEL}") + stat = os.statvfs("/") + nvcc = command("nvcc", "--version") + cpu = sorted({line.partition(":")[2].strip() for line in Path("/proc/cpuinfo").read_text().splitlines() + if line.partition(":")[0].strip() in ("model name", "CPU part")}) + fw_bits = Path("/sys/firmware/efi/fw_platform_size") + bundle = { + "schema_version": "2.0.0", + "generated_at_utc": datetime.datetime.now(datetime.timezone.utc).isoformat(), + "config_identity": {"host": platform.node(), "kernel": platform.release(), + "architecture": platform.machine(), + "os_distribution": platform.freedesktop_os_release().get("PRETTY_NAME"), + "kernel_command_line": Path("/proc/cmdline").read_text().strip()}, + "machine_capsule": { + "firmware": {"uefi_present": Path("/sys/firmware/efi").is_dir(), + "platform_bits": fw_bits.read_text().strip() if fw_bits.exists() else None}, + "cpu": {"models": cpu, "cores": os.cpu_count(), "architecture": platform.machine()}, + "accelerator": gpu(), + "memory": {"total_kb": memory().get("MemTotal"), "swap_kb": memory().get("SwapTotal")}, + "storage": {"root_available_bytes": stat.f_bavail * stat.f_frsize, + "block_devices": json.loads(command("lsblk", "--json", "--output", "NAME,TYPE,SIZE,MODEL,MOUNTPOINTS") or "{}")}}, + "toolchains": {"rustc": command("rustc", "--version"), "cargo": command("cargo", "--version"), + "python": platform.python_version(), + "cuda_compiler_release": re.search(r"release ([^,]+)", nvcc).group(1) + if nvcc and re.search(r"release ([^,]+)", nvcc) else None}, + "baseline_model": {"path": str(MODEL), "size_bytes": MODEL.stat().st_size, "sha256": file_hash(MODEL)}, + "workspace_repositories": repositories(), + "reference_workload": workload(), + "recovery_procedure": {"status": "documented_only", "native_boot_rollback_tested": False}, + } + canonical = json.dumps(bundle, indent=2, sort_keys=True) + bundle["bundle_checksum_sha256"] = hashlib.sha256(canonical.encode()).hexdigest() + output = ROOT / "evidence" / "config_a_reference_bundle.json" + output.parent.mkdir(exist_ok=True) + output.write_text(json.dumps(bundle, indent=2) + "\n") + print(f"Captured observed Config A data: {output}") + print(f"Workload samples: {len(bundle['reference_workload']['samples'])}") + + +if __name__ == "__main__": + main() diff --git a/scripts/freeze_reality.sh b/scripts/freeze_reality.sh new file mode 100755 index 00000000..ec80e384 --- /dev/null +++ b/scripts/freeze_reality.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +# Capture observed Config A data without changing host boot state. +set -euo pipefail +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +exec python3 "${repo_root}/scripts/capture_config_a.py" "$@" diff --git a/scripts/verify_all.sh b/scripts/verify_all.sh new file mode 100755 index 00000000..a208e77a --- /dev/null +++ b/scripts/verify_all.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +# AIENOS End-to-End Build and Evidence Verification Harness +# Enforces sequential integration gates on the host DGX Spark environment. + +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "${REPO_ROOT}" + +echo "============================================================" +echo "AIENOS Integration Verification Harness" +echo "Host: $(uname -n) | Arch: $(uname -m) | Kernel: $(uname -r)" +echo "Date: $(date -u +"%Y-%m-%dT%H:%M:%SZ")" +echo "============================================================" + +# Step 1: Gate 1 Verification (Config A Reference Bundle) +echo "" +echo "--- [Gate 1 Verification: Config A Freeze] ---" +if [[ ! -f "evidence/config_a_reference_bundle.json" ]]; then + echo "Running freeze_reality.sh..." + ./scripts/freeze_reality.sh +fi +./scripts/verify_evidence.sh "evidence/config_a_reference_bundle.json" + +# Step 2: Host component test suite +echo "" +echo "--- [Host Component Testing: 5 Workspace Crates] ---" +cargo test --workspace + +# Step 3: Linting & Zero-Warning Enforcement +echo "" +echo "--- [Clippy Verification: -D warnings] ---" +cargo clippy --workspace --all-targets -- -D warnings + +# Step 4: Bare-metal library compilation check (not a boot test) +echo "" +echo "--- [Bare-Metal Target Compilation Check] ---" +cargo check -p aienos-kernel --target aarch64-unknown-none --no-default-features +cargo build -p aienos-kernel --target aarch64-unknown-none --no-default-features + +echo "" +echo "============================================================" +echo "HOST VERIFICATIONS PASSED." +echo "Config A: observed capture and three local inference samples verified." +echo "Kernel: aarch64-unknown-none library compiles. Native boot remains untested." +echo "============================================================" diff --git a/scripts/verify_evidence.py b/scripts/verify_evidence.py new file mode 100755 index 00000000..4b57a113 --- /dev/null +++ b/scripts/verify_evidence.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +"""Validate observed Config A evidence, not merely its self-checksum.""" + +import hashlib +import json +from pathlib import Path +import re +import sys + + +def check(bundle): + errors = [] + stored = bundle.pop("bundle_checksum_sha256", None) + actual = hashlib.sha256(json.dumps(bundle, indent=2, sort_keys=True).encode()).hexdigest() + if stored != actual: + errors.append("bundle checksum mismatch") + if bundle.get("schema_version") != "2.0.0": + errors.append("unsupported evidence schema") + identity = bundle.get("config_identity", {}) + if not all(identity.get(k) for k in ("host", "kernel", "architecture", "os_distribution", "kernel_command_line")): + errors.append("incomplete host identity") + capsule = bundle.get("machine_capsule", {}) + if not capsule.get("firmware", {}).get("uefi_present"): + errors.append("UEFI was not observed") + if not capsule.get("accelerator") or not all( + gpu.get("model") and gpu.get("driver_version") and gpu.get("pci_bus_id") + for gpu in capsule.get("accelerator") or []): + errors.append("GPU identity was not observed") + if not capsule.get("cpu", {}).get("cores") or not capsule.get("memory", {}).get("total_kb"): + errors.append("CPU or memory identity missing") + if not capsule.get("storage", {}).get("block_devices", {}).get("blockdevices"): + errors.append("block device inventory missing") + model = bundle.get("baseline_model", {}) + if not re.fullmatch(r"[0-9a-f]{64}", model.get("sha256", "")) or not model.get("size_bytes"): + errors.append("baseline model digest or size missing") + if not bundle.get("workspace_repositories") or any(not item.get("commit") for item in bundle["workspace_repositories"]): + errors.append("workspace commit inventory missing") + samples = bundle.get("reference_workload", {}).get("samples", []) + if len(samples) < 3 or any(not sample.get("ttft_ms") or not sample.get("output_tokens") + or not sample.get("output_tokens_per_second") for sample in samples): + errors.append("three complete measured inference samples required") + return errors + + +def main(): + path = Path(sys.argv[1]) + try: + bundle = json.loads(path.read_text()) + except (OSError, ValueError) as error: + raise SystemExit(f"Evidence unavailable: {error}") from error + errors = check(bundle) + if errors: + for error in errors: + print(f"FAIL: {error}") + raise SystemExit(1) + samples = bundle["reference_workload"]["samples"] + print(f"Config A capture verified for {bundle['config_identity']['host']}: {len(samples)} measured inference samples") + print("Native boot and recovery qualification remain separate gates.") + + +if __name__ == "__main__": + main() diff --git a/scripts/verify_evidence.sh b/scripts/verify_evidence.sh new file mode 100755 index 00000000..c3efee8e --- /dev/null +++ b/scripts/verify_evidence.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -euo pipefail +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +exec python3 "${repo_root}/scripts/verify_evidence.py" "${1:-${repo_root}/evidence/config_a_reference_bundle.json}"