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/blob/main/crates/aien-allen/src/resolve.rs # 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 branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-allen / src / resolve.rs` 360 lines ยท 12364 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 //! Resolve-only gate. Never provisions: no function in this crate creates a 17 //! subject object (a test scans the source for that). Missing or damaged 18 //! state is a [`Refusal`]. 19 use crate::binding::{self, Pin}; 20 use crate::subject_v0::{self, Subject}; 21 use crate::{hex, unhex32, ENV_ADOPT, ENV_SUBJECT}; 22 use std::path::{Path, PathBuf}; 23 24 #[derive(Debug, Clone)] 25 pub enum SubjectSource { 26 /// One exported head object file. Chain claims are NOT made. 27 Head(PathBuf), 28 /// A directory of raw objects `.bin`: the chain is checked. 29 Dir(PathBuf), 30 } 31 32 #[derive(Debug, Clone, PartialEq, Eq)] 33 pub enum Refusal { 34 /// No subject at the named path: never created. 35 Absent(String), 36 Corrupt(String), 37 /// An object names another agent or root than the rest of the chain / the pin. 38 ForeignIdentity(String), 39 Forked(u64), 40 Gap(u64), 41 NoActiveIntent, 42 LineageUnbound, 43 /// The Cortex journal has no record 1. 44 LineageMissing, 45 LineageMismatch, 46 /// Subject valid, no pin, and no explicit operator adoption. 47 PinAbsent, 48 PinDamaged(String), 49 AdoptMismatch, 50 AdoptRefusedPinExists, 51 AdoptBadValue, 52 MachineChanged, 53 RolledBack { 54 pinned: u64, 55 found: u64, 56 }, 57 SameSequenceDifferentId, 58 ForkedFromPin, 59 Io(String), 60 } 61 62 impl std::fmt::Display for Refusal { 63 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 64 use Refusal::*; 65 match self { 66 Absent(w) => write!(f, "Absent: no subject ({w}); ALLEN is never created implicitly"), 67 Corrupt(w) => write!(f, "Corrupt: {w}"), 68 ForeignIdentity(w) => write!(f, "ForeignIdentity: {w}"), 69 Forked(s) => write!(f, "Forked: two subject objects at sequence {s}"), 70 Gap(s) => write!(f, "Gap: no subject object at sequence {s}"), 71 NoActiveIntent => write!(f, "NoActiveIntent: no ACTIVE GOAL_LATENCY intent"), 72 LineageUnbound => write!(f, "LineageUnbound: subject names no Cortex lineage"), 73 LineageMissing => write!(f, "LineageMissing: the Cortex journal has no record 1"), 74 LineageMismatch => write!( 75 f, 76 "LineageMismatch: this Cortex journal is not the subject's memory" 77 ), 78 PinAbsent => write!( 79 f, 80 "PinAbsent: a valid subject but no pin; set {ENV_ADOPT}= to adopt once" 81 ), 82 PinDamaged(w) => write!(f, "PinDamaged: {w}"), 83 AdoptMismatch => write!( 84 f, 85 "AdoptMismatch: {ENV_ADOPT} is not this subject's agent id" 86 ), 87 AdoptRefusedPinExists => write!( 88 f, 89 "AdoptRefusedPinExists: a pin exists; {ENV_ADOPT} is refused" 90 ), 91 AdoptBadValue => write!(f, "AdoptBadValue: {ENV_ADOPT} must be 64 hex characters"), 92 MachineChanged => write!( 93 f, 94 "MachineChanged: the machine id differs from the pin; never rebound (ruling pending)" 95 ), 96 RolledBack { pinned, found } => write!( 97 f, 98 "RolledBack: head sequence {found} is below the pinned {pinned}" 99 ), 100 SameSequenceDifferentId => write!( 101 f, 102 "SameSequenceDifferentId: same sequence as the pin, different object" 103 ), 104 ForkedFromPin => write!( 105 f, 106 "ForkedFromPin: the chain does not contain the pinned head" 107 ), 108 Io(w) => write!(f, "Io: {w}"), 109 } 110 } 111 } 112 113 #[derive(Debug, Clone)] 114 pub struct Resolved { 115 pub agent: [u8; 32], 116 pub root: [u8; 32], 117 pub head_id: [u8; 32], 118 pub head_seq: u64, 119 pub lineage: [u8; 32], 120 /// True only in directory mode (gap-free, fork-free, link-correct to sequence 1). 121 pub chain_verified: bool, 122 /// True when this call wrote the pin for the first time (adoption). 123 pub adopted: bool, 124 } 125 126 /// What the host knows about itself and the journal at open time. 127 #[derive(Debug, Clone, Copy)] 128 pub struct Context { 129 pub machine_id: [u8; 32], 130 /// Digest of the Cortex journal's record 1 (`None` = journal has none). 131 pub lineage: Option<[u8; 32]>, 132 } 133 134 #[derive(Debug, Clone)] 135 pub struct Engagement { 136 pub source: SubjectSource, 137 pub adopt: Option, 138 } 139 140 pub enum Gate { 141 NotEngaged, 142 Engaged(Resolved), 143 Refused(Refusal), 144 } 145 146 impl Engagement { 147 /// `None` = not engaged (variable unset or empty). 148 pub fn from_env(get: &dyn Fn(&str) -> Option) -> Option { 149 let p = get(ENV_SUBJECT).filter(|s| !s.trim().is_empty())?; 150 let p = PathBuf::from(p.trim()); 151 let source = if p.is_dir() { 152 SubjectSource::Dir(p) 153 } else { 154 SubjectSource::Head(p) 155 }; 156 Some(Engagement { 157 source, 158 adopt: get(ENV_ADOPT).filter(|s| !s.trim().is_empty()), 159 }) 160 } 161 } 162 163 /// The one entry point the daemon calls when a compose home is opened. 164 pub fn gate(home: &Path, ctx: &Context, get: &dyn Fn(&str) -> Option) -> Gate { 165 let Some(e) = Engagement::from_env(get) else { 166 return Gate::NotEngaged; 167 }; 168 match resolve(&e.source, &binding::pin_path(home), ctx, e.adopt.as_deref()) { 169 Ok(r) => Gate::Engaged(r), 170 Err(r) => Gate::Refused(r), 171 } 172 } 173 174 fn read_object(path: &Path) -> Result, Refusal> { 175 match std::fs::read(path) { 176 Ok(b) if b.is_empty() => Err(Refusal::Absent(format!("{} is empty", path.display()))), 177 Ok(b) => Ok(b), 178 Err(e) if e.kind() == std::io::ErrorKind::NotFound => { 179 Err(Refusal::Absent(format!("{} not found", path.display()))) 180 } 181 Err(e) => Err(Refusal::Io(format!("{}: {e}", path.display()))), 182 } 183 } 184 185 struct Loaded { 186 head: Subject, 187 head_id: [u8; 32], 188 /// (sequence, object id) of every verified chain object; empty in head mode. 189 chain: Vec<(u64, [u8; 32])>, 190 chain_verified: bool, 191 } 192 193 fn load(src: &SubjectSource) -> Result { 194 match src { 195 SubjectSource::Head(p) => { 196 let b = read_object(p)?; 197 let head = subject_v0::decode(&b).map_err(Refusal::Corrupt)?; 198 Ok(Loaded { 199 head, 200 head_id: subject_v0::object_id(&b), 201 chain: Vec::new(), 202 chain_verified: false, 203 }) 204 } 205 SubjectSource::Dir(d) => load_dir(d), 206 } 207 } 208 209 fn load_dir(d: &Path) -> Result { 210 let rd = std::fs::read_dir(d).map_err(|e| Refusal::Absent(format!("{}: {e}", d.display())))?; 211 let mut objs: Vec<([u8; 32], Subject)> = Vec::new(); 212 let mut names: Vec<_> = rd.filter_map(|x| x.ok()).map(|x| x.path()).collect(); 213 names.sort(); 214 for p in names { 215 if p.extension().and_then(|x| x.to_str()) != Some("bin") { 216 continue; 217 } 218 let b = read_object(&p)?; 219 let id = subject_v0::object_id(&b); 220 let stem = p.file_stem().and_then(|s| s.to_str()).unwrap_or(""); 221 if stem != hex(&id) { 222 return Err(Refusal::Corrupt(format!( 223 "{} does not hash to its name (changed bytes)", 224 p.display() 225 ))); 226 } 227 let s = subject_v0::decode(&b) 228 .map_err(|w| Refusal::Corrupt(format!("{}: {w}", p.display())))?; 229 objs.push((id, s)); 230 } 231 if objs.is_empty() { 232 return Err(Refusal::Absent(format!("{} holds no objects", d.display()))); 233 } 234 let max = objs.iter().map(|o| o.1.sequence).max().expect("non-empty"); 235 let (g_agent, g_root) = match objs.iter().find(|o| o.1.sequence == 1) { 236 Some(g) => (g.1.agent, g.1.root), 237 None => return Err(Refusal::Gap(1)), 238 }; 239 let mut chain = Vec::new(); 240 let mut prev: Option<[u8; 32]> = None; 241 let mut head = None; 242 for s in 1..=max { 243 let at: Vec<_> = objs.iter().filter(|o| o.1.sequence == s).collect(); 244 match at.len() { 245 0 => return Err(Refusal::Gap(s)), 246 1 => {} 247 _ => return Err(Refusal::Forked(s)), 248 } 249 let (id, o) = (&at[0].0, &at[0].1); 250 if o.agent != g_agent || o.root != g_root { 251 return Err(Refusal::ForeignIdentity(format!( 252 "object at sequence {s} names another agent or root" 253 ))); 254 } 255 if let Some(p) = prev { 256 if o.previous != p { 257 return Err(Refusal::Corrupt(format!("link broken at sequence {s}"))); 258 } 259 } 260 prev = Some(*id); 261 chain.push((s, *id)); 262 head = Some((*id, o.clone())); 263 } 264 let (head_id, head) = head.expect("max >= 1"); 265 Ok(Loaded { 266 head, 267 head_id, 268 chain, 269 chain_verified: true, 270 }) 271 } 272 273 pub fn resolve( 274 src: &SubjectSource, 275 pin_path: &Path, 276 ctx: &Context, 277 adopt: Option<&str>, 278 ) -> Result { 279 let l = load(src)?; 280 let h = &l.head; 281 if !h 282 .intents 283 .iter() 284 .any(|i| i.state == subject_v0::ACTIVE && i.kind == subject_v0::INTENT_GOAL_LATENCY) 285 { 286 return Err(Refusal::NoActiveIntent); 287 } 288 if h.cortex.iter().all(|&b| b == 0) { 289 return Err(Refusal::LineageUnbound); 290 } 291 match ctx.lineage { 292 None => return Err(Refusal::LineageMissing), 293 Some(j) if j != h.cortex => return Err(Refusal::LineageMismatch), 294 Some(_) => {} 295 } 296 let pin = binding::read(pin_path).map_err(Refusal::PinDamaged)?; 297 let mut adopted = false; 298 match (&pin, adopt) { 299 (None, None) => return Err(Refusal::PinAbsent), 300 (None, Some(a)) => { 301 let want = unhex32(a.trim()).ok_or(Refusal::AdoptBadValue)?; 302 if want != h.agent { 303 return Err(Refusal::AdoptMismatch); 304 } 305 adopted = true; 306 } 307 (Some(_), Some(_)) => return Err(Refusal::AdoptRefusedPinExists), 308 (Some(p), None) => { 309 if p.agent != h.agent || p.root != h.root { 310 return Err(Refusal::ForeignIdentity( 311 "subject agent or root differs from the pin".into(), 312 )); 313 } 314 if p.machine_id != ctx.machine_id { 315 return Err(Refusal::MachineChanged); 316 } 317 if p.lineage != h.cortex { 318 return Err(Refusal::LineageMismatch); 319 } 320 if h.sequence < p.head_seq { 321 return Err(Refusal::RolledBack { 322 pinned: p.head_seq, 323 found: h.sequence, 324 }); 325 } 326 if h.sequence == p.head_seq && l.head_id != p.head_id { 327 return Err(Refusal::SameSequenceDifferentId); 328 } 329 if l.chain_verified 330 && !l 331 .chain 332 .iter() 333 .any(|(s, id)| *s == p.head_seq && *id == p.head_id) 334 { 335 return Err(Refusal::ForkedFromPin); 336 } 337 } 338 } 339 if adopted || pin.as_ref().is_some_and(|p| p.head_seq < h.sequence) { 340 let np = Pin { 341 agent: h.agent, 342 root: h.root, 343 head_id: l.head_id, 344 head_seq: h.sequence, 345 lineage: h.cortex, 346 machine_id: ctx.machine_id, 347 provenance: h.provenance, 348 }; 349 binding::write_atomic(pin_path, &np).map_err(Refusal::Io)?; 350 } 351 Ok(Resolved { 352 agent: h.agent, 353 root: h.root, 354 head_id: l.head_id, 355 head_seq: h.sequence, 356 lineage: h.cortex, 357 chain_verified: l.chain_verified, 358 adopted, 359 }) 360 }