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-memory/src/schema.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-memory / src / schema.rs` 279 lines ยท 8675 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 //! Schema `aien.allen.memory/1`. Every struct read from disk denies unknown 17 //! fields. The log holds ciphertext only; plaintext never reaches `log/`. 18 use crate::refusal::MemoryRefusal as R; 19 use serde::{Deserialize, Serialize}; 20 use std::fmt; 21 22 pub const MEMORY_SCHEMA: &str = "aien.allen.memory/1"; 23 /// Printed with every standing goal. A host goal is not a SubjectState intent. 24 pub const GOAL_LABEL: &str = "host goal record, not a subject intent"; 25 pub const MAX_TEXT_BYTES: usize = 2048; 26 pub const MAX_RECORD_BYTES: u64 = 8 * 1024; 27 pub const MAX_RECORDS: u64 = 100_000; 28 pub const GENESIS_PREV: &str = "`0000000000000000000000000000000000000000000000000000000000000000`"; 29 pub const TAG_LEN: usize = 16; 30 pub const NONCE_LEN: usize = 12; 31 32 /// `personal`, `work`, or `project:` with name `^[a-z0-9_.-]{1,48}$`. 33 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] 34 #[serde(try_from = "String", into = "String")] 35 pub enum Scope { 36 Personal, 37 Work, 38 Project(String), 39 } 40 41 impl Scope { 42 pub fn parse(s: &str) -> Result { 43 match s { 44 "personal" => Ok(Scope::Personal), 45 "work" => Ok(Scope::Work), 46 _ => match s.strip_prefix("project:") { 47 Some(n) 48 if (1..=48).contains(&n.len()) 49 && n.bytes().all(|b| { 50 b.is_ascii_lowercase() 51 || b.is_ascii_digit() 52 || b == b'_' 53 || b == b'.' 54 || b == b'-' 55 }) => 56 { 57 Ok(Scope::Project(n.to_string())) 58 } 59 _ => Err(R::Invalid(format!( 60 "scope \"{s}\" (use personal, work or project: with name of 1 to 48 of a-z 0-9 _ . -)" 61 ))), 62 }, 63 } 64 } 65 } 66 67 impl fmt::Display for Scope { 68 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 69 match self { 70 Scope::Personal => f.write_str("personal"), 71 Scope::Work => f.write_str("work"), 72 Scope::Project(n) => write!(f, "project:{n}"), 73 } 74 } 75 } 76 77 impl TryFrom for Scope { 78 type Error = String; 79 fn try_from(s: String) -> Result { 80 Scope::parse(&s).map_err(|e| e.to_string()) 81 } 82 } 83 84 impl From for String { 85 fn from(s: Scope) -> String { 86 s.to_string() 87 } 88 } 89 90 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] 91 #[serde(rename_all = "lowercase")] 92 pub enum Kind { 93 Fact, 94 Preference, 95 Goal, 96 } 97 98 impl Kind { 99 pub fn as_str(self) -> &'static str { 100 match self { 101 Kind::Fact => "fact", 102 Kind::Preference => "preference", 103 Kind::Goal => "goal", 104 } 105 } 106 } 107 108 #[derive(Debug, Clone, Serialize, Deserialize)] 109 #[serde(deny_unknown_fields)] 110 pub struct Record { 111 pub schema: String, 112 pub agent: String, 113 pub root: String, 114 pub seq: u64, 115 pub prev_sha256: String, 116 pub at: String, 117 pub op: Op, 118 } 119 120 #[derive(Debug, Clone, Serialize, Deserialize)] 121 #[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)] 122 pub enum Op { 123 Put { 124 item: String, 125 scope: Scope, 126 kind: Kind, 127 version: u32, 128 ciphertext: String, 129 nonce: String, 130 key_id: String, 131 }, 132 Correct { 133 item: String, 134 supersedes_version: u32, 135 version: u32, 136 ciphertext: String, 137 nonce: String, 138 key_id: String, 139 }, 140 /// Metadata only: item id and scope. The content key is already destroyed. 141 ForgetItem { 142 item: String, 143 scope: Scope, 144 }, 145 ForgetScope { 146 scope: Scope, 147 }, 148 GoalClose { 149 item: String, 150 }, 151 } 152 153 pub fn is_hex(s: &str, len: Option) -> bool { 154 len.is_none_or(|l| s.len() == l) 155 && !s.is_empty() 156 && s.bytes() 157 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) 158 } 159 160 pub fn unhex(s: &str) -> Option> { 161 if !s.len().is_multiple_of(2) || !s.is_ascii() { 162 return None; 163 } 164 (0..s.len() / 2) 165 .map(|i| u8::from_str_radix(&s[2 * i..2 * i + 2], 16).ok()) 166 .collect() 167 } 168 169 pub fn key_id(item: &str, version: u32) -> String { 170 format!("{item}-v{version}") 171 } 172 173 fn check_blob(item: &str, version: u32, ct: &str, nonce: &str, kid: &str) -> Result<(), String> { 174 if !is_hex(item, Some(32)) { 175 return Err("item id is not 32 hex characters".into()); 176 } 177 if version == 0 { 178 return Err("version 0".into()); 179 } 180 if !is_hex(nonce, Some(NONCE_LEN * 2)) { 181 return Err("bad nonce".into()); 182 } 183 if !is_hex(ct, None) 184 || !ct.len().is_multiple_of(2) 185 || ct.len() < TAG_LEN * 2 186 || ct.len() > (MAX_TEXT_BYTES + TAG_LEN) * 2 187 { 188 return Err("bad ciphertext size".into()); 189 } 190 if kid != key_id(item, version) { 191 return Err("key_id does not match item and version".into()); 192 } 193 Ok(()) 194 } 195 196 impl Record { 197 pub fn validate(&self) -> Result<(), String> { 198 if self.schema != MEMORY_SCHEMA { 199 return Err(format!("unknown schema \"{}\"", self.schema)); 200 } 201 if !is_hex(&self.agent, Some(64)) || !is_hex(&self.root, Some(64)) { 202 return Err("agent or root is not 64 hex characters".into()); 203 } 204 if !is_hex(&self.prev_sha256, Some(64)) { 205 return Err("prev_sha256 is not 64 hex characters".into()); 206 } 207 if self.at.len() != 20 || !self.at.is_ascii() || self.seq == 0 { 208 return Err("bad timestamp or sequence".into()); 209 } 210 match &self.op { 211 Op::Put { 212 item, 213 version, 214 ciphertext, 215 nonce, 216 key_id, 217 .. 218 } => { 219 if *version != 1 { 220 return Err("put must be version 1".into()); 221 } 222 check_blob(item, *version, ciphertext, nonce, key_id) 223 } 224 Op::Correct { 225 item, 226 supersedes_version, 227 version, 228 ciphertext, 229 nonce, 230 key_id, 231 } => { 232 if *supersedes_version == 0 || *version != supersedes_version.saturating_add(1) { 233 return Err("correct must supersede the previous version by one".into()); 234 } 235 check_blob(item, *version, ciphertext, nonce, key_id) 236 } 237 Op::ForgetItem { item, .. } | Op::GoalClose { item } => { 238 if is_hex(item, Some(32)) { 239 Ok(()) 240 } else { 241 Err("item id is not 32 hex characters".into()) 242 } 243 } 244 Op::ForgetScope { .. } => Ok(()), 245 } 246 } 247 } 248 249 /// The intent written before keys are destroyed (see RETENTION.md). 250 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 251 #[serde(deny_unknown_fields, rename_all = "snake_case")] 252 pub enum Marker { 253 Item(String), 254 Scope(Scope), 255 } 256 257 /// UTC `YYYY-MM-DDTHH:MM:SSZ` from the system clock (informational only). 258 pub fn now_utc() -> String { 259 let secs = std::time::SystemTime::now() 260 .duration_since(std::time::UNIX_EPOCH) 261 .map(|d| d.as_secs() as i64) 262 .unwrap_or(0); 263 let (days, rem) = (secs.div_euclid(86400), secs.rem_euclid(86400)); 264 let z = days + 719468; 265 let era = z.div_euclid(146097); 266 let doe = z.rem_euclid(146097); 267 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; 268 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); 269 let mp = (5 * doy + 2) / 153; 270 let d = doy - (153 * mp + 2) / 5 + 1; 271 let m = if mp < 10 { mp + 3 } else { mp - 9 }; 272 let y = yoe + era * 400 + i64::from(m <= 2); 273 format!( 274 "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", 275 rem / 3600, 276 rem % 3600 / 60, 277 rem % 60 278 ) 279 }