From 92e7032a9bdc7270fcb176aabd21c8e30a0ab9bc Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Fri, 25 Sep 2026 17:18:24 -0500 Subject: [PATCH 1/4] feat(continuity): M4 continuity objects over Store v1 (ADR 0016, Proposed) aienos_kernel::continuity (no_std): canonical encodings for AgentRoot, ContinuityManifest, AgentStateCheckpoint and CortexWalSegment (format version 0 while ADR 0016 is Proposed), strict decoders, and deterministic boot resolution: 0 roots -> Unprovisioned (never mint), >1 -> Conflict, broken/forked/gapped manifest chain -> Corrupt, DegradedRecovery mount -> read-only resume. provision() is the only path that writes an AgentRoot; resume() commits incarnation+1 before returning (commit-before-observation). Host tests: provision -> commit memory + fork -> cold restart returns the same LogicalAgentId, Cortex records, lineage, incarnation+1; power cut before every unit write of a commit reopens as old or new state, never a third, same identity; conflict/gap/fork/degraded/tamper/lineage cases. store::genesis::genesis_units moves the canonical genesis builder into the kernel; the boot qualification delegates to it. Co-Authored-By: Drake Stapleton Co-Authored-By: Claude Opus 5.5 --- crates/aienos-boot/src/store_qual.rs | 58 +- crates/aienos-kernel/src/continuity.rs | 850 ++++++++++++++++++ crates/aienos-kernel/src/continuity_tests.rs | 345 +++++++ crates/aienos-kernel/src/lib.rs | 1 + crates/aienos-kernel/src/store.rs | 1 + crates/aienos-kernel/src/store/genesis.rs | 62 ++ .../0016-continuity-objects-over-store-v1.md | 99 ++ docs/adr/README.md | 1 + 8 files changed, 1363 insertions(+), 54 deletions(-) create mode 100644 crates/aienos-kernel/src/continuity.rs create mode 100644 crates/aienos-kernel/src/continuity_tests.rs create mode 100644 crates/aienos-kernel/src/store/genesis.rs create mode 100644 docs/adr/0016-continuity-objects-over-store-v1.md diff --git a/crates/aienos-boot/src/store_qual.rs b/crates/aienos-boot/src/store_qual.rs index e9c81d59..eb0e9c6f 100644 --- a/crates/aienos-boot/src/store_qual.rs +++ b/crates/aienos-boot/src/store_qual.rs @@ -81,58 +81,8 @@ pub const STORE_UNIT_BYTES: usize = 4096; /// the first transaction exercises the "inactive slot initially zero" case), /// an empty catalog at unit 2, and the CommitRecord at unit 3. pub fn genesis_units(region_units: u64) -> [[u8; STORE_UNIT_BYTES]; 4] { - use aienos_kernel::store::v1::{ - object_unit_count, Catalog, CommitRecord, ObjectId, Superblock, OBJECT_KIND_CATALOG, - OBJECT_VERSION_V1, - }; - - let catalog = Catalog { - entries: alloc::vec::Vec::new(), - }; - let catalog_bytes = catalog.encode().expect("catalog encode"); - let catalog_id = ObjectId::calculate(OBJECT_KIND_CATALOG, OBJECT_VERSION_V1, &catalog_bytes) - .expect("catalog id"); - let catalog_units = object_unit_count(catalog_bytes.len() as u64).expect("catalog units"); - let catalog_first = 2u64; - let commit_unit = catalog_first + u64::from(catalog_units); - let high_water = commit_unit + 1; - let uuid = [0x5Au8; 16]; - - let commit = CommitRecord { - store_uuid: uuid, - region_units, - generation: 1, - previous_generation: 0, - previous_commit_id: ObjectId([0u8; 32]), - previous_catalog_id: ObjectId([0u8; 32]), - catalog_id, - catalog_first_unit: catalog_first, - catalog_byte_length: catalog_bytes.len() as u64, - catalog_unit_count: catalog_units, - catalog_entry_count: 0, - committed_high_water: high_water, - }; - let commit_bytes = commit.encode().expect("commit encode"); - let commit_id = commit.object_id().expect("commit id"); - - let superblock = Superblock { - store_uuid: uuid, - slot_id: 0, - region_units, - generation: 1, - commit_record_id: commit_id, - commit_record_unit: commit_unit, - catalog_id, - catalog_first_unit: catalog_first, - catalog_byte_length: catalog_bytes.len() as u64, - catalog_unit_count: catalog_units, - catalog_entry_count: 0, - committed_high_water: high_water, - }; - - let mut out = [[0u8; STORE_UNIT_BYTES]; 4]; - out[0].copy_from_slice(&superblock.encode().expect("superblock encode")); - out[2][..catalog_bytes.len()].copy_from_slice(&catalog_bytes); - out[3][..commit_bytes.len()].copy_from_slice(&commit_bytes); - out + aienos_kernel::store::genesis::genesis_units(QUAL_STORE_UUID, region_units) } + +/// Fixed test-only Store UUID used by the qualification images. +pub const QUAL_STORE_UUID: [u8; 16] = [0x5A; 16]; diff --git a/crates/aienos-kernel/src/continuity.rs b/crates/aienos-kernel/src/continuity.rs new file mode 100644 index 00000000..5b5f8ba0 --- /dev/null +++ b/crates/aienos-kernel/src/continuity.rs @@ -0,0 +1,850 @@ +//! M4 continuity objects over System Store v1 (ADR 0016, Proposed). +//! +//! AIEN is provisioned once (ADR 0007). Every later start must locate, verify +//! and resume the one durable `LogicalAgentId`, or stop. This module holds the +//! canonical encodings of the continuity objects and the deterministic boot +//! resolution over a mounted [`Store`]. No model, no network, `no_std`. +//! +//! The encodings carry `format_version = 0` while ADR 0016 is Proposed: they +//! are qualification formats on disposable media, not a frozen on-disk format. +//! Store v1 object `version` is 1 for all of them (Store v1 rejects 0). + +use alloc::vec::Vec; + +use crate::crypto::sha256::Sha256; +use crate::store::engine::{MountState, ObjectInput, Store, StoreDevice, StoreError}; +use crate::store::v1::ObjectId; + +pub const KIND_AGENT_ROOT: u16 = 16; +pub const KIND_MANIFEST: u16 = 17; +pub const KIND_AGENT_STATE: u16 = 18; +pub const KIND_CORTEX_WAL: u16 = 20; +/// Store v1 object version used for every continuity object. +pub const STORE_OBJECT_VERSION: u16 = 1; +/// Continuity encoding version while ADR 0016 is Proposed. +pub const FORMAT_VERSION: u16 = 0; + +pub const MAX_WAL_SEGMENTS: usize = 64; +pub const MAX_BRANCHES: usize = 256; +pub const MAX_WAL_RECORDS: usize = 64; +pub const MAX_STATEMENT_BYTES: usize = 1024; + +const HEADER_BYTES: usize = 16; +const MAGIC_ROOT: &[u8; 8] = b"AIENROOT"; +const MAGIC_MANIFEST: &[u8; 8] = b"AIENMANI"; +const MAGIC_BRANCHES: &[u8; 8] = b"AIENBRAN"; +const MAGIC_WAL: &[u8; 8] = b"AIENCWAL"; +const ZERO_ID: [u8; 32] = [0; 32]; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ContinuityError { + Store(StoreError), + /// No agent root and provisioning was not requested: stop, never mint. + Unprovisioned, + /// More than one agent root: stop. + Conflict, + /// A root already exists; provisioning refused. + AlreadyProvisioned, + /// The mount is read-only (`DegradedRecovery`); nothing may be committed. + ReadOnly, + /// The continuity graph is inconsistent: stop in the Recovery Core. + Corrupt(&'static str), + /// An update exceeds a format bound. + Limit(&'static str), +} + +impl From for ContinuityError { + fn from(e: StoreError) -> Self { + Self::Store(e) + } +} + +type Result = core::result::Result; + +// --------------------------------------------------------------------------- +// Identity derivations (shared with the host `aienos-agent-state` crate) +// --------------------------------------------------------------------------- + +/// Root branch id of an agent: SHA-256("AIENOS_ROOT_BRANCH_v1:" || agent). +pub fn root_branch_id(agent: &[u8; 32]) -> [u8; 32] { + let mut h = Sha256::new(); + h.update(b"AIENOS_ROOT_BRANCH_v1:"); + h.update(agent); + h.finalize() +} + +/// Child branch id: SHA-256("AIENOS_CHILD_BRANCH_v1:" || parent || index BE). +pub fn child_branch_id(parent: &[u8; 32], index: u64) -> [u8; 32] { + let mut h = Sha256::new(); + h.update(b"AIENOS_CHILD_BRANCH_v1:"); + h.update(parent); + h.update(&index.to_be_bytes()); + h.finalize() +} + +// --------------------------------------------------------------------------- +// Canonical byte helpers +// --------------------------------------------------------------------------- + +fn header(out: &mut Vec, magic: &[u8; 8], body_len: usize) { + out.extend_from_slice(magic); + out.extend_from_slice(&FORMAT_VERSION.to_le_bytes()); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(&(body_len as u32).to_le_bytes()); +} + +/// Strict reader: every read is bounds-checked and the whole input must be +/// consumed. +struct Reader<'a> { + bytes: &'a [u8], + at: usize, +} + +impl<'a> Reader<'a> { + fn open(bytes: &'a [u8], magic: &[u8; 8]) -> Result { + let mut r = Self { bytes, at: 0 }; + if r.take(8)? != magic { + return Err(ContinuityError::Corrupt("bad magic")); + } + if r.u16()? != FORMAT_VERSION { + return Err(ContinuityError::Corrupt( + "unsupported continuity format version", + )); + } + if r.u16()? != 0 { + return Err(ContinuityError::Corrupt("nonzero header reserved")); + } + if r.u32()? as usize != bytes.len() - HEADER_BYTES { + return Err(ContinuityError::Corrupt("body length mismatch")); + } + Ok(r) + } + fn take(&mut self, n: usize) -> Result<&'a [u8]> { + let end = self + .at + .checked_add(n) + .filter(|end| *end <= self.bytes.len()) + .ok_or(ContinuityError::Corrupt("truncated object"))?; + let s = &self.bytes[self.at..end]; + self.at = end; + Ok(s) + } + fn id(&mut self) -> Result<[u8; 32]> { + let mut out = [0; 32]; + out.copy_from_slice(self.take(32)?); + Ok(out) + } + fn u8(&mut self) -> Result { + Ok(self.take(1)?[0]) + } + fn u16(&mut self) -> Result { + let b = self.take(2)?; + Ok(u16::from_le_bytes([b[0], b[1]])) + } + fn u32(&mut self) -> Result { + let b = self.take(4)?; + Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]])) + } + fn u64(&mut self) -> Result { + let mut a = [0; 8]; + a.copy_from_slice(self.take(8)?); + Ok(u64::from_le_bytes(a)) + } + fn zeros(&mut self, n: usize) -> Result<()> { + if self.take(n)?.iter().any(|b| *b != 0) { + return Err(ContinuityError::Corrupt("nonzero reserved")); + } + Ok(()) + } + fn finish(self) -> Result<()> { + if self.at != self.bytes.len() { + return Err(ContinuityError::Corrupt("trailing bytes")); + } + Ok(()) + } +} + +fn object_id(kind: u16, bytes: &[u8]) -> Result { + ObjectId::calculate(kind, STORE_OBJECT_VERSION, bytes) + .map_err(|e| ContinuityError::Store(StoreError::Format(e))) +} + +fn opt_id(id: [u8; 32]) -> Option { + (id != ZERO_ID).then_some(ObjectId(id)) +} + +fn raw(id: Option) -> [u8; 32] { + id.map_or(ZERO_ID, |i| i.0) +} + +// --------------------------------------------------------------------------- +// AgentRoot (kind 16): written once, at provisioning +// --------------------------------------------------------------------------- + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ProvisionSource { + /// An operator-authorised provisioning action (Recovery Core, ADR 0006). + Operator = 1, + /// A qualification harness on disposable media. + Qualification = 2, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct AgentRoot { + pub agent_id: [u8; 32], + pub store_uuid: [u8; 16], + pub root_branch: [u8; 32], + pub provisioned_generation: u64, + pub source: ProvisionSource, +} + +const ROOT_BODY: usize = 32 + 16 + 32 + 8 + 1 + 7; + +impl AgentRoot { + pub fn encode(&self) -> Vec { + let mut out = Vec::with_capacity(HEADER_BYTES + ROOT_BODY); + header(&mut out, MAGIC_ROOT, ROOT_BODY); + out.extend_from_slice(&self.agent_id); + out.extend_from_slice(&self.store_uuid); + out.extend_from_slice(&self.root_branch); + out.extend_from_slice(&self.provisioned_generation.to_le_bytes()); + out.push(self.source as u8); + out.extend_from_slice(&[0; 7]); + out + } + + pub fn decode(bytes: &[u8]) -> Result { + let mut r = Reader::open(bytes, MAGIC_ROOT)?; + let agent_id = r.id()?; + let mut store_uuid = [0; 16]; + store_uuid.copy_from_slice(r.take(16)?); + let root_branch = r.id()?; + let provisioned_generation = r.u64()?; + let source = match r.u8()? { + 1 => ProvisionSource::Operator, + 2 => ProvisionSource::Qualification, + _ => return Err(ContinuityError::Corrupt("unknown provisioning source")), + }; + r.zeros(7)?; + r.finish()?; + if agent_id == ZERO_ID { + return Err(ContinuityError::Corrupt("zero agent id")); + } + if root_branch != root_branch_id(&agent_id) { + return Err(ContinuityError::Corrupt( + "root branch does not derive from agent", + )); + } + Ok(Self { + agent_id, + store_uuid, + root_branch, + provisioned_generation, + source, + }) + } +} + +// --------------------------------------------------------------------------- +// ContinuityManifest (kind 17): one per Class A commit +// --------------------------------------------------------------------------- + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Manifest { + pub root: ObjectId, + pub previous: Option, + pub sequence: u64, + pub incarnation: u64, + pub agent_state: Option, + pub cortex_wal: Vec, +} + +impl Manifest { + pub fn encode(&self) -> Result> { + if self.cortex_wal.len() > MAX_WAL_SEGMENTS { + return Err(ContinuityError::Limit("too many cortex WAL segments")); + } + let body = 32 + 32 + 8 + 8 + 32 + 2 + 6 + 32 * self.cortex_wal.len(); + let mut out = Vec::with_capacity(HEADER_BYTES + body); + header(&mut out, MAGIC_MANIFEST, body); + out.extend_from_slice(&self.root.0); + out.extend_from_slice(&raw(self.previous)); + out.extend_from_slice(&self.sequence.to_le_bytes()); + out.extend_from_slice(&self.incarnation.to_le_bytes()); + out.extend_from_slice(&raw(self.agent_state)); + out.extend_from_slice(&(self.cortex_wal.len() as u16).to_le_bytes()); + out.extend_from_slice(&[0; 6]); + for id in &self.cortex_wal { + out.extend_from_slice(&id.0); + } + Ok(out) + } + + pub fn decode(bytes: &[u8]) -> Result { + let mut r = Reader::open(bytes, MAGIC_MANIFEST)?; + let root = ObjectId(r.id()?); + let previous = opt_id(r.id()?); + let sequence = r.u64()?; + let incarnation = r.u64()?; + let agent_state = opt_id(r.id()?); + let wal_count = r.u16()? as usize; + r.zeros(6)?; + if wal_count > MAX_WAL_SEGMENTS { + return Err(ContinuityError::Corrupt("too many cortex WAL segments")); + } + let mut cortex_wal = Vec::with_capacity(wal_count); + for _ in 0..wal_count { + cortex_wal.push(ObjectId(r.id()?)); + } + r.finish()?; + if sequence == 0 || (sequence == 1) != previous.is_none() { + return Err(ContinuityError::Corrupt( + "manifest sequence/previous mismatch", + )); + } + Ok(Self { + root, + previous, + sequence, + incarnation, + agent_state, + cortex_wal, + }) + } +} + +// --------------------------------------------------------------------------- +// AgentStateCheckpoint (kind 18): the branch table +// --------------------------------------------------------------------------- + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Branch { + pub id: [u8; 32], + /// `None` only for the root branch. + pub parent: Option<[u8; 32]>, + pub depth: u32, + /// Number of children forked from this branch so far. + pub forks: u64, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct AgentState { + pub agent_id: [u8; 32], + /// Manifest sequence this checkpoint was written at (keeps ids unique). + pub written_at: u64, + /// Sorted by branch id. + pub branches: Vec, +} + +const BRANCH_BYTES: usize = 32 + 32 + 4 + 4 + 8; + +impl AgentState { + /// A fresh agent: only the root branch. + pub fn genesis(agent_id: [u8; 32], written_at: u64) -> Self { + Self { + agent_id, + written_at, + branches: alloc::vec![Branch { + id: root_branch_id(&agent_id), + parent: None, + depth: 0, + forks: 0, + }], + } + } + + pub fn branch(&self, id: &[u8; 32]) -> Option<&Branch> { + self.branches + .binary_search_by(|b| b.id.cmp(id)) + .ok() + .map(|i| &self.branches[i]) + } + + /// Forks a child of `parent` with the next deterministic index. + pub fn fork(&mut self, parent: &[u8; 32]) -> Result<[u8; 32]> { + if self.branches.len() >= MAX_BRANCHES { + return Err(ContinuityError::Limit("too many branches")); + } + let i = self + .branches + .binary_search_by(|b| b.id.cmp(parent)) + .map_err(|_| ContinuityError::Corrupt("fork parent is absent"))?; + let (index, depth) = (self.branches[i].forks, self.branches[i].depth); + let child = Branch { + id: child_branch_id(parent, index), + parent: Some(*parent), + depth: depth + .checked_add(1) + .ok_or(ContinuityError::Limit("branch depth"))?, + forks: 0, + }; + self.branches[i].forks = index + 1; + let at = self + .branches + .binary_search_by(|b| b.id.cmp(&child.id)) + .err() + .ok_or(ContinuityError::Corrupt("child branch id collision"))?; + self.branches.insert(at, child); + Ok(child.id) + } + + pub fn encode(&self) -> Result> { + self.validate()?; + let body = 32 + 8 + 4 + 4 + BRANCH_BYTES * self.branches.len(); + let mut out = Vec::with_capacity(HEADER_BYTES + body); + header(&mut out, MAGIC_BRANCHES, body); + out.extend_from_slice(&self.agent_id); + out.extend_from_slice(&self.written_at.to_le_bytes()); + out.extend_from_slice(&(self.branches.len() as u32).to_le_bytes()); + out.extend_from_slice(&[0; 4]); + for b in &self.branches { + out.extend_from_slice(&b.id); + out.extend_from_slice(&b.parent.unwrap_or(ZERO_ID)); + out.extend_from_slice(&b.depth.to_le_bytes()); + out.extend_from_slice(&[0; 4]); + out.extend_from_slice(&b.forks.to_le_bytes()); + } + Ok(out) + } + + pub fn decode(bytes: &[u8]) -> Result { + let mut r = Reader::open(bytes, MAGIC_BRANCHES)?; + let agent_id = r.id()?; + let written_at = r.u64()?; + let count = r.u32()? as usize; + r.zeros(4)?; + if count == 0 || count > MAX_BRANCHES { + return Err(ContinuityError::Corrupt("branch count out of range")); + } + let mut branches = Vec::with_capacity(count); + for _ in 0..count { + let id = r.id()?; + let parent = r.id()?; + let depth = r.u32()?; + r.zeros(4)?; + let forks = r.u64()?; + branches.push(Branch { + id, + parent: (parent != ZERO_ID).then_some(parent), + depth, + forks, + }); + } + r.finish()?; + let state = Self { + agent_id, + written_at, + branches, + }; + state.validate()?; + Ok(state) + } + + /// Exactly one root derived from the agent; every child derives from its + /// parent with depth + 1; each parent's children are exactly indexes + /// `0..forks`; ids strictly sorted. + pub fn validate(&self) -> Result<()> { + let bad = ContinuityError::Corrupt; + if self.branches.is_empty() || self.branches.len() > MAX_BRANCHES { + return Err(bad("branch count out of range")); + } + if self.branches.windows(2).any(|w| w[0].id >= w[1].id) { + return Err(bad("branches not strictly sorted")); + } + let root = root_branch_id(&self.agent_id); + let mut roots = 0; + let mut children = 0u64; + for b in &self.branches { + match b.parent { + None => { + if b.id != root || b.depth != 0 { + return Err(bad("unexpected root branch")); + } + roots += 1; + } + Some(p) => { + let parent = self.branch(&p).ok_or(bad("parent branch is absent"))?; + let index_ok = (0..parent.forks).any(|i| child_branch_id(&p, i) == b.id); + if !index_ok || Some(b.depth) != parent.depth.checked_add(1) { + return Err(bad("branch lineage is inconsistent")); + } + children += 1; + } + } + } + let forks: u64 = self.branches.iter().map(|b| b.forks).sum(); + if roots != 1 || forks != children { + return Err(bad("fork indexes are not contiguous")); + } + Ok(()) + } +} + +// --------------------------------------------------------------------------- +// CortexWalSegment (kind 20): committed Cortex records +// --------------------------------------------------------------------------- + +/// Mirrors `aienos-cortex` `EpistemicStatus` discriminants. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Epistemic { + DirectObservation = 1, + VerifiedFact = 2, + Inference = 3, + Hypothesis = 4, + Contradiction = 5, + OperatorDecision = 6, +} + +impl Epistemic { + fn from_u8(v: u8) -> Option { + Some(match v { + 1 => Self::DirectObservation, + 2 => Self::VerifiedFact, + 3 => Self::Inference, + 4 => Self::Hypothesis, + 5 => Self::Contradiction, + 6 => Self::OperatorDecision, + _ => return None, + }) + } +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct CortexRecord { + pub status: Epistemic, + pub evidence_hash: [u8; 32], + pub statement: Vec, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct WalSegment { + /// Manifest sequence this segment was committed in. + pub sequence: u64, + pub records: Vec, +} + +impl WalSegment { + pub fn encode(&self) -> Result> { + if self.records.is_empty() || self.records.len() > MAX_WAL_RECORDS { + return Err(ContinuityError::Limit("WAL segment record count")); + } + let mut body = 8 + 4 + 4; + for rec in &self.records { + if rec.statement.is_empty() || rec.statement.len() > MAX_STATEMENT_BYTES { + return Err(ContinuityError::Limit("statement length")); + } + body += 4 + 32 + rec.statement.len(); + } + let mut out = Vec::with_capacity(HEADER_BYTES + body); + header(&mut out, MAGIC_WAL, body); + out.extend_from_slice(&self.sequence.to_le_bytes()); + out.extend_from_slice(&(self.records.len() as u32).to_le_bytes()); + out.extend_from_slice(&[0; 4]); + for rec in &self.records { + out.push(rec.status as u8); + out.push(0); + out.extend_from_slice(&(rec.statement.len() as u16).to_le_bytes()); + out.extend_from_slice(&rec.evidence_hash); + out.extend_from_slice(&rec.statement); + } + Ok(out) + } + + pub fn decode(bytes: &[u8]) -> Result { + let mut r = Reader::open(bytes, MAGIC_WAL)?; + let sequence = r.u64()?; + let count = r.u32()? as usize; + r.zeros(4)?; + if count == 0 || count > MAX_WAL_RECORDS { + return Err(ContinuityError::Corrupt("WAL segment record count")); + } + let mut records = Vec::with_capacity(count); + for _ in 0..count { + let status = Epistemic::from_u8(r.u8()?) + .ok_or(ContinuityError::Corrupt("unknown epistemic status"))?; + r.zeros(1)?; + let len = r.u16()? as usize; + if len == 0 || len > MAX_STATEMENT_BYTES { + return Err(ContinuityError::Corrupt("statement length")); + } + let evidence_hash = r.id()?; + let statement = r.take(len)?.to_vec(); + records.push(CortexRecord { + status, + evidence_hash, + statement, + }); + } + r.finish()?; + Ok(Self { sequence, records }) + } +} + +// --------------------------------------------------------------------------- +// Boot resolution +// --------------------------------------------------------------------------- + +/// The verified continuity view of one Store generation. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Continuity { + pub root_id: ObjectId, + pub root: AgentRoot, + pub manifest_id: ObjectId, + pub manifest: Manifest, + pub state: AgentState, + /// Every committed Cortex record, in commit order. + pub cortex: Vec, +} + +/// Class A changes to commit with the next manifest. +#[derive(Clone, Debug, Default)] +pub struct Update { + /// Replace the branch table (e.g. after a fork). + pub state: Option, + /// Append these Cortex records as one WAL segment. + pub cortex: Vec, +} + +fn ids_of_kind(store: &Store, kind: u16) -> Vec { + store + .catalog() + .entries + .iter() + .filter(|e| e.kind == kind) + .map(|e| e.object_id) + .collect() +} + +fn read_kind(store: &mut Store, id: ObjectId, kind: u16) -> Result> { + let entry = store + .catalog() + .entries + .iter() + .find(|e| e.object_id == id) + .copied() + .ok_or(ContinuityError::Corrupt("referenced object is absent"))?; + if entry.kind != kind || entry.version != STORE_OBJECT_VERSION { + return Err(ContinuityError::Corrupt( + "referenced object has the wrong kind", + )); + } + Ok(store.read_object(id)?) +} + +/// Locates and verifies the continuity view without writing anything. +/// Never creates an identity. +pub fn resolve(store: &mut Store) -> Result { + let roots = ids_of_kind(store, KIND_AGENT_ROOT); + let root_id = match roots.as_slice() { + [] => return Err(ContinuityError::Unprovisioned), + [one] => *one, + _ => return Err(ContinuityError::Conflict), + }; + let root = AgentRoot::decode(&read_kind(store, root_id, KIND_AGENT_ROOT)?)?; + + // Every manifest must belong to one unbroken chain 1..=n for this root. + let mut manifests = Vec::new(); + for id in ids_of_kind(store, KIND_MANIFEST) { + let m = Manifest::decode(&read_kind(store, id, KIND_MANIFEST)?)?; + if m.root != root_id { + return Err(ContinuityError::Corrupt("manifest names a foreign root")); + } + manifests.push((id, m)); + } + if manifests.is_empty() { + return Err(ContinuityError::Corrupt("agent root has no manifest")); + } + manifests.sort_by_key(|(_, m)| m.sequence); + for (i, (id, m)) in manifests.iter().enumerate() { + if m.sequence != i as u64 + 1 { + return Err(ContinuityError::Corrupt("manifest sequence gap or fork")); + } + let expected_previous = i.checked_sub(1).map(|p| manifests[p].0); + if m.previous != expected_previous { + return Err(ContinuityError::Corrupt("manifest chain is broken")); + } + let _ = id; + } + let (manifest_id, manifest) = manifests.pop().expect("non-empty"); + + let state_id = manifest + .agent_state + .ok_or(ContinuityError::Corrupt("manifest has no agent state"))?; + let state = AgentState::decode(&read_kind(store, state_id, KIND_AGENT_STATE)?)?; + if state.agent_id != root.agent_id { + return Err(ContinuityError::Corrupt( + "agent state belongs to another agent", + )); + } + + let mut cortex = Vec::new(); + let mut last_sequence = 0; + for id in &manifest.cortex_wal { + let seg = WalSegment::decode(&read_kind(store, *id, KIND_CORTEX_WAL)?)?; + if seg.sequence <= last_sequence || seg.sequence > manifest.sequence { + return Err(ContinuityError::Corrupt("WAL segments out of order")); + } + last_sequence = seg.sequence; + cortex.extend(seg.records); + } + + Ok(Continuity { + root_id, + root, + manifest_id, + manifest, + state, + cortex, + }) +} + +fn writable(store: &Store) -> Result<()> { + if store.mount_state() != MountState::Valid { + return Err(ContinuityError::ReadOnly); + } + Ok(()) +} + +/// Creates the one durable identity. Only reachable from an explicit, +/// authorised provisioning request; refuses if any root exists. +pub fn provision( + store: &mut Store, + agent_id: [u8; 32], + store_uuid: [u8; 16], + source: ProvisionSource, +) -> Result { + writable(store)?; + if !ids_of_kind(store, KIND_AGENT_ROOT).is_empty() { + return Err(ContinuityError::AlreadyProvisioned); + } + if agent_id == ZERO_ID { + return Err(ContinuityError::Corrupt("zero agent id")); + } + let root = AgentRoot { + agent_id, + store_uuid, + root_branch: root_branch_id(&agent_id), + provisioned_generation: store.generation() + 1, + source, + }; + let root_bytes = root.encode(); + let root_id = object_id(KIND_AGENT_ROOT, &root_bytes)?; + let state_bytes = AgentState::genesis(agent_id, 1).encode()?; + let state_id = object_id(KIND_AGENT_STATE, &state_bytes)?; + let manifest = Manifest { + root: root_id, + previous: None, + sequence: 1, + incarnation: 1, + agent_state: Some(state_id), + cortex_wal: Vec::new(), + }; + let manifest_bytes = manifest.encode()?; + store.transact(&[ + ObjectInput { + kind: KIND_AGENT_ROOT, + version: STORE_OBJECT_VERSION, + bytes: &root_bytes, + }, + ObjectInput { + kind: KIND_AGENT_STATE, + version: STORE_OBJECT_VERSION, + bytes: &state_bytes, + }, + ObjectInput { + kind: KIND_MANIFEST, + version: STORE_OBJECT_VERSION, + bytes: &manifest_bytes, + }, + ])?; + resolve(store) +} + +/// Commits `update` and a new manifest in one Store transaction. With +/// `new_incarnation` the incarnation advances (a resume); otherwise it is kept. +pub fn commit( + store: &mut Store, + current: &Continuity, + update: Update, + new_incarnation: bool, +) -> Result { + writable(store)?; + let sequence = current + .manifest + .sequence + .checked_add(1) + .ok_or(ContinuityError::Limit("manifest sequence"))?; + let mut objects: Vec<(u16, Vec)> = Vec::new(); + + let mut agent_state = current.manifest.agent_state; + if let Some(mut state) = update.state { + if state.agent_id != current.root.agent_id { + return Err(ContinuityError::Corrupt( + "agent state belongs to another agent", + )); + } + state.written_at = sequence; + let bytes = state.encode()?; + agent_state = Some(object_id(KIND_AGENT_STATE, &bytes)?); + objects.push((KIND_AGENT_STATE, bytes)); + } + + let mut cortex_wal = current.manifest.cortex_wal.clone(); + if !update.cortex.is_empty() { + if cortex_wal.len() >= MAX_WAL_SEGMENTS { + return Err(ContinuityError::Limit("cortex WAL needs compaction")); + } + let bytes = WalSegment { + sequence, + records: update.cortex, + } + .encode()?; + cortex_wal.push(object_id(KIND_CORTEX_WAL, &bytes)?); + objects.push((KIND_CORTEX_WAL, bytes)); + } + + let incarnation = if new_incarnation { + current + .manifest + .incarnation + .checked_add(1) + .ok_or(ContinuityError::Limit("incarnation"))? + } else { + current.manifest.incarnation + }; + let manifest = Manifest { + root: current.root_id, + previous: Some(current.manifest_id), + sequence, + incarnation, + agent_state, + cortex_wal, + }; + objects.push((KIND_MANIFEST, manifest.encode()?)); + + let inputs: Vec> = objects + .iter() + .map(|(kind, bytes)| ObjectInput { + kind: *kind, + version: STORE_OBJECT_VERSION, + bytes, + }) + .collect(); + store.transact(&inputs)?; + resolve(store) +} + +/// A normal boot: resolve the existing identity and durably advance the +/// incarnation before anything acts on it (commit-before-observation). +/// On a read-only mount the verified view is returned without committing. +pub fn resume(store: &mut Store) -> Result<(Continuity, bool)> { + let current = resolve(store)?; + if store.mount_state() != MountState::Valid { + return Ok((current, false)); + } + Ok((commit(store, ¤t, Update::default(), true)?, true)) +} + +#[cfg(test)] +#[path = "continuity_tests.rs"] +mod tests; diff --git a/crates/aienos-kernel/src/continuity_tests.rs b/crates/aienos-kernel/src/continuity_tests.rs new file mode 100644 index 00000000..1066d740 --- /dev/null +++ b/crates/aienos-kernel/src/continuity_tests.rs @@ -0,0 +1,345 @@ +use super::*; +use crate::store::engine::{MountState, ObjectInput, Store, StoreDevice}; +use crate::store::genesis::genesis_units; +use crate::store::v1::STORE_UNIT_BYTES; +use alloc::vec; + +const UUID: [u8; 16] = [0x5a; 16]; +const AGENT: [u8; 32] = [0x11; 32]; + +#[derive(Clone)] +struct Mem { + units: Vec<[u8; STORE_UNIT_BYTES]>, + /// Writes accepted before the device "loses power" (None = unlimited). + writes_left: Option, +} + +impl StoreDevice for Mem { + type Error = (); + fn region_units(&self) -> u64 { + self.units.len() as u64 + } + fn read_unit( + &mut self, + unit: u64, + out: &mut [u8; STORE_UNIT_BYTES], + ) -> core::result::Result<(), ()> { + *out = *self.units.get(unit as usize).ok_or(())?; + Ok(()) + } + fn write_unit( + &mut self, + unit: u64, + bytes: &[u8; STORE_UNIT_BYTES], + ) -> core::result::Result<(), ()> { + if let Some(left) = self.writes_left.as_mut() { + if *left == 0 { + return Err(()); + } + *left -= 1; + } + *self.units.get_mut(unit as usize).ok_or(())? = *bytes; + Ok(()) + } + fn flush(&mut self) -> core::result::Result<(), ()> { + Ok(()) + } +} + +fn formatted() -> Mem { + let mut units = vec![[0u8; STORE_UNIT_BYTES]; 256]; + for (i, u) in genesis_units(UUID, 256).iter().enumerate() { + units[i] = *u; + } + Mem { + units, + writes_left: None, + } +} + +fn open(dev: Mem) -> Store { + Store::open(dev).expect("store opens") +} + +fn fact(text: &str) -> CortexRecord { + CortexRecord { + status: Epistemic::OperatorDecision, + evidence_hash: [0x42; 32], + statement: text.as_bytes().to_vec(), + } +} + +fn provisioned() -> Store { + let mut store = open(formatted()); + provision(&mut store, AGENT, UUID, ProvisionSource::Qualification).unwrap(); + store +} + +/// Simulates a cold restart: drop everything in memory, reopen the medium. +fn restart(store: Store) -> Store { + open(store.into_device()) +} + +#[test] +fn unprovisioned_store_never_mints_an_identity() { + let mut store = open(formatted()); + let generation = store.generation(); + assert_eq!(resolve(&mut store), Err(ContinuityError::Unprovisioned)); + assert_eq!( + resume(&mut store).map(|_| ()), + Err(ContinuityError::Unprovisioned) + ); + assert_eq!(store.generation(), generation, "nothing was written"); + assert!(store.catalog().entries.is_empty()); +} + +#[test] +fn provision_then_cold_restart_returns_the_same_identity_and_memory() { + let mut store = provisioned(); + let c1 = resolve(&mut store).unwrap(); + assert_eq!(c1.root.agent_id, AGENT); + assert_eq!(c1.manifest.sequence, 1); + assert_eq!(c1.manifest.incarnation, 1); + + // Commit memory and a branch fork. + let mut state = c1.state.clone(); + let child = state.fork(&c1.root.root_branch).unwrap(); + let c2 = commit( + &mut store, + &c1, + Update { + state: Some(state), + cortex: vec![fact("the operator's name is Drake"), fact("M4 is next")], + }, + false, + ) + .unwrap(); + assert_eq!(c2.cortex.len(), 2); + + // Cold restart: same identity, same memory, same lineage, incarnation + 1. + let mut store = restart(store); + let (c3, committed) = resume(&mut store).unwrap(); + assert!(committed); + assert_eq!(c3.root_id, c1.root_id); + assert_eq!(c3.root.agent_id, AGENT); + assert_eq!(c3.manifest.incarnation, 2); + assert_eq!(c3.manifest.sequence, 3); + assert_eq!(c3.cortex, c2.cortex); + let branch = c3.state.branch(&child).expect("forked branch survived"); + assert_eq!(branch.parent, Some(c1.root.root_branch)); + assert_eq!(branch.depth, 1); + + // A second restart advances only the incarnation. + let mut store = restart(store); + let (c4, _) = resume(&mut store).unwrap(); + assert_eq!(c4.manifest.incarnation, 3); + assert_eq!(c4.root, c3.root); + assert_eq!(c4.state, c3.state); + assert_eq!(c4.cortex, c3.cortex); +} + +#[test] +fn provisioning_twice_is_refused() { + let mut store = provisioned(); + assert_eq!( + provision(&mut store, [0x22; 32], UUID, ProvisionSource::Operator).map(|_| ()), + Err(ContinuityError::AlreadyProvisioned) + ); + assert_eq!(resolve(&mut store).unwrap().root.agent_id, AGENT); +} + +#[test] +fn two_roots_stop_with_conflict() { + let mut store = provisioned(); + // Bypass `provision` to plant a second root, as corruption or a bad merge could. + let other = AgentRoot { + agent_id: [0x22; 32], + store_uuid: UUID, + root_branch: root_branch_id(&[0x22; 32]), + provisioned_generation: 9, + source: ProvisionSource::Operator, + } + .encode(); + store + .transact(&[ObjectInput { + kind: KIND_AGENT_ROOT, + version: STORE_OBJECT_VERSION, + bytes: &other, + }]) + .unwrap(); + assert_eq!(resolve(&mut store), Err(ContinuityError::Conflict)); + assert_eq!( + resume(&mut store).map(|_| ()), + Err(ContinuityError::Conflict) + ); +} + +#[test] +fn forked_or_gapped_manifest_chains_are_corrupt() { + // Fork: two manifests both claiming sequence 2. + let mut store = provisioned(); + let c1 = resolve(&mut store).unwrap(); + let mut bad = c1.manifest.clone(); + bad.previous = Some(c1.manifest_id); + bad.sequence = 2; + bad.incarnation = 7; + let bytes = bad.encode().unwrap(); + commit(&mut store, &c1, Update::default(), true).unwrap(); + store + .transact(&[ObjectInput { + kind: KIND_MANIFEST, + version: STORE_OBJECT_VERSION, + bytes: &bytes, + }]) + .unwrap(); + assert!(matches!( + resolve(&mut store), + Err(ContinuityError::Corrupt(_)) + )); + + // Gap: a manifest at sequence 5 with nothing between. + let mut store = provisioned(); + let c1 = resolve(&mut store).unwrap(); + let mut gap = c1.manifest.clone(); + gap.previous = Some(c1.manifest_id); + gap.sequence = 5; + let bytes = gap.encode().unwrap(); + store + .transact(&[ObjectInput { + kind: KIND_MANIFEST, + version: STORE_OBJECT_VERSION, + bytes: &bytes, + }]) + .unwrap(); + assert!(matches!( + resolve(&mut store), + Err(ContinuityError::Corrupt(_)) + )); +} + +#[test] +fn degraded_mount_resumes_read_only() { + let store = provisioned(); + let mut dev = store.into_device(); + // Plant a malformed peer superblock: the engine mounts DegradedRecovery. + let active = Store::open(dev.clone()).unwrap().active_slot() as usize; + dev.units[1 - active] = [0xa5; STORE_UNIT_BYTES]; + dev.units[1 - active][..8].copy_from_slice(b"AIENSTR1"); + let mut store = open(dev); + assert_eq!(store.mount_state(), MountState::DegradedRecovery); + let generation = store.generation(); + let (c, committed) = resume(&mut store).unwrap(); + assert!(!committed); + assert_eq!(c.root.agent_id, AGENT); + assert_eq!(store.generation(), generation, "nothing was committed"); + assert_eq!( + commit(&mut store, &c, Update::default(), true).map(|_| ()), + Err(ContinuityError::ReadOnly) + ); +} + +#[test] +fn a_crash_at_every_write_of_a_commit_leaves_old_or_new_never_a_third_state() { + let mut base = provisioned(); + let c1 = resolve(&mut base).unwrap(); + let before = base.into_device(); + + let update = || Update { + state: None, + cortex: vec![fact("remember across the crash")], + }; + // Count the unit writes one continuity commit performs. + let mut counting = before.clone(); + counting.writes_left = Some(usize::MAX); + let mut counted = open(counting); + commit(&mut counted, &c1, update(), true).unwrap(); + let total = usize::MAX - counted.into_device().writes_left.unwrap(); + assert!(total >= 4, "payload, catalog, commit record and superblock"); + + // Cut power before each write in turn (0..total) and after the last one. + for allowed in 0..=total { + let mut dev = before.clone(); + dev.writes_left = Some(allowed); + let mut store = open(dev); + let _ = commit(&mut store, &c1, update(), true); + // Power returns: reopen the medium as written so far. + let mut dev = store.into_device(); + dev.writes_left = None; + let mut store = open(dev); + let c = resolve(&mut store).unwrap(); + assert_eq!( + c.root.agent_id, AGENT, + "identity survives a crash at write {allowed}" + ); + match c.manifest.sequence { + 1 => assert!(c.cortex.is_empty()), + 2 => assert_eq!(c.cortex, vec![fact("remember across the crash")]), + s => panic!("third state: sequence {s} after crash at write {allowed}"), + } + if allowed == total { + assert_eq!(c.manifest.sequence, 2, "all writes landed: the new state"); + } + } +} + +#[test] +fn encodings_round_trip_and_reject_tampering() { + let root = AgentRoot { + agent_id: AGENT, + store_uuid: UUID, + root_branch: root_branch_id(&AGENT), + provisioned_generation: 2, + source: ProvisionSource::Operator, + }; + let bytes = root.encode(); + assert_eq!(AgentRoot::decode(&bytes).unwrap(), root); + + // Every single-byte flip is rejected or changes the decoded value. + for i in 0..bytes.len() { + let mut t = bytes.clone(); + t[i] ^= 0x01; + if let Ok(decoded) = AgentRoot::decode(&t) { + assert_ne!(decoded, root, "flip at byte {i} went unnoticed"); + } + } + // Truncation and trailing bytes are rejected. + assert!(AgentRoot::decode(&bytes[..bytes.len() - 1]).is_err()); + let mut long = bytes.clone(); + long.push(0); + assert!(AgentRoot::decode(&long).is_err()); + // A root branch that does not derive from the agent is rejected. + let mut wrong = root; + wrong.root_branch = [0x99; 32]; + assert!(AgentRoot::decode(&wrong.encode()).is_err()); + + let seg = WalSegment { + sequence: 3, + records: vec![fact("a"), fact("bb")], + }; + assert_eq!(WalSegment::decode(&seg.encode().unwrap()).unwrap(), seg); + + let mut state = AgentState::genesis(AGENT, 1); + let child = state.fork(&root_branch_id(&AGENT)).unwrap(); + state.fork(&child).unwrap(); + assert_eq!(AgentState::decode(&state.encode().unwrap()).unwrap(), state); +} + +#[test] +fn branch_table_validation_rejects_broken_lineage() { + let mut state = AgentState::genesis(AGENT, 1); + let root = root_branch_id(&AGENT); + let child = state.fork(&root).unwrap(); + assert!(state.validate().is_ok()); + + let mut t = state.clone(); + t.branches.iter_mut().find(|b| b.id == child).unwrap().depth = 5; + assert!(t.validate().is_err(), "wrong depth"); + + let mut t = state.clone(); + t.branches.iter_mut().find(|b| b.id == root).unwrap().forks = 2; + assert!(t.validate().is_err(), "missing fork index 1"); + + let mut t = state.clone(); + t.branches.retain(|b| b.id != root); + assert!(t.validate().is_err(), "no root"); +} diff --git a/crates/aienos-kernel/src/lib.rs b/crates/aienos-kernel/src/lib.rs index 3acd1228..f64769dc 100644 --- a/crates/aienos-kernel/src/lib.rs +++ b/crates/aienos-kernel/src/lib.rs @@ -20,6 +20,7 @@ pub mod boot; pub mod budget; pub mod caps; pub mod console; +pub mod continuity; pub mod crypto; pub mod device; pub mod display; diff --git a/crates/aienos-kernel/src/store.rs b/crates/aienos-kernel/src/store.rs index 5bc7990c..6ab452b7 100644 --- a/crates/aienos-kernel/src/store.rs +++ b/crates/aienos-kernel/src/store.rs @@ -10,6 +10,7 @@ pub mod checkpoint; pub mod device; pub mod engine; +pub mod genesis; /// Canonical System Store v1 format and bounded Store-unit mount/transaction engine. pub mod v1; pub use checkpoint::{Checkpoint, CheckpointHook, NullCheckpointHook}; diff --git a/crates/aienos-kernel/src/store/genesis.rs b/crates/aienos-kernel/src/store/genesis.rs new file mode 100644 index 00000000..cb6982cf --- /dev/null +++ b/crates/aienos-kernel/src/store/genesis.rs @@ -0,0 +1,62 @@ +//! Canonical System Store v1 genesis units (ADR 0015 §5). + +use alloc::vec::Vec; + +use super::v1::{ + object_unit_count, Catalog, CommitRecord, ObjectId, Superblock, OBJECT_KIND_CATALOG, + OBJECT_VERSION_V1, STORE_UNIT_BYTES, +}; + +/// Units 0..4 of a freshly formatted Store: Superblock A, an all-zero slot B +/// (so the first transaction exercises the "inactive slot initially zero" +/// case), the empty catalog at unit 2 and the genesis CommitRecord at unit 3. +pub fn genesis_units(store_uuid: [u8; 16], region_units: u64) -> [[u8; STORE_UNIT_BYTES]; 4] { + let catalog = Catalog { + entries: Vec::new(), + }; + let catalog_bytes = catalog.encode().expect("empty catalog encodes"); + let catalog_id = ObjectId::calculate(OBJECT_KIND_CATALOG, OBJECT_VERSION_V1, &catalog_bytes) + .expect("catalog id"); + let catalog_units = object_unit_count(catalog_bytes.len() as u64).expect("catalog units"); + let catalog_first = 2u64; + let commit_unit = catalog_first + u64::from(catalog_units); + let high_water = commit_unit + 1; + + let commit = CommitRecord { + store_uuid, + region_units, + generation: 1, + previous_generation: 0, + previous_commit_id: ObjectId([0u8; 32]), + previous_catalog_id: ObjectId([0u8; 32]), + catalog_id, + catalog_first_unit: catalog_first, + catalog_byte_length: catalog_bytes.len() as u64, + catalog_unit_count: catalog_units, + catalog_entry_count: 0, + committed_high_water: high_water, + }; + let commit_bytes = commit.encode().expect("genesis commit encodes"); + let commit_id = commit.object_id().expect("commit id"); + + let superblock = Superblock { + store_uuid, + slot_id: 0, + region_units, + generation: 1, + commit_record_id: commit_id, + commit_record_unit: commit_unit, + catalog_id, + catalog_first_unit: catalog_first, + catalog_byte_length: catalog_bytes.len() as u64, + catalog_unit_count: catalog_units, + catalog_entry_count: 0, + committed_high_water: high_water, + }; + + let mut out = [[0u8; STORE_UNIT_BYTES]; 4]; + out[0].copy_from_slice(&superblock.encode().expect("genesis superblock encodes")); + out[2][..catalog_bytes.len()].copy_from_slice(&catalog_bytes); + out[3][..commit_bytes.len()].copy_from_slice(&commit_bytes); + out +} diff --git a/docs/adr/0016-continuity-objects-over-store-v1.md b/docs/adr/0016-continuity-objects-over-store-v1.md new file mode 100644 index 00000000..8531f06c --- /dev/null +++ b/docs/adr/0016-continuity-objects-over-store-v1.md @@ -0,0 +1,99 @@ +# ADR 0016: Continuity objects over System Store v1 + +Status: **Proposed.** Implemented as a QEMU qualification only. The object +encodings below are a durable data format, so they are not frozen until the +operator approves (escalation trigger: irreversible data formats). Until then +every object carries format version 0 and every store holding them is +disposable test media. + +Related: ADR 0003 (minimal object store), ADR 0006 (Recovery Core), +ADR 0007 (provisioning once), ADR 0015 (System Store v1 format), +docs/CONTINUOUS_EXISTENCE_AMENDMENT.md (Class A state, commit-before-observation). + +## Context + +System Store v1 (ADR 0015) gives AIENOS a crash-safe, generation-numbered, +content-addressed object store over the native NVMe driver, qualified in +QEMU at 4096- and 512-byte LBA (#134, #136). It stores opaque objects; it does +not know what AIEN is. ADR 0007 requires that a normal boot locate, verify +and resume one durable `LogicalAgentId`, and never mint a replacement. M4 is +not done when storage works; it is done when a cold restart returns the same +identity and the same committed memory. + +## Decision + +Continuity state is a small set of Store v1 objects with canonical, +fixed-layout little-endian encodings (no serde, no JSON, `no_std`), defined in +`aienos_kernel::continuity`. Every Store transaction that changes Class A +state also writes a new `ContinuityManifest`, so each Store generation has +exactly one continuity view. + +Object kinds (Store v1 `kind`; Store `version` is 1 because Store v1 rejects +version 0; each object's own 16-byte header carries `format_version = 0` +while this ADR is Proposed, and decoders reject any other value): + +| kind | name | written | content | +|---|---|---|---| +| 16 | `AgentRoot` | once, at provisioning | magic, `LogicalAgentId` (32 B), store UUID it was provisioned into, root `LogicalBranchId`, provisioning generation, provisioning source (operator / test) | +| 17 | `ContinuityManifest` | every Class A commit | magic, `AgentRoot` ObjectId, previous manifest ObjectId (zero for the first), sequence (previous + 1), incarnation (boot counter), ObjectIds of: agent-state checkpoint, Cortex checkpoint, Cortex WAL segments (bounded list), admission receipts (bounded list) | +| 18 | `AgentStateCheckpoint` | when branch state changes | canonical branch table: branch id, parent, agent id, depth, fork counter | +| 19 | `CortexCheckpoint` | when Cortex compacts | canonical committed records | +| 20 | `CortexWalSegment` | on each committed Cortex update | append-only records since the checkpoint | + +Boot resolution (deterministic, no model, no network): + +1. Open the Store (ADR 0015). A `DegradedRecovery` mount is read-only: resume + is allowed for inspection, but no new incarnation is committed; report + `CONTINUITY: DEGRADED`. +2. Count `AgentRoot` objects in the catalog. + - 0 and provisioning was explicitly requested for this boot: create one + `LogicalAgentId` from the boot entropy source, commit `AgentRoot` and the + first manifest in one transaction, report `CONTINUITY: PROVISIONED`. + - 0 otherwise: **stop** with `CONTINUITY: UNPROVISIONED` (Recovery Core). + Never mint. + - more than 1: **stop** with `CONTINUITY: CONFLICT` (Recovery Core). + - exactly 1: continue. +3. The current manifest is the unique catalog manifest that no other manifest + names as previous, whose chain reaches the first manifest with strictly + consecutive sequence numbers and the same `AgentRoot` id. Anything else + (fork, gap, dangling reference, foreign root, undecodable object) stops + with `CONTINUITY: CORRUPT` (Recovery Core), never with a new identity. +4. Resume: verify every object the manifest names decodes; commit a new + manifest with `incarnation + 1` (commit-before-observation: the new + incarnation is durable before AIEN acts on it); report + `CONTINUITY: RESUMED agent= incarnation= sequence=`. + +Provisioning is only reachable from an explicit request (QEMU control block +today; an operator-authenticated Recovery Core action on hardware later, +ADR 0006). The normal boot path contains no code that writes an `AgentRoot`. + +## Qualification (QEMU) + +`CONTINUITY_QEMU: PASS` requires, over the real NVMe path at 4096-byte LBA: + +- provision → commit Cortex facts and a branch fork → cold restart → same + `LogicalAgentId`, same facts, same branch lineage, incarnation + 1; +- a second restart advances the incarnation again and changes nothing else; +- SIGKILL at every Store checkpoint of a continuity commit → reopen resumes + the old or the new manifest, never a third state, same identity; +- identity-loss refusal: an unprovisioned store booted normally stops with + `UNPROVISIONED` and writes nothing; a store with two roots stops with + `CONFLICT`; a broken manifest chain stops with `CORRUPT`; +- `DegradedRecovery` mounts resume read-only and commit nothing. + +## Consequences + +- M4 continuity is proven in QEMU without freezing the encodings; freezing is a + separate operator decision that turns version 0 into version 1 with golden + vectors, as ADR 0015 did. +- The host crates `aienos-agent-state` and `aienos-cortex` remain the richer + std models; their persisted form becomes these canonical objects. +- Encryption (M5) wraps these objects later; this ADR fixes structure, not + confidentiality. +- The Store v1 catalog is append-only and bounded (4096 entries), and every + Class A commit adds a manifest, so continuity needs catalog compaction before + long-running use. Out of scope here; tracked as follow-up. +- Provisioning entropy is `RNDR` (FEAT_RNG). If the CPU does not implement it, + provisioning fails closed (`CONTINUITY: NO_ENTROPY`); it never falls back to + a predictable identity. Whether Machine 1's cores implement FEAT_RNG is a + hardware fact to record at the qualification wave. diff --git a/docs/adr/README.md b/docs/adr/README.md index 2be8fb04..84f2a254 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -21,6 +21,7 @@ This directory documents the key architectural decisions and formal technical sp | [ADR 0013](0013-aienos-abi-v1.md) | AIENOS ABI v1 | Proposed | 2026-09-24 | [ADR 0012](0012-self-construction-capability-growth-and-generations.md); [ADR 0004](0004-reversibility-definition-and-network-effect-boundary.md); [issue #30](https://github.com/aien-dev/aienos/issues/30); [PR #106](https://github.com/aien-dev/aienos/pull/106); [`abi.rs`](../../crates/aienos-kernel/src/abi.rs) | | [ADR 0014](0014-binary-artifact-v0-and-native-admission.md) | Binary Artifact v0 and Native Admission | Proposed | 2026-09-25 | [ADR 0012](0012-self-construction-capability-growth-and-generations.md); [ADR 0013](0013-aienos-abi-v1.md); SEED-0B qualification | | [ADR 0015](0015-system-store-v1-format.md) | AIENOS System Store v1 Format | Accepted for P3-1 format freeze | 2026-09-25 | [ADR 0003](0003-bootstrap-firmware-handoff-and-minimal-object-store.md); P3 Native Persistence & Continuity | +| [ADR 0016](0016-continuity-objects-over-store-v1.md) | Continuity objects over System Store v1 | Proposed (format freeze needs operator approval) | 2026-09-25 | [ADR 0007](0007-continuous-existence-provisioning-once.md), [ADR 0015](0015-system-store-v1-format.md); M4 continuity | --- From 110ceb82d2f781b7c2d6142265f878853e5970e1 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Fri, 25 Sep 2026 17:21:57 -0500 Subject: [PATCH 2/4] qual(continuity): QEMU cold-restart continuity campaign (CONTINUITY_QEMU) - arch::aarch64::rndr(): FEAT_RNG RNDR with retry; None when absent, and provisioning then fails closed (CONTINUITY: NO_ENTROPY). - continuity::commit_with_hook for Store checkpoint crash campaigns. - aienos-boot feature continuity-qual: modes 5 provision, 6 resume, 7 remember (fact + fork), 8 hooked commit; one CONTINUITY summary line per boot (full agent id, incarnation, sequence, cortex/branch counts, memory digest); every STOP path returns before any Store write. - aienos-store-tool inject accepts SLOT=inactive. - scripts/qemu_continuity_test.sh: refusals on blank and unprovisioned media (image byte-identical), provision once (+ independent RNDR draws differ, re-provision refused), remember then two cold restarts (same agent, memory, lineage; incarnation advances), SIGKILL at all 7 Store checkpoints of a continuity commit (old or new memory, same agent), degraded mount resumes read-only. Co-Authored-By: Drake Stapleton Co-Authored-By: Claude Opus 5.5 --- crates/aienos-boot/Cargo.toml | 4 + crates/aienos-boot/src/nvme_read.rs | 177 +++++++++++++++++++ crates/aienos-boot/src/store_qual.rs | 22 +++ crates/aienos-kernel/src/arch/aarch64.rs | 37 ++++ crates/aienos-kernel/src/continuity.rs | 14 +- crates/aienos-store-tool/src/main.rs | 31 +++- scripts/qemu_continuity_test.sh | 214 +++++++++++++++++++++++ 7 files changed, 495 insertions(+), 4 deletions(-) create mode 100755 scripts/qemu_continuity_test.sh diff --git a/crates/aienos-boot/Cargo.toml b/crates/aienos-boot/Cargo.toml index 6baaedef..9f25eda8 100644 --- a/crates/aienos-boot/Cargo.toml +++ b/crates/aienos-boot/Cargo.toml @@ -27,6 +27,10 @@ nvme-write = ["nvme-read"] # P3 candidate: Store-over-NVMe qualification (test-only). QEMU only. # scripts/qemu_store_crash_test.sh enables it; hardware staging never does. store-qual = ["nvme-write"] +# M4 continuity qualification (ADR 0016, test-only, QEMU only): provision / +# resume / remember / crash modes over the Store-over-NVMe path. +# scripts/qemu_continuity_test.sh enables it; hardware staging never does. +continuity-qual = ["store-qual"] # SEED-0B qualification build (ADR 0014 §6): the kernel trusts the public, # TEST ONLY RFC 8032 qualification key in addition to the (empty) production # set, and every report says so. Without it, every artifact candidate is diff --git a/crates/aienos-boot/src/nvme_read.rs b/crates/aienos-boot/src/nvme_read.rs index f31dc59a..cf58d1cc 100644 --- a/crates/aienos-boot/src/nvme_read.rs +++ b/crates/aienos-boot/src/nvme_read.rs @@ -885,6 +885,16 @@ fn run_store_phase(screen: &mut Option, mut controller: QualController, }; let region_units = adapter.region_units(); + #[cfg(feature = "continuity-qual")] + if crate::store_qual::is_continuity_mode(mode) { + if is_512_qual { + qualify_fail(screen, "continuity qualification runs at 4096-byte LBA"); + return; + } + continuity_phase(screen, adapter, mode); + return; + } + if mode == MODE_VERIFY || mode == MODE_VERIFY_512B { verify_reopen(screen, adapter, settle, is_512_qual); return; @@ -1072,3 +1082,170 @@ fn verify_reopen(screen: &mut Option, adapter: QualAdapter, settle: u8, ); say(screen, done.as_str()); } + +/// M4 continuity qualification (ADR 0016). One summary line per boot: +/// `CONTINUITY: agent=<64 hex> incarnation=N sequence=S cortex=K +/// branches=B memory=<16 hex>` or `CONTINUITY: ...`. Every STOP +/// path returns before any Store write. +#[cfg(feature = "continuity-qual")] +fn continuity_phase(screen: &mut Option, mut adapter: QualAdapter, mode: u8) { + use crate::store_qual::{ + genesis_units, MODE_CONT_CRASH, MODE_CONT_PROVISION, MODE_CONT_REMEMBER, QUAL_STORE_UUID, + }; + use aienos_kernel::continuity::{ + self, Continuity, ContinuityError, CortexRecord, Epistemic, ProvisionSource, Update, + }; + use aienos_kernel::store::engine::Store; + + fn line(screen: &mut Option, args: core::fmt::Arguments<'_>) { + let mut l = aienos_kernel::report::ReportBuf::<256>::new(); + let _ = l.write_fmt(args); + let _ = writeln!(l); + say(screen, l.as_str()); + } + fn summary(screen: &mut Option, word: &str, c: &Continuity) { + let mut memory = aienos_kernel::crypto::sha256::Sha256::new(); + for rec in &c.cortex { + memory.update(&(rec.statement.len() as u32).to_le_bytes()); + memory.update(&rec.statement); + } + let memory = memory.finalize(); + let mut l = aienos_kernel::report::ReportBuf::<256>::new(); + let _ = write!(l, "CONTINUITY: {word} agent="); + for b in &c.root.agent_id { + let _ = write!(l, "{b:02x}"); + } + let _ = write!( + l, + " incarnation={} sequence={} cortex={} branches={} memory=", + c.manifest.incarnation, + c.manifest.sequence, + c.cortex.len(), + c.state.branches.len() + ); + for b in &memory[..8] { + let _ = write!(l, "{b:02x}"); + } + let _ = writeln!(l); + say(screen, l.as_str()); + } + fn stop(screen: &mut Option, e: ContinuityError) { + match e { + ContinuityError::Unprovisioned => { + line(screen, format_args!("CONTINUITY: UNPROVISIONED")) + } + ContinuityError::Conflict => line(screen, format_args!("CONTINUITY: CONFLICT")), + ContinuityError::Corrupt(why) => { + line(screen, format_args!("CONTINUITY: CORRUPT ({why})")) + } + other => line(screen, format_args!("CONTINUITY: STOP ({other:?})")), + } + } + + if mode == MODE_CONT_PROVISION { + let mut probe = [0u8; 4096]; + let blank = adapter.read_unit(0, &mut probe).is_ok() && probe.iter().all(|b| *b == 0); + if blank { + let units = genesis_units(adapter.region_units()); + for (i, unit) in units.iter().enumerate() { + if adapter.write_unit(i as u64, unit).is_err() { + line(screen, format_args!("CONTINUITY: STOP (genesis write)")); + return; + } + } + if adapter.flush().is_err() { + line(screen, format_args!("CONTINUITY: STOP (genesis flush)")); + return; + } + } + } + + let mut store = match Store::open(adapter) { + Ok(s) => s, + Err(e) => { + line(screen, format_args!("CONTINUITY: STOP (store {e:?})")); + return; + } + }; + + if mode == MODE_CONT_PROVISION { + let mut agent = [0u8; 32]; + for chunk in agent.as_chunks_mut::<8>().0 { + match aienos_kernel::arch::aarch64::rndr() { + Some(v) => chunk.copy_from_slice(&v.to_le_bytes()), + None => { + line(screen, format_args!("CONTINUITY: NO_ENTROPY")); + return; + } + } + } + match continuity::provision( + &mut store, + agent, + QUAL_STORE_UUID, + ProvisionSource::Qualification, + ) { + Ok(c) => summary(screen, "PROVISIONED", &c), + Err(e) => stop(screen, e), + } + return; + } + + let current = match continuity::resume(&mut store) { + Ok((c, true)) => { + summary(screen, "RESUMED", &c); + c + } + Ok((c, false)) => { + summary(screen, "RESUMED_READONLY", &c); + return; + } + Err(e) => { + stop(screen, e); + return; + } + }; + + let fact = |text: &[u8]| CortexRecord { + status: Epistemic::DirectObservation, + evidence_hash: [0; 32], + statement: text.to_vec(), + }; + if mode == MODE_CONT_REMEMBER { + let mut state = current.state.clone(); + if state.fork(¤t.root.root_branch).is_err() { + line(screen, format_args!("CONTINUITY: STOP (fork)")); + return; + } + let update = Update { + state: Some(state), + cortex: alloc::vec![fact(b"qemu: the operator asked AIEN to remember this")], + }; + match continuity::commit(&mut store, ¤t, update, false) { + Ok(c) => summary(screen, "REMEMBERED", &c), + Err(e) => stop(screen, e), + } + } else if mode == MODE_CONT_CRASH { + let hook = |cp: aienos_kernel::store::checkpoint::Checkpoint| { + let mut l = aienos_kernel::report::ReportBuf::<64>::new(); + let _ = writeln!(l, "CHECKPOINT: {}", cp.as_str()); + say(screen, l.as_str()); + // Observation hold only: no flush, no write, no ordering change. + let hz = counter_frequency_hz(); + if hz > 0 { + let start = counter_ticks(); + while counter_ticks().wrapping_sub(start) < hz / 2 { + core::hint::spin_loop(); + } + } + }; + let update = Update { + state: None, + cortex: alloc::vec![fact(b"qemu: committed across a crash")], + }; + match continuity::commit_with_hook(&mut store, ¤t, update, false, hook) { + Ok(c) => summary(screen, "COMMITTED", &c), + Err(e) => stop(screen, e), + } + } +} diff --git a/crates/aienos-boot/src/store_qual.rs b/crates/aienos-boot/src/store_qual.rs index eb0e9c6f..1de034ef 100644 --- a/crates/aienos-boot/src/store_qual.rs +++ b/crates/aienos-boot/src/store_qual.rs @@ -24,6 +24,28 @@ pub const STORE_BASE_LBA_512: u64 = 512; pub const STORE_REGION_BLOCKS_512: u64 = 2048; pub const CONFIG_LBA_512: u64 = 256; +/// M4 continuity qualification modes (ADR 0016), 4096-byte LBA only. +/// Provision: format if blank, then create the one identity from RNDR. +#[cfg(feature = "continuity-qual")] +pub const MODE_CONT_PROVISION: u8 = 5; +/// Resume: locate and verify the identity, commit incarnation + 1. Never mints. +#[cfg(feature = "continuity-qual")] +pub const MODE_CONT_RESUME: u8 = 6; +/// Resume, then commit one Cortex fact and one branch fork. +#[cfg(feature = "continuity-qual")] +pub const MODE_CONT_REMEMBER: u8 = 7; +/// Resume, then commit one Cortex fact while emitting Store checkpoints. +#[cfg(feature = "continuity-qual")] +pub const MODE_CONT_CRASH: u8 = 8; + +#[cfg(feature = "continuity-qual")] +pub const fn is_continuity_mode(mode: u8) -> bool { + matches!( + mode, + MODE_CONT_PROVISION | MODE_CONT_RESUME | MODE_CONT_REMEMBER | MODE_CONT_CRASH + ) +} + /// Adds a fixed LBA offset and rejects accesses past the bounded region. pub struct BoundedNvme { inner: NvmeController, diff --git a/crates/aienos-kernel/src/arch/aarch64.rs b/crates/aienos-kernel/src/arch/aarch64.rs index d2dcdb94..b02120aa 100644 --- a/crates/aienos-kernel/src/arch/aarch64.rs +++ b/crates/aienos-kernel/src/arch/aarch64.rs @@ -167,6 +167,43 @@ pub fn midr_el1() -> u64 { } } +/// One 64-bit value from the architectural random number generator (FEAT_RNG +/// `RNDR`), or `None` if the core does not implement it or it keeps failing. +/// Callers that need entropy must fail closed on `None`; there is no fallback. +pub fn rndr() -> Option { + #[cfg(target_arch = "aarch64")] + { + let isar0: u64; + unsafe { + core::arch::asm!("mrs {0}, id_aa64isar0_el1", out(reg) isar0, options(nomem, nostack, preserves_flags)); + } + if (isar0 >> 60) & 0xf == 0 { + return None; + } + for _ in 0..16 { + let (value, nzcv): (u64, u64); + // RNDR is s3_3_c2_c4_0; a failed read returns 0 with PSTATE.Z = 1. + unsafe { + core::arch::asm!( + "mrs {0}, s3_3_c2_c4_0", + "mrs {1}, nzcv", + out(reg) value, + out(reg) nzcv, + options(nomem, nostack), + ); + } + if nzcv & (1 << 30) == 0 { + return Some(value); + } + } + None + } + #[cfg(not(target_arch = "aarch64"))] + { + None + } +} + /// Multiprocessor affinity of the executing core (matches MADT GICC MPIDR). #[inline(always)] pub fn mpidr_el1() -> u64 { diff --git a/crates/aienos-kernel/src/continuity.rs b/crates/aienos-kernel/src/continuity.rs index 5b5f8ba0..e98cac97 100644 --- a/crates/aienos-kernel/src/continuity.rs +++ b/crates/aienos-kernel/src/continuity.rs @@ -12,6 +12,7 @@ use alloc::vec::Vec; use crate::crypto::sha256::Sha256; +use crate::store::checkpoint::CheckpointHook; use crate::store::engine::{MountState, ObjectInput, Store, StoreDevice, StoreError}; use crate::store::v1::ObjectId; @@ -767,6 +768,17 @@ pub fn commit( current: &Continuity, update: Update, new_incarnation: bool, +) -> Result { + commit_with_hook(store, current, update, new_incarnation, |_| {}) +} + +/// [`commit`] with a Store checkpoint hook (qualification crash campaigns). +pub fn commit_with_hook( + store: &mut Store, + current: &Continuity, + update: Update, + new_incarnation: bool, + hook: H, ) -> Result { writable(store)?; let sequence = current @@ -830,7 +842,7 @@ pub fn commit( bytes, }) .collect(); - store.transact(&inputs)?; + store.transact_with_hook(&inputs, hook)?; resolve(store) } diff --git a/crates/aienos-store-tool/src/main.rs b/crates/aienos-store-tool/src/main.rs index d444e6c3..dd22a9f6 100644 --- a/crates/aienos-store-tool/src/main.rs +++ b/crates/aienos-store-tool/src/main.rs @@ -10,7 +10,7 @@ //! tear-closure OLD NEW STORE_BYTE_OFFSET SECTOR_BYTES //! Prove that every sector-granular tear of the one superblock write that //! separates OLD from NEW leaves either the old or the new slot bytes. -//! inject IMAGE STORE_BYTE_OFFSET SLOT CASE [SOURCE] +//! inject IMAGE STORE_BYTE_OFFSET SLOT|inactive CASE [SOURCE] //! Overwrite superblock SLOT with one deterministic defect (see `CASES`). use std::env; @@ -225,6 +225,27 @@ fn tear_outcomes(old: &Unit, new: &Unit, sector: usize) -> Result<(u32, u32), u3 Ok((as_old, as_new)) } +/// The slot the engine would overwrite next: the zero slot, else the valid +/// superblock with the lower generation. Refuses anything ambiguous. +fn inactive_slot(image: &str, store_offset: u64) -> Result { + let mut generation = [None; 2]; + for slot in 0..2u32 { + let unit = read_unit_at( + image, + store_offset + u64::from(slot) * STORE_UNIT_BYTES as u64, + )?; + if unit.iter().all(|b| *b == 0) { + return Ok(slot); + } + generation[slot as usize] = Superblock::decode(&unit, slot).ok().map(|sb| sb.generation); + } + match generation { + [Some(a), Some(b)] if a < b => Ok(0), + [Some(a), Some(b)] if b < a => Ok(1), + _ => Err("cannot determine the inactive slot (both slots valid at one generation, or one undecodable)".into()), + } +} + /// xorshift64 stream with a fixed seed: the same 4096 bytes on every run. fn seeded_garbage() -> Unit { let mut state: u64 = 0x4149_454E_4F53_0136; @@ -242,9 +263,13 @@ fn inject(args: &[String]) -> Result { arity(args, 4, 5)?; let image = &args[0]; let store_offset = num(&args[1], "store offset")?; - let slot = u32::try_from(num(&args[2], "slot")?).map_err(|e| e.to_string())?; + let slot = if args[2] == "inactive" { + inactive_slot(image, store_offset)? + } else { + u32::try_from(num(&args[2], "slot")?).map_err(|e| e.to_string())? + }; if slot > 1 { - return Err("slot must be 0 or 1".into()); + return Err("slot must be 0, 1 or inactive".into()); } let case = args[3].as_str(); let slot_offset = store_offset + u64::from(slot) * STORE_UNIT_BYTES as u64; diff --git a/scripts/qemu_continuity_test.sh b/scripts/qemu_continuity_test.sh new file mode 100755 index 00000000..b2fe8ac4 --- /dev/null +++ b/scripts/qemu_continuity_test.sh @@ -0,0 +1,214 @@ +#!/usr/bin/env bash +# M4 continuity qualification in QEMU (ADR 0016, Proposed): the same AIEN +# identity and committed memory survive cold restarts over System Store v1 on +# the native NVMe driver, and no boot path ever mints a replacement identity. +# +# Geometry: 4096-byte LBA (atomic-root qualified namespace). Every boot is a +# fresh QEMU process (cold restart); only the NVMe image persists. +# +# Emits CONTINUITY_QEMU: PASS only when every step passes. QEMU only; no +# Machine 1 claim. The continuity encodings are format version 0 (Proposed). +set -uo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "${repo_root}" + +code_fd="${AAVMF_CODE:-/usr/share/AAVMF/AAVMF_CODE.no-secboot.fd}" +vars_fd="${AAVMF_VARS:-/usr/share/AAVMF/AAVMF_VARS.fd}" +command -v qemu-system-aarch64 >/dev/null || { echo "qemu-system-aarch64 not installed"; exit 2; } +[[ -r "${code_fd}" && -r "${vars_fd}" ]] || { echo "AAVMF firmware not found"; exit 2; } + +boot_timeout="${AIENOS_QEMU_TIMEOUT:-180}" +img_bytes=67108864 +lba_bytes=4096 +cfg_offset=$(( 32 * lba_bytes )) +store_offset=$(( 64 * lba_bytes )) +machine="virt,virtualization=on,gic-version=3,iommu=smmuv3" +target_dir="target/qemu-continuity" + +echo "=== Building aienos-handoff (continuity-qual) and aienos-store-tool ===" +commit="$(git rev-parse HEAD 2>/dev/null || echo unknown)" +git diff --quiet HEAD 2>/dev/null || commit="${commit}-dirty" +AIENOS_COMMIT="${commit}" AIENOS_RESTART_SECS=1 cargo build --quiet --release \ + -p aienos-boot --target aarch64-unknown-uefi --features continuity-qual --bin aienos-handoff \ + --target-dir "${target_dir}" || { echo "build failed"; exit 2; } +cargo build --quiet --release -p aienos-store-tool || { echo "store tool build failed"; exit 2; } +tool="target/release/aienos-store-tool" + +work="$(mktemp -d)" +qemu_pid="" +cleanup() { [[ -n "${qemu_pid}" ]] && kill -9 "${qemu_pid}" 2>/dev/null || true; rm -rf "${work}"; } +trap cleanup EXIT +mkdir -p "${work}/esp/EFI/BOOT" "${work}/esp/EFI/AIENOS" +touch "${work}/esp/EFI/AIENOS/BOOTREPORT.TXT" +cp "${target_dir}/aarch64-unknown-uefi/release/aienos-handoff.efi" "${work}/esp/EFI/BOOT/BOOTAA64.EFI" + +image="${work}/nvme.img" +serial="${work}/serial.log" +fail=0 + +fresh_image() { rm -f "${image}"; truncate -s "${img_bytes}" "${image}"; } +write_cfg() { "${tool}" cfg "${image}" "${cfg_offset}" "$1" 0 >/dev/null || { echo "cfg write failed"; exit 2; }; } +digest() { sha256sum "${image}" | cut -d' ' -f1; } +pass() { echo "PASS $1"; } +bad() { echo "FAIL $1"; fail=1; } + +# run_qemu [kill]: one cold boot; returns when QEMU exits (or is killed). +run_qemu() { + cp -f "${vars_fd}" "${work}/vars.fd" + rm -f "${serial}" + qemu-system-aarch64 \ + -M "${machine}" -accel tcg,thread=single -cpu max -smp 4 -m 2048 \ + -drive if=pflash,format=raw,readonly=on,file="${code_fd}" \ + -drive if=pflash,format=raw,file="${work}/vars.fd" \ + -drive if=none,id=esp,format=raw,file=fat:rw:"${work}/esp" \ + -device virtio-blk-pci,drive=esp \ + -drive if=none,id=nvme0,format=raw,file="${image}" \ + -device nvme,drive=nvme0,serial=aienos-continuity,logical_block_size=${lba_bytes},physical_block_size=${lba_bytes} \ + -display none -nic none -serial file:"${serial}" -no-reboot & + qemu_pid=$! + local deadline=$(( $(date +%s) + boot_timeout )) + while (( $(date +%s) < deadline )); do + grep -q -- "$1" "${serial}" 2>/dev/null && break + kill -0 "${qemu_pid}" 2>/dev/null || break + sleep 0.1 + done + if [[ "${2:-}" == "kill" ]]; then + kill -9 "${qemu_pid}" 2>/dev/null || true + fi + wait "${qemu_pid}" 2>/dev/null || true + qemu_pid="" +} + +# boot_mode : cfg + cold boot until the guest resets. +boot_mode() { write_cfg "$1"; run_qemu "AIENOS_NEVER_PRINTED_MARKER"; } + +# cont : the last "CONTINUITY: WORD ..." line of this boot (empty if none). +cont() { tr -d '\r' <"${serial}" | grep -oE "CONTINUITY: $1( .*)?$" | tail -1; } +field() { sed -nE "s/.* $1=([0-9a-f]+).*/\1/p" <<<"$2"; } + +echo "=== 1. Refusals: no boot path mints an identity ===" +fresh_image +before=$(digest); boot_mode 6; after=$(digest) +if [[ -n "$(cont 'STOP \(store Unformatted\)')" && "${before}" == "${after}" ]]; then + pass "resume on blank media stops (store Unformatted) and writes nothing" +else + bad "resume on blank media: $(tr -d '\r' <"${serial}" | grep 'CONTINUITY:' | head -2)" +fi + +fresh_image +write_cfg 1; run_qemu "STORE_CHECKPOINT_QEMU" # formatted Store with data, no identity +grep -q "STORE_CHECKPOINT_QEMU: PASS" "${serial}" || bad "could not build a formatted, unprovisioned store" +before=$(digest); boot_mode 6; after=$(digest) +if [[ -n "$(cont UNPROVISIONED)" && "${before}" == "${after}" ]]; then + pass "resume on a formatted but unprovisioned store stops UNPROVISIONED and writes nothing" +else + bad "unprovisioned resume: $(tr -d '\r' <"${serial}" | grep 'CONTINUITY:' | head -2)" +fi + +echo "=== 2. Provisioning happens once ===" +fresh_image +boot_mode 5 +line=$(cont PROVISIONED) +agent=$(field agent "${line}") +if [[ ${#agent} == 64 && "${line}" == *"incarnation=1 sequence=1 cortex=0 branches=1 "* ]]; then + pass "provisioned agent ${agent:0:16}... (incarnation 1, empty memory, root branch)" +else + bad "provision: ${line:-$(tr -d '\r' <"${serial}" | grep 'CONTINUITY:' | head -2)}" +fi +provisioned_img="${work}/provisioned.img"; cp "${image}" "${provisioned_img}" + +before=$(digest); boot_mode 5; after=$(digest) +if [[ -n "$(cont 'STOP \(AlreadyProvisioned\)')" && "${before}" == "${after}" ]]; then + pass "a second provisioning request is refused and writes nothing" +else + bad "re-provision: $(tr -d '\r' <"${serial}" | grep 'CONTINUITY:' | head -2)" +fi + +cp "${image}" "${work}/keep.img"; fresh_image; boot_mode 5 +other=$(field agent "$(cont PROVISIONED)") +if [[ ${#other} == 64 && "${other}" != "${agent}" ]]; then + pass "independent provisioning draws a different identity from RNDR" +else + bad "second fresh provisioning gave '${other}'" +fi +cp "${work}/keep.img" "${image}" + +echo "=== 3. Memory and lineage survive cold restarts ===" +boot_mode 7 +r=$(cont RESUMED); m=$(cont REMEMBERED) +memory=$(field memory "${m}") +if [[ "$(field agent "${r}")" == "${agent}" && "${r}" == *"incarnation=2 sequence=2 cortex=0 branches=1 "* && \ + "$(field agent "${m}")" == "${agent}" && "${m}" == *"incarnation=2 sequence=3 cortex=1 branches=2 "* ]]; then + pass "resume + remember: incarnation 2, one Cortex fact and one forked branch committed" +else + bad "remember: resumed='${r}' remembered='${m}'" +fi + +inc=3; seq=4 +for n in 1 2; do + boot_mode 6 + r=$(cont RESUMED) + if [[ "$(field agent "${r}")" == "${agent}" && "$(field memory "${r}")" == "${memory}" && \ + "${r}" == *"incarnation=${inc} sequence=${seq} cortex=1 branches=2 "* ]]; then + pass "cold restart ${n}: same agent, same memory ${memory}, same lineage, incarnation ${inc}" + else + bad "cold restart ${n}: '${r}'" + fi + inc=$(( inc + 1 )); seq=$(( seq + 1 )) +done +base="${work}/remembered.img"; cp "${image}" "${base}" + +echo "=== 4. SIGKILL at every Store checkpoint of a continuity commit ===" +cp "${base}" "${image}"; boot_mode 8 +new_memory=$(field memory "$(cont COMMITTED)") +[[ -n "${new_memory}" && "${new_memory}" != "${memory}" ]] || bad "reference commit did not produce new memory" +checkpoints=(before_first_write after_payloads after_catalog after_commit_record \ + after_first_flush after_superblock_write after_final_flush) +for cp in "${checkpoints[@]}"; do + cp "${base}" "${image}"; write_cfg 8 + run_qemu "CHECKPOINT: ${cp}" kill + saw=0; grep -q -- "CHECKPOINT: ${cp}" "${serial}" && saw=1 + boot_mode 6 + r=$(cont RESUMED); got=$(field memory "${r}") + case "${cp}" in + after_final_flush) want="${new_memory}" ;; + after_superblock_write) want="either" ;; + *) want="${memory}" ;; + esac + ok=0 + if [[ "${saw}" == 1 && "$(field agent "${r}")" == "${agent}" ]]; then + if [[ "${want}" == either ]]; then + [[ "${got}" == "${memory}" || "${got}" == "${new_memory}" ]] && ok=1 + else + [[ "${got}" == "${want}" ]] && ok=1 + fi + fi + state="old"; [[ "${got}" == "${new_memory}" ]] && state="new" + if [[ "${ok}" == 1 ]]; then + pass "kill at ${cp}: same agent, ${state} memory" + else + bad "kill at ${cp}: saw=${saw} '${r}'" + fi +done + +echo "=== 5. Degraded mount resumes read-only ===" +cp "${base}" "${image}" +"${tool}" inject "${image}" "${store_offset}" inactive seeded_garbage >/dev/null || bad "inject failed" +before=$(digest); boot_mode 6; after=$(digest) +r=$(cont RESUMED_READONLY) +if [[ "$(field agent "${r}")" == "${agent}" && "$(field memory "${r}")" == "${memory}" && "${before}" == "${after}" ]]; then + pass "malformed peer superblock: same agent and memory, read-only, nothing written" +else + bad "degraded: '${r:-$(tr -d '\r' <"${serial}" | grep 'CONTINUITY:' | head -2)}'" +fi + +echo +echo "=== Summary (commit ${commit}) ===" +if [[ "${fail}" == 0 ]]; then + echo "CONTINUITY_QEMU: PASS" +else + echo "CONTINUITY_QEMU: FAIL" + exit 1 +fi +echo "CONTINUITY_NATIVE: NOT CLAIMED (Machine 1 waits on TRUST-1)" From 3df62b23f3a0441c73bed8bd4b5a89f82d866ccc Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Fri, 25 Sep 2026 17:25:29 -0500 Subject: [PATCH 3/4] qual(continuity): hash the image after the host's control-block write The refusal checks hashed before write_cfg, so the host's own mode byte made the image differ; hash after it so only guest writes count. Co-Authored-By: Drake Stapleton Co-Authored-By: Claude Opus 5.5 --- scripts/qemu_continuity_test.sh | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/scripts/qemu_continuity_test.sh b/scripts/qemu_continuity_test.sh index b2fe8ac4..7a90b5ab 100755 --- a/scripts/qemu_continuity_test.sh +++ b/scripts/qemu_continuity_test.sh @@ -80,7 +80,8 @@ run_qemu() { qemu_pid="" } -# boot_mode : cfg + cold boot until the guest resets. +# boot_mode : cfg + cold boot until the guest resets. "Writes nothing" +# checks hash the image after write_cfg, so only guest writes can change it. boot_mode() { write_cfg "$1"; run_qemu "AIENOS_NEVER_PRINTED_MARKER"; } # cont : the last "CONTINUITY: WORD ..." line of this boot (empty if none). @@ -89,7 +90,7 @@ field() { sed -nE "s/.* $1=([0-9a-f]+).*/\1/p" <<<"$2"; } echo "=== 1. Refusals: no boot path mints an identity ===" fresh_image -before=$(digest); boot_mode 6; after=$(digest) +write_cfg 6; before=$(digest); run_qemu "AIENOS_NEVER_PRINTED_MARKER"; after=$(digest) if [[ -n "$(cont 'STOP \(store Unformatted\)')" && "${before}" == "${after}" ]]; then pass "resume on blank media stops (store Unformatted) and writes nothing" else @@ -99,7 +100,7 @@ fi fresh_image write_cfg 1; run_qemu "STORE_CHECKPOINT_QEMU" # formatted Store with data, no identity grep -q "STORE_CHECKPOINT_QEMU: PASS" "${serial}" || bad "could not build a formatted, unprovisioned store" -before=$(digest); boot_mode 6; after=$(digest) +write_cfg 6; before=$(digest); run_qemu "AIENOS_NEVER_PRINTED_MARKER"; after=$(digest) if [[ -n "$(cont UNPROVISIONED)" && "${before}" == "${after}" ]]; then pass "resume on a formatted but unprovisioned store stops UNPROVISIONED and writes nothing" else @@ -118,7 +119,7 @@ else fi provisioned_img="${work}/provisioned.img"; cp "${image}" "${provisioned_img}" -before=$(digest); boot_mode 5; after=$(digest) +write_cfg 5; before=$(digest); run_qemu "AIENOS_NEVER_PRINTED_MARKER"; after=$(digest) if [[ -n "$(cont 'STOP \(AlreadyProvisioned\)')" && "${before}" == "${after}" ]]; then pass "a second provisioning request is refused and writes nothing" else @@ -195,7 +196,7 @@ done echo "=== 5. Degraded mount resumes read-only ===" cp "${base}" "${image}" "${tool}" inject "${image}" "${store_offset}" inactive seeded_garbage >/dev/null || bad "inject failed" -before=$(digest); boot_mode 6; after=$(digest) +write_cfg 6; before=$(digest); run_qemu "AIENOS_NEVER_PRINTED_MARKER"; after=$(digest) r=$(cont RESUMED_READONLY) if [[ "$(field agent "${r}")" == "${agent}" && "$(field memory "${r}")" == "${memory}" && "${before}" == "${after}" ]]; then pass "malformed peer superblock: same agent and memory, read-only, nothing written" From 1d367c6886b6b6f0d2355ec6321199c4b4c135cb Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Fri, 25 Sep 2026 17:29:07 -0500 Subject: [PATCH 4/4] verify_all: gate CONTINUITY_QEMU; evidence at 3df62b2 Step 6e runs scripts/qemu_continuity_test.sh; step 3b lints continuity-qual. evidence/continuity_qemu_2026-09-25.md records CONTINUITY_QEMU: PASS from clean commit 3df62b2. Co-Authored-By: Drake Stapleton Co-Authored-By: Claude Opus 5.5 --- evidence/continuity_qemu_2026-09-25.md | 71 ++++++++++++++++++++++++++ scripts/verify_all.sh | 6 ++- 2 files changed, 75 insertions(+), 2 deletions(-) create mode 100644 evidence/continuity_qemu_2026-09-25.md diff --git a/evidence/continuity_qemu_2026-09-25.md b/evidence/continuity_qemu_2026-09-25.md new file mode 100644 index 00000000..47c50181 --- /dev/null +++ b/evidence/continuity_qemu_2026-09-25.md @@ -0,0 +1,71 @@ +# M4 continuity over System Store v1: QEMU qualification (2026-09-25) + +Code commit `3df62b23f3a0441c73bed8bd4b5a89f82d866ccc` (clean tree), branch +`feat/m4-continuity`, base `main` `2276906`. +Design: [ADR 0016](../docs/adr/0016-continuity-objects-over-store-v1.md) +(**Proposed**: continuity encodings are format version 0 on disposable media; +freezing them is an operator decision). +QEMU only, 4096-byte LBA, native NVMe driver, SMMUv3-confined DMA. +`CONTINUITY_NATIVE` is not claimed: Machine 1 waits on TRUST-1. + +Reproduce: `./scripts/qemu_continuity_test.sh` + +## What is proven + +Every boot is a separate QEMU process (a cold restart); only the NVMe image +carries state between boots. The guest prints one line per boot from +`aienos_kernel::continuity`, including the full 256-bit `LogicalAgentId` and a +digest of every committed Cortex statement. + +| Claim (ADR 0007 / Continuous-Existence Amendment) | Step | +|---|---| +| A normal boot never mints an identity: blank media stops `STOP (store Unformatted)`, a formatted store with data but no agent root stops `UNPROVISIONED`, and the image is byte-identical after both boots | 1 | +| Provisioning happens once, from an explicit request, with an identity drawn from `RNDR`; a second request is refused (`AlreadyProvisioned`) without writing; an independent provisioning draws a different identity | 2 | +| Committed memory and branch lineage survive cold restarts under the same `LogicalAgentId`; each start durably advances the incarnation before acting (commit-before-observation) | 3 | +| A crash (SIGKILL) at every Store checkpoint of a continuity commit leaves the old or the new committed memory, never a third state, and never another identity; the switch happens exactly at the superblock write | 4 | +| A `DegradedRecovery` mount (malformed peer superblock) resumes read-only with the same identity and memory and writes nothing | 5 | + +Conflict (two agent roots), forked or gapped manifest chains, tampered +encodings, broken branch lineage and a power cut before every unit write of a +commit are covered by host tests (`cargo test -p aienos-kernel --lib +continuity`, 9 tests). + +## Result + +```text +=== 1. Refusals: no boot path mints an identity === +PASS resume on blank media stops (store Unformatted) and writes nothing +PASS resume on a formatted but unprovisioned store stops UNPROVISIONED and writes nothing +=== 2. Provisioning happens once === +PASS provisioned agent 1e87cd17709ddce9... (incarnation 1, empty memory, root branch) +PASS a second provisioning request is refused and writes nothing +PASS independent provisioning draws a different identity from RNDR +=== 3. Memory and lineage survive cold restarts === +PASS resume + remember: incarnation 2, one Cortex fact and one forked branch committed +PASS cold restart 1: same agent, same memory 93153a653f8f3b39, same lineage, incarnation 3 +PASS cold restart 2: same agent, same memory 93153a653f8f3b39, same lineage, incarnation 4 +=== 4. SIGKILL at every Store checkpoint of a continuity commit === +PASS kill at before_first_write: same agent, old memory +PASS kill at after_payloads: same agent, old memory +PASS kill at after_catalog: same agent, old memory +PASS kill at after_commit_record: same agent, old memory +PASS kill at after_first_flush: same agent, old memory +PASS kill at after_superblock_write: same agent, new memory +PASS kill at after_final_flush: same agent, new memory +=== 5. Degraded mount resumes read-only === +PASS malformed peer superblock: same agent and memory, read-only, nothing written + +=== Summary (commit 3df62b23f3a0441c73bed8bd4b5a89f82d866ccc) === +CONTINUITY_QEMU: PASS +CONTINUITY_NATIVE: NOT CLAIMED (Machine 1 waits on TRUST-1) +``` + +## Not claimed + +- Machine 1 behaviour, TRUST-1, encryption at rest (M5). +- Recovery Core operator flows (ADR 0006): the STOP states here are the entry + conditions; the operator-authenticated recovery actions are the next step. +- Catalog compaction: every Class A commit adds a manifest to the append-only + Store v1 catalog (bounded at 4096 entries). +- Whether Machine 1's cores implement FEAT_RNG (`RNDR`); provisioning fails + closed (`NO_ENTROPY`) if not. diff --git a/scripts/verify_all.sh b/scripts/verify_all.sh index 1333889f..e98309e1 100755 --- a/scripts/verify_all.sh +++ b/scripts/verify_all.sh @@ -67,7 +67,7 @@ echo "" echo "--- [Clippy Verification: AArch64 targets, -D warnings] ---" cargo clippy -p aienos-kernel --target aarch64-unknown-none --no-default-features -- -D warnings cargo clippy -p aienos-kernel --target aarch64-unknown-none --no-default-features --features seed0b-test-anchor -- -D warnings -for features in firmware handoff seed0b-qualification usb-keyboard nvme-read nvme-write store-qual; do +for features in firmware handoff seed0b-qualification usb-keyboard nvme-read nvme-write store-qual continuity-qual; do cargo clippy -p aienos-boot --target aarch64-unknown-uefi --features "${features}" --bins -- -D warnings done echo "PASS clippy: aarch64-unknown-none kernel and aarch64-unknown-uefi images, zero warnings" @@ -157,7 +157,8 @@ fi # Step 6e: P3 native NVMe driver and System Store v1 over NVMe (QEMU only). # Read and write/flush in both DMA modes (SMMU-confined, and fail-closed with # no SMMU), 4K root-write atomicity, the 4K Store crash/reboot campaign and the -# 512-byte Store campaign. Never an unsafe DMA bypass build here. +# 512-byte Store campaign, and the M4 continuity campaign (ADR 0016). Never an +# unsafe DMA bypass build here. echo "" echo "--- [P3 NVMe + System Store v1 in QEMU] ---" if command -v qemu-system-aarch64 >/dev/null && [[ -r "${AAVMF_CODE:-/usr/share/AAVMF/AAVMF_CODE.no-secboot.fd}" ]]; then @@ -169,6 +170,7 @@ if command -v qemu-system-aarch64 >/dev/null && [[ -r "${AAVMF_CODE:-/usr/share/ ./scripts/qemu_nvme_atomicity_test.sh ./scripts/qemu_store_crash_test.sh ./scripts/qemu_store_512b_crash_test.sh + ./scripts/qemu_continuity_test.sh else skipped "qemu-system-aarch64 or AAVMF firmware not present on host." fi