Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/patches/88aa1a989910c412 # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aien-sovereign-core-mv#263 (code only) closed derived `88aa1a989910c412` #263 Imported from GitHub aien-dev/aien-sovereign-core-mv#263 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `75b16e266418ccb719ad279e58736a82ea74fbf2` · Head `42b40cd611794e5b109e43510d5138d1c587ffce` ### Fetch it A git bundle of the pull request's head, 29761 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/88aa1a989910c412.bundle -o 88aa1a989910c412.bundle git fetch 88aa1a989910c412.bundle refs/pull/263/head ``` Raw bundle · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-sovereign-core-mv 263 42b40cd611794e5b109e43510d5138d1c587ffce ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":263,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/263","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:34Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index 755d737d..20b16d43 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:4ff1a56b7c8ac606ad5709f2ba1141f16055c34f5f242ac491233dca20d5153e", - "compiled_at": "2026-10-07T02:57:36Z", + "compiled_at": "2026-10-07T03:12:39Z", "compiler": "crumb-compile/1", - "digest": "sha256:28cf40d152e8cc6a9bb05d94a80bebc6075881eb96a5183e6739c5bda85bf634", + "digest": "sha256:e7fad4dcac6c621181a7cb2d6dacbea9d7fd217cf5b23eb6171b8a7a42917b4d", "evidence_files": 155, "evidence_root": "sha256:ff6dddfecfcc02cea55f46acaccc7eaecd27557209e98c3d5616ec02bdde31db", - "files": 1093, - "generated_at_commit": "9d2902ed6d03359faadd1567da7f8e7bbba7a1b5", - "source_tree": "sha256:24d9c8192bd7ca9590dab90710d0e88ad262641643fe166c6b99af8ed30b67ff" + "files": 1106, + "generated_at_commit": "ec1891165204a5114781513c04b24a284e6eb404", + "source_tree": "sha256:3e4d3a33a5e90481eeb10be72b8e24893eed8a3273b692a0d67a288947492265" } }, "history": [], diff --git a/Cargo.lock b/Cargo.lock index 1178d100..125fe4b8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -34,6 +34,16 @@ dependencies = [ "serde_json", ] +[[package]] +name = "aien-allen" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "sha2 0.10.9", + "tempfile", +] + [[package]] name = "aien-campaign-verifier" version = "0.1.0" @@ -291,6 +301,7 @@ name = "aien-runtime" version = "0.1.0" dependencies = [ "aien-abi-core", + "aien-allen", "aien-inference-abi", "aien-kv-cache", "aien-omega-compose", diff --git a/Cargo.toml b/Cargo.toml index 6c1c53f1..96999ae3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,6 +41,7 @@ members = [ "crates/aien-closure", "crates/aien-switchboard", "crates/aien-dual-observation", + "crates/aien-allen", "tools/aien-test", "crates/aien-drive", ] diff --git a/crates/aien-allen/.crumb b/crates/aien-allen/.crumb new file mode 100644 index 00000000..828951be --- /dev/null +++ b/crates/aien-allen/.crumb @@ -0,0 +1,19 @@ +{ + "extensions": { + "generated": { + "children": [], + "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "compiled_at": "2026-10-07T01:41:35Z", + "compiler": "crumb-compile/1", + "digest": "sha256:7a9e933c991bf5b10f997d745fb1b38eff638d186e5597fed0ab0f2dcfb1bcab", + "evidence_files": 0, + "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "files": 12, + "generated_at_commit": "80012f49a23cfc38d4c41f13f66d733f7966f738", + "source_tree": "sha256:a84f7ef9543b78d85af775bbbfb3a4e85045fe299a2205464754ff700cdc3c8f" + } + }, + "name": "aien-allen", + "purpose": "ALLEN identity gate: resolve-only subject check, host pin record, deployment record (ADR 0035). Never provisions.", + "schema_version": "1.0.0" +} diff --git a/crates/aien-allen/Cargo.toml b/crates/aien-allen/Cargo.toml new file mode 100644 index 00000000..662862a9 --- /dev/null +++ b/crates/aien-allen/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "aien-allen" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +repository.workspace = true +description = "ALLEN identity gate for the host runtime: resolve-only subject check, pin record, deployment record (ADR 0035)" + +[dependencies] +sha2 = "0.10" +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" + +[dev-dependencies] +tempfile = "3.10" diff --git a/crates/aien-allen/src/binding.rs b/crates/aien-allen/src/binding.rs new file mode 100644 index 00000000..0988a720 --- /dev/null +++ b/crates/aien-allen/src/binding.rs @@ -0,0 +1,111 @@ +//! The host pin record `.allen-binding`: what this machine resolved +//! last. It is sovereign-core's own record, NOT part of the ALLEN subject +//! (ADR 0035 I3: the subject holds no machine id). The machine id is its own +//! field; there is no model field and no KV field. +//! +//! Layout (248 bytes, little-endian): "AIENALB1" | u32 version 1 | u32 0 | +//! agent 32 | root 32 | head object id 32 | u64 head sequence | lineage 32 | +//! machine id 32 | provenance 32 | sha256 of the first 216 bytes. +//! Limits (NOT_PROVED): the sha256 is unkeyed, so a pin deleted and +//! re-adopted, or the pin and the subject rolled back together, are not +//! detected. +use sha2::{Digest, Sha256}; +use std::io::Write; +use std::path::{Path, PathBuf}; + +pub const PIN_LEN: usize = 248; +const MAGIC: &[u8; 8] = b"AIENALB1"; +const VERSION: u32 = 1; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Pin { + pub agent: [u8; 32], + pub root: [u8; 32], + pub head_id: [u8; 32], + pub head_seq: u64, + pub lineage: [u8; 32], + pub machine_id: [u8; 32], + pub provenance: [u8; 32], +} + +/// `.allen-binding`, beside `.machine-root` and `.cortex-mark`. +pub fn pin_path(home: &Path) -> PathBuf { + let mut n = home.as_os_str().to_owned(); + n.push(".allen-binding"); + PathBuf::from(n) +} + +impl Pin { + pub fn encode(&self) -> [u8; PIN_LEN] { + let mut b = [0u8; PIN_LEN]; + b[..8].copy_from_slice(MAGIC); + b[8..12].copy_from_slice(&VERSION.to_le_bytes()); + b[16..48].copy_from_slice(&self.agent); + b[48..80].copy_from_slice(&self.root); + b[80..112].copy_from_slice(&self.head_id); + b[112..120].copy_from_slice(&self.head_seq.to_le_bytes()); + b[120..152].copy_from_slice(&self.lineage); + b[152..184].copy_from_slice(&self.machine_id); + b[184..216].copy_from_slice(&self.provenance); + let h = Sha256::digest(&b[..216]); + b[216..].copy_from_slice(&h); + b + } + + pub fn decode(b: &[u8]) -> Result { + if b.len() != PIN_LEN { + return Err(format!("{} bytes, expected {PIN_LEN}", b.len())); + } + if &b[..8] != MAGIC { + return Err("bad magic".into()); + } + let v = u32::from_le_bytes(b[8..12].try_into().expect("4")); + if v != VERSION || b[12..16] != [0u8; 4] { + return Err(format!("unknown version {v}")); + } + if Sha256::digest(&b[..216]).as_slice() != &b[216..] { + return Err("checksum mismatch".into()); + } + let f = |a: usize| -> [u8; 32] { b[a..a + 32].try_into().expect("32") }; + Ok(Pin { + agent: f(16), + root: f(48), + head_id: f(80), + head_seq: u64::from_le_bytes(b[112..120].try_into().expect("8")), + lineage: f(120), + machine_id: f(152), + provenance: f(184), + }) + } +} + +/// `Ok(None)` when no pin file exists; `Err` when it exists and is damaged. +pub fn read(path: &Path) -> Result, String> { + match std::fs::read(path) { + Ok(b) => Pin::decode(&b).map(Some), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(format!("read {}: {e}", path.display())), + } +} + +/// Atomic write: temp file, fsync, rename, fsync of the directory. +pub fn write_atomic(path: &Path, pin: &Pin) -> Result<(), String> { + let mut tmp = path.as_os_str().to_owned(); + tmp.push(".tmp"); + let tmp = PathBuf::from(tmp); + let werr = |what: &str, e: std::io::Error| format!("{what} {}: {e}", path.display()); + if let Some(p) = path.parent() { + std::fs::create_dir_all(p).map_err(|e| werr("create dir for", e))?; + } + let mut f = std::fs::File::create(&tmp).map_err(|e| werr("create temp for", e))?; + f.write_all(&pin.encode()).map_err(|e| werr("write", e))?; + f.sync_all().map_err(|e| werr("sync", e))?; + drop(f); + std::fs::rename(&tmp, path).map_err(|e| werr("rename onto", e))?; + if let Some(p) = path.parent() { + std::fs::File::open(p) + .and_then(|d| d.sync_all()) + .map_err(|e| werr("sync dir of", e))?; + } + Ok(()) +} diff --git a/crates/aien-allen/src/deployment.rs b/crates/aien-allen/src/deployment.rs new file mode 100644 index 00000000..3cebb69e --- /dev/null +++ b/crates/aien-allen/src/deployment.rs @@ -0,0 +1,185 @@ +//! Host-produced deployment record `.allen-deployments`: which model +//! artifacts served which logical agent, in order. Append-only JSON lines, +//! each line hash-chained to the previous one. Digests come from hashing +//! files on the host; model-supplied identity never enters (arch#150 s4.4). +//! The subject object is never written here or by a model swap: a swap or a +//! rollback appends a line and nothing else. +//! +//! `placeholder: true` marks synthetic digests used by tests. Such a line +//! does NOT establish real model-swap continuity. +use crate::{hex, unhex32}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; + +pub const GENESIS_PREV: &str = "0000000000000000000000000000000000000000000000000000000000000000"; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Entry { + pub seq: u64, + pub prev: String, + /// Logical agent id (hex) this deployment serves. + pub agent: String, + pub model_sha256: String, + pub config_sha256: String, + pub candidate_id: String, + pub executable_sha256: String, + pub revision: String, + pub placeholder: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +struct Line { + entry: Entry, + sha256: String, +} + +#[derive(Debug, Clone)] +pub struct Input { + pub model_sha256: String, + pub config_sha256: String, + pub candidate_id: String, + pub executable_sha256: String, + pub revision: String, + pub placeholder: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DeployRefusal { + Damaged(String), + ChainBroken(u64), + ForgedIdentity(u64), + ArtifactChanged { + seq: u64, + recorded: String, + actual: String, + }, + Io(String), +} + +impl std::fmt::Display for DeployRefusal { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Damaged(w) => write!(f, "deployment record damaged: {w}"), + Self::ChainBroken(s) => write!(f, "deployment chain broken at line {s}"), + Self::ForgedIdentity(s) => { + write!(f, "deployment line {s} names another logical agent") + } + Self::ArtifactChanged { + seq, + recorded, + actual, + } => write!( + f, + "artifact bytes changed since deployment {seq}: recorded {recorded}, now {actual}" + ), + Self::Io(w) => write!(f, "deployment record io: {w}"), + } + } +} + +pub fn deployments_path(home: &Path) -> PathBuf { + let mut n = home.as_os_str().to_owned(); + n.push(".allen-deployments"); + PathBuf::from(n) +} + +fn entry_hash(e: &Entry) -> String { + hex(&Sha256::digest( + serde_json::to_string(e) + .expect("entry serializes") + .as_bytes(), + )) +} + +/// sha256 of a file, hex: the host-side way to name a model artifact. +pub fn sha256_file_hex(path: &Path) -> std::io::Result { + let mut f = std::fs::File::open(path)?; + let mut h = Sha256::new(); + let mut buf = vec![0u8; 1 << 20]; + loop { + let n = f.read(&mut buf)?; + if n == 0 { + break; + } + h.update(&buf[..n]); + } + Ok(hex(&h.finalize())) +} + +/// Read and verify the whole record for `agent` (hex). Empty/missing = no history. +pub fn verify(path: &Path, agent: &[u8; 32]) -> Result, DeployRefusal> { + let text = match std::fs::read_to_string(path) { + Ok(t) => t, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(e) => return Err(DeployRefusal::Damaged(e.to_string())), + }; + let agent_hex = hex(agent); + let mut out: Vec = Vec::new(); + for (i, raw) in text.lines().enumerate() { + let n = i as u64 + 1; + let line: Line = serde_json::from_str(raw) + .map_err(|e| DeployRefusal::Damaged(format!("line {n}: {e}")))?; + let e = line.entry; + if entry_hash(&e) != line.sha256 || e.seq != n { + return Err(DeployRefusal::ChainBroken(n)); + } + let want_prev = out.last().map_or(GENESIS_PREV.to_string(), entry_hash); + if e.prev != want_prev { + return Err(DeployRefusal::ChainBroken(n)); + } + if unhex32(&e.agent).is_none() || e.agent != agent_hex { + return Err(DeployRefusal::ForgedIdentity(n)); + } + out.push(e); + } + if !text.is_empty() && !text.ends_with('\n') { + return Err(DeployRefusal::Damaged("truncated final line".into())); + } + Ok(out) +} + +/// Append one deployment line (verifies the existing record first). +pub fn append(path: &Path, agent: &[u8; 32], input: Input) -> Result { + let have = verify(path, agent)?; + let e = Entry { + seq: have.len() as u64 + 1, + prev: have.last().map_or(GENESIS_PREV.to_string(), entry_hash), + agent: hex(agent), + model_sha256: input.model_sha256, + config_sha256: input.config_sha256, + candidate_id: input.candidate_id, + executable_sha256: input.executable_sha256, + revision: input.revision, + placeholder: input.placeholder, + }; + let line = Line { + sha256: entry_hash(&e), + entry: e.clone(), + }; + let io = |e: std::io::Error| DeployRefusal::Io(e.to_string()); + let mut f = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(path) + .map_err(io)?; + let mut s = serde_json::to_string(&line).expect("line serializes"); + s.push('\n'); + f.write_all(s.as_bytes()).map_err(io)?; + f.sync_all().map_err(io)?; + Ok(e) +} + +/// Does the model file on disk still match deployment `e`? +pub fn check_artifact(e: &Entry, file: &Path) -> Result<(), DeployRefusal> { + let actual = sha256_file_hex(file).map_err(|x| DeployRefusal::Io(x.to_string()))?; + if actual != e.model_sha256 { + return Err(DeployRefusal::ArtifactChanged { + seq: e.seq, + recorded: e.model_sha256.clone(), + actual, + }); + } + Ok(()) +} diff --git a/crates/aien-allen/src/lib.rs b/crates/aien-allen/src/lib.rs new file mode 100644 index 00000000..45b0752a --- /dev/null +++ b/crates/aien-allen/src/lib.rs @@ -0,0 +1,42 @@ +//! ALLEN identity gate (aien-architecture ADR 0035, aienos ADR 0018). +//! +//! RESOLVE ONLY. This crate reads a kind-24 SubjectState object that AIENOS +//! provisioned and exported; it never creates, encodes or edits one (I8: ALLEN +//! is never created implicitly). The logical agent identity, the machine id +//! (host pin record) and the model binding (deployment record) are three +//! separate records; KV state is in none of them. +//! +//! Opt-in: engaged only when `AIEN_ALLEN_SUBJECT` is set. When engaged every +//! refusal is fatal (see [`EXIT_REFUSED`]); there is never a silent fallback. +pub mod binding; +pub mod deployment; +pub mod resolve; +pub mod subject_v0; + +pub use resolve::{gate, Context, Engagement, Gate, Refusal, Resolved, SubjectSource}; + +/// Environment variable naming the exported subject (a head object file, or a +/// directory of raw objects named `.bin`). +pub const ENV_SUBJECT: &str = "AIEN_ALLEN_SUBJECT"; +/// One-time operator adoption: the expected logical agent id (64 hex). +pub const ENV_ADOPT: &str = "AIEN_ALLEN_ADOPT"; +/// Process exit code when an engaged ALLEN gate refuses (EX_CONFIG). +pub const EXIT_REFUSED: i32 = 78; +/// The one log line when the gate is not engaged. +pub const NOT_ENGAGED_LINE: &str = + "ALLEN: not engaged (AIEN_ALLEN_SUBJECT unset); no identity claim"; + +pub fn hex(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02x}")).collect() +} + +pub fn unhex32(s: &str) -> Option<[u8; 32]> { + if s.len() != 64 || !s.is_ascii() { + return None; + } + let mut out = [0u8; 32]; + for (i, o) in out.iter_mut().enumerate() { + *o = u8::from_str_radix(&s[2 * i..2 * i + 2], 16).ok()?; + } + Some(out) +} diff --git a/crates/aien-allen/src/resolve.rs b/crates/aien-allen/src/resolve.rs new file mode 100644 index 00000000..bb928613 --- /dev/null +++ b/crates/aien-allen/src/resolve.rs @@ -0,0 +1,345 @@ +//! Resolve-only gate. Never provisions: no function in this crate creates a +//! subject object (a test scans the source for that). Missing or damaged +//! state is a [`Refusal`]. +use crate::binding::{self, Pin}; +use crate::subject_v0::{self, Subject}; +use crate::{hex, unhex32, ENV_ADOPT, ENV_SUBJECT}; +use std::path::{Path, PathBuf}; + +#[derive(Debug, Clone)] +pub enum SubjectSource { + /// One exported head object file. Chain claims are NOT made. + Head(PathBuf), + /// A directory of raw objects `.bin`: the chain is checked. + Dir(PathBuf), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Refusal { + /// No subject at the named path: never created. + Absent(String), + Corrupt(String), + /// An object names another agent or root than the rest of the chain / the pin. + ForeignIdentity(String), + Forked(u64), + Gap(u64), + NoActiveIntent, + LineageUnbound, + /// The Cortex journal has no record 1. + LineageMissing, + LineageMismatch, + /// Subject valid, no pin, and no explicit operator adoption. + PinAbsent, + PinDamaged(String), + AdoptMismatch, + AdoptRefusedPinExists, + AdoptBadValue, + MachineChanged, + RolledBack { + pinned: u64, + found: u64, + }, + SameSequenceDifferentId, + ForkedFromPin, + Io(String), +} + +impl std::fmt::Display for Refusal { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + use Refusal::*; + match self { + Absent(w) => write!(f, "Absent: no subject ({w}); ALLEN is never created implicitly"), + Corrupt(w) => write!(f, "Corrupt: {w}"), + ForeignIdentity(w) => write!(f, "ForeignIdentity: {w}"), + Forked(s) => write!(f, "Forked: two subject objects at sequence {s}"), + Gap(s) => write!(f, "Gap: no subject object at sequence {s}"), + NoActiveIntent => write!(f, "NoActiveIntent: no ACTIVE GOAL_LATENCY intent"), + LineageUnbound => write!(f, "LineageUnbound: subject names no Cortex lineage"), + LineageMissing => write!(f, "LineageMissing: the Cortex journal has no record 1"), + LineageMismatch => write!( + f, + "LineageMismatch: this Cortex journal is not the subject's memory" + ), + PinAbsent => write!( + f, + "PinAbsent: a valid subject but no pin; set {ENV_ADOPT}= to adopt once" + ), + PinDamaged(w) => write!(f, "PinDamaged: {w}"), + AdoptMismatch => write!( + f, + "AdoptMismatch: {ENV_ADOPT} is not this subject's agent id" + ), + AdoptRefusedPinExists => write!( + f, + "AdoptRefusedPinExists: a pin exists; {ENV_ADOPT} is refused" + ), + AdoptBadValue => write!(f, "AdoptBadValue: {ENV_ADOPT} must be 64 hex characters"), + MachineChanged => write!( + f, + "MachineChanged: the machine id differs from the pin; never rebound (ruling pending)" + ), + RolledBack { pinned, found } => write!( + f, + "RolledBack: head sequence {found} is below the pinned {pinned}" + ), + SameSequenceDifferentId => write!( + f, + "SameSequenceDifferentId: same sequence as the pin, different object" + ), + ForkedFromPin => write!( + f, + "ForkedFromPin: the chain does not contain the pinned head" + ), + Io(w) => write!(f, "Io: {w}"), + } + } +} + +#[derive(Debug, Clone)] +pub struct Resolved { + pub agent: [u8; 32], + pub root: [u8; 32], + pub head_id: [u8; 32], + pub head_seq: u64, + pub lineage: [u8; 32], + /// True only in directory mode (gap-free, fork-free, link-correct to sequence 1). + pub chain_verified: bool, + /// True when this call wrote the pin for the first time (adoption). + pub adopted: bool, +} + +/// What the host knows about itself and the journal at open time. +#[derive(Debug, Clone, Copy)] +pub struct Context { + pub machine_id: [u8; 32], + /// Digest of the Cortex journal's record 1 (`None` = journal has none). + pub lineage: Option<[u8; 32]>, +} + +#[derive(Debug, Clone)] +pub struct Engagement { + pub source: SubjectSource, + pub adopt: Option, +} + +pub enum Gate { + NotEngaged, + Engaged(Resolved), + Refused(Refusal), +} + +impl Engagement { + /// `None` = not engaged (variable unset or empty). + pub fn from_env(get: &dyn Fn(&str) -> Option) -> Option { + let p = get(ENV_SUBJECT).filter(|s| !s.trim().is_empty())?; + let p = PathBuf::from(p.trim()); + let source = if p.is_dir() { + SubjectSource::Dir(p) + } else { + SubjectSource::Head(p) + }; + Some(Engagement { + source, + adopt: get(ENV_ADOPT).filter(|s| !s.trim().is_empty()), + }) + } +} + +/// The one entry point the daemon calls when a compose home is opened. +pub fn gate(home: &Path, ctx: &Context, get: &dyn Fn(&str) -> Option) -> Gate { + let Some(e) = Engagement::from_env(get) else { + return Gate::NotEngaged; + }; + match resolve(&e.source, &binding::pin_path(home), ctx, e.adopt.as_deref()) { + Ok(r) => Gate::Engaged(r), + Err(r) => Gate::Refused(r), + } +} + +fn read_object(path: &Path) -> Result, Refusal> { + match std::fs::read(path) { + Ok(b) if b.is_empty() => Err(Refusal::Absent(format!("{} is empty", path.display()))), + Ok(b) => Ok(b), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + Err(Refusal::Absent(format!("{} not found", path.display()))) + } + Err(e) => Err(Refusal::Io(format!("{}: {e}", path.display()))), + } +} + +struct Loaded { + head: Subject, + head_id: [u8; 32], + /// (sequence, object id) of every verified chain object; empty in head mode. + chain: Vec<(u64, [u8; 32])>, + chain_verified: bool, +} + +fn load(src: &SubjectSource) -> Result { + match src { + SubjectSource::Head(p) => { + let b = read_object(p)?; + let head = subject_v0::decode(&b).map_err(Refusal::Corrupt)?; + Ok(Loaded { + head, + head_id: subject_v0::object_id(&b), + chain: Vec::new(), + chain_verified: false, + }) + } + SubjectSource::Dir(d) => load_dir(d), + } +} + +fn load_dir(d: &Path) -> Result { + let rd = std::fs::read_dir(d).map_err(|e| Refusal::Absent(format!("{}: {e}", d.display())))?; + let mut objs: Vec<([u8; 32], Subject)> = Vec::new(); + let mut names: Vec<_> = rd.filter_map(|x| x.ok()).map(|x| x.path()).collect(); + names.sort(); + for p in names { + if p.extension().and_then(|x| x.to_str()) != Some("bin") { + continue; + } + let b = read_object(&p)?; + let id = subject_v0::object_id(&b); + let stem = p.file_stem().and_then(|s| s.to_str()).unwrap_or(""); + if stem != hex(&id) { + return Err(Refusal::Corrupt(format!( + "{} does not hash to its name (changed bytes)", + p.display() + ))); + } + let s = subject_v0::decode(&b) + .map_err(|w| Refusal::Corrupt(format!("{}: {w}", p.display())))?; + objs.push((id, s)); + } + if objs.is_empty() { + return Err(Refusal::Absent(format!("{} holds no objects", d.display()))); + } + let max = objs.iter().map(|o| o.1.sequence).max().expect("non-empty"); + let (g_agent, g_root) = match objs.iter().find(|o| o.1.sequence == 1) { + Some(g) => (g.1.agent, g.1.root), + None => return Err(Refusal::Gap(1)), + }; + let mut chain = Vec::new(); + let mut prev: Option<[u8; 32]> = None; + let mut head = None; + for s in 1..=max { + let at: Vec<_> = objs.iter().filter(|o| o.1.sequence == s).collect(); + match at.len() { + 0 => return Err(Refusal::Gap(s)), + 1 => {} + _ => return Err(Refusal::Forked(s)), + } + let (id, o) = (&at[0].0, &at[0].1); + if o.agent != g_agent || o.root != g_root { + return Err(Refusal::ForeignIdentity(format!( + "object at sequence {s} names another agent or root" + ))); + } + if let Some(p) = prev { + if o.previous != p { + return Err(Refusal::Corrupt(format!("link broken at sequence {s}"))); + } + } + prev = Some(*id); + chain.push((s, *id)); + head = Some((*id, o.clone())); + } + let (head_id, head) = head.expect("max >= 1"); + Ok(Loaded { + head, + head_id, + chain, + chain_verified: true, + }) +} + +pub fn resolve( + src: &SubjectSource, + pin_path: &Path, + ctx: &Context, + adopt: Option<&str>, +) -> Result { + let l = load(src)?; + let h = &l.head; + if !h + .intents + .iter() + .any(|i| i.state == subject_v0::ACTIVE && i.kind == subject_v0::INTENT_GOAL_LATENCY) + { + return Err(Refusal::NoActiveIntent); + } + if h.cortex.iter().all(|&b| b == 0) { + return Err(Refusal::LineageUnbound); + } + match ctx.lineage { + None => return Err(Refusal::LineageMissing), + Some(j) if j != h.cortex => return Err(Refusal::LineageMismatch), + Some(_) => {} + } + let pin = binding::read(pin_path).map_err(Refusal::PinDamaged)?; + let mut adopted = false; + match (&pin, adopt) { + (None, None) => return Err(Refusal::PinAbsent), + (None, Some(a)) => { + let want = unhex32(a.trim()).ok_or(Refusal::AdoptBadValue)?; + if want != h.agent { + return Err(Refusal::AdoptMismatch); + } + adopted = true; + } + (Some(_), Some(_)) => return Err(Refusal::AdoptRefusedPinExists), + (Some(p), None) => { + if p.agent != h.agent || p.root != h.root { + return Err(Refusal::ForeignIdentity( + "subject agent or root differs from the pin".into(), + )); + } + if p.machine_id != ctx.machine_id { + return Err(Refusal::MachineChanged); + } + if p.lineage != h.cortex { + return Err(Refusal::LineageMismatch); + } + if h.sequence < p.head_seq { + return Err(Refusal::RolledBack { + pinned: p.head_seq, + found: h.sequence, + }); + } + if h.sequence == p.head_seq && l.head_id != p.head_id { + return Err(Refusal::SameSequenceDifferentId); + } + if l.chain_verified + && !l + .chain + .iter() + .any(|(s, id)| *s == p.head_seq && *id == p.head_id) + { + return Err(Refusal::ForkedFromPin); + } + } + } + if adopted || pin.as_ref().is_some_and(|p| p.head_seq < h.sequence) { + let np = Pin { + agent: h.agent, + root: h.root, + head_id: l.head_id, + head_seq: h.sequence, + lineage: h.cortex, + machine_id: ctx.machine_id, + provenance: h.provenance, + }; + binding::write_atomic(pin_path, &np).map_err(Refusal::Io)?; + } + Ok(Resolved { + agent: h.agent, + root: h.root, + head_id: l.head_id, + head_seq: h.sequence, + lineage: h.cortex, + chain_verified: l.chain_verified, + adopted, + }) +} diff --git a/crates/aien-allen/src/subject_v0.rs b/crates/aien-allen/src/subject_v0.rs new file mode 100644 index 00000000..d2a0560e --- /dev/null +++ b/crates/aien-allen/src/subject_v0.rs @@ -0,0 +1,257 @@ +//! The ONLY file that knows the kind-24 SubjectState byte layout. +//! +//! Format: aienos ADR 0018 s2.2 (PROPOSED, not frozen). Reference decoder: +//! aienos `native/kernel/svc/continuity_subject.c` (`cs_subject_decode`, +//! `cs_subject_validate`, `cs_intent_id`); object id: `continuity_codec.c` +//! `cc_object_id`. If the format changes, change this file only. +//! Decode and id only: there is deliberately no encoder here. +use sha2::{Digest, Sha256}; + +const MAGIC: &[u8; 8] = b"AIENSUBJ"; +pub const HEADER: usize = 16; +pub const MAX_OBJECT_BYTES: usize = 16384; +pub const KIND: u16 = 24; +const MAX_INTENTS: usize = 64; +const MAX_KNOWLEDGE: usize = 64; +pub const INTENT_GOAL_LATENCY: u32 = 1; +pub const ACTIVE: u8 = 1; +const INACTIVE: u8 = 2; +const SUPERSEDED: u8 = 3; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Intent { + pub id: [u8; 32], + pub supersedes: [u8; 32], + pub kind: u32, + pub state: u8, + pub since: u64, + pub payload: [u64; 2], +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Subject { + pub root: [u8; 32], + pub agent: [u8; 32], + pub previous: [u8; 32], + pub sequence: u64, + pub cortex: [u8; 32], + pub provenance: [u8; 32], + pub origin: u8, + pub intents: Vec, + pub knowledge: Vec<([u8; 32], u64, u64)>, +} + +struct Rd<'a> { + b: &'a [u8], + at: usize, +} + +impl<'a> Rd<'a> { + fn take(&mut self, n: usize) -> Result<&'a [u8], String> { + if n > self.b.len() - self.at { + return Err("truncated object".into()); + } + let s = &self.b[self.at..self.at + n]; + self.at += n; + Ok(s) + } + fn id(&mut self) -> Result<[u8; 32], String> { + Ok(self.take(32)?.try_into().expect("32")) + } + fn u64(&mut self) -> Result { + Ok(u64::from_le_bytes(self.take(8)?.try_into().expect("8"))) + } + fn u32(&mut self) -> Result { + Ok(u32::from_le_bytes(self.take(4)?.try_into().expect("4"))) + } + fn u16(&mut self) -> Result { + Ok(u16::from_le_bytes(self.take(2)?.try_into().expect("2"))) + } + fn zeros(&mut self, n: usize, what: &str) -> Result<(), String> { + if self.take(n)?.iter().any(|&x| x != 0) { + return Err(format!("nonzero {what}")); + } + Ok(()) + } +} + +fn zero(x: &[u8; 32]) -> bool { + x.iter().all(|&b| b == 0) +} + +/// `cs_intent_id`: SHA-256("AIENOS_INTENT_v0:" || agent || kind || since || p0 || p1). +fn intent_id(agent: &[u8; 32], kind: u32, since: u64, p: [u64; 2]) -> [u8; 32] { + let mut h = Sha256::new(); + h.update(b"AIENOS_INTENT_v0:"); + h.update(agent); + h.update(kind.to_le_bytes()); + h.update(since.to_le_bytes()); + h.update(p[0].to_le_bytes()); + h.update(p[1].to_le_bytes()); + h.finalize().into() +} + +/// `cc_object_id(24, bytes, len)`: SHA-256("AIENOS-STORE-OBJECT-V1\0" || +/// kind u16 || store object version u16 (1) || len u64 || bytes). +pub fn object_id(bytes: &[u8]) -> [u8; 32] { + let mut h = Sha256::new(); + h.update(b"AIENOS-STORE-OBJECT-V1\0"); + h.update(KIND.to_le_bytes()); + h.update(1u16.to_le_bytes()); + h.update((bytes.len() as u64).to_le_bytes()); + h.update(bytes); + h.finalize().into() +} + +/// Strict decode with every rule of `cs_subject_decode` + `cs_subject_validate`. +pub fn decode(bytes: &[u8]) -> Result { + if bytes.len() > MAX_OBJECT_BYTES { + return Err("object exceeds the 16384-byte cap".into()); + } + let mut r = Rd { b: bytes, at: 0 }; + if r.take(8)? != MAGIC { + return Err("bad magic".into()); + } + if r.u16()? != 0 { + return Err("unsupported continuity format version".into()); + } + r.zeros(2, "header reserved")?; + if r.u32()? as usize != bytes.len() - HEADER { + return Err("body length mismatch".into()); + } + let root = r.id()?; + let agent = r.id()?; + let previous = r.id()?; + let sequence = r.u64()?; + let cortex = r.id()?; + let provenance = r.id()?; + let origin = r.take(1)?[0]; + r.zeros(7, "reserved")?; + let n_in = r.u16()? as usize; + if n_in > MAX_INTENTS { + return Err("too many standing intents".into()); + } + let n_kn = r.u16()? as usize; + if n_kn > MAX_KNOWLEDGE { + return Err("too many knowledge references".into()); + } + r.zeros(4, "reserved")?; + let mut intents = Vec::with_capacity(n_in); + for _ in 0..n_in { + let id = r.id()?; + let supersedes = r.id()?; + let kind = r.u32()?; + let state = r.take(1)?[0]; + r.zeros(3, "intent reserved")?; + let since = r.u64()?; + let payload = [r.u64()?, r.u64()?]; + intents.push(Intent { + id, + supersedes, + kind, + state, + since, + payload, + }); + } + let mut knowledge = Vec::with_capacity(n_kn); + for _ in 0..n_kn { + let d = r.id()?; + knowledge.push((d, r.u64()?, r.u64()?)); + } + if r.at != bytes.len() { + return Err("trailing bytes".into()); + } + let s = Subject { + root, + agent, + previous, + sequence, + cortex, + provenance, + origin, + intents, + knowledge, + }; + validate(&s)?; + Ok(s) +} + +fn validate(s: &Subject) -> Result<(), String> { + if zero(&s.root) { + return Err("zero root id".into()); + } + if zero(&s.agent) { + return Err("zero agent id".into()); + } + if s.sequence == 0 { + return Err("zero sequence".into()); + } + if s.sequence == 1 && !zero(&s.previous) { + return Err("genesis subject names a previous object".into()); + } + if s.sequence > 1 && zero(&s.previous) { + return Err("subject object after the first has no previous".into()); + } + if zero(&s.provenance) { + return Err("zero provenance".into()); + } + if s.origin != 1 && s.origin != 2 { + return Err("unknown subject origin".into()); + } + for (i, a) in s.intents.iter().enumerate() { + if i > 0 && s.intents[i - 1].id >= a.id { + return Err("intents not strictly ascending by id".into()); + } + if ![ACTIVE, INACTIVE, SUPERSEDED].contains(&a.state) { + return Err("unknown intent state".into()); + } + if a.kind != INTENT_GOAL_LATENCY { + return Err("unknown intent kind".into()); + } + if a.since == 0 || a.since > s.sequence { + return Err("intent created outside the subject chain".into()); + } + if intent_id(&s.agent, a.kind, a.since, a.payload) != a.id { + return Err("intent id does not derive from its content".into()); + } + if !zero(&a.supersedes) { + if a.supersedes == a.id { + return Err("intent supersedes itself".into()); + } + let Some(j) = s.intents.iter().find(|x| x.id == a.supersedes) else { + return Err("superseded intent is absent".into()); + }; + if j.state != SUPERSEDED { + return Err("superseded intent is not marked superseded".into()); + } + if j.since > a.since { + return Err("intent supersedes a newer intent".into()); + } + } + if a.state == ACTIVE + && s.intents[..i] + .iter() + .any(|j| j.state == ACTIVE && j.kind == a.kind && j.payload[0] == a.payload[0]) + { + return Err("two active intents in one slot".into()); + } + } + for a in s.intents.iter().filter(|a| a.state == SUPERSEDED) { + if s.intents.iter().filter(|j| j.supersedes == a.id).count() != 1 { + return Err("superseded intent not named by exactly one successor".into()); + } + } + for (i, k) in s.knowledge.iter().enumerate() { + if zero(&k.0) { + return Err("zero knowledge digest".into()); + } + if i > 0 && s.knowledge[i - 1].0 >= k.0 { + return Err("knowledge not strictly ascending by digest".into()); + } + if k.2 == 0 || k.2 > s.sequence { + return Err("knowledge held outside the subject chain".into()); + } + } + Ok(()) +} diff --git a/crates/aien-allen/tests/deployment_test.rs b/crates/aien-allen/tests/deployment_test.rs new file mode 100644 index 00000000..a63721e9 --- /dev/null +++ b/crates/aien-allen/tests/deployment_test.rs @@ -0,0 +1,225 @@ +//! Model swap / rollback / KV discard / deployment record tamper rows. +//! +//! PLACEHOLDER rows use synthetic digests and do NOT establish real +//! model-swap continuity. REAL_DIGESTS rows hash two real, checked-in weight +//! files (crates/aien-inference-abi/fixtures) with the host hasher; no model +//! is run, so they prove the record binds real artifact bytes, not behaviour. +mod support; +use aien_allen::binding::{pin_path, Pin}; +use aien_allen::deployment::{ + append, check_artifact, deployments_path, sha256_file_hex, verify, DeployRefusal, Input, +}; +use aien_allen::hex; +use aien_allen::resolve::{resolve, Context, SubjectSource}; +use std::path::PathBuf; +use support::*; + +const M1: [u8; 32] = [1; 32]; + +fn input(model: &str, placeholder: bool) -> Input { + Input { + model_sha256: model.to_string(), + config_sha256: hex(&h32("config")), + candidate_id: "cand-test".into(), + executable_sha256: hex(&h32("exe")), + revision: "rev-test".into(), + placeholder, + } +} + +struct Rig { + _t: tempfile::TempDir, + home: PathBuf, + subj: PathBuf, + kv: PathBuf, + f: Fx, +} + +fn rig() -> Rig { + let t = tempfile::tempdir().unwrap(); + let f = fx("a"); + let c = chain(&f, 2); + let subj = write_head(&t.path().join("subject.bin"), c.last().unwrap()); + let kv = t.path().join("kv-standin"); + std::fs::create_dir_all(&kv).unwrap(); + std::fs::write(kv.join("block0"), b"reconstructible kv bytes").unwrap(); + let r = Rig { + home: t.path().join("compose"), + subj, + kv, + f, + _t: t, + }; + resolve( + &SubjectSource::Head(r.subj.clone()), + &pin_path(&r.home), + &Context { + machine_id: M1, + lineage: Some(r.f.cortex), + }, + Some(&hex(&r.f.agent)), + ) + .unwrap(); + r +} + +fn state(r: &Rig) -> (Vec, Vec) { + ( + std::fs::read(&r.subj).unwrap(), + std::fs::read(pin_path(&r.home)).unwrap(), + ) +} + +#[test] +fn placeholder_model_swap_and_rollback_leave_identity_untouched() { + let r = rig(); + let before = state(&r); + let dep = deployments_path(&r.home); + let (a, b) = (hex(&h32("PLACEHOLDER-A")), hex(&h32("PLACEHOLDER-B"))); + append(&dep, &r.f.agent, input(&a, true)).unwrap(); + append(&dep, &r.f.agent, input(&b, true)).unwrap(); + append(&dep, &r.f.agent, input(&a, true)).unwrap(); // rollback to A + // Subject object and pin: byte-identical (empty diff). + assert_eq!(before, state(&r)); + let h = verify(&dep, &r.f.agent).unwrap(); + assert_eq!(h.len(), 3, "history retained, never rewound"); + assert_eq!(h[0].model_sha256, h[2].model_sha256); + assert_ne!(h[0].model_sha256, h[1].model_sha256); + assert!(h.iter().all(|e| e.placeholder)); + // The pin has no model field: it is the same bytes, so it cannot name one. + let p = std::fs::read(pin_path(&r.home)).unwrap(); + assert!(!p.windows(32).any(|w| w == h32("PLACEHOLDER-A"))); + // Identity still resolves to the same logical agent. + let res = resolve( + &SubjectSource::Head(r.subj.clone()), + &pin_path(&r.home), + &Context { + machine_id: M1, + lineage: Some(r.f.cortex), + }, + None, + ) + .unwrap(); + assert_eq!(res.agent, r.f.agent); +} + +#[test] +fn real_digests_of_two_checked_in_weight_files() { + let r = rig(); + let fx_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../aien-inference-abi/fixtures"); + let wa = fx_dir.join("openwaldo-byte/model.safetensors"); + let wb = fx_dir.join("llama32_1b_oracle.safetensors"); + let (da, db) = (sha256_file_hex(&wa).unwrap(), sha256_file_hex(&wb).unwrap()); + assert_ne!(da, db); + let before = state(&r); + let dep = deployments_path(&r.home); + append(&dep, &r.f.agent, input(&da, false)).unwrap(); + append(&dep, &r.f.agent, input(&db, false)).unwrap(); + let h = verify(&dep, &r.f.agent).unwrap(); + check_artifact(&h[0], &wa).unwrap(); + check_artifact(&h[1], &wb).unwrap(); + // Cross-check: model A's record does not match model B's bytes. + assert!(matches!( + check_artifact(&h[0], &wb), + Err(DeployRefusal::ArtifactChanged { .. }) + )); + assert_eq!( + before, + state(&r), + "subject and pin unchanged across the swap" + ); +} + +#[test] +fn changed_artifact_bytes_are_refused() { + let r = rig(); + let art = r._t.path().join("model.bin"); + std::fs::write(&art, b"weights v1").unwrap(); + let dep = deployments_path(&r.home); + append( + &dep, + &r.f.agent, + input(&sha256_file_hex(&art).unwrap(), true), + ) + .unwrap(); + let h = verify(&dep, &r.f.agent).unwrap(); + check_artifact(&h[0], &art).unwrap(); + std::fs::write(&art, b"weights v2").unwrap(); + assert!(matches!( + check_artifact(&h[0], &art), + Err(DeployRefusal::ArtifactChanged { seq: 1, .. }) + )); +} + +#[test] +fn kv_discard_does_not_change_identity() { + let r = rig(); + let before = state(&r); + std::fs::remove_dir_all(&r.kv).unwrap(); + assert_eq!(before, state(&r)); + let res = resolve( + &SubjectSource::Head(r.subj.clone()), + &pin_path(&r.home), + &Context { + machine_id: M1, + lineage: Some(r.f.cortex), + }, + None, + ) + .unwrap(); + assert_eq!(res.agent, r.f.agent); + // The pin type has no field in which KV could be named. + let p = Pin::decode(&before.1).unwrap(); + assert_eq!(p.agent, r.f.agent); +} + +#[test] +fn tampered_deployment_records_are_refused() { + let r = rig(); + let dep = deployments_path(&r.home); + for n in 0..3 { + append(&dep, &r.f.agent, input(&hex(&h32(&format!("m{n}"))), true)).unwrap(); + } + let good = std::fs::read_to_string(&dep).unwrap(); + let lines: Vec<&str> = good.lines().collect(); + // Edited content (hash no longer matches). + std::fs::write(&dep, good.replace("rev-test", "rev-evil")).unwrap(); + assert!(matches!( + verify(&dep, &r.f.agent), + Err(DeployRefusal::ChainBroken(1)) + )); + // Deleted middle line. + std::fs::write(&dep, format!("{}\n{}\n", lines[0], lines[2])).unwrap(); + assert!(matches!( + verify(&dep, &r.f.agent), + Err(DeployRefusal::ChainBroken(2)) + )); + // Reordered lines. + std::fs::write(&dep, format!("{}\n{}\n{}\n", lines[1], lines[0], lines[2])).unwrap(); + assert!(verify(&dep, &r.f.agent).is_err()); + // Truncated final line. + std::fs::write(&dep, &good[..good.len() - 5]).unwrap(); + assert!(verify(&dep, &r.f.agent).is_err()); + // Appending onto a damaged record is refused, not repaired. + assert!(append(&dep, &r.f.agent, input("x", true)).is_err()); + // Forged identity: a record for another agent is refused for this one. + std::fs::write(&dep, &good).unwrap(); + let other = h32("other agent"); + assert!(matches!( + verify(&dep, &other), + Err(DeployRefusal::ForgedIdentity(1)) + )); + // Restored original verifies again. + assert_eq!(verify(&dep, &r.f.agent).unwrap().len(), 3); +} + +#[test] +fn model_supplied_text_cannot_become_identity() { + // The record's agent field is the host-resolved agent; an attempt to pass + // a model-claimed identity has no API: append takes the agent from the + // resolved subject. A hand-forged line with another agent is refused above. + let r = rig(); + let dep = deployments_path(&r.home); + let e = append(&dep, &r.f.agent, input(&hex(&h32("m")), true)).unwrap(); + assert_eq!(e.agent, hex(&r.f.agent)); +} diff --git a/crates/aien-allen/tests/identity_test.rs b/crates/aien-allen/tests/identity_test.rs new file mode 100644 index 00000000..0dc8a93a --- /dev/null +++ b/crates/aien-allen/tests/identity_test.rs @@ -0,0 +1,366 @@ +//! Restart, corruption, rollback, machine change, negative control. +mod support; +use aien_allen::binding::{self, pin_path}; +use aien_allen::hex; +use aien_allen::resolve::{resolve, Context, Refusal, SubjectSource}; +use aien_allen::subject_v0::object_id; +use support::*; + +const M1: [u8; 32] = [1; 32]; +const M2: [u8; 32] = [2; 32]; + +fn ctx(f: &Fx, m: [u8; 32]) -> Context { + Context { + machine_id: m, + lineage: Some(f.cortex), + } +} + +struct Rig { + _t: tempfile::TempDir, + home: std::path::PathBuf, + subj: std::path::PathBuf, + f: Fx, +} + +fn rig_head(n: u64) -> Rig { + let t = tempfile::tempdir().unwrap(); + let f = fx("a"); + let c = chain(&f, n); + let subj = write_head(&t.path().join("subject.bin"), c.last().unwrap()); + Rig { + home: t.path().join("compose"), + subj, + f, + _t: t, + } +} + +fn adopt(r: &Rig) -> aien_allen::Resolved { + resolve( + &SubjectSource::Head(r.subj.clone()), + &pin_path(&r.home), + &ctx(&r.f, M1), + Some(&hex(&r.f.agent)), + ) + .unwrap() +} + +fn again(r: &Rig, m: [u8; 32]) -> Result { + resolve( + &SubjectSource::Head(r.subj.clone()), + &pin_path(&r.home), + &ctx(&r.f, m), + None, + ) +} + +#[test] +fn restart_preserves_identity() { + let r = rig_head(2); + let first = adopt(&r); + assert!(first.adopted); + let pin_bytes = std::fs::read(pin_path(&r.home)).unwrap(); + // "Restart": nothing in memory, everything from files. + let second = again(&r, M1).unwrap(); + assert!(!second.adopted); + assert_eq!(first.agent, second.agent); + assert_eq!(first.head_id, second.head_id); + assert_eq!(first.root, second.root); + assert_eq!(pin_bytes, std::fs::read(pin_path(&r.home)).unwrap()); +} + +#[test] +fn negative_control_nothing_is_ever_minted() { + let r = rig_head(1); + // No subject file at all, even with a correct adopt value. + let missing = r._t.path().join("nope.bin"); + let e = resolve( + &SubjectSource::Head(missing), + &pin_path(&r.home), + &ctx(&r.f, M1), + Some(&hex(&r.f.agent)), + ) + .unwrap_err(); + assert!(matches!(e, Refusal::Absent(_)), "{e}"); + assert!(!pin_path(&r.home).exists(), "no pin written"); + // An empty subject file. + std::fs::write(&r.subj, b"").unwrap(); + assert!(matches!(again(&r, M1), Err(Refusal::Absent(_)))); + // An empty directory. + let d = r._t.path().join("d"); + std::fs::create_dir(&d).unwrap(); + let e = resolve( + &SubjectSource::Dir(d.clone()), + &pin_path(&r.home), + &ctx(&r.f, M1), + None, + ) + .unwrap_err(); + assert!(matches!(e, Refusal::Absent(_))); + assert_eq!( + std::fs::read_dir(&d).unwrap().count(), + 0, + "directory untouched" + ); + assert!(!pin_path(&r.home).exists()); +} + +#[test] +fn no_pin_means_refusal_not_adoption() { + let r = rig_head(1); + assert_eq!(again(&r, M1).unwrap_err(), Refusal::PinAbsent); + assert!(!pin_path(&r.home).exists()); +} + +#[test] +fn adopt_rules() { + let r = rig_head(1); + let src = SubjectSource::Head(r.subj.clone()); + let p = pin_path(&r.home); + let c = ctx(&r.f, M1); + // wrong agent value + assert_eq!( + resolve(&src, &p, &c, Some(&hex(&h32("other")))).unwrap_err(), + Refusal::AdoptMismatch + ); + assert_eq!( + resolve(&src, &p, &c, Some("zz")).unwrap_err(), + Refusal::AdoptBadValue + ); + assert!(!p.exists()); + adopt(&r); + // adopt variable refused once a pin exists + assert_eq!( + resolve(&src, &p, &c, Some(&hex(&r.f.agent))).unwrap_err(), + Refusal::AdoptRefusedPinExists + ); +} + +#[test] +fn corrupted_pin_is_refused_and_untouched() { + let r = rig_head(1); + adopt(&r); + let p = pin_path(&r.home); + let good = std::fs::read(&p).unwrap(); + for i in [0usize, 9, 20, 100, 115, 160, 230] { + let mut bad = good.clone(); + bad[i] ^= 1; + std::fs::write(&p, &bad).unwrap(); + assert!( + matches!(again(&r, M1), Err(Refusal::PinDamaged(_))), + "byte {i}" + ); + assert_eq!(std::fs::read(&p).unwrap(), bad, "pin not repaired"); + } + // truncated and extended + std::fs::write(&p, &good[..100]).unwrap(); + assert!(matches!(again(&r, M1), Err(Refusal::PinDamaged(_)))); + let mut long = good.clone(); + long.push(0); + std::fs::write(&p, &long).unwrap(); + assert!(matches!(again(&r, M1), Err(Refusal::PinDamaged(_)))); + assert!(binding::read(&p).is_err()); +} + +#[test] +fn corrupted_or_truncated_subject_is_refused() { + let r = rig_head(1); + adopt(&r); + let good = std::fs::read(&r.subj).unwrap(); + for i in [0usize, 9, 20, 60, 130, 200, good.len() - 1] { + let mut bad = good.clone(); + bad[i] ^= 1; + std::fs::write(&r.subj, &bad).unwrap(); + assert!(again(&r, M1).is_err(), "flip at {i} must be refused"); + } + std::fs::write(&r.subj, &good[..good.len() - 8]).unwrap(); + assert!(matches!(again(&r, M1), Err(Refusal::Corrupt(_)))); + let mut long = good.clone(); + long.push(0); + std::fs::write(&r.subj, &long).unwrap(); + assert!(matches!(again(&r, M1), Err(Refusal::Corrupt(_)))); +} + +#[test] +fn rolled_back_head_is_refused_and_same_sequence_other_object_too() { + let r = rig_head(3); + adopt(&r); + let c = chain(&r.f, 3); + std::fs::write(&r.subj, &c[1]).unwrap(); // sequence 2 < pinned 3 + assert_eq!( + again(&r, M1).unwrap_err(), + Refusal::RolledBack { + pinned: 3, + found: 2 + } + ); + // Same sequence, different bytes (different payload). + let other = encode(&r.f, 3, object_id(&c[1]), [7, 2000]); + std::fs::write(&r.subj, &other).unwrap(); + assert_eq!(again(&r, M1).unwrap_err(), Refusal::SameSequenceDifferentId); +} + +#[test] +fn legitimate_successor_advances_the_pin() { + let r = rig_head(2); + adopt(&r); + let c = chain(&r.f, 3); + std::fs::write(&r.subj, &c[2]).unwrap(); + let res = again(&r, M1).unwrap(); + assert_eq!(res.head_seq, 3); + assert_eq!( + binding::read(&pin_path(&r.home)).unwrap().unwrap().head_seq, + 3 + ); +} + +#[test] +fn machine_change_is_refused_never_rebound() { + let r = rig_head(1); + adopt(&r); + let before = std::fs::read(pin_path(&r.home)).unwrap(); + assert_eq!(again(&r, M2).unwrap_err(), Refusal::MachineChanged); + assert_eq!( + before, + std::fs::read(pin_path(&r.home)).unwrap(), + "pin not rebound" + ); + // identity (the subject file) is untouched by the machine id + assert!(again(&r, M1).is_ok()); +} + +#[test] +fn lineage_rules() { + let r = rig_head(1); + let src = SubjectSource::Head(r.subj.clone()); + let a = Some(hex(&r.f.agent)); + let mut c = ctx(&r.f, M1); + c.lineage = Some(h32("another journal")); + assert_eq!( + resolve(&src, &pin_path(&r.home), &c, a.as_deref()).unwrap_err(), + Refusal::LineageMismatch + ); + c.lineage = None; + assert_eq!( + resolve(&src, &pin_path(&r.home), &c, a.as_deref()).unwrap_err(), + Refusal::LineageMissing + ); + assert!(!pin_path(&r.home).exists()); +} + +#[test] +fn foreign_subject_against_pin_is_refused() { + let r = rig_head(1); + adopt(&r); + let g = fx("b"); + let o = chain(&g, 1); + std::fs::write(&r.subj, &o[0]).unwrap(); + let c = Context { + machine_id: M1, + lineage: Some(g.cortex), + }; + let e = resolve( + &SubjectSource::Head(r.subj.clone()), + &pin_path(&r.home), + &c, + None, + ) + .unwrap_err(); + assert!(matches!(e, Refusal::ForeignIdentity(_)), "{e}"); +} + +#[test] +fn directory_mode_chain_rows() { + let t = tempfile::tempdir().unwrap(); + let f = fx("a"); + let c = chain(&f, 3); + let home = t.path().join("compose"); + let d = t.path().join("subj"); + write_dir(&d, &c); + let src = SubjectSource::Dir(d.clone()); + let cx = ctx(&f, M1); + let ok = resolve(&src, &pin_path(&home), &cx, Some(&hex(&f.agent))).unwrap(); + assert!(ok.chain_verified); + assert_eq!(ok.head_seq, 3); + // forked: a second object at sequence 3 + let fork = encode(&f, 3, object_id(&c[1]), [7, 9]); + write_dir(&d, std::slice::from_ref(&fork)); + assert_eq!( + resolve(&src, &pin_path(&home), &cx, None).unwrap_err(), + Refusal::Forked(3) + ); + std::fs::remove_file(d.join(format!("{}.bin", hex(&object_id(&fork))))).unwrap(); + // gap: remove sequence 2 + std::fs::remove_file(d.join(format!("{}.bin", hex(&object_id(&c[1]))))).unwrap(); + assert_eq!( + resolve(&src, &pin_path(&home), &cx, None).unwrap_err(), + Refusal::Gap(2) + ); + write_dir(&d, std::slice::from_ref(&c[1])); + // changed bytes under an id name + let name = d.join(format!("{}.bin", hex(&object_id(&c[0])))); + let mut bad = c[0].clone(); + bad[100] ^= 1; + std::fs::write(&name, &bad).unwrap(); + assert!(matches!( + resolve(&src, &pin_path(&home), &cx, None), + Err(Refusal::Corrupt(_)) + )); + std::fs::write(&name, &c[0]).unwrap(); + // link broken: sequence 2 naming a wrong previous + let wrong = encode(&f, 2, h32("nonsense"), [7, 1000]); + let d2 = t.path().join("subj2"); + write_dir(&d2, &[c[0].clone(), wrong, c[2].clone()]); + assert!(matches!( + resolve(&SubjectSource::Dir(d2), &pin_path(&home), &cx, None), + Err(Refusal::Corrupt(_)) + )); + // foreign object mixed into the chain + let g = fx("b"); + let alien = encode(&g, 2, object_id(&c[0]), [7, 1000]); + let d3 = t.path().join("subj3"); + write_dir(&d3, &[c[0].clone(), alien]); + assert!(matches!( + resolve(&SubjectSource::Dir(d3), &pin_path(&home), &cx, None), + Err(Refusal::ForeignIdentity(_)) + )); +} + +#[test] +fn directory_mode_rejects_a_chain_that_forks_from_the_pin() { + let t = tempfile::tempdir().unwrap(); + let f = fx("a"); + let c = chain(&f, 2); + let home = t.path().join("compose"); + let d = t.path().join("subj"); + write_dir(&d, &c); + let cx = ctx(&f, M1); + resolve( + &SubjectSource::Dir(d.clone()), + &pin_path(&home), + &cx, + Some(&hex(&f.agent)), + ) + .unwrap(); + // A different history with the same agent: seq 2 differs, seq 3 added. + let alt2 = encode(&f, 2, object_id(&c[0]), [7, 5555]); + let alt3 = encode(&f, 3, object_id(&alt2), [7, 1000]); + let d2 = t.path().join("alt"); + write_dir(&d2, &[c[0].clone(), alt2, alt3]); + assert_eq!( + resolve(&SubjectSource::Dir(d2), &pin_path(&home), &cx, None).unwrap_err(), + Refusal::ForkedFromPin + ); +} + +#[test] +fn known_object_ids_are_stable() { + // Same bytes, same id, on any machine, under any model (ADR 0018 s2.2). + let f = fx("a"); + let o = encode(&f, 1, [0; 32], [7, 1000]); + assert_eq!(object_id(&o), object_id(&o.clone())); + let mut o2 = o.clone(); + o2[100] ^= 1; + assert_ne!(object_id(&o), object_id(&o2)); +} diff --git a/crates/aien-allen/tests/oracle_test.rs b/crates/aien-allen/tests/oracle_test.rs new file mode 100644 index 00000000..e95fa036 --- /dev/null +++ b/crates/aien-allen/tests/oracle_test.rs @@ -0,0 +1,72 @@ +//! Known-answer vectors produced by the REFERENCE C implementation, aienos +//! 61bd76a `native/kernel/svc/continuity_subject.c` (cs_subject_genesis, +//! cs_subject_intend, cs_subject_advance, cs_subject_hold, +//! cs_subject_bind_cortex, cs_subject_encode, cs_subject_id), compiled with the +//! host sources of `make -C native/kernel test-continuity-subject-restart` +//! (CPU only; that target also passed: CK_CONTINUITY_SUBJECT_RESTART PASS). +//! Vector A: genesis, root 0x11.., agent 0x22.., one intent (7, 1000). +//! Vector B: successor of A, bound to Cortex lineage 0x77.., a second intent +//! (9, 2000) and one held knowledge digest 0x5c.. record 17. +//! The format is PROPOSED (ADR 0018): if the C encoder changes, regenerate. +mod support; +use aien_allen::subject_v0::{decode, object_id}; +use support::*; + +const A_HEX: &str = "4149454e5355424a000000001801000011111111111111111111111111111111111111111111111111111111111111112222222222222222222222222222222222222222222222222222222222222222000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000aabbcc0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d010000000000000001000000000000000e1a1094faedf6000d0a1b24a8b379b5ade90e0258fd34a86f98d37c624c94020000000000000000000000000000000000000000000000000000000000000000010000000100000001000000000000000700000000000000e803000000000000"; +const A_ID: &str = "0c1ef058eeba1e58ba0f3a4da741f10c69f91ada838f187d5e8d5626b1b446c0"; +const B_HEX: &str = "4149454e5355424a00000000a8010000111111111111111111111111111111111111111111111111111111111111111122222222222222222222222222222222222222222222222222222222222222220c1ef058eeba1e58ba0f3a4da741f10c69f91ada838f187d5e8d5626b1b446c002000000000000007777777777777777777777777777777777777777777777777777777777777777aabbcc0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d0100000000000000020001000000000003aec9f97a530f279c35bb8d99025c2feb0f2448aff977510f6012d90b5206510000000000000000000000000000000000000000000000000000000000000000010000000100000002000000000000000900000000000000d0070000000000000e1a1094faedf6000d0a1b24a8b379b5ade90e0258fd34a86f98d37c624c94020000000000000000000000000000000000000000000000000000000000000000010000000100000001000000000000000700000000000000e8030000000000005c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c5c11000000000000000200000000000000"; +const B_ID: &str = "9b579318dccfe570234c66bd82e8cc6656e9aae68907f469751ea84016f9bb6d"; + +fn unhex(s: &str) -> Vec { + (0..s.len() / 2) + .map(|i| u8::from_str_radix(&s[2 * i..2 * i + 2], 16).unwrap()) + .collect() +} + +#[test] +fn reference_object_ids_match() { + assert_eq!(aien_allen::hex(&object_id(&unhex(A_HEX))), A_ID); + assert_eq!(aien_allen::hex(&object_id(&unhex(B_HEX))), B_ID); +} + +#[test] +fn reference_objects_decode() { + let a = decode(&unhex(A_HEX)).unwrap(); + assert_eq!((a.sequence, a.root, a.agent), (1, [0x11; 32], [0x22; 32])); + assert_eq!(a.intents.len(), 1); + assert_eq!(a.intents[0].payload, [7, 1000]); + let b = decode(&unhex(B_HEX)).unwrap(); + assert_eq!(b.sequence, 2); + assert_eq!(b.previous.to_vec(), unhex(A_ID)); + assert_eq!(b.cortex, [0x77; 32]); + assert_eq!(b.intents.len(), 2); + assert_eq!(b.knowledge.len(), 1); + assert_eq!(b.knowledge[0].0, [0x5c; 32]); +} + +#[test] +fn fixture_encoder_matches_the_reference_bytes() { + let mut f = fx("ignored"); + f.root = [0x11; 32]; + f.agent = [0x22; 32]; + f.cortex = [0; 32]; + f.provenance = unhex("aabbcc0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d") + .try_into() + .unwrap(); + assert_eq!(encode(&f, 1, [0; 32], [7, 1000]), unhex(A_HEX)); +} + +#[test] +fn flipping_any_reference_byte_is_caught() { + // Negative control: every single-byte change of B either fails to decode + // or changes the object id (so a pin on the id would notice). + let b = unhex(B_HEX); + for i in 0..b.len() { + let mut m = b.clone(); + m[i] ^= 1; + assert!( + decode(&m).is_err() || object_id(&m) != object_id(&b), + "byte {i}" + ); + } +} diff --git a/crates/aien-allen/tests/refusal_rows_test.rs b/crates/aien-allen/tests/refusal_rows_test.rs new file mode 100644 index 00000000..c1b1311e --- /dev/null +++ b/crates/aien-allen/tests/refusal_rows_test.rs @@ -0,0 +1,68 @@ +//! The no-provision invariant (source scan, G5 analog) and the arch#150 +//! s4(6) row table. Rows that need approvals live outside this crate: +//! DEPENDENCY sc#249, NOT_RUN. +use std::path::PathBuf; + +fn src_files() -> Vec<(String, String)> { + let d = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("src"); + std::fs::read_dir(d) + .unwrap() + .map(|e| e.unwrap().path()) + .map(|p| { + ( + p.file_name().unwrap().to_string_lossy().into_owned(), + std::fs::read_to_string(&p).unwrap(), + ) + }) + .collect() +} + +const BANNED: &[&str] = &[ + "fn encode_subject", + "fn genesis", + "fn provision", + "fn mint", + "cs_provision", + "fn create_subject", + "thread::spawn", + "std::thread", + "tokio", +]; + +fn violations(text: &str) -> Vec<&'static str> { + BANNED + .iter() + .copied() + .filter(|b| text.contains(b)) + .collect() +} + +#[test] +fn production_source_has_no_provision_or_encode_path() { + for (name, text) in src_files() { + assert!( + violations(&text).is_empty(), + "{name}: {:?}", + violations(&text) + ); + } + // The subject module has a decoder and an id function only. + let s = src_files() + .into_iter() + .find(|(n, _)| n == "subject_v0.rs") + .unwrap() + .1; + assert!(!s.contains("pub fn encode")); + // Only the pin and deployment writers touch the filesystem for writing. + for (name, text) in src_files() { + let writes = text.contains("fs::write") || text.contains("File::create"); + assert_eq!(writes, name == "binding.rs", "{name}: unexpected writer"); + } +} + +#[test] +fn the_scan_would_catch_a_provision_function() { + // Negative control: the scan flags a provisioning function. + assert_eq!(violations("pub fn provision() {}"), vec!["fn provision"]); + assert!(violations("pub fn decode() {}").is_empty()); +} diff --git a/crates/aien-allen/tests/subject_decode_test.rs b/crates/aien-allen/tests/subject_decode_test.rs new file mode 100644 index 00000000..f731af50 --- /dev/null +++ b/crates/aien-allen/tests/subject_decode_test.rs @@ -0,0 +1,76 @@ +//! Decoder refusals (unsupported dialect, damage) and the id/derivation rules. +mod support; +use aien_allen::subject_v0::{decode, object_id}; +use support::*; + +fn good() -> Vec { + encode(&fx("a"), 1, [0; 32], [7, 1000]) +} + +#[test] +fn good_object_decodes() { + let s = decode(&good()).unwrap(); + assert_eq!(s.sequence, 1); + assert_eq!(s.intents.len(), 1); + assert_eq!(s.intents[0].payload, [7, 1000]); +} + +#[test] +fn unsupported_dialect_is_refused() { + let mut b = good(); + b[8] = 1; // format version 1 + assert!(decode(&b).unwrap_err().contains("version")); + let mut b = good(); + b[..8].copy_from_slice(b"AIENSUBX"); + assert!(decode(&b).unwrap_err().contains("magic")); + // unknown intent kind (offset: header 16 + fixed body 184 = 200; id 32, supersedes 32, kind at +64) + let mut b = good(); + b[200 + 64] = 2; + assert!(decode(&b).is_err()); + // unknown origin + let mut b = good(); + b[16 + 32 * 5 + 8] = 9; + assert!(decode(&b).unwrap_err().contains("origin")); +} + +#[test] +fn damage_is_refused() { + let g = good(); + for n in 0..g.len() { + assert!(decode(&g[..n]).is_err(), "prefix {n}"); + } + let mut b = g.clone(); + b.push(0); + assert!(decode(&b).is_err()); + // intent id must derive from content + let mut b = g.clone(); + b[200 + 64 + 4 + 8 + 8] ^= 1; // payload[0] + assert!(decode(&b).unwrap_err().contains("derive")); +} + +#[test] +fn zero_provenance_and_zero_ids_refused() { + let mut f = fx("a"); + f.provenance = [0; 32]; + assert!(decode(&encode(&f, 1, [0; 32], [7, 1000])) + .unwrap_err() + .contains("provenance")); + let mut f = fx("a"); + f.agent = [0; 32]; + assert!(decode(&encode(&f, 1, [0; 32], [7, 1000])).is_err()); + // sequence 2 with zero previous + assert!(decode(&encode(&fx("a"), 2, [0; 32], [7, 1000])).is_err()); + // genesis naming a previous + assert!(decode(&encode(&fx("a"), 1, [9; 32], [7, 1000])).is_err()); +} + +#[test] +fn object_id_depends_on_every_byte() { + let g = good(); + let id = object_id(&g); + for i in (0..g.len()).step_by(7) { + let mut b = g.clone(); + b[i] ^= 1; + assert_ne!(object_id(&b), id); + } +} diff --git a/crates/aien-allen/tests/support/mod.rs b/crates/aien-allen/tests/support/mod.rs new file mode 100644 index 00000000..460f6d08 --- /dev/null +++ b/crates/aien-allen/tests/support/mod.rs @@ -0,0 +1,98 @@ +//! TEST-ONLY subject fixture builder. A second, independent encoder of the +//! kind-24 layout (aienos ADR 0018 s2.2). It lives under tests/ so the +//! production crate gains no provisioning path: real subjects are created +//! only by AIENOS `cs_provision`. Anything built here is a fixture. +#![allow(dead_code)] +use aien_allen::subject_v0::object_id; +use sha2::{Digest, Sha256}; +use std::path::{Path, PathBuf}; + +pub fn h32(tag: &str) -> [u8; 32] { + Sha256::digest(tag.as_bytes()).into() +} + +pub struct Fx { + pub root: [u8; 32], + pub agent: [u8; 32], + pub cortex: [u8; 32], + pub provenance: [u8; 32], +} + +pub fn fx(name: &str) -> Fx { + Fx { + root: h32(&format!("root:{name}")), + agent: h32(&format!("agent:{name}")), + cortex: h32(&format!("cortex:{name}")), + provenance: h32(&format!("prov:{name}")), + } +} + +fn intent_id(agent: &[u8; 32], kind: u32, since: u64, p: [u64; 2]) -> [u8; 32] { + let mut h = Sha256::new(); + h.update(b"AIENOS_INTENT_v0:"); + h.update(agent); + h.update(kind.to_le_bytes()); + h.update(since.to_le_bytes()); + h.update(p[0].to_le_bytes()); + h.update(p[1].to_le_bytes()); + h.finalize().into() +} + +/// One object: sequence `seq`, `previous` (zero for 1), one ACTIVE GOAL_LATENCY +/// intent created at sequence 1 with payload (regime, target ns). +pub fn encode(f: &Fx, seq: u64, previous: [u8; 32], payload: [u64; 2]) -> Vec { + let id = intent_id(&f.agent, 1, 1, payload); + let mut b = Vec::new(); + b.extend_from_slice(b"AIENSUBJ"); + b.extend_from_slice(&0u16.to_le_bytes()); + b.extend_from_slice(&0u16.to_le_bytes()); + b.extend_from_slice(&[0; 4]); // body length, patched below + b.extend_from_slice(&f.root); + b.extend_from_slice(&f.agent); + b.extend_from_slice(&previous); + b.extend_from_slice(&seq.to_le_bytes()); + b.extend_from_slice(&f.cortex); + b.extend_from_slice(&f.provenance); + b.push(1); // origin operator + b.extend_from_slice(&[0; 7]); + b.extend_from_slice(&1u16.to_le_bytes()); // n_intents + b.extend_from_slice(&0u16.to_le_bytes()); // n_knowledge + b.extend_from_slice(&[0; 4]); + b.extend_from_slice(&id); + b.extend_from_slice(&[0; 32]); + b.extend_from_slice(&1u32.to_le_bytes()); + b.push(1); // ACTIVE + b.extend_from_slice(&[0; 3]); + b.extend_from_slice(&1u64.to_le_bytes()); + b.extend_from_slice(&payload[0].to_le_bytes()); + b.extend_from_slice(&payload[1].to_le_bytes()); + let n = (b.len() - 16) as u32; + b[12..16].copy_from_slice(&n.to_le_bytes()); + b +} + +/// A chain of `n` objects; returns the encoded objects in order. +pub fn chain(f: &Fx, n: u64) -> Vec> { + let mut out: Vec> = Vec::new(); + let mut prev = [0u8; 32]; + for s in 1..=n { + let o = encode(f, s, prev, [7, 1000]); + prev = object_id(&o); + out.push(o); + } + out +} + +/// Write objects into `dir` as `.bin`. +pub fn write_dir(dir: &Path, objs: &[Vec]) { + std::fs::create_dir_all(dir).unwrap(); + for o in objs { + let name = aien_allen::hex(&object_id(o)); + std::fs::write(dir.join(format!("{name}.bin")), o).unwrap(); + } +} + +pub fn write_head(path: &Path, o: &[u8]) -> PathBuf { + std::fs::write(path, o).unwrap(); + path.to_path_buf() +} diff --git a/crates/aien-runtime/Cargo.toml b/crates/aien-runtime/Cargo.toml index 49adba9b..0833289b 100644 --- a/crates/aien-runtime/Cargo.toml +++ b/crates/aien-runtime/Cargo.toml @@ -16,6 +16,7 @@ aien-inference-abi = { path = "../aien-inference-abi" } aien-security = { path = "../aien-security" } cortex-rs = { path = "../cortex-rs" } aien-omega-compose = { path = "../aien-omega-compose" } +aien-allen = { path = "../aien-allen" } tokio = { version = "1.37", features = ["full"] } parking_lot = "0.12" diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs index 3dc72e0b..82a5e0af 100644 --- a/crates/aien-runtime/src/spine.rs +++ b/crates/aien-runtime/src/spine.rs @@ -622,6 +622,55 @@ fn proposal_handle(text: &str) -> u64 { } } +/// ALLEN identity gate (aien-allen, ADR 0035), run once per compose-home open. +/// Not engaged (AIEN_ALLEN_SUBJECT unset): one log line, nothing else changes. +/// Engaged: any refusal is FATAL (message, nonzero exit), never a fallback. +fn allen_gate(dir: &Path, compose: &mut Compose, machine_id: &[u8; 32]) { + use aien_allen::{Context, Gate}; + static NOT_ENGAGED_ONCE: std::sync::Once = std::sync::Once::new(); + let lineage = compose.record(1).ok().map(|r| r.digest); + let ctx = Context { + machine_id: *machine_id, + lineage, + }; + // The operator adoption variable is honoured once per process: after this + // process wrote the pin, later opens (recover, re-open) see it as spent. + static ADOPTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + let get = |k: &str| { + if k == aien_allen::ENV_ADOPT && ADOPTED.load(std::sync::atomic::Ordering::SeqCst) { + return None; + } + std::env::var(k).ok() + }; + match aien_allen::gate(dir, &ctx, &get) { + Gate::NotEngaged => { + NOT_ENGAGED_ONCE.call_once(|| println!("{}", aien_allen::NOT_ENGAGED_LINE)); + } + Gate::Engaged(r) => { + if r.adopted { + ADOPTED.store(true, std::sync::atomic::Ordering::SeqCst); + } + let adopted = if r.adopted { + " (ADOPTED: pin written once, operator-approved)" + } else { + "" + }; + println!( + "ALLEN: engaged agent={} head_sequence={} chain_verified={}{adopted}", + aien_allen::hex(&r.agent), + r.head_seq, + r.chain_verified + ); + } + Gate::Refused(why) => { + let msg = format!("FATAL ALLEN refused: {why}"); + tracing::error!("{msg}"); + eprintln!("{msg}"); + std::process::exit(aien_allen::EXIT_REFUSED); + } + } +} + /// A named refusal for an rxc_host open error: the operator learns what is /// wrong and that `RecoverComposeHome` is the remedy (never a silent repair). fn refusal(dir: &Path, e: &ComposeError) -> String { @@ -1293,6 +1342,9 @@ impl ComposeBridge { cortex_mark::check_digest(m, at).map_err(|r| mark_refusal(&self.dir, &r))?; } } + // ALLEN identity gate: after the open (record 1 exists, skills are + // registered), before the home is handed out. Fatal when engaged. + allen_gate(&self.dir, &mut compose, &info.machine_id); let mut home = ComposeHome { compose, machine_id: hex(&info.machine_id), diff --git a/crates/aien-runtime/tests/allen_spine_test.rs b/crates/aien-runtime/tests/allen_spine_test.rs new file mode 100644 index 00000000..b76b2a96 --- /dev/null +++ b/crates/aien-runtime/tests/allen_spine_test.rs @@ -0,0 +1,254 @@ +//! ALLEN identity gate wired into the compose-home open (spine.rs `allen_gate`). +//! +//! Refusals exit the process (merge-control condition b), so every case runs +//! the daemon open path in a CHILD process: this test binary re-executes +//! itself on `child_open` with the environment under test, and the parent +//! checks exit code and output. With the stub omega library (no +//! librx_compose.a) the compose home cannot open at all, so every case +//! reports NOT_RUN and returns; with `AIEN_OMEGA_COMPOSE_DIR` set they run. +#[path = "../../aien-allen/tests/support/mod.rs"] +mod support; + +use aien_allen::binding::{self, pin_path}; +use aien_allen::{hex, ENV_ADOPT, ENV_SUBJECT, EXIT_REFUSED, NOT_ENGAGED_LINE}; +use aien_omega_compose::{Compose, RootKind, LINKED}; +use aien_runtime::spine::{ComposeBridge, ComposeProposer, Generation}; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::Arc; + +fn proposer() -> ComposeProposer { + Arc::new(|_p: &str, _l: std::time::Duration| { + Ok(Generation { + text: "filename: NOTES.md\nnote\n".into(), + tokens: 4, + finish_reason: Some("eos".into()), + ..Default::default() + }) + }) +} + +/// The child: open the home twice (as two daemon requests would) and note once. +#[test] +fn child_open() { + let Ok(home) = std::env::var("ALLEN_SPINE_CHILD_HOME") else { + return; // not the child + }; + let b = ComposeBridge::new(PathBuf::from(home), proposer(), "test"); + let r = b.note("constraint", "keep changes inside the workspace", &[]); + println!( + "CHILD_NOTE_OK={}", + matches!(r, aien_runtime::control::ControlResponse::ComposeNoted(_)) + ); + if !matches!(r, aien_runtime::control::ControlResponse::ComposeNoted(_)) { + println!("CHILD_NOTE_RESPONSE={r:?}"); + } + let r2 = b.recall(&[], None); + println!( + "CHILD_RECALL_OK={}", + matches!( + r2, + aien_runtime::control::ControlResponse::ComposeRecalled(_) + ) + ); +} + +struct Out { + code: i32, + stdout: String, + stderr: String, +} + +fn run_child(home: &Path, env: &[(&str, &str)]) -> Out { + let mut c = Command::new(std::env::current_exe().unwrap()); + c.args(["--exact", "child_open", "--nocapture", "--test-threads=1"]) + .env("ALLEN_SPINE_CHILD_HOME", home) + .env_remove(ENV_SUBJECT) + .env_remove(ENV_ADOPT); + for (k, v) in env { + c.env(k, v); + } + let o = c.output().unwrap(); + Out { + code: o.status.code().unwrap_or(-1), + stdout: String::from_utf8_lossy(&o.stdout).into_owned(), + stderr: String::from_utf8_lossy(&o.stderr).into_owned(), + } +} + +fn skip() -> bool { + if !LINKED { + println!("NOT_RUN: stub omega build (no librx_compose.a); set AIEN_OMEGA_COMPOSE_DIR"); + return true; + } + false +} + +fn names(dir: &Path) -> Vec { + let mut v: Vec = std::fs::read_dir(dir) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + v.sort(); + v +} + +/// (machine id, digest of Cortex record 1) of a home the daemon already opened. +fn home_facts(home: &Path) -> ([u8; 32], [u8; 32]) { + let mut name = home.as_os_str().to_owned(); + name.push(".machine-root"); + let root = std::fs::read(PathBuf::from(name)).unwrap(); + let (mut c, info) = Compose::open(home, RootKind::Provisioned, &root, 0xA1E4_0001).unwrap(); + let d = c.record(1).unwrap().digest; + assert_ne!(d, [0u8; 32], "record 1 has a digest"); + (info.machine_id, d) +} + +fn subject_for(dir: &Path, lineage: [u8; 32]) -> (PathBuf, support::Fx) { + let mut f = support::fx("spine"); + f.cortex = lineage; + let c = support::chain(&f, 2); + ( + support::write_head(&dir.join("subject.bin"), c.last().unwrap()), + f, + ) +} + +#[test] +fn not_engaged_path_is_unchanged() { + if skip() { + return; + } + let t = tempfile::tempdir().unwrap(); + let home = t.path().join("compose"); + let o = run_child(&home, &[]); + assert_eq!(o.code, 0, "{}{}", o.stdout, o.stderr); + assert!(o.stdout.contains("CHILD_NOTE_OK=true") && o.stdout.contains("CHILD_RECALL_OK=true")); + // Exactly one not-engaged line even though the home opened more than once + // per process, and the line is the agreed text. + assert_eq!( + o.stdout.matches(NOT_ENGAGED_LINE).count(), + 1, + "{}", + o.stdout + ); + assert!(!o.stderr.contains("ALLEN"), "{}", o.stderr); + // No ALLEN artifact beside the home: the gate wrote and read nothing. + let beside = names(t.path()); + assert!(beside.iter().all(|n| !n.contains("allen")), "{beside:?}"); + // Reopening gives the same home and the same record count (second run adds + // one more note; nothing else). + let before = names(&home); + let o2 = run_child(&home, &[]); + assert_eq!(o2.code, 0); + assert_eq!(before, names(&home)); +} + +#[test] +fn engaged_without_pin_or_adopt_is_fatal_and_creates_nothing() { + if skip() { + return; + } + let t = tempfile::tempdir().unwrap(); + let home = t.path().join("compose"); + assert_eq!(run_child(&home, &[]).code, 0); // creates a journal + let (_, lin) = home_facts(&home); + let (subj, _) = subject_for(t.path(), lin); + let o = run_child(&home, &[(ENV_SUBJECT, subj.to_str().unwrap())]); + assert_eq!(o.code, EXIT_REFUSED, "{}{}", o.stdout, o.stderr); + assert!( + o.stderr.contains("FATAL ALLEN refused: PinAbsent"), + "{}", + o.stderr + ); + assert!(!pin_path(&home).exists(), "no silent adoption"); +} + +#[test] +fn engaged_missing_subject_is_fatal_never_minted() { + if skip() { + return; + } + let t = tempfile::tempdir().unwrap(); + let home = t.path().join("compose"); + assert_eq!(run_child(&home, &[]).code, 0); + let missing = t.path().join("none.bin"); + let o = run_child(&home, &[(ENV_SUBJECT, missing.to_str().unwrap())]); + assert_eq!(o.code, EXIT_REFUSED); + assert!( + o.stderr.contains("FATAL ALLEN refused: Absent"), + "{}", + o.stderr + ); + assert!(!missing.exists() && !pin_path(&home).exists()); +} + +#[test] +fn adopt_restart_machine_change_and_foreign_journal() { + if skip() { + return; + } + let t = tempfile::tempdir().unwrap(); + let home = t.path().join("compose"); + assert_eq!(run_child(&home, &[]).code, 0); + let (machine, lin) = home_facts(&home); + let (subj, f) = subject_for(t.path(), lin); + let s = subj.to_str().unwrap(); + // Wrong adopt value: fatal, no pin. + let wrong = hex(&support::h32("someone else")); + let o = run_child(&home, &[(ENV_SUBJECT, s), (ENV_ADOPT, &wrong)]); + assert_eq!(o.code, EXIT_REFUSED); + assert!(o.stderr.contains("AdoptMismatch"), "{}", o.stderr); + assert!(!pin_path(&home).exists()); + // Operator adoption with the right agent id: engaged, pin written. + let agent = hex(&f.agent); + let o = run_child(&home, &[(ENV_SUBJECT, s), (ENV_ADOPT, &agent)]); + assert_eq!(o.code, 0, "{}{}", o.stdout, o.stderr); + assert!(o.stdout.contains("ADOPTED"), "{}", o.stdout); + let pin = binding::read(&pin_path(&home)).unwrap().unwrap(); + assert_eq!(pin.agent, f.agent); + assert_eq!(pin.machine_id, machine); + // Restart without the adopt variable: same identity, pin unchanged. + let pin_bytes = std::fs::read(pin_path(&home)).unwrap(); + let o = run_child(&home, &[(ENV_SUBJECT, s)]); + assert_eq!(o.code, 0, "{}{}", o.stdout, o.stderr); + assert!(o.stdout.contains(&format!("agent={agent}"))); + assert_eq!(pin_bytes, std::fs::read(pin_path(&home)).unwrap()); + // The adopt variable is refused once a pin exists. + let o = run_child(&home, &[(ENV_SUBJECT, s), (ENV_ADOPT, &agent)]); + assert_eq!(o.code, EXIT_REFUSED); + assert!(o.stderr.contains("AdoptRefusedPinExists"), "{}", o.stderr); + // Corrupt the pin: fatal. + let mut bad = pin_bytes.clone(); + bad[20] ^= 1; + std::fs::write(pin_path(&home), &bad).unwrap(); + let o = run_child(&home, &[(ENV_SUBJECT, s)]); + assert_eq!(o.code, EXIT_REFUSED); + assert!(o.stderr.contains("PinDamaged"), "{}", o.stderr); + // Machine id differs from the pin: fatal, never rebound. + let mut other = pin.clone(); + other.machine_id = [0xEE; 32]; + binding::write_atomic(&pin_path(&home), &other).unwrap(); + let o = run_child(&home, &[(ENV_SUBJECT, s)]); + assert_eq!(o.code, EXIT_REFUSED); + assert!(o.stderr.contains("MachineChanged"), "{}", o.stderr); + assert_eq!( + binding::read(&pin_path(&home)).unwrap().unwrap(), + other, + "not rebound" + ); + // Foreign journal: restore the pin, point at another home's journal. + binding::write_atomic(&pin_path(&home), &pin).unwrap(); + let home2 = t.path().join("compose2"); + assert_eq!(run_child(&home2, &[]).code, 0); + let (_, lin2) = home_facts(&home2); + // Two fresh homes may share record-1 content; only test when they differ. + if lin2 != lin { + let o = run_child(&home2, &[(ENV_SUBJECT, s), (ENV_ADOPT, &agent)]); + assert_eq!(o.code, EXIT_REFUSED); + assert!(o.stderr.contains("LineageMismatch"), "{}", o.stderr); + assert!(!pin_path(&home2).exists()); + } else { + println!("NOT_RUN: foreign-journal row (two fresh journals have the same record 1)"); + } +} ```