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
aien-sovereign-core-mv / crates / aien-allen-profile / src / schema.rs
| 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.profile/1` and its validation. Every struct that is |
| 17 | //! read from disk or from a request denies unknown fields. |
| 18 | use crate::refusal::ProfileRefusal; |
| 19 | use serde::{Deserialize, Serialize}; |
| 20 | |
| 21 | pub const PROFILE_SCHEMA: &str = "aien.allen.profile/1"; |
| 22 | pub const DEFAULT_NAME: &str = "ALLEN"; |
| 23 | /// Largest revision file, in bytes. |
| 24 | pub const MAX_FILE_BYTES: u64 = 16 * 1024; |
| 25 | pub const MAX_NAME_CHARS: usize = 64; |
| 26 | pub const MAX_NOTE_CHARS: usize = 200; |
| 27 | pub const MAX_VALUE_CHARS: usize = 200; |
| 28 | pub const MAX_PREFS: usize = 32; |
| 29 | pub const GENESIS_PREV: &str = "0000000000000000000000000000000000000000000000000000000000000000"; |
| 30 | const PROVENANCE: &str = "user_explicit"; |
| 31 | /// A key containing any of these is refused (case-insensitive). |
| 32 | const PERMISSION_WORDS: [&str; 11] = [ |
| 33 | "grant", |
| 34 | "perm", |
| 35 | "approv", |
| 36 | "capab", |
| 37 | "allow", |
| 38 | "authori", |
| 39 | "bypass", |
| 40 | "sudo", |
| 41 | "admin", |
| 42 | "override", |
| 43 | "unrestrict", |
| 44 | ]; |
| 45 | |
| 46 | /// The engaged identity a profile is bound to (the resolved agent and root). |
| 47 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 48 | pub struct Identity { |
| 49 | pub agent: [u8; 32], |
| 50 | pub root: [u8; 32], |
| 51 | } |
| 52 | |
| 53 | impl From<&aien_allen::Resolved> for Identity { |
| 54 | fn from(r: &aien_allen::Resolved) -> Self { |
| 55 | Identity { |
| 56 | agent: r.agent, |
| 57 | root: r.root, |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | impl Identity { |
| 63 | pub fn agent_hex(&self) -> String { |
| 64 | aien_allen::hex(&self.agent) |
| 65 | } |
| 66 | pub fn root_hex(&self) -> String { |
| 67 | aien_allen::hex(&self.root) |
| 68 | } |
| 69 | /// First 8 hex characters of the agent id, for display. |
| 70 | pub fn fingerprint(&self) -> String { |
| 71 | self.agent_hex()[..8].to_string() |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 76 | #[serde(rename_all = "lowercase")] |
| 77 | pub enum Tone { |
| 78 | Neutral, |
| 79 | Warm, |
| 80 | Direct, |
| 81 | Formal, |
| 82 | } |
| 83 | |
| 84 | impl Tone { |
| 85 | pub fn as_str(self) -> &'static str { |
| 86 | match self { |
| 87 | Tone::Neutral => "neutral", |
| 88 | Tone::Warm => "warm", |
| 89 | Tone::Direct => "direct", |
| 90 | Tone::Formal => "formal", |
| 91 | } |
| 92 | } |
| 93 | pub fn parse(s: &str) -> Result<Tone, ProfileRefusal> { |
| 94 | match s { |
| 95 | "neutral" => Ok(Tone::Neutral), |
| 96 | "warm" => Ok(Tone::Warm), |
| 97 | "direct" => Ok(Tone::Direct), |
| 98 | "formal" => Ok(Tone::Formal), |
| 99 | o => Err(ProfileRefusal::Invalid(format!( |
| 100 | "tone \"{o}\" (use neutral, warm, direct or formal)" |
| 101 | ))), |
| 102 | } |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 107 | #[serde(rename_all = "lowercase")] |
| 108 | pub enum Verbosity { |
| 109 | Brief, |
| 110 | Normal, |
| 111 | Detailed, |
| 112 | } |
| 113 | |
| 114 | impl Verbosity { |
| 115 | pub fn as_str(self) -> &'static str { |
| 116 | match self { |
| 117 | Verbosity::Brief => "brief", |
| 118 | Verbosity::Normal => "normal", |
| 119 | Verbosity::Detailed => "detailed", |
| 120 | } |
| 121 | } |
| 122 | pub fn parse(s: &str) -> Result<Verbosity, ProfileRefusal> { |
| 123 | match s { |
| 124 | "brief" => Ok(Verbosity::Brief), |
| 125 | "normal" => Ok(Verbosity::Normal), |
| 126 | "detailed" => Ok(Verbosity::Detailed), |
| 127 | o => Err(ProfileRefusal::Invalid(format!( |
| 128 | "verbosity \"{o}\" (use brief, normal or detailed)" |
| 129 | ))), |
| 130 | } |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 135 | #[serde(rename_all = "lowercase")] |
| 136 | pub enum Scope { |
| 137 | All, |
| 138 | Personal, |
| 139 | Work, |
| 140 | Project, |
| 141 | } |
| 142 | |
| 143 | impl Scope { |
| 144 | pub fn as_str(self) -> &'static str { |
| 145 | match self { |
| 146 | Scope::All => "all", |
| 147 | Scope::Personal => "personal", |
| 148 | Scope::Work => "work", |
| 149 | Scope::Project => "project", |
| 150 | } |
| 151 | } |
| 152 | pub fn parse(s: &str) -> Result<Scope, ProfileRefusal> { |
| 153 | match s { |
| 154 | "all" => Ok(Scope::All), |
| 155 | "personal" => Ok(Scope::Personal), |
| 156 | "work" => Ok(Scope::Work), |
| 157 | "project" => Ok(Scope::Project), |
| 158 | o => Err(ProfileRefusal::Invalid(format!( |
| 159 | "scope \"{o}\" (use all, personal, work or project)" |
| 160 | ))), |
| 161 | } |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | /// Who wrote a revision: the user, a reset, or a revert to revision N. |
| 166 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 167 | pub enum Author { |
| 168 | User, |
| 169 | Reset, |
| 170 | Revert(u64), |
| 171 | } |
| 172 | |
| 173 | impl Author { |
| 174 | fn to_text(self) -> String { |
| 175 | match self { |
| 176 | Author::User => "user".into(), |
| 177 | Author::Reset => "reset".into(), |
| 178 | Author::Revert(n) => format!("revert:{n}"), |
| 179 | } |
| 180 | } |
| 181 | fn from_text(s: &str) -> Option<Author> { |
| 182 | match s { |
| 183 | "user" => Some(Author::User), |
| 184 | "reset" => Some(Author::Reset), |
| 185 | _ => s |
| 186 | .strip_prefix("revert:") |
| 187 | .and_then(|n| n.parse().ok()) |
| 188 | .filter(|n: &u64| *n >= 1) |
| 189 | .map(Author::Revert), |
| 190 | } |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | impl Serialize for Author { |
| 195 | fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { |
| 196 | s.serialize_str(&self.to_text()) |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | impl<'de> Deserialize<'de> for Author { |
| 201 | fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> { |
| 202 | let t = String::deserialize(d)?; |
| 203 | Author::from_text(&t).ok_or_else(|| serde::de::Error::custom(format!("author {t:?}"))) |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 208 | #[serde(deny_unknown_fields)] |
| 209 | pub struct Persona { |
| 210 | pub display_name: String, |
| 211 | pub tone: Tone, |
| 212 | pub verbosity: Verbosity, |
| 213 | pub plain_language: bool, |
| 214 | } |
| 215 | |
| 216 | impl Default for Persona { |
| 217 | fn default() -> Self { |
| 218 | Persona { |
| 219 | display_name: DEFAULT_NAME.into(), |
| 220 | tone: Tone::Neutral, |
| 221 | verbosity: Verbosity::Normal, |
| 222 | plain_language: false, |
| 223 | } |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 228 | #[serde(deny_unknown_fields)] |
| 229 | pub struct WorkingPref { |
| 230 | pub key: String, |
| 231 | pub value: String, |
| 232 | pub scope: Scope, |
| 233 | pub provenance: String, |
| 234 | } |
| 235 | |
| 236 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 237 | #[serde(deny_unknown_fields)] |
| 238 | pub struct Profile { |
| 239 | pub schema: String, |
| 240 | pub agent: String, |
| 241 | pub root: String, |
| 242 | pub revision: u64, |
| 243 | pub prev_sha256: String, |
| 244 | /// UTC, informational only. Nothing orders or trusts it. |
| 245 | pub written_at: String, |
| 246 | pub author: Author, |
| 247 | pub note: String, |
| 248 | pub persona: Persona, |
| 249 | pub working_preferences: Vec<WorkingPref>, |
| 250 | } |
| 251 | |
| 252 | /// One requested preference change. |
| 253 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 254 | #[serde(deny_unknown_fields)] |
| 255 | pub struct PrefChange { |
| 256 | pub key: String, |
| 257 | pub value: String, |
| 258 | pub scope: Scope, |
| 259 | } |
| 260 | |
| 261 | /// What `set` may change. Anything left `None`/empty is kept as it is. |
| 262 | #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] |
| 263 | #[serde(deny_unknown_fields, default)] |
| 264 | pub struct Changes { |
| 265 | pub name: Option<String>, |
| 266 | pub tone: Option<Tone>, |
| 267 | pub verbosity: Option<Verbosity>, |
| 268 | pub plain_language: Option<bool>, |
| 269 | pub set_prefs: Vec<PrefChange>, |
| 270 | pub unset_prefs: Vec<String>, |
| 271 | pub note: Option<String>, |
| 272 | } |
| 273 | |
| 274 | /// One line of `history`. |
| 275 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 276 | pub struct HistoryEntry { |
| 277 | pub revision: u64, |
| 278 | pub written_at: String, |
| 279 | pub author: Author, |
| 280 | pub note: String, |
| 281 | pub display_name: String, |
| 282 | } |
| 283 | |
| 284 | fn has_control(s: &str) -> bool { |
| 285 | s.chars().any(|c| { |
| 286 | c.is_control() |
| 287 | || matches!(c, '\u{2028}' | '\u{2029}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}') |
| 288 | }) |
| 289 | } |
| 290 | |
| 291 | pub fn is_hex64(s: &str) -> bool { |
| 292 | s.len() == 64 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) |
| 293 | } |
| 294 | |
| 295 | pub fn clean_name(raw: &str) -> Result<String, ProfileRefusal> { |
| 296 | let n = raw.trim(); |
| 297 | let chars = n.chars().count(); |
| 298 | if chars == 0 || chars > MAX_NAME_CHARS { |
| 299 | return Err(ProfileRefusal::Invalid(format!( |
| 300 | "the name must be 1 to {MAX_NAME_CHARS} characters" |
| 301 | ))); |
| 302 | } |
| 303 | if has_control(n) { |
| 304 | return Err(ProfileRefusal::Invalid( |
| 305 | "the name may not contain control characters".into(), |
| 306 | )); |
| 307 | } |
| 308 | Ok(n.to_string()) |
| 309 | } |
| 310 | |
| 311 | pub fn clean_note(raw: &str) -> Result<String, ProfileRefusal> { |
| 312 | let n = raw.trim(); |
| 313 | if n.chars().count() > MAX_NOTE_CHARS || has_control(n) { |
| 314 | return Err(ProfileRefusal::Invalid(format!( |
| 315 | "a note is at most {MAX_NOTE_CHARS} characters, no control characters" |
| 316 | ))); |
| 317 | } |
| 318 | Ok(n.to_string()) |
| 319 | } |
| 320 | |
| 321 | pub fn check_key(key: &str) -> Result<(), ProfileRefusal> { |
| 322 | let ok = !key.is_empty() |
| 323 | && key.len() <= 48 |
| 324 | && key |
| 325 | .bytes() |
| 326 | .all(|b| matches!(b, b'a'..=b'z' | b'0'..=b'9' | b'_' | b'.' | b'-')); |
| 327 | if !ok { |
| 328 | return Err(ProfileRefusal::Invalid(format!( |
| 329 | "preference key \"{key}\" (1 to 48 characters from a-z, 0-9, _ . -)" |
| 330 | ))); |
| 331 | } |
| 332 | let norm = key.to_ascii_lowercase().replace(['-', '.'], "_"); |
| 333 | if PERMISSION_WORDS.iter().any(|w| norm.contains(w)) { |
| 334 | return Err(ProfileRefusal::PermissionKey(key.to_string())); |
| 335 | } |
| 336 | Ok(()) |
| 337 | } |
| 338 | |
| 339 | pub fn check_value(key: &str, value: &str) -> Result<(), ProfileRefusal> { |
| 340 | let n = value.chars().count(); |
| 341 | if n == 0 || n > MAX_VALUE_CHARS || has_control(value) { |
| 342 | return Err(ProfileRefusal::Invalid(format!( |
| 343 | "the value for \"{key}\" must be 1 to {MAX_VALUE_CHARS} characters, one line" |
| 344 | ))); |
| 345 | } |
| 346 | Ok(()) |
| 347 | } |
| 348 | |
| 349 | impl Profile { |
| 350 | /// Structural validation of a profile (as read from disk or about to be written). |
| 351 | pub fn validate(&self) -> Result<(), ProfileRefusal> { |
| 352 | let bad = |w: String| Err(ProfileRefusal::Damaged(w)); |
| 353 | if self.schema != PROFILE_SCHEMA { |
| 354 | return bad(format!("unknown schema \"{}\"", self.schema)); |
| 355 | } |
| 356 | if !is_hex64(&self.agent) || !is_hex64(&self.root) || !is_hex64(&self.prev_sha256) { |
| 357 | return bad("agent, root and prev_sha256 must be 64 hex characters".into()); |
| 358 | } |
| 359 | if self.revision == 0 { |
| 360 | return bad("revision 0".into()); |
| 361 | } |
| 362 | if self.written_at.len() > 40 || has_control(&self.written_at) { |
| 363 | return bad("written_at".into()); |
| 364 | } |
| 365 | clean_note(&self.note).map_err(|e| ProfileRefusal::Damaged(e.to_string()))?; |
| 366 | clean_name(&self.persona.display_name) |
| 367 | .map_err(|e| ProfileRefusal::Damaged(e.to_string()))?; |
| 368 | if self.persona.display_name != self.persona.display_name.trim() { |
| 369 | return bad("display_name is not trimmed".into()); |
| 370 | } |
| 371 | if self.working_preferences.len() > MAX_PREFS { |
| 372 | return bad(format!("more than {MAX_PREFS} preferences")); |
| 373 | } |
| 374 | let mut last: Option<&str> = None; |
| 375 | for p in &self.working_preferences { |
| 376 | check_key(&p.key).map_err(|e| ProfileRefusal::Damaged(e.to_string()))?; |
| 377 | check_value(&p.key, &p.value).map_err(|e| ProfileRefusal::Damaged(e.to_string()))?; |
| 378 | if p.provenance != PROVENANCE { |
| 379 | return bad(format!("preference \"{}\" provenance", p.key)); |
| 380 | } |
| 381 | if last.is_some_and(|l| l >= p.key.as_str()) { |
| 382 | return bad("preferences are not sorted by unique key".into()); |
| 383 | } |
| 384 | last = Some(&p.key); |
| 385 | } |
| 386 | Ok(()) |
| 387 | } |
| 388 | |
| 389 | pub fn is_bound_to(&self, id: &Identity) -> bool { |
| 390 | self.agent == id.agent_hex() && self.root == id.root_hex() |
| 391 | } |
| 392 | |
| 393 | /// The editable part, to compare "would anything change". |
| 394 | pub fn content(&self) -> (&Persona, &[WorkingPref]) { |
| 395 | (&self.persona, &self.working_preferences) |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | /// Apply `ch` to a persona and preference list, validating every part. |
| 400 | pub fn apply_changes( |
| 401 | persona: &Persona, |
| 402 | prefs: &[WorkingPref], |
| 403 | ch: &Changes, |
| 404 | ) -> Result<(Persona, Vec<WorkingPref>), ProfileRefusal> { |
| 405 | let mut p = persona.clone(); |
| 406 | if let Some(n) = &ch.name { |
| 407 | p.display_name = clean_name(n)?; |
| 408 | } |
| 409 | if let Some(t) = ch.tone { |
| 410 | p.tone = t; |
| 411 | } |
| 412 | if let Some(v) = ch.verbosity { |
| 413 | p.verbosity = v; |
| 414 | } |
| 415 | if let Some(b) = ch.plain_language { |
| 416 | p.plain_language = b; |
| 417 | } |
| 418 | let mut list: Vec<WorkingPref> = prefs.to_vec(); |
| 419 | for key in &ch.unset_prefs { |
| 420 | let before = list.len(); |
| 421 | list.retain(|w| &w.key != key); |
| 422 | if list.len() == before { |
| 423 | return Err(ProfileRefusal::Invalid(format!( |
| 424 | "no saved preference \"{key}\" to remove" |
| 425 | ))); |
| 426 | } |
| 427 | } |
| 428 | for c in &ch.set_prefs { |
| 429 | check_key(&c.key)?; |
| 430 | check_value(&c.key, &c.value)?; |
| 431 | let new = WorkingPref { |
| 432 | key: c.key.clone(), |
| 433 | value: c.value.clone(), |
| 434 | scope: c.scope, |
| 435 | provenance: PROVENANCE.into(), |
| 436 | }; |
| 437 | match list.iter_mut().find(|w| w.key == c.key) { |
| 438 | Some(slot) => *slot = new, |
| 439 | None => list.push(new), |
| 440 | } |
| 441 | } |
| 442 | if list.len() > MAX_PREFS { |
| 443 | return Err(ProfileRefusal::Invalid(format!( |
| 444 | "at most {MAX_PREFS} preferences" |
| 445 | ))); |
| 446 | } |
| 447 | list.sort_by(|a, b| a.key.cmp(&b.key)); |
| 448 | Ok((p, list)) |
| 449 | } |
| 450 | |
| 451 | pub fn preference_provenance() -> &'static str { |
| 452 | PROVENANCE |
| 453 | } |
| 454 | |
| 455 | /// UTC "YYYY-MM-DDTHH:MM:SSZ" from the system clock. |
| 456 | pub fn now_utc() -> String { |
| 457 | let secs = std::time::SystemTime::now() |
| 458 | .duration_since(std::time::UNIX_EPOCH) |
| 459 | .map(|d| d.as_secs()) |
| 460 | .unwrap_or(0); |
| 461 | let (days, rem) = ((secs / 86_400) as i64, secs % 86_400); |
| 462 | // Civil-from-days (Howard Hinnant's algorithm). |
| 463 | let z = days + 719_468; |
| 464 | let era = z.div_euclid(146_097); |
| 465 | let doe = z.rem_euclid(146_097); |
| 466 | let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; |
| 467 | let y = yoe + era * 400; |
| 468 | let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); |
| 469 | let mp = (5 * doy + 2) / 153; |
| 470 | let d = doy - (153 * mp + 2) / 5 + 1; |
| 471 | let m = if mp < 10 { mp + 3 } else { mp - 9 }; |
| 472 | let y = if m <= 2 { y + 1 } else { y }; |
| 473 | format!( |
| 474 | "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", |
| 475 | rem / 3600, |
| 476 | (rem % 3600) / 60, |
| 477 | rem % 60 |
| 478 | ) |
| 479 | } |