interplane.Get Omega
Read in your language

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

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-runtime / tests / allen_persona_test.rs

577 lines · 20243 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//! ALLEN persona profile (arch#159) in the runtime. FIXTURE-ONLY: identities
17//! come from the test-only subject encoder in aien-allen/tests/support, resolved
18//! through the production resolver. No model runs.
19//!
20//! Part A needs no composition library and always runs. Part B (marked
21//! `b_*`) re-executes this binary against a real compose home and reports
22//! NOT_RUN in a stub omega build, like allen_spine_test.
23#[path = "support/home_guard.rs"]
24mod home_guard;
25
26#[path = "../../aien-allen/tests/support/mod.rs"]
27mod support;
28
29use aien_allen::binding::pin_path;
30use aien_allen::deployment::{self, Input};
31use aien_allen::resolve::{resolve, Context, Resolved, SubjectSource};
32use aien_allen::{hex, ENV_ADOPT, ENV_SUBJECT};
33use aien_allen_profile::{profile_dir, Changes, Identity, Store, Tone};
34use aien_omega_compose::LINKED;
35use aien_runtime::control::{ComposeTaskReport, ControlCommand, ControlResponse, PersonaReport};
36use aien_runtime::persona::{context_for, handle_allen_command, prefix_prompt, report_for};
37use aien_runtime::{ComposeBridge, ComposeProposer, Generation};
38use std::path::{Path, PathBuf};
39use std::process::Command;
40use std::sync::Arc;
41
42struct Rig {
43 _t: tempfile::TempDir,
44 home: PathBuf,
45 r: Resolved,
46}
47
48fn rig() -> Rig {
49 let t = tempfile::tempdir().unwrap();
50 let f = support::fx("persona");
51 let c = support::chain(&f, 2);
52 let subj = support::write_head(&t.path().join("subject.bin"), c.last().unwrap());
53 let home = t.path().join("compose");
54 let r = resolve(
55 &SubjectSource::Head(subj),
56 &pin_path(&home),
57 &Context {
58 machine_id: [1; 32],
59 lineage: Some(f.cortex),
60 },
61 Some(&hex(&f.agent)),
62 )
63 .unwrap();
64 Rig { _t: t, home, r }
65}
66
67fn set(expected: u64, ch: Changes) -> ControlCommand {
68 ControlCommand::AllenProfileSet {
69 expected_revision: expected,
70 changes: ch,
71 }
72}
73
74fn name(n: &str) -> Changes {
75 Changes {
76 name: Some(n.into()),
77 ..Default::default()
78 }
79}
80
81fn run(rig: &Rig, cmd: ControlCommand) -> ControlResponse {
82 handle_allen_command(&rig.home, Some(&rig.r), "model:test", &cmd)
83}
84
85fn profile(r: ControlResponse) -> aien_runtime::control::AllenProfileReport {
86 match r {
87 ControlResponse::AllenProfile(p) => *p,
88 o => panic!("expected AllenProfile, got {o:?}"),
89 }
90}
91
92fn refusal(r: ControlResponse) -> aien_runtime::control::AllenRefusalReport {
93 match r {
94 ControlResponse::AllenRefused(p) => *p,
95 o => panic!("expected AllenRefused, got {o:?}"),
96 }
97}
98
99fn dir_bytes(d: &Path) -> Vec<(String, Vec<u8>)> {
100 let mut v: Vec<_> = std::fs::read_dir(d)
101 .unwrap()
102 .map(|e| {
103 let e = e.unwrap();
104 (
105 e.file_name().to_string_lossy().into_owned(),
106 std::fs::read(e.path()).unwrap(),
107 )
108 })
109 .collect();
110 v.sort();
111 v
112}
113
114#[test]
115fn not_engaged_refuses_profile_commands_and_changes_nothing() {
116 let t = tempfile::tempdir().unwrap();
117 let home = t.path().join("compose");
118 for cmd in [
119 ControlCommand::AllenProfileShow,
120 ControlCommand::AllenProfileHistory,
121 set(0, name("Nova")),
122 ControlCommand::AllenProfileRevert {
123 expected_revision: 1,
124 to: 1,
125 },
126 ControlCommand::AllenProfileReset {
127 expected_revision: 1,
128 },
129 ] {
130 let r = refusal(handle_allen_command(&home, None, "model:test", &cmd));
131 assert_eq!(r.code, "not_engaged");
132 assert!(r.message.contains("not engaged"));
133 }
134 assert!(!profile_dir(&home).exists());
135 // Status still answers, and says so.
136 match handle_allen_command(&home, None, "model:test", &ControlCommand::AllenStatus) {
137 ControlResponse::AllenStatusReport(s) => {
138 assert_eq!(s.identity, "not_engaged");
139 assert_eq!(s.persona.state, "not_engaged");
140 assert!(s.fingerprint.is_none());
141 assert_eq!(s.unsupported, vec!["avatar", "voice"]);
142 }
143 o => panic!("{o:?}"),
144 }
145 // The task prompt is byte-identical when ALLEN is not engaged.
146 assert!(context_for(&home, None).is_none());
147 assert_eq!(prefix_prompt("PROMPT", None), "PROMPT");
148}
149
150#[test]
151fn engaged_set_show_history_revert_reset_and_stale() {
152 let rig = rig();
153 let p = profile(run(&rig, ControlCommand::AllenProfileShow));
154 assert_eq!((p.revision, p.state.as_str()), (0, "default"));
155 assert_eq!(p.defaults.unwrap().display_name, "ALLEN");
156
157 let ch = Changes {
158 name: Some("Nova".into()),
159 tone: Some(Tone::Warm),
160 ..Default::default()
161 };
162 let p = profile(run(&rig, set(0, ch)));
163 assert_eq!(p.revision, 1);
164 // Stale expect: refused, the current revision is reported, nothing written.
165 let e = refusal(run(&rig, set(0, name("Other"))));
166 assert_eq!(
167 (e.code.as_str(), e.current_revision),
168 ("stale_update", Some(1))
169 );
170 assert!(e.message.contains("--expect 1"));
171 profile(run(&rig, set(1, name("Echo"))));
172 match run(&rig, ControlCommand::AllenProfileHistory) {
173 ControlResponse::AllenHistory(h) => assert_eq!(h.entries.len(), 2),
174 o => panic!("{o:?}"),
175 }
176 let p = profile(run(
177 &rig,
178 ControlCommand::AllenProfileRevert {
179 expected_revision: 2,
180 to: 1,
181 },
182 ));
183 assert_eq!(p.profile.unwrap().persona.display_name, "Nova");
184 let p = profile(run(
185 &rig,
186 ControlCommand::AllenProfileReset {
187 expected_revision: 3,
188 },
189 ));
190 assert_eq!(p.profile.unwrap().persona.display_name, "ALLEN");
191 // Status shows identity and profile separately; the identity never moved.
192 match run(&rig, ControlCommand::AllenStatus) {
193 ControlResponse::AllenStatusReport(s) => {
194 assert_eq!(s.identity, "engaged");
195 assert_eq!(s.fingerprint.as_deref(), Some(&hex(&rig.r.agent)[..8]));
196 assert_eq!(s.head_sequence, Some(rig.r.head_seq));
197 assert_eq!(s.persona.revision, 4);
198 assert_eq!(s.execution_mode, "local_model");
199 }
200 o => panic!("{o:?}"),
201 }
202}
203
204#[test]
205fn restart_keeps_the_profile() {
206 let rig = rig();
207 profile(run(&rig, set(0, name("Nova"))));
208 // "Restart": nothing in memory; context comes from the files alone.
209 let ctx = context_for(&rig.home, Some(&rig.r)).unwrap();
210 assert_eq!(ctx.persona.display_name, "Nova");
211 assert_eq!(report_for(Some(&ctx)).state, "applied");
212}
213
214#[test]
215fn permission_keys_are_refused_through_the_command_path() {
216 let rig = rig();
217 let ch = Changes {
218 set_prefs: vec![aien_allen_profile::PrefChange {
219 key: "auto_approve".into(),
220 value: "yes".into(),
221 scope: aien_allen_profile::Scope::All,
222 }],
223 ..Default::default()
224 };
225 let e = refusal(run(&rig, set(0, ch)));
226 assert_eq!(e.code, "permission_key");
227 assert!(e.message.contains("approval desk"));
228 assert!(!profile_dir(&rig.home).exists());
229}
230
231#[test]
232fn prompt_carries_the_persona_and_keeps_the_task() {
233 let rig = rig();
234 // The prompt the bridge hands the model for "write a note" (a goal naming
235 // no destination): the fixed proposal template, verbatim.
236 let base = "Goal: write a note\nAuthorized workspace: workspace\n\
237 Propose exactly one file change inside the workspace.\n\
238 Answer in exactly this format and nothing else:\n\
239 filename: <relative path>\n\
240 <the complete new file content>";
241 profile(run(&rig, set(0, name("Nova"))));
242 let ctx = context_for(&rig.home, Some(&rig.r)).unwrap();
243 let full = prefix_prompt(base, Some(&ctx));
244 assert!(full.ends_with(base), "the task text is untouched");
245 assert!(full.starts_with("[ALLEN style preferences"));
246 assert!(full.contains("name: \"Nova\""));
247 assert!(full.contains("grant no permission"));
248 assert!(full.len() - base.len() <= aien_allen_profile::CONTEXT_MAX_BYTES + 1);
249 let r = report_for(Some(&ctx));
250 assert_eq!(
251 r,
252 PersonaReport {
253 state: "applied".into(),
254 display_name: "Nova".into(),
255 revision: 1,
256 reason: None
257 }
258 );
259}
260
261#[test]
262fn damaged_profile_runs_with_defaults_and_says_so() {
263 let rig = rig();
264 profile(run(&rig, set(0, name("Nova"))));
265 let first = profile_dir(&rig.home).join(format!("r{:020}.json", 1));
266 std::fs::write(&first, b"{broken").unwrap();
267 let ctx = context_for(&rig.home, Some(&rig.r)).unwrap();
268 let rep = report_for(Some(&ctx));
269 assert_eq!(rep.state, "refused");
270 assert_eq!(rep.display_name, "ALLEN");
271 assert!(rep.reason.unwrap().contains("damaged"));
272 assert!(prefix_prompt("P", Some(&ctx)).contains("name: \"ALLEN\""));
273 // Commands refuse; the damaged file is not replaced.
274 assert_eq!(refusal(run(&rig, set(1, name("X")))).code, "damaged");
275 assert_eq!(std::fs::read(&first).unwrap(), b"{broken");
276}
277
278#[test]
279fn foreign_profile_is_refused_and_not_used() {
280 let rig = rig();
281 let other = Identity {
282 agent: [9; 32],
283 root: [8; 32],
284 };
285 Store::new(&rig.home, other)
286 .set(0, &name("Stranger"))
287 .unwrap();
288 let ctx = context_for(&rig.home, Some(&rig.r)).unwrap();
289 assert_eq!(report_for(Some(&ctx)).state, "refused");
290 assert_eq!(ctx.persona.display_name, "ALLEN");
291 assert_eq!(
292 refusal(run(&rig, set(1, name("X")))).code,
293 "foreign_profile"
294 );
295}
296
297#[test]
298fn a_model_swap_record_leaves_the_profile_untouched() {
299 let rig = rig();
300 profile(run(&rig, set(0, name("Nova"))));
301 let before = dir_bytes(&profile_dir(&rig.home));
302 let dep = deployment::deployments_path(&rig.home);
303 for (i, model) in ["aa", "bb"].iter().enumerate() {
304 deployment::append(
305 &dep,
306 &rig.r.agent,
307 Input {
308 model_sha256: model.repeat(32),
309 config_sha256: "cc".repeat(32),
310 candidate_id: format!("cand-{i}"),
311 executable_sha256: "dd".repeat(32),
312 revision: "r".into(),
313 placeholder: true,
314 },
315 )
316 .unwrap();
317 }
318 assert_eq!(before, dir_bytes(&profile_dir(&rig.home)));
319 let ctx = context_for(&rig.home, Some(&rig.r)).unwrap();
320 assert_eq!(ctx.persona.display_name, "Nova");
321 match run(&rig, ControlCommand::AllenStatus) {
322 ControlResponse::AllenStatusReport(s) => {
323 let d = s.deployment.unwrap();
324 assert_eq!((d.seq, d.candidate_id.as_str()), (2, "cand-1"));
325 assert_eq!(s.persona.display_name, "Nova");
326 }
327 o => panic!("{o:?}"),
328 }
329}
330
331/// Every file under `dir`, subdirectories included.
332fn rs_tree(dir: &Path) -> Vec<PathBuf> {
333 let mut out = Vec::new();
334 for ent in std::fs::read_dir(dir).unwrap() {
335 let p = ent.unwrap().path();
336 if p.is_dir() {
337 out.extend(rs_tree(&p));
338 } else {
339 out.push(p);
340 }
341 }
342 out
343}
344
345/// No code path from a task, a model reply or a workspace file to the profile
346/// writer: only the operator-command handler in persona.rs calls a writer,
347/// and nothing else in the runtime even names the profile crate's store.
348#[test]
349fn only_the_command_handler_can_write_the_profile() {
350 let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
351 for p in rs_tree(&src) {
352 let name = p.file_name().unwrap().to_string_lossy().into_owned();
353 let text = std::fs::read_to_string(&p).unwrap();
354 if name != "persona.rs" && name != "control.rs" {
355 assert!(
356 !text.contains("aien_allen_profile"),
357 "{name} must not touch the profile crate"
358 );
359 }
360 }
361 let persona = std::fs::read_to_string(src.join("persona.rs")).unwrap();
362 let ctx_fn = persona
363 .split("pub fn context_for")
364 .nth(1)
365 .unwrap()
366 .split("pub fn report_for")
367 .next()
368 .unwrap();
369 for w in [".set(", ".revert(", ".reset(", "write"] {
370 assert!(!ctx_fn.contains(w), "context_for must be read-only ({w})");
371 }
372 // The compose bridge calls the handler only for operator control commands.
373 let bridge = std::fs::read_to_string(src.join("compose/bridge.rs")).unwrap();
374 assert!(bridge.contains("handle_allen_command"));
375}
376
377#[test]
378fn old_reports_without_persona_still_parse() {
379 let report = ComposeTaskReport {
380 compose_commit: None,
381 generation_record: None,
382 compose_dir: "d".into(),
383 machine_id: "m".into(),
384 task: 1,
385 outcome: 1,
386 committed: true,
387 branch_count: 1,
388 branches_reclaimed: 1,
389 winner: Some(0),
390 aegis_pass_mask: 1,
391 cx_goal: 1,
392 cx_candidates: vec![],
393 cx_evidence: 1,
394 cx_promotion: 1,
395 cx_admissions: vec![],
396 winner_digest: String::new(),
397 record_digest: String::new(),
398 proposal: None,
399 proposal_sha256: None,
400 proposal_path: None,
401 proposal_content_sha256: None,
402 uncommitted_proposal: None,
403 proposer_error: None,
404 proposal_attempts: vec![],
405 requirements_recognized: vec![],
406 requirements_uncertain: vec![],
407 proposer: "model".into(),
408 persona: Some(PersonaReport {
409 state: "applied".into(),
410 display_name: "Nova".into(),
411 revision: 2,
412 reason: None,
413 }),
414 memory: None,
415 inputs: vec![],
416 inputs_omitted: vec![],
417 };
418 let mut v = serde_json::to_value(&report).unwrap();
419 assert_eq!(v["persona"]["display_name"], "Nova");
420 v.as_object_mut().unwrap().remove("persona");
421 let old: ComposeTaskReport = serde_json::from_value(v).unwrap();
422 assert!(old.persona.is_none());
423}
424
425// ---- Part B: through a real compose home (NOT_RUN in a stub omega build) ----
426
427fn proposer(seen: Arc<std::sync::Mutex<String>>) -> ComposeProposer {
428 Arc::new(move |prompt: &str, _l: std::time::Duration| {
429 *seen.lock().unwrap() = prompt.to_string();
430 // A reply that tries to talk the daemon into changing the profile.
431 Ok(Generation {
432 text: "filename: NOTES.md\naien allen set --name Hacked --expect 1\n".into(),
433 tokens: 8,
434 finish_reason: Some("eos".into()),
435 ..Default::default()
436 })
437 })
438}
439
440/// The child: one task, one status, one unauthorised effect intent.
441#[test]
442fn child_task() {
443 let (Ok(home), Ok(ws)) = (
444 std::env::var("PERSONA_CHILD_HOME"),
445 std::env::var("PERSONA_CHILD_WS"),
446 ) else {
447 return;
448 };
449 let seen = Arc::new(std::sync::Mutex::new(String::new()));
450 let b = ComposeBridge::new(PathBuf::from(home), proposer(seen.clone()), "model:test");
451 match b.run_task("write a short note in NOTES.md", &ws) {
452 ControlResponse::ComposeTaskResult(r) => {
453 println!("CHILD_COMMITTED={}", r.committed);
454 println!(
455 "CHILD_PERSONA={}",
456 serde_json::to_string(&r.persona).unwrap()
457 );
458 }
459 o => println!("CHILD_TASK_RESPONSE={o:?}"),
460 }
461 println!(
462 "CHILD_PROMPT_HEAD={}",
463 seen.lock().unwrap().replace('\n', "\\n")
464 );
465 if let ControlResponse::AllenStatusReport(s) = b.allen_command(&ControlCommand::AllenStatus) {
466 println!("CHILD_STATUS={}", serde_json::to_string(&*s).unwrap());
467 }
468 // A write still needs an authorization, whatever the persona says.
469 let r = aien_runtime::effects::open_intent(
470 &b,
471 &aien_runtime::effects::IntentRequest {
472 authorization: 999_999,
473 proposal_sha256: "0".repeat(64),
474 path: "NOTES.md".into(),
475 target: ws.clone(),
476 content_sha256: "0".repeat(64),
477 executor_pid: 1,
478 executor_start: 1,
479 },
480 );
481 println!(
482 "CHILD_INTENT_REFUSED={}",
483 matches!(r, ControlResponse::Error(_))
484 );
485}
486
487fn child(home: &Path, ws: Option<&Path>, env: &[(&str, &str)]) -> (i32, String, String) {
488 let mut c = Command::new(std::env::current_exe().unwrap());
489 c.args(["--exact", "child_task", "--nocapture", "--test-threads=1"])
490 .env("PERSONA_CHILD_HOME", home)
491 .env_remove(ENV_SUBJECT)
492 .env_remove(ENV_ADOPT);
493 if let Some(w) = ws {
494 c.env("PERSONA_CHILD_WS", w);
495 } else {
496 c.env("PERSONA_CHILD_WS", home.parent().unwrap());
497 }
498 for (k, v) in env {
499 c.env(k, v);
500 }
501 let o = c.output().unwrap();
502 (
503 o.status.code().unwrap_or(-1),
504 String::from_utf8_lossy(&o.stdout).into_owned(),
505 String::from_utf8_lossy(&o.stderr).into_owned(),
506 )
507}
508
509#[test]
510fn b_engaged_task_uses_the_persona_and_a_reply_cannot_change_it() {
511 let _home = home_guard::home_slot();
512 if !LINKED {
513 println!("NOT_RUN: stub omega build (no librx_compose.a); set AIEN_OMEGA_COMPOSE_DIR");
514 return;
515 }
516 let t = tempfile::tempdir().unwrap();
517 let home = t.path().join("compose");
518 let ws = t.path().join("ws");
519 std::fs::create_dir_all(&ws).unwrap();
520 // Not engaged first: creates the home, no persona text, report says so.
521 let (code, out, err) = child(&home, Some(&ws), &[]);
522 assert_eq!(code, 0, "{out}{err}");
523 assert!(out.contains("\"state\":\"not_engaged\""), "{out}");
524 assert!(!out.contains("ALLEN style preferences"), "{out}");
525 // Engage: subject built for this home's Cortex lineage, adopted once.
526 let mut name = home.as_os_str().to_owned();
527 name.push(".machine-root");
528 let root = std::fs::read(PathBuf::from(name)).unwrap();
529 let (mut c, _) = aien_omega_compose::Compose::open(
530 &home,
531 aien_omega_compose::RootKind::Provisioned,
532 &root,
533 0xA1E4_0001,
534 )
535 .unwrap();
536 let lineage = c.record(1).unwrap().digest;
537 drop(c);
538 let mut f = support::fx("persona-b");
539 f.cortex = lineage;
540 let chain = support::chain(&f, 2);
541 let subj = support::write_head(&t.path().join("subject.bin"), chain.last().unwrap());
542 let env = [
543 (ENV_SUBJECT, subj.to_str().unwrap()),
544 (ENV_ADOPT, &hex(&f.agent)[..]),
545 ];
546 // Adoption run (no profile yet): defaults, state "default".
547 let (code, out, err) = child(&home, Some(&ws), &env);
548 assert_eq!(code, 0, "{out}{err}");
549 assert!(out.contains("\"state\":\"default\""), "{out}");
550 assert!(out.contains("CHILD_INTENT_REFUSED=true"), "{out}");
551 // Save a profile, run again.
552 let store = Store::new(
553 &home,
554 Identity {
555 agent: f.agent,
556 root: f.root,
557 },
558 );
559 store.set(0, &name_change("Nova")).unwrap();
560 let before = dir_bytes(&profile_dir(&home));
561 let (code, out, err) = child(&home, Some(&ws), &[(ENV_SUBJECT, subj.to_str().unwrap())]);
562 assert_eq!(code, 0, "{out}{err}");
563 assert!(
564 out.contains("\"state\":\"applied\"") && out.contains("\"display_name\":\"Nova\""),
565 "{out}"
566 );
567 assert!(out.contains("name: \"Nova\"\\ntone: neutral"), "{out}");
568 assert!(out.contains("CHILD_INTENT_REFUSED=true"), "{out}");
569 assert!(out.contains("\"identity\":\"engaged\""), "{out}");
570 // The model reply asked for a rename; the profile did not move.
571 assert_eq!(before, dir_bytes(&profile_dir(&home)));
572 assert!(!ws.join("NOTES.md").exists(), "no write without authorize");
573}
574
575fn name_change(n: &str) -> Changes {
576 name(n)
577}