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-cli / src / allen.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 | //! `aien allen ...`: the ALLEN persona profile (arch#159), one operator step |
| 17 | //! per subcommand, against the running daemon. Each call prints ONE JSON |
| 18 | //! object on stdout (`"ok": true|false`) and exits 1 on failure. |
| 19 | //! |
| 20 | //! status identity, persona, model, unsupported facilities |
| 21 | //! show the saved profile (or the defaults) |
| 22 | //! set --expect R [--name N] [--tone T] [--verbosity V] [--plain-language 0|1] |
| 23 | //! [--pref key=value[@scope]]... [--unset-pref key]... [--note TEXT] |
| 24 | //! history every saved revision |
| 25 | //! revert --to N --expect R new revision copying revision N |
| 26 | //! reset --expect R new revision with the defaults |
| 27 | //! memory put|recall|inspect|correct|forget|export scoped memory, see parse_memory |
| 28 | //! goals list|add|close host goal records |
| 29 | //! Memory and goal calls name their context: --context personal|work|project:NAME. |
| 30 | //! Only inspect, export and goals list take --owner 1 (every context) instead. |
| 31 | //! |
| 32 | //! Every change needs `--expect <current revision>` (0 when nothing is saved |
| 33 | //! yet): if the profile moved since you looked, the change is refused. |
| 34 | //! The daemon owns the profile store; this side only asks. |
| 35 | use aien_allen_profile::{Changes, PrefChange, Scope, Tone, Verbosity}; |
| 36 | use aien_runtime::client::AienRuntimeClient; |
| 37 | use aien_runtime::control::{ControlCommand, ControlResponse}; |
| 38 | use serde_json::{json, Value}; |
| 39 | |
| 40 | type Flags = Vec<(String, String)>; |
| 41 | |
| 42 | fn flags(args: &[String], allowed: &[&str]) -> Result<Flags, String> { |
| 43 | let mut out = Vec::new(); |
| 44 | let mut i = 0; |
| 45 | while i < args.len() { |
| 46 | let k = args[i] |
| 47 | .strip_prefix("--") |
| 48 | .ok_or_else(|| format!("expected --flag, got {:?}", args[i]))?; |
| 49 | if !allowed.contains(&k) { |
| 50 | return Err(format!("unknown flag --{k}")); |
| 51 | } |
| 52 | let v = args |
| 53 | .get(i + 1) |
| 54 | .ok_or_else(|| format!("--{k} needs a value"))?; |
| 55 | out.push((k.to_string(), v.clone())); |
| 56 | i += 2; |
| 57 | } |
| 58 | Ok(out) |
| 59 | } |
| 60 | |
| 61 | fn one<'a>(f: &'a Flags, k: &str) -> Result<Option<&'a str>, String> { |
| 62 | let mut it = f.iter().filter(|(n, _)| n == k); |
| 63 | let first = it.next().map(|(_, v)| v.as_str()); |
| 64 | if it.next().is_some() { |
| 65 | return Err(format!("--{k} given more than once")); |
| 66 | } |
| 67 | Ok(first) |
| 68 | } |
| 69 | |
| 70 | fn number(f: &Flags, k: &str) -> Result<u64, String> { |
| 71 | let v = one(f, k)?.ok_or_else(|| { |
| 72 | if k == "expect" { |
| 73 | "--expect is required: the revision you looked at (0 when nothing is saved yet)".into() |
| 74 | } else { |
| 75 | format!("--{k} is required") |
| 76 | } |
| 77 | })?; |
| 78 | v.trim() |
| 79 | .parse::<u64>() |
| 80 | .map_err(|_| format!("--{k} must be a whole number, got {v:?}")) |
| 81 | } |
| 82 | |
| 83 | /// `key=value` or `key=value@scope` (scope one of all, personal, work, project). |
| 84 | fn parse_pref(s: &str) -> Result<PrefChange, String> { |
| 85 | let (key, rest) = s |
| 86 | .split_once('=') |
| 87 | .ok_or_else(|| format!("--pref needs key=value, got {s:?}"))?; |
| 88 | let (value, scope) = match rest.rsplit_once('@') { |
| 89 | Some((v, sc)) if matches!(sc, "all" | "personal" | "work" | "project") => { |
| 90 | (v, Scope::parse(sc).map_err(|e| e.to_string())?) |
| 91 | } |
| 92 | _ => (rest, Scope::All), |
| 93 | }; |
| 94 | Ok(PrefChange { |
| 95 | key: key.to_string(), |
| 96 | value: value.to_string(), |
| 97 | scope, |
| 98 | }) |
| 99 | } |
| 100 | |
| 101 | /// Turn the command line into the daemon command (pure, no I/O). |
| 102 | pub fn parse(sub: &str, args: &[String]) -> Result<ControlCommand, String> { |
| 103 | match sub { |
| 104 | "memory" => parse_memory(args), |
| 105 | "goals" => parse_goals(args), |
| 106 | "status" => { |
| 107 | flags(args, &[])?; |
| 108 | Ok(ControlCommand::AllenStatus) |
| 109 | } |
| 110 | "show" => { |
| 111 | flags(args, &[])?; |
| 112 | Ok(ControlCommand::AllenProfileShow) |
| 113 | } |
| 114 | "history" => { |
| 115 | flags(args, &[])?; |
| 116 | Ok(ControlCommand::AllenProfileHistory) |
| 117 | } |
| 118 | "set" => { |
| 119 | let f = flags( |
| 120 | args, |
| 121 | &[ |
| 122 | "expect", |
| 123 | "name", |
| 124 | "tone", |
| 125 | "verbosity", |
| 126 | "plain-language", |
| 127 | "pref", |
| 128 | "unset-pref", |
| 129 | "note", |
| 130 | ], |
| 131 | )?; |
| 132 | let expected_revision = number(&f, "expect")?; |
| 133 | let plain_language = match one(&f, "plain-language")? { |
| 134 | None => None, |
| 135 | Some("1") => Some(true), |
| 136 | Some("0") => Some(false), |
| 137 | Some(o) => return Err(format!("--plain-language must be 0 or 1, got {o:?}")), |
| 138 | }; |
| 139 | let changes = Changes { |
| 140 | name: one(&f, "name")?.map(str::to_string), |
| 141 | tone: one(&f, "tone")? |
| 142 | .map(Tone::parse) |
| 143 | .transpose() |
| 144 | .map_err(|e| e.to_string())?, |
| 145 | verbosity: one(&f, "verbosity")? |
| 146 | .map(Verbosity::parse) |
| 147 | .transpose() |
| 148 | .map_err(|e| e.to_string())?, |
| 149 | plain_language, |
| 150 | set_prefs: f |
| 151 | .iter() |
| 152 | .filter(|(k, _)| k == "pref") |
| 153 | .map(|(_, v)| parse_pref(v)) |
| 154 | .collect::<Result<_, _>>()?, |
| 155 | unset_prefs: f |
| 156 | .iter() |
| 157 | .filter(|(k, _)| k == "unset-pref") |
| 158 | .map(|(_, v)| v.clone()) |
| 159 | .collect(), |
| 160 | note: one(&f, "note")?.map(str::to_string), |
| 161 | }; |
| 162 | Ok(ControlCommand::AllenProfileSet { |
| 163 | expected_revision, |
| 164 | changes, |
| 165 | }) |
| 166 | } |
| 167 | "revert" => { |
| 168 | let f = flags(args, &["expect", "to"])?; |
| 169 | Ok(ControlCommand::AllenProfileRevert { |
| 170 | expected_revision: number(&f, "expect")?, |
| 171 | to: number(&f, "to")?, |
| 172 | }) |
| 173 | } |
| 174 | "reset" => { |
| 175 | let f = flags(args, &["expect"])?; |
| 176 | Ok(ControlCommand::AllenProfileReset { |
| 177 | expected_revision: number(&f, "expect")?, |
| 178 | }) |
| 179 | } |
| 180 | other => Err(format!( |
| 181 | "unknown step {other:?} (status, show, set, history, revert, reset, memory, goals)" |
| 182 | )), |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | /// `--context C` or `--owner 1`, exactly one (the daemon checks again). |
| 187 | fn context_or_owner(f: &Flags) -> Result<(Option<String>, bool), String> { |
| 188 | let context = one(f, "context")?.map(str::to_string); |
| 189 | let owner = match one(f, "owner")? { |
| 190 | None => false, |
| 191 | Some("1") => true, |
| 192 | Some(o) => return Err(format!("--owner must be 1, got {o:?}")), |
| 193 | }; |
| 194 | match (&context, owner) { |
| 195 | (None, false) => Err( |
| 196 | "name a context (--context personal|work|project:NAME) or use --owner 1 for every context" |
| 197 | .into(), |
| 198 | ), |
| 199 | (Some(_), true) => Err("give either --context or --owner 1, not both".into()), |
| 200 | _ => Ok((context, owner)), |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | fn required(f: &Flags, k: &str) -> Result<String, String> { |
| 205 | one(f, k)? |
| 206 | .map(str::to_string) |
| 207 | .ok_or_else(|| format!("--{k} is required")) |
| 208 | } |
| 209 | |
| 210 | fn parse_memory(args: &[String]) -> Result<ControlCommand, String> { |
| 211 | let (op, rest) = args.split_first().ok_or( |
| 212 | "usage: aien allen memory <put|recall|inspect|correct|forget|export> --context C ...", |
| 213 | )?; |
| 214 | match op.as_str() { |
| 215 | "put" => { |
| 216 | let f = flags(rest, &["context", "kind", "text"])?; |
| 217 | Ok(ControlCommand::AllenMemoryPut { |
| 218 | context: required(&f, "context")?, |
| 219 | kind: one(&f, "kind")?.unwrap_or("fact").to_string(), |
| 220 | text: required(&f, "text")?, |
| 221 | }) |
| 222 | } |
| 223 | "recall" => { |
| 224 | let f = flags(rest, &["context", "query"])?; |
| 225 | Ok(ControlCommand::AllenMemoryRecall { |
| 226 | context: required(&f, "context")?, |
| 227 | query: one(&f, "query")?.map(str::to_string), |
| 228 | }) |
| 229 | } |
| 230 | "inspect" => { |
| 231 | let f = flags(rest, &["context", "owner"])?; |
| 232 | let (context, owner) = context_or_owner(&f)?; |
| 233 | Ok(ControlCommand::AllenMemoryInspect { context, owner }) |
| 234 | } |
| 235 | "export" => { |
| 236 | let f = flags(rest, &["context", "owner"])?; |
| 237 | let (context, owner) = context_or_owner(&f)?; |
| 238 | Ok(ControlCommand::AllenMemoryExport { context, owner }) |
| 239 | } |
| 240 | "correct" => { |
| 241 | let f = flags(rest, &["context", "item", "text"])?; |
| 242 | Ok(ControlCommand::AllenMemoryCorrect { |
| 243 | context: required(&f, "context")?, |
| 244 | item: required(&f, "item")?, |
| 245 | text: required(&f, "text")?, |
| 246 | }) |
| 247 | } |
| 248 | "forget" => { |
| 249 | let f = flags(rest, &["context", "item", "all-in-context"])?; |
| 250 | let all_in_context = match one(&f, "all-in-context")? { |
| 251 | None => false, |
| 252 | Some("1") => true, |
| 253 | Some(o) => return Err(format!("--all-in-context must be 1, got {o:?}")), |
| 254 | }; |
| 255 | let item = one(&f, "item")?.map(str::to_string); |
| 256 | if item.is_some() == all_in_context { |
| 257 | return Err("give exactly one of --item ID or --all-in-context 1".into()); |
| 258 | } |
| 259 | Ok(ControlCommand::AllenMemoryForget { |
| 260 | context: required(&f, "context")?, |
| 261 | item, |
| 262 | all_in_context, |
| 263 | }) |
| 264 | } |
| 265 | other => Err(format!( |
| 266 | "unknown memory step {other:?} (put, recall, inspect, correct, forget, export)" |
| 267 | )), |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | fn parse_goals(args: &[String]) -> Result<ControlCommand, String> { |
| 272 | let (op, rest) = args |
| 273 | .split_first() |
| 274 | .ok_or("usage: aien allen goals <list|add|close> --context C ...")?; |
| 275 | match op.as_str() { |
| 276 | "list" => { |
| 277 | let f = flags(rest, &["context", "owner"])?; |
| 278 | let (context, owner) = context_or_owner(&f)?; |
| 279 | Ok(ControlCommand::AllenGoalsList { context, owner }) |
| 280 | } |
| 281 | "add" => { |
| 282 | let f = flags(rest, &["context", "text"])?; |
| 283 | Ok(ControlCommand::AllenGoalAdd { |
| 284 | context: required(&f, "context")?, |
| 285 | text: required(&f, "text")?, |
| 286 | }) |
| 287 | } |
| 288 | "close" => { |
| 289 | let f = flags(rest, &["context", "item"])?; |
| 290 | Ok(ControlCommand::AllenGoalClose { |
| 291 | context: required(&f, "context")?, |
| 292 | item: required(&f, "item")?, |
| 293 | }) |
| 294 | } |
| 295 | other => Err(format!("unknown goals step {other:?} (list, add, close)")), |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | fn to_json<T: serde::Serialize>(v: &T) -> Result<Value, String> { |
| 300 | serde_json::to_value(v).map_err(|e| e.to_string()) |
| 301 | } |
| 302 | |
| 303 | /// Daemon answer to the one printed JSON object. `Err` = the call failed. |
| 304 | fn render(sub: &str, r: ControlResponse) -> Result<Value, Value> { |
| 305 | let ok = |body: Value| { |
| 306 | let mut v = json!({"ok": true, "step": sub}); |
| 307 | v["result"] = body; |
| 308 | Ok(v) |
| 309 | }; |
| 310 | match r { |
| 311 | ControlResponse::AllenStatusReport(x) => ok(to_json(&*x).unwrap_or(Value::Null)), |
| 312 | ControlResponse::AllenProfile(x) => ok(to_json(&*x).unwrap_or(Value::Null)), |
| 313 | ControlResponse::AllenHistory(x) => ok(to_json(&*x).unwrap_or(Value::Null)), |
| 314 | ControlResponse::AllenMemoryResult(x) => ok(to_json(&*x).unwrap_or(Value::Null)), |
| 315 | ControlResponse::AllenRefused(x) => Err(json!({ |
| 316 | "ok": false, |
| 317 | "step": sub, |
| 318 | "refused": to_json(&*x).unwrap_or(Value::Null), |
| 319 | "changed": false, |
| 320 | })), |
| 321 | ControlResponse::Error(e) => Err(json!({"ok": false, "step": sub, "error": e})), |
| 322 | other => Err(json!({ |
| 323 | "ok": false, "step": sub, "error": format!("unexpected response {other:?}"), |
| 324 | })), |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | pub async fn handle_allen_command(args: &[String]) { |
| 329 | let Some(sub) = args.first() else { |
| 330 | println!( |
| 331 | "{}", |
| 332 | json!({"ok": false, "error": "usage: aien allen <status|show|set|history|revert|reset|memory|goals> [--flag value ...]"}) |
| 333 | ); |
| 334 | std::process::exit(1); |
| 335 | }; |
| 336 | let cmd = match parse(sub, &args[1..]) { |
| 337 | Ok(c) => c, |
| 338 | Err(e) => { |
| 339 | println!("{}", json!({"ok": false, "step": sub, "error": e})); |
| 340 | std::process::exit(1); |
| 341 | } |
| 342 | }; |
| 343 | let out = match AienRuntimeClient::default_client().send_command(cmd).await { |
| 344 | Ok(r) => render(sub, r), |
| 345 | // The daemon is a separate process. Not reaching it says nothing about |
| 346 | // the identity or the saved profile; both stay on disk. |
| 347 | Err(e) => Err(json!({ |
| 348 | "ok": false, |
| 349 | "step": sub, |
| 350 | "daemon": "unreachable", |
| 351 | "error": e, |
| 352 | "note": "temporary: the daemon is not reachable. Your identity and saved profile are not lost or changed.", |
| 353 | })), |
| 354 | }; |
| 355 | match out { |
| 356 | Ok(v) => println!("{v}"), |
| 357 | Err(v) => { |
| 358 | println!("{v}"); |
| 359 | std::process::exit(1); |
| 360 | } |
| 361 | } |
| 362 | } |
| 363 | |
| 364 | #[cfg(test)] |
| 365 | mod tests { |
| 366 | use super::*; |
| 367 | |
| 368 | fn a(s: &[&str]) -> Vec<String> { |
| 369 | s.iter().map(|x| x.to_string()).collect() |
| 370 | } |
| 371 | |
| 372 | #[test] |
| 373 | fn set_requires_expect() { |
| 374 | let e = parse("set", &a(&["--name", "Nova"])).unwrap_err(); |
| 375 | assert!(e.contains("--expect is required"), "{e}"); |
| 376 | assert!(parse("reset", &a(&[])).is_err()); |
| 377 | assert!(parse("revert", &a(&["--to", "1"])).is_err()); |
| 378 | } |
| 379 | |
| 380 | #[test] |
| 381 | fn set_parses_every_field() { |
| 382 | let c = parse( |
| 383 | "set", |
| 384 | &a(&[ |
| 385 | "--expect", |
| 386 | "3", |
| 387 | "--name", |
| 388 | "Nova", |
| 389 | "--tone", |
| 390 | "warm", |
| 391 | "--verbosity", |
| 392 | "brief", |
| 393 | "--plain-language", |
| 394 | "1", |
| 395 | "--pref", |
| 396 | "units=metric@work", |
| 397 | "--pref", |
| 398 | "mail=a@b.example", |
| 399 | "--unset-pref", |
| 400 | "old", |
| 401 | "--note", |
| 402 | "why", |
| 403 | ]), |
| 404 | ) |
| 405 | .unwrap(); |
| 406 | let ControlCommand::AllenProfileSet { |
| 407 | expected_revision, |
| 408 | changes, |
| 409 | } = c |
| 410 | else { |
| 411 | panic!() |
| 412 | }; |
| 413 | assert_eq!(expected_revision, 3); |
| 414 | assert_eq!(changes.name.as_deref(), Some("Nova")); |
| 415 | assert_eq!(changes.tone, Some(Tone::Warm)); |
| 416 | assert_eq!(changes.plain_language, Some(true)); |
| 417 | assert_eq!(changes.set_prefs[0].scope, Scope::Work); |
| 418 | assert_eq!(changes.set_prefs[0].value, "metric"); |
| 419 | // '@' that is not a scope stays in the value. |
| 420 | assert_eq!(changes.set_prefs[1].value, "a@b.example"); |
| 421 | assert_eq!(changes.set_prefs[1].scope, Scope::All); |
| 422 | assert_eq!(changes.unset_prefs, vec!["old".to_string()]); |
| 423 | } |
| 424 | |
| 425 | #[test] |
| 426 | fn bad_input_is_refused_before_any_call() { |
| 427 | for bad in [ |
| 428 | vec!["--expect", "x"], |
| 429 | vec!["--expect", "1", "--tone", "grumpy"], |
| 430 | vec!["--expect", "1", "--plain-language", "yes"], |
| 431 | vec!["--expect", "1", "--pref", "novalue"], |
| 432 | vec!["--expect", "1", "--avatar", "cat"], |
| 433 | vec!["--expect", "1", "--expect", "2"], |
| 434 | ] { |
| 435 | assert!(parse("set", &a(&bad)).is_err(), "{bad:?}"); |
| 436 | } |
| 437 | assert!(parse("status", &a(&["--x", "1"])).is_err()); |
| 438 | assert!(parse("nope", &a(&[])).is_err()); |
| 439 | } |
| 440 | |
| 441 | #[test] |
| 442 | fn memory_and_goal_calls_must_name_a_context() { |
| 443 | for bad in [ |
| 444 | vec!["put", "--text", "x"], |
| 445 | vec!["recall"], |
| 446 | vec!["inspect"], |
| 447 | vec!["export"], |
| 448 | vec!["inspect", "--context", "work", "--owner", "1"], |
| 449 | vec!["inspect", "--owner", "yes"], |
| 450 | vec!["forget", "--context", "work"], |
| 451 | vec![ |
| 452 | "forget", |
| 453 | "--context", |
| 454 | "work", |
| 455 | "--item", |
| 456 | "a", |
| 457 | "--all-in-context", |
| 458 | "1", |
| 459 | ], |
| 460 | vec![ |
| 461 | "put", |
| 462 | "--context", |
| 463 | "work", |
| 464 | "--scope", |
| 465 | "personal", |
| 466 | "--text", |
| 467 | "x", |
| 468 | ], |
| 469 | ] { |
| 470 | assert!(parse("memory", &a(&bad)).is_err(), "{bad:?}"); |
| 471 | } |
| 472 | for bad in [ |
| 473 | vec!["list"], |
| 474 | vec!["add", "--text", "g"], |
| 475 | vec!["close", "--item", "i"], |
| 476 | ] { |
| 477 | assert!(parse("goals", &a(&bad)).is_err(), "{bad:?}"); |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | #[test] |
| 482 | fn memory_calls_parse() { |
| 483 | let c = parse( |
| 484 | "memory", |
| 485 | &a(&[ |
| 486 | "put", |
| 487 | "--context", |
| 488 | "project:a", |
| 489 | "--kind", |
| 490 | "preference", |
| 491 | "--text", |
| 492 | "t", |
| 493 | ]), |
| 494 | ) |
| 495 | .unwrap(); |
| 496 | assert!(matches!( |
| 497 | c, |
| 498 | ControlCommand::AllenMemoryPut { ref context, ref kind, .. } |
| 499 | if context == "project:a" && kind == "preference" |
| 500 | )); |
| 501 | let c = parse("memory", &a(&["inspect", "--owner", "1"])).unwrap(); |
| 502 | assert!(matches!( |
| 503 | c, |
| 504 | ControlCommand::AllenMemoryInspect { |
| 505 | context: None, |
| 506 | owner: true |
| 507 | } |
| 508 | )); |
| 509 | let c = parse("goals", &a(&["list", "--context", "work"])).unwrap(); |
| 510 | assert!(matches!( |
| 511 | c, |
| 512 | ControlCommand::AllenGoalsList { |
| 513 | context: Some(_), |
| 514 | owner: false |
| 515 | } |
| 516 | )); |
| 517 | } |
| 518 | } |