diff --git a/.crumb b/.crumb index 83318be9..02035558 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:c5269f93385287c09996ff41f0247f72de9237a2317f47c94c51273d6a0acef1", - "compiled_at": "2026-10-08T00:26:00Z", + "compiled_at": "2026-10-08T01:03:32Z", "compiler": "crumb-compile/1", - "digest": "sha256:1954daabc1a9e3711344a840a77f8eb73e52a8225964e708a73ffbc737aba410", + "digest": "sha256:05a58e3c29a88c25f0cc5a31f5c1dccec1f79342ce811f9ba19e4b02ad3a0c81", "evidence_files": 186, "evidence_root": "sha256:fbe849218d18dc4b21a74410fdd8f7d98431a1d0123a0c69264386f770da4db4", - "files": 1320, - "generated_at_commit": "0732b6dd9530903eb47dcc0c5c2d2670b7875726", - "source_tree": "sha256:a333c601db9df31b7fbf8543839222e6245571fd8f62d37ab6b5cf4d1b11cbcc" + "files": 1332, + "generated_at_commit": "65edba04eb654df6123345163631cacae780d7e6", + "source_tree": "sha256:791727683d76080cfff2b5c6b8946ca8ab870f8e80433815c0eee897e700a0fb" } }, "history": [], diff --git a/Cargo.lock b/Cargo.lock index 3194199b..98f1095c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -44,6 +44,18 @@ dependencies = [ "tempfile", ] +[[package]] +name = "aien-allen-profile" +version = "0.1.0" +dependencies = [ + "aien-allen", + "aien-allen-profile", + "serde", + "serde_json", + "sha2 0.10.9", + "tempfile", +] + [[package]] name = "aien-campaign-verifier" version = "0.1.0" @@ -65,6 +77,7 @@ dependencies = [ name = "aien-cli" version = "0.1.0" dependencies = [ + "aien-allen-profile", "aien-inference-abi", "aien-kv-cache", "aien-omega-compose", @@ -303,6 +316,7 @@ version = "0.1.0" dependencies = [ "aien-abi-core", "aien-allen", + "aien-allen-profile", "aien-inference-abi", "aien-kv-cache", "aien-omega-compose", diff --git a/Cargo.toml b/Cargo.toml index 96999ae3..6207d830 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -42,6 +42,7 @@ members = [ "crates/aien-switchboard", "crates/aien-dual-observation", "crates/aien-allen", + "crates/aien-allen-profile", "tools/aien-test", "crates/aien-drive", ] diff --git a/crates/aien-allen-profile/.crumb b/crates/aien-allen-profile/.crumb new file mode 100644 index 00000000..50b6bffb --- /dev/null +++ b/crates/aien-allen-profile/.crumb @@ -0,0 +1,19 @@ +{ + "extensions": { + "generated": { + "children": [], + "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "compiled_at": "2026-10-08T01:03:32Z", + "compiler": "crumb-compile/1", + "digest": "sha256:cd47dee5280a769dfc65a68275cc8a78b68392024f4d2bf25bd57383bce5c32a", + "evidence_files": 0, + "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "files": 8, + "generated_at_commit": "65edba04eb654df6123345163631cacae780d7e6", + "source_tree": "sha256:595d7155fdeb036754b502b29a8b30aeed0a229de41c8631cb935e995d6e8ea7" + } + }, + "name": "aien-allen-profile", + "purpose": "ALLEN persona profile v1: versioned, user-editable profile bound to the engaged ALLEN identity; the only writer of .allen-profile (arch#159).", + "schema_version": "1.0.0" +} diff --git a/crates/aien-allen-profile/Cargo.toml b/crates/aien-allen-profile/Cargo.toml new file mode 100644 index 00000000..94016b8a --- /dev/null +++ b/crates/aien-allen-profile/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "aien-allen-profile" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +repository.workspace = true +description = "ALLEN persona profile v1: versioned, user-editable profile bound to the existing ALLEN identity (arch#159)" + +[dependencies] +aien-allen = { path = "../aien-allen" } +sha2 = "0.10" +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" + +[features] +# Test seam: lets a test stop the write sequence at a named step (simulated +# crash). Enabled only by the dev-dependency below, never by a daemon build. +fault-injection = [] + +[dev-dependencies] +tempfile = "3.10" +aien-allen-profile = { path = ".", features = ["fault-injection"] } diff --git a/crates/aien-allen-profile/README.md b/crates/aien-allen-profile/README.md new file mode 100644 index 00000000..d0705850 --- /dev/null +++ b/crates/aien-allen-profile/README.md @@ -0,0 +1,106 @@ +# aien-allen-profile + +A small profile you can change for your ALLEN: a name, a tone, how much it says, +whether it keeps to plain language, and a few working preferences. It is tied to +your ALLEN identity, but it is not the identity. Renaming ALLEN never changes +who it is. + +Tracks aien-dev/aien-architecture#159. This is version 1, host side only. + +## What you can change + +| Setting | Allowed values | +| --- | --- | +| name | 1 to 64 characters, one line. Default `ALLEN`. | +| tone | `neutral` (default), `warm`, `direct`, `formal` | +| verbosity | `brief`, `normal` (default), `detailed` | +| plain language | on or off (default off) | +| preferences | up to 32 of `key=value`, value up to 200 characters, scope `all`, `personal`, `work` or `project` | + +Preference keys use lowercase letters, digits, `_`, `.` and `-` (up to 48 +characters). A key that contains grant, permission, approve, capability, allow +or authori is refused: permissions are not profile fields, approvals go through +the approval desk. + +## How to use it + +The daemon owns the profile. You talk to it with `aien allen`. Each call prints +one JSON object and exits 1 on failure. + +```text +aien allen status +aien allen show +aien allen set --expect 0 --name Nova --tone warm --pref units=metric@work +aien allen history +aien allen revert --to 1 --expect 3 +aien allen reset --expect 4 +``` + +Every change needs `--expect ` (0 when nothing is saved +yet). If the profile moved since, the change is refused and nothing is written. +`set` also takes `--verbosity`, `--plain-language 0|1`, `--unset-pref KEY` and +`--note TEXT`. Undo is `revert`: it writes a new revision that copies an earlier +one, so history is never rewritten. `reset` writes a new revision with the +defaults. The identity is untouched by both. + +If the daemon is not running, `aien allen` says so and calls it temporary. Your +identity and saved profile are not lost. + +## What is enforced and what is advice + +Enforced by code, with tests: + +- The schema, its limits, and the rule that permission-like keys are refused. +- The binding to the engaged identity: a profile written for another agent or + root is refused, not used and not changed. With ALLEN not engaged, every + profile command refuses. +- Compare-and-swap: two writers racing, exactly one wins. +- Crash safety: each revision is written to a temporary file, flushed, hard + linked into place, and the folder is flushed. A crash leaves the old head or + the new head, never a mix. +- A damaged, oversize, unknown-schema, unknown-field, gapped or foreign file is + a clear refusal. It is never silently replaced. +- No path from a model reply, a task or a workspace file to the profile writer. + Only the operator commands write. +- Saving a profile does not authorize any write. A file write still needs the + approval step (authorize, then execute). + +Advice, not enforcement: + +- How a model behaves with the style block. The block is text placed in front of + the task prompt: at most 2048 bytes, preferences sorted by key, extra + preferences dropped and counted. It says the preferences grant no permission + and that the task wins on conflict. A model may still ignore it. + +When the saved profile is damaged or foreign, tasks still run with the defaults +and the task report says `persona.state = "refused"` with the reason. + +## Limits (v1) + +- No avatar and no voice. `status` lists them as unsupported; there are no + controls for them. +- No memory scoping. The `scope` on a preference is a label in the style block, + not a wall around memory. +- No standing goals. That needs a native format decision (aienos ADR 0018) and + is not in v1. +- Tests are fixture based. Identities come from the test-only subject encoder. + The real-model run is NOT_RUN (the GPU lane belongs to another session). +- The store needs a filesystem that supports hard links. +- Timestamps are informational. Nothing orders or trusts them. +- Profile commands go through the compose home, so they wait while a task is + running. +- If syncing the folder fails after a revision is linked in, the call reports an + error even though the revision exists. A retry then says the profile moved + on (StaleUpdate), so check `aien allen history` before trying again. +- Any unexpected file in the profile folder makes the store refuse it as + damaged, and the persona falls back to defaults, reported as refused. + Leftover temp files from a crash are ignored but are not cleaned up. +- Every request re-reads and re-checks the whole revision chain, and there is + no cap on the number of revisions yet. + +## Layout + +The store is the folder `.allen-profile/`, beside +`.allen-binding`. Files are `r00000000000000000001.json`, `...2.json` and +so on, never edited in place. Each holds the sha256 of the previous file's +bytes. Leftover `.tmp-*` files from a crash are ignored. diff --git a/crates/aien-allen-profile/src/context.rs b/crates/aien-allen-profile/src/context.rs new file mode 100644 index 00000000..5e30f802 --- /dev/null +++ b/crates/aien-allen-profile/src/context.rs @@ -0,0 +1,154 @@ +//! `PersonaContext`: the ONE typed function between a saved profile and the +//! prompt. Deterministic (preferences sorted by key), bounded (the rendered +//! block is at most [`CONTEXT_MAX_BYTES`]; preferences that do not fit are +//! dropped and counted), and read-only: nothing here, and no model output, +//! can reach the profile writer. +use crate::refusal::ProfileRefusal; +use crate::schema::{Persona, Profile, WorkingPref}; +use crate::store::Store; +use serde::{Deserialize, Serialize}; + +pub const CONTEXT_MAX_BYTES: usize = 2048; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum PersonaState { + /// No profile saved yet: the documented defaults. + Default, + /// The head profile is in use. + Applied, + /// The saved profile is damaged or foreign: defaults are used, the reason is reported. + Refused, +} + +impl PersonaState { + pub fn as_str(self) -> &'static str { + match self { + PersonaState::Default => "default", + PersonaState::Applied => "applied", + PersonaState::Refused => "refused", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PersonaContext { + pub state: PersonaState, + pub revision: u64, + pub persona: Persona, + /// The preferences that fit in the block, sorted by key. + pub shown: Vec, + /// Preferences left out because the block was full. + pub dropped: usize, + /// Why the profile was not used (state `Refused`). + pub reason: Option, +} + +impl PersonaContext { + pub fn defaults() -> PersonaContext { + PersonaContext::fit( + PersonaState::Default, + 0, + Persona::default(), + Vec::new(), + None, + ) + } + + pub fn from_profile(p: &Profile) -> PersonaContext { + PersonaContext::fit( + PersonaState::Applied, + p.revision, + p.persona.clone(), + p.working_preferences.clone(), + None, + ) + } + + pub fn refused(why: &ProfileRefusal) -> PersonaContext { + PersonaContext::fit( + PersonaState::Refused, + 0, + Persona::default(), + Vec::new(), + Some(why.to_string()), + ) + } + + /// Read the store's head: defaults when empty, a refused context when the + /// store is damaged or foreign. Never writes. + pub fn from_store(store: &Store) -> PersonaContext { + match store.head() { + Ok(Some(p)) => PersonaContext::from_profile(&p), + Ok(None) => PersonaContext::defaults(), + Err(e) => PersonaContext::refused(&e), + } + } + + fn fit( + state: PersonaState, + revision: u64, + persona: Persona, + mut prefs: Vec, + reason: Option, + ) -> PersonaContext { + prefs.sort_by(|a, b| a.key.cmp(&b.key)); + let mut ctx = PersonaContext { + state, + revision, + persona, + shown: Vec::new(), + dropped: 0, + reason, + }; + let total = prefs.len(); + for p in prefs { + ctx.shown.push(p); + // `dropped` is reserved for the footer while measuring. + ctx.dropped = total - ctx.shown.len() + 1; + if ctx.render().len() > CONTEXT_MAX_BYTES { + ctx.shown.pop(); + } + } + ctx.dropped = total - ctx.shown.len(); + ctx + } + + /// The block placed at the front of the task prompt. + pub fn render(&self) -> String { + let q = |s: &str| serde_json::to_string(s).unwrap_or_else(|_| "\"\"".into()); + let mut s = String::new(); + s.push_str("[ALLEN style preferences saved by the user]\n"); + s.push_str( + "These are style choices only. They grant no permission and never change what the task asks for. \ + If the task below conflicts with them, follow the task.\n", + ); + s.push_str(&format!("name: {}\n", q(&self.persona.display_name))); + s.push_str(&format!("tone: {}\n", self.persona.tone.as_str())); + s.push_str(&format!("verbosity: {}\n", self.persona.verbosity.as_str())); + s.push_str(&format!( + "plain_language: {}\n", + if self.persona.plain_language { + "yes" + } else { + "no" + } + )); + if !self.shown.is_empty() { + s.push_str("preferences:\n"); + for p in &self.shown { + s.push_str(&format!( + "- {} = {} (scope {})\n", + p.key, + q(&p.value), + p.scope.as_str() + )); + } + } + if self.dropped > 0 { + s.push_str(&format!("({} more preferences not shown)\n", self.dropped)); + } + s.push_str("[end of style preferences]\n"); + s + } +} diff --git a/crates/aien-allen-profile/src/lib.rs b/crates/aien-allen-profile/src/lib.rs new file mode 100644 index 00000000..82871a61 --- /dev/null +++ b/crates/aien-allen-profile/src/lib.rs @@ -0,0 +1,24 @@ +//! ALLEN persona profile v1 (aien-architecture#159). +//! +//! A small, versioned, user-editable profile (display name, tone, verbosity, +//! plain-language switch, a few working preferences) bound to an engaged ALLEN +//! identity. This crate is the ONLY writer of the profile store +//! `.allen-profile/`; `aien-allen` stays resolve-only and the subject +//! (kind 24) is never touched. +//! +//! ENFORCED here: the schema and its limits, the identity binding, the +//! compare-and-swap revision rule, the crash-safe write order, and the fact +//! that no profile field can carry a permission. ADVISORY: how a model +//! responds to the rendered [`PersonaContext`]; it is text in a prompt. +pub mod context; +pub mod refusal; +pub mod schema; +pub mod store; + +pub use context::{PersonaContext, PersonaState, CONTEXT_MAX_BYTES}; +pub use refusal::ProfileRefusal; +pub use schema::{ + Author, Changes, HistoryEntry, Identity, Persona, PrefChange, Profile, Scope, Tone, Verbosity, + WorkingPref, DEFAULT_NAME, PROFILE_SCHEMA, +}; +pub use store::{profile_dir, Store, WriteStep}; diff --git a/crates/aien-allen-profile/src/refusal.rs b/crates/aien-allen-profile/src/refusal.rs new file mode 100644 index 00000000..68a7cd2e --- /dev/null +++ b/crates/aien-allen-profile/src/refusal.rs @@ -0,0 +1,86 @@ +//! Every way a profile operation can say no, in plain words. +use std::fmt; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ProfileRefusal { + /// ALLEN is not engaged on this machine: there is no identity to attach a profile to. + NotEngaged, + /// `expected` revision differs from the current one (or another writer won the race). + StaleUpdate { + expected: u64, + current: u64, + }, + /// A stored revision names another agent or root than the engaged identity. + ForeignProfile(String), + /// A stored file is damaged, has an unknown schema/field, is oversize, or breaks the chain. + Damaged(String), + /// A requested value is not allowed. + Invalid(String), + /// Permissions are not profile fields. + PermissionKey(String), + /// The change would leave the profile exactly as it is. + NothingToChange, + /// `revert --to N` names a revision that does not exist. + UnknownRevision(u64), + /// Reset or revert with no profile yet. + NoProfile, + Io(String), + /// Test seam only (feature `fault-injection`): the write was stopped on purpose. + Crashed(String), +} + +impl ProfileRefusal { + /// Short stable code for scripts. + pub fn code(&self) -> &'static str { + use ProfileRefusal::*; + match self { + NotEngaged => "not_engaged", + StaleUpdate { .. } => "stale_update", + ForeignProfile(_) => "foreign_profile", + Damaged(_) => "damaged", + Invalid(_) => "invalid", + PermissionKey(_) => "permission_key", + NothingToChange => "nothing_to_change", + UnknownRevision(_) => "unknown_revision", + NoProfile => "no_profile", + Io(_) => "io", + Crashed(_) => "crashed", + } + } +} + +impl fmt::Display for ProfileRefusal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + use ProfileRefusal::*; + match self { + NotEngaged => write!( + f, + "ALLEN is not engaged on this machine, so there is no identity to attach a profile to. Nothing was changed." + ), + StaleUpdate { expected, current } => write!( + f, + "The profile is at revision {current}, not {expected}. Someone or something changed it since you looked. Show it again, then retry with --expect {current}. Nothing was changed." + ), + ForeignProfile(w) => write!( + f, + "The saved profile belongs to a different ALLEN identity ({w}). It was not used or changed." + ), + Damaged(w) => write!( + f, + "The saved profile is damaged or not understood ({w}). It was not replaced; ask the operator to inspect the profile folder." + ), + Invalid(w) => write!(f, "Not allowed: {w}. Nothing was changed."), + PermissionKey(k) => write!( + f, + "Not allowed: \"{k}\" looks like a permission. Permissions are not profile fields; approvals go through the approval desk. Nothing was changed." + ), + NothingToChange => write!(f, "That would leave the profile exactly as it is. Nothing was changed."), + UnknownRevision(n) => write!(f, "There is no revision {n} in this profile's history. Nothing was changed."), + NoProfile => write!(f, "No profile has been saved yet, so there is nothing to revert or reset. Nothing was changed."), + Io(w) => write!(f, "Could not read or write the profile store: {w}. Nothing was changed."), + Crashed(w) => write!(f, "write stopped on purpose (test): {w}"), + } + } +} + +impl std::error::Error for ProfileRefusal {} diff --git a/crates/aien-allen-profile/src/schema.rs b/crates/aien-allen-profile/src/schema.rs new file mode 100644 index 00000000..a4f0578a --- /dev/null +++ b/crates/aien-allen-profile/src/schema.rs @@ -0,0 +1,464 @@ +//! Schema `aien.allen.profile/1` and its validation. Every struct that is +//! read from disk or from a request denies unknown fields. +use crate::refusal::ProfileRefusal; +use serde::{Deserialize, Serialize}; + +pub const PROFILE_SCHEMA: &str = "aien.allen.profile/1"; +pub const DEFAULT_NAME: &str = "ALLEN"; +/// Largest revision file, in bytes. +pub const MAX_FILE_BYTES: u64 = 16 * 1024; +pub const MAX_NAME_CHARS: usize = 64; +pub const MAX_NOTE_CHARS: usize = 200; +pub const MAX_VALUE_CHARS: usize = 200; +pub const MAX_PREFS: usize = 32; +pub const GENESIS_PREV: &str = "0000000000000000000000000000000000000000000000000000000000000000"; +const PROVENANCE: &str = "user_explicit"; +/// A key containing any of these is refused (case-insensitive). +const PERMISSION_WORDS: [&str; 11] = [ + "grant", + "perm", + "approv", + "capab", + "allow", + "authori", + "bypass", + "sudo", + "admin", + "override", + "unrestrict", +]; + +/// The engaged identity a profile is bound to (the resolved agent and root). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Identity { + pub agent: [u8; 32], + pub root: [u8; 32], +} + +impl From<&aien_allen::Resolved> for Identity { + fn from(r: &aien_allen::Resolved) -> Self { + Identity { + agent: r.agent, + root: r.root, + } + } +} + +impl Identity { + pub fn agent_hex(&self) -> String { + aien_allen::hex(&self.agent) + } + pub fn root_hex(&self) -> String { + aien_allen::hex(&self.root) + } + /// First 8 hex characters of the agent id, for display. + pub fn fingerprint(&self) -> String { + self.agent_hex()[..8].to_string() + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Tone { + Neutral, + Warm, + Direct, + Formal, +} + +impl Tone { + pub fn as_str(self) -> &'static str { + match self { + Tone::Neutral => "neutral", + Tone::Warm => "warm", + Tone::Direct => "direct", + Tone::Formal => "formal", + } + } + pub fn parse(s: &str) -> Result { + match s { + "neutral" => Ok(Tone::Neutral), + "warm" => Ok(Tone::Warm), + "direct" => Ok(Tone::Direct), + "formal" => Ok(Tone::Formal), + o => Err(ProfileRefusal::Invalid(format!( + "tone \"{o}\" (use neutral, warm, direct or formal)" + ))), + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Verbosity { + Brief, + Normal, + Detailed, +} + +impl Verbosity { + pub fn as_str(self) -> &'static str { + match self { + Verbosity::Brief => "brief", + Verbosity::Normal => "normal", + Verbosity::Detailed => "detailed", + } + } + pub fn parse(s: &str) -> Result { + match s { + "brief" => Ok(Verbosity::Brief), + "normal" => Ok(Verbosity::Normal), + "detailed" => Ok(Verbosity::Detailed), + o => Err(ProfileRefusal::Invalid(format!( + "verbosity \"{o}\" (use brief, normal or detailed)" + ))), + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Scope { + All, + Personal, + Work, + Project, +} + +impl Scope { + pub fn as_str(self) -> &'static str { + match self { + Scope::All => "all", + Scope::Personal => "personal", + Scope::Work => "work", + Scope::Project => "project", + } + } + pub fn parse(s: &str) -> Result { + match s { + "all" => Ok(Scope::All), + "personal" => Ok(Scope::Personal), + "work" => Ok(Scope::Work), + "project" => Ok(Scope::Project), + o => Err(ProfileRefusal::Invalid(format!( + "scope \"{o}\" (use all, personal, work or project)" + ))), + } + } +} + +/// Who wrote a revision: the user, a reset, or a revert to revision N. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Author { + User, + Reset, + Revert(u64), +} + +impl Author { + fn to_text(self) -> String { + match self { + Author::User => "user".into(), + Author::Reset => "reset".into(), + Author::Revert(n) => format!("revert:{n}"), + } + } + fn from_text(s: &str) -> Option { + match s { + "user" => Some(Author::User), + "reset" => Some(Author::Reset), + _ => s + .strip_prefix("revert:") + .and_then(|n| n.parse().ok()) + .filter(|n: &u64| *n >= 1) + .map(Author::Revert), + } + } +} + +impl Serialize for Author { + fn serialize(&self, s: S) -> Result { + s.serialize_str(&self.to_text()) + } +} + +impl<'de> Deserialize<'de> for Author { + fn deserialize>(d: D) -> Result { + let t = String::deserialize(d)?; + Author::from_text(&t).ok_or_else(|| serde::de::Error::custom(format!("author {t:?}"))) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Persona { + pub display_name: String, + pub tone: Tone, + pub verbosity: Verbosity, + pub plain_language: bool, +} + +impl Default for Persona { + fn default() -> Self { + Persona { + display_name: DEFAULT_NAME.into(), + tone: Tone::Neutral, + verbosity: Verbosity::Normal, + plain_language: false, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct WorkingPref { + pub key: String, + pub value: String, + pub scope: Scope, + pub provenance: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Profile { + pub schema: String, + pub agent: String, + pub root: String, + pub revision: u64, + pub prev_sha256: String, + /// UTC, informational only. Nothing orders or trusts it. + pub written_at: String, + pub author: Author, + pub note: String, + pub persona: Persona, + pub working_preferences: Vec, +} + +/// One requested preference change. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PrefChange { + pub key: String, + pub value: String, + pub scope: Scope, +} + +/// What `set` may change. Anything left `None`/empty is kept as it is. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields, default)] +pub struct Changes { + pub name: Option, + pub tone: Option, + pub verbosity: Option, + pub plain_language: Option, + pub set_prefs: Vec, + pub unset_prefs: Vec, + pub note: Option, +} + +/// One line of `history`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct HistoryEntry { + pub revision: u64, + pub written_at: String, + pub author: Author, + pub note: String, + pub display_name: String, +} + +fn has_control(s: &str) -> bool { + s.chars().any(|c| { + c.is_control() + || matches!(c, '\u{2028}' | '\u{2029}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}') + }) +} + +pub fn is_hex64(s: &str) -> bool { + s.len() == 64 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) +} + +pub fn clean_name(raw: &str) -> Result { + let n = raw.trim(); + let chars = n.chars().count(); + if chars == 0 || chars > MAX_NAME_CHARS { + return Err(ProfileRefusal::Invalid(format!( + "the name must be 1 to {MAX_NAME_CHARS} characters" + ))); + } + if has_control(n) { + return Err(ProfileRefusal::Invalid( + "the name may not contain control characters".into(), + )); + } + Ok(n.to_string()) +} + +pub fn clean_note(raw: &str) -> Result { + let n = raw.trim(); + if n.chars().count() > MAX_NOTE_CHARS || has_control(n) { + return Err(ProfileRefusal::Invalid(format!( + "a note is at most {MAX_NOTE_CHARS} characters, no control characters" + ))); + } + Ok(n.to_string()) +} + +pub fn check_key(key: &str) -> Result<(), ProfileRefusal> { + let ok = !key.is_empty() + && key.len() <= 48 + && key + .bytes() + .all(|b| matches!(b, b'a'..=b'z' | b'0'..=b'9' | b'_' | b'.' | b'-')); + if !ok { + return Err(ProfileRefusal::Invalid(format!( + "preference key \"{key}\" (1 to 48 characters from a-z, 0-9, _ . -)" + ))); + } + let norm = key.to_ascii_lowercase().replace(['-', '.'], "_"); + if PERMISSION_WORDS.iter().any(|w| norm.contains(w)) { + return Err(ProfileRefusal::PermissionKey(key.to_string())); + } + Ok(()) +} + +pub fn check_value(key: &str, value: &str) -> Result<(), ProfileRefusal> { + let n = value.chars().count(); + if n == 0 || n > MAX_VALUE_CHARS || has_control(value) { + return Err(ProfileRefusal::Invalid(format!( + "the value for \"{key}\" must be 1 to {MAX_VALUE_CHARS} characters, one line" + ))); + } + Ok(()) +} + +impl Profile { + /// Structural validation of a profile (as read from disk or about to be written). + pub fn validate(&self) -> Result<(), ProfileRefusal> { + let bad = |w: String| Err(ProfileRefusal::Damaged(w)); + if self.schema != PROFILE_SCHEMA { + return bad(format!("unknown schema \"{}\"", self.schema)); + } + if !is_hex64(&self.agent) || !is_hex64(&self.root) || !is_hex64(&self.prev_sha256) { + return bad("agent, root and prev_sha256 must be 64 hex characters".into()); + } + if self.revision == 0 { + return bad("revision 0".into()); + } + if self.written_at.len() > 40 || has_control(&self.written_at) { + return bad("written_at".into()); + } + clean_note(&self.note).map_err(|e| ProfileRefusal::Damaged(e.to_string()))?; + clean_name(&self.persona.display_name) + .map_err(|e| ProfileRefusal::Damaged(e.to_string()))?; + if self.persona.display_name != self.persona.display_name.trim() { + return bad("display_name is not trimmed".into()); + } + if self.working_preferences.len() > MAX_PREFS { + return bad(format!("more than {MAX_PREFS} preferences")); + } + let mut last: Option<&str> = None; + for p in &self.working_preferences { + check_key(&p.key).map_err(|e| ProfileRefusal::Damaged(e.to_string()))?; + check_value(&p.key, &p.value).map_err(|e| ProfileRefusal::Damaged(e.to_string()))?; + if p.provenance != PROVENANCE { + return bad(format!("preference \"{}\" provenance", p.key)); + } + if last.is_some_and(|l| l >= p.key.as_str()) { + return bad("preferences are not sorted by unique key".into()); + } + last = Some(&p.key); + } + Ok(()) + } + + pub fn is_bound_to(&self, id: &Identity) -> bool { + self.agent == id.agent_hex() && self.root == id.root_hex() + } + + /// The editable part, to compare "would anything change". + pub fn content(&self) -> (&Persona, &[WorkingPref]) { + (&self.persona, &self.working_preferences) + } +} + +/// Apply `ch` to a persona and preference list, validating every part. +pub fn apply_changes( + persona: &Persona, + prefs: &[WorkingPref], + ch: &Changes, +) -> Result<(Persona, Vec), ProfileRefusal> { + let mut p = persona.clone(); + if let Some(n) = &ch.name { + p.display_name = clean_name(n)?; + } + if let Some(t) = ch.tone { + p.tone = t; + } + if let Some(v) = ch.verbosity { + p.verbosity = v; + } + if let Some(b) = ch.plain_language { + p.plain_language = b; + } + let mut list: Vec = prefs.to_vec(); + for key in &ch.unset_prefs { + let before = list.len(); + list.retain(|w| &w.key != key); + if list.len() == before { + return Err(ProfileRefusal::Invalid(format!( + "no saved preference \"{key}\" to remove" + ))); + } + } + for c in &ch.set_prefs { + check_key(&c.key)?; + check_value(&c.key, &c.value)?; + let new = WorkingPref { + key: c.key.clone(), + value: c.value.clone(), + scope: c.scope, + provenance: PROVENANCE.into(), + }; + match list.iter_mut().find(|w| w.key == c.key) { + Some(slot) => *slot = new, + None => list.push(new), + } + } + if list.len() > MAX_PREFS { + return Err(ProfileRefusal::Invalid(format!( + "at most {MAX_PREFS} preferences" + ))); + } + list.sort_by(|a, b| a.key.cmp(&b.key)); + Ok((p, list)) +} + +pub fn preference_provenance() -> &'static str { + PROVENANCE +} + +/// UTC "YYYY-MM-DDTHH:MM:SSZ" from the system clock. +pub fn now_utc() -> String { + let secs = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + let (days, rem) = ((secs / 86_400) as i64, secs % 86_400); + // Civil-from-days (Howard Hinnant's algorithm). + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let y = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = if m <= 2 { y + 1 } else { y }; + format!( + "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", + rem / 3600, + (rem % 3600) / 60, + rem % 60 + ) +} diff --git a/crates/aien-allen-profile/src/store.rs b/crates/aien-allen-profile/src/store.rs new file mode 100644 index 00000000..e0ce2fb1 --- /dev/null +++ b/crates/aien-allen-profile/src/store.rs @@ -0,0 +1,419 @@ +//! The revision store `.allen-profile/`: immutable files +//! `r00000000000000000001.json`, `r...2.json`, ... never edited in place. +//! +//! Write order for revision N: create a private temp file, write, fsync, +//! `hard_link(temp, rN)` (fails if rN already exists: that is a lost race, +//! reported as a stale update), fsync the directory, remove the temp file. +//! A crash at any step leaves the old head or the new head, never a mix; a +//! leftover temp file (`.tmp-*`) is ignored. The head is the highest N whose +//! chain 1..N is intact (each `prev_sha256` is the sha256 of the previous +//! file's bytes). Anything else in the directory (a gap, a damaged or +//! oversize file, an unknown schema or field, a foreign file, another +//! identity's revision) is a refusal: the store never silently replaces or +//! skips it. +use crate::refusal::ProfileRefusal as R; +use crate::schema::{ + apply_changes, clean_note, now_utc, Author, Changes, HistoryEntry, Identity, Persona, Profile, + WorkingPref, GENESIS_PREV, MAX_FILE_BYTES, PROFILE_SCHEMA, +}; +use sha2::{Digest, Sha256}; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// `.allen-profile`, beside `.allen-binding`. +pub fn profile_dir(home: &Path) -> PathBuf { + let mut n = home.as_os_str().to_owned(); + n.push(".allen-profile"); + PathBuf::from(n) +} + +/// The steps of one revision write, in order. A step is named after it completes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum WriteStep { + TempCreated, + TempWritten, + TempSynced, + Linked, + DirSynced, + TempRemoved, +} + +impl WriteStep { + pub const ALL: [WriteStep; 6] = [ + WriteStep::TempCreated, + WriteStep::TempWritten, + WriteStep::TempSynced, + WriteStep::Linked, + WriteStep::DirSynced, + WriteStep::TempRemoved, + ]; +} + +#[cfg(feature = "fault-injection")] +type Hook = std::sync::Arc bool + Send + Sync>; + +pub struct Store { + dir: PathBuf, + id: Identity, + #[cfg(feature = "fault-injection")] + hook: Option, +} + +struct Rev { + profile: Profile, + sha: String, +} + +fn sha_hex(b: &[u8]) -> String { + aien_allen::hex(&Sha256::digest(b)) +} + +fn file_name(n: u64) -> String { + format!("r{n:020}.json") +} + +fn parse_name(s: &str) -> Option { + let d = s.strip_prefix('r')?.strip_suffix(".json")?; + if d.len() != 20 || !d.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + d.parse().ok().filter(|n| *n >= 1) +} + +fn io(what: &str, e: std::io::Error) -> R { + R::Io(format!("{what}: {e}")) +} + +impl Store { + /// The store beside `home` for the engaged identity `id`. + pub fn new(home: &Path, id: Identity) -> Store { + Store::at(profile_dir(home), id) + } + + pub fn at(dir: PathBuf, id: Identity) -> Store { + Store { + dir, + id, + #[cfg(feature = "fault-injection")] + hook: None, + } + } + + pub fn dir(&self) -> &Path { + &self.dir + } + + /// Test seam: `hook(step)` runs after each write step; returning true + /// stops the write there, as a crash would (no cleanup). + #[cfg(feature = "fault-injection")] + pub fn with_fault_hook(mut self, hook: Hook) -> Store { + self.hook = Some(hook); + self + } + + fn after(&self, step: WriteStep) -> Result<(), R> { + #[cfg(feature = "fault-injection")] + if let Some(h) = &self.hook { + if h(step) { + return Err(R::Crashed(format!("{step:?}"))); + } + } + let _ = step; + Ok(()) + } + + /// Every revision 1..=head, fully verified. Empty when no store exists. + fn chain(&self) -> Result, R> { + let rd = match std::fs::read_dir(&self.dir) { + Ok(rd) => rd, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(e) => return Err(io("read profile folder", e)), + }; + let mut nums: Vec = Vec::new(); + for ent in rd { + let ent = ent.map_err(|e| io("read profile folder", e))?; + let name = ent.file_name().to_string_lossy().into_owned(); + if name.starts_with(".tmp-") { + continue; // a crashed writer's leftover + } + match parse_name(&name) { + Some(n) => nums.push(n), + None => return Err(R::Damaged(format!("unexpected file \"{name}\""))), + } + } + nums.sort_unstable(); + for (i, n) in nums.iter().enumerate() { + if *n != i as u64 + 1 { + return Err(R::Damaged(format!( + "revision files are not contiguous (found {n} where {} was expected)", + i + 1 + ))); + } + } + let mut out: Vec = Vec::with_capacity(nums.len()); + let mut prev = GENESIS_PREV.to_string(); + for n in nums { + let path = self.dir.join(file_name(n)); + let meta = std::fs::metadata(&path).map_err(|e| io("stat revision", e))?; + if meta.len() > MAX_FILE_BYTES { + return Err(R::Damaged(format!( + "revision {n} is {} bytes (limit {MAX_FILE_BYTES})", + meta.len() + ))); + } + let bytes = std::fs::read(&path).map_err(|e| io("read revision", e))?; + let p: Profile = serde_json::from_slice(&bytes) + .map_err(|e| R::Damaged(format!("revision {n}: {e}")))?; + p.validate() + .map_err(|e| R::Damaged(format!("revision {n}: {e}")))?; + if !p.is_bound_to(&self.id) { + return Err(R::ForeignProfile(format!( + "revision {n} names agent {}", + &p.agent[..8] + ))); + } + if p.revision != n { + return Err(R::Damaged(format!( + "revision {n} says it is revision {}", + p.revision + ))); + } + if p.prev_sha256 != prev { + return Err(R::Damaged(format!("revision {n} breaks the hash chain"))); + } + prev = sha_hex(&bytes); + out.push(Rev { + profile: p, + sha: prev.clone(), + }); + } + Ok(out) + } + + /// The current head, or `None` when no profile has been saved. + pub fn head(&self) -> Result, R> { + Ok(self.chain()?.pop().map(|r| r.profile)) + } + + /// Current revision number (0 = none). + pub fn revision(&self) -> Result { + Ok(self.head()?.map_or(0, |p| p.revision)) + } + + pub fn get(&self, revision: u64) -> Result { + self.chain()? + .into_iter() + .find(|r| r.profile.revision == revision) + .map(|r| r.profile) + .ok_or(R::UnknownRevision(revision)) + } + + pub fn history(&self) -> Result, R> { + Ok(self + .chain()? + .into_iter() + .map(|r| HistoryEntry { + revision: r.profile.revision, + written_at: r.profile.written_at, + author: r.profile.author, + note: r.profile.note, + display_name: r.profile.persona.display_name, + }) + .collect()) + } + + /// Apply `changes` on top of revision `expected`. + pub fn set(&self, expected: u64, changes: &Changes) -> Result { + let chain = self.chain()?; + check_expected(expected, &chain)?; + let (base_p, base_w) = base(&chain); + let note = match &changes.note { + Some(n) => clean_note(n)?, + None => String::new(), + }; + let (p, w) = apply_changes(&base_p, &base_w, changes)?; + self.commit(chain, Author::User, note, p, w) + } + + /// Write a NEW revision whose content is a copy of revision `to`. + pub fn revert(&self, expected: u64, to: u64) -> Result { + let chain = self.chain()?; + check_expected(expected, &chain)?; + if chain.is_empty() { + return Err(R::NoProfile); + } + let src = chain + .iter() + .find(|r| r.profile.revision == to) + .ok_or(R::UnknownRevision(to))?; + let (p, w) = ( + src.profile.persona.clone(), + src.profile.working_preferences.clone(), + ); + self.commit( + chain, + Author::Revert(to), + format!("reverted to revision {to}"), + p, + w, + ) + } + + /// Write a NEW revision with the defaults. The identity is untouched. + pub fn reset(&self, expected: u64) -> Result { + let chain = self.chain()?; + check_expected(expected, &chain)?; + if chain.is_empty() { + return Err(R::NoProfile); + } + self.commit( + chain, + Author::Reset, + "reset to defaults".into(), + Persona::default(), + Vec::new(), + ) + } + + fn commit( + &self, + chain: Vec, + author: Author, + note: String, + persona: Persona, + prefs: Vec, + ) -> Result { + let (cur_p, cur_w) = base(&chain); + if persona == cur_p && prefs == cur_w { + return Err(R::NothingToChange); + } + let revision = chain.len() as u64 + 1; + let prev_sha256 = chain + .last() + .map_or_else(|| GENESIS_PREV.to_string(), |r| r.sha.clone()); + let profile = Profile { + schema: PROFILE_SCHEMA.into(), + agent: self.id.agent_hex(), + root: self.id.root_hex(), + revision, + prev_sha256, + written_at: now_utc(), + author, + note, + persona, + working_preferences: prefs, + }; + profile.validate().map_err(|e| match e { + R::Damaged(w) => R::Invalid(w), + o => o, + })?; + let bytes = serde_json::to_vec(&profile).map_err(|e| R::Io(format!("serialize: {e}")))?; + if bytes.len() as u64 > MAX_FILE_BYTES { + return Err(R::Invalid(format!( + "the profile would be {} bytes (limit {MAX_FILE_BYTES})", + bytes.len() + ))); + } + self.write_revision(revision, &bytes)?; + Ok(profile) + } + + fn write_revision(&self, n: u64, bytes: &[u8]) -> Result<(), R> { + static COUNTER: AtomicU64 = AtomicU64::new(0); + let fresh = !self.dir.exists(); + std::fs::create_dir_all(&self.dir).map_err(|e| io("create profile folder", e))?; + if fresh { + if let Some(parent) = self.dir.parent() { + sync_dir(parent)?; + } + } + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + let tmp = self.dir.join(format!( + ".tmp-{}-{}-{nanos}", + std::process::id(), + COUNTER.fetch_add(1, Ordering::SeqCst) + )); + let r = self.write_steps(&tmp, &self.dir.join(file_name(n)), bytes); + match &r { + // A simulated crash leaves things exactly as they are. + Err(R::Crashed(_)) => {} + // Any other failure: the temp file must not linger. + Err(_) => { + let _ = std::fs::remove_file(&tmp); + } + Ok(()) => {} + } + match r { + Err(R::StaleUpdate { .. }) => { + let current = self.revision().unwrap_or(n); + Err(R::StaleUpdate { + expected: n - 1, + current, + }) + } + o => o, + } + } + + fn write_steps(&self, tmp: &Path, dst: &Path, bytes: &[u8]) -> Result<(), R> { + let mut oo = std::fs::OpenOptions::new(); + oo.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + oo.mode(0o600); + } + let mut f = oo.open(tmp).map_err(|e| io("create temp file", e))?; + self.after(WriteStep::TempCreated)?; + f.write_all(bytes).map_err(|e| io("write", e))?; + self.after(WriteStep::TempWritten)?; + f.sync_all().map_err(|e| io("fsync", e))?; + drop(f); + self.after(WriteStep::TempSynced)?; + match std::fs::hard_link(tmp, dst) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { + let _ = std::fs::remove_file(tmp); + return Err(R::StaleUpdate { + expected: 0, + current: 0, + }); + } + Err(e) => return Err(io("link revision", e)), + } + self.after(WriteStep::Linked)?; + sync_dir(&self.dir)?; + self.after(WriteStep::DirSynced)?; + std::fs::remove_file(tmp).map_err(|e| io("remove temp file", e))?; + self.after(WriteStep::TempRemoved)?; + Ok(()) + } +} + +fn sync_dir(p: &Path) -> Result<(), R> { + std::fs::File::open(p) + .and_then(|d| d.sync_all()) + .map_err(|e| io("fsync folder", e)) +} + +fn check_expected(expected: u64, chain: &[Rev]) -> Result<(), R> { + let current = chain.len() as u64; + if expected != current { + return Err(R::StaleUpdate { expected, current }); + } + Ok(()) +} + +fn base(chain: &[Rev]) -> (Persona, Vec) { + match chain.last() { + Some(r) => ( + r.profile.persona.clone(), + r.profile.working_preferences.clone(), + ), + None => (Persona::default(), Vec::new()), + } +} diff --git a/crates/aien-allen-profile/tests/profile_test.rs b/crates/aien-allen-profile/tests/profile_test.rs new file mode 100644 index 00000000..ecf6173b --- /dev/null +++ b/crates/aien-allen-profile/tests/profile_test.rs @@ -0,0 +1,488 @@ +//! Profile store tests. FIXTURE-ONLY: identities here are fixed byte arrays, +//! not subjects resolved from AIENOS. No model is involved. +use aien_allen_profile::{ + Changes, Identity, PersonaContext, PersonaState, PrefChange, ProfileRefusal as R, Scope, Store, + Tone, Verbosity, WriteStep, CONTEXT_MAX_BYTES, +}; +use std::sync::{Arc, Barrier}; + +fn id(tag: u8) -> Identity { + Identity { + agent: [tag; 32], + root: [tag.wrapping_add(100); 32], + } +} + +fn name(n: &str) -> Changes { + Changes { + name: Some(n.into()), + ..Default::default() + } +} + +fn pref(k: &str, v: &str) -> PrefChange { + PrefChange { + key: k.into(), + value: v.into(), + scope: Scope::All, + } +} + +fn dir(t: &tempfile::TempDir) -> std::path::PathBuf { + t.path().join("compose.allen-profile") +} + +#[test] +fn rename_tone_verbosity_and_pref_survive_reopen() { + let t = tempfile::tempdir().unwrap(); + let s = Store::at(dir(&t), id(1)); + assert!(s.head().unwrap().is_none()); + let ch = Changes { + name: Some(" Nova ".into()), + tone: Some(Tone::Warm), + verbosity: Some(Verbosity::Brief), + plain_language: Some(true), + set_prefs: vec![pref("summary.style", "bullet points")], + ..Default::default() + }; + let p = s.set(0, &ch).unwrap(); + assert_eq!(p.revision, 1); + drop(s); + // "Restart": a new Store from the same folder. + let s2 = Store::at(dir(&t), id(1)); + let h = s2.head().unwrap().unwrap(); + assert_eq!(h.persona.display_name, "Nova"); + assert_eq!(h.persona.tone, Tone::Warm); + assert_eq!(h.persona.verbosity, Verbosity::Brief); + assert!(h.persona.plain_language); + assert_eq!(h.working_preferences[0].key, "summary.style"); + assert_eq!(h.working_preferences[0].provenance, "user_explicit"); +} + +#[test] +fn foreign_agent_and_wrong_root_are_refused() { + let t = tempfile::tempdir().unwrap(); + Store::at(dir(&t), id(1)).set(0, &name("Nova")).unwrap(); + let other_agent = Store::at(dir(&t), id(2)); + assert!(matches!(other_agent.head(), Err(R::ForeignProfile(_)))); + assert!(matches!( + other_agent.set(1, &name("X")), + Err(R::ForeignProfile(_)) + )); + // Same agent, different root. + let wrong_root = Store::at( + dir(&t), + Identity { + agent: id(1).agent, + root: [9; 32], + }, + ); + assert!(matches!(wrong_root.head(), Err(R::ForeignProfile(_)))); + // The original identity still reads its own profile, untouched. + assert_eq!( + Store::at(dir(&t), id(1)).head().unwrap().unwrap().revision, + 1 + ); +} + +#[test] +fn stale_expect_changes_nothing() { + let t = tempfile::tempdir().unwrap(); + let s = Store::at(dir(&t), id(1)); + s.set(0, &name("A")).unwrap(); + match s.set(0, &name("B")) { + Err(R::StaleUpdate { expected, current }) => assert_eq!((expected, current), (0, 1)), + o => panic!("{o:?}"), + } + assert!(matches!(s.set(5, &name("B")), Err(R::StaleUpdate { .. }))); + assert_eq!(s.head().unwrap().unwrap().persona.display_name, "A"); + assert_eq!(s.history().unwrap().len(), 1); +} + +#[test] +fn concurrent_writers_exactly_one_wins() { + let t = tempfile::tempdir().unwrap(); + let d = Arc::new(dir(&t)); + let barrier = Arc::new(Barrier::new(8)); + let results: Vec<_> = (0..8) + .map(|i| { + let d = d.clone(); + let barrier = barrier.clone(); + std::thread::spawn(move || { + barrier.wait(); + Store::at((*d).clone(), id(1)).set(0, &name(&format!("Name{i}"))) + }) + }) + .collect::>() + .into_iter() + .map(|h| h.join().unwrap()) + .collect(); + let wins = results.iter().filter(|r| r.is_ok()).count(); + assert_eq!(wins, 1, "{results:?}"); + assert!(results + .iter() + .filter_map(|r| r.as_ref().err()) + .all(|e| matches!(e, R::StaleUpdate { .. }))); + let s = Store::at((*d).clone(), id(1)); + assert_eq!(s.history().unwrap().len(), 1); + // No temp files linger after clean runs. + let leftovers = std::fs::read_dir(&*d) + .unwrap() + .filter(|e| { + e.as_ref() + .unwrap() + .file_name() + .to_string_lossy() + .starts_with(".tmp-") + }) + .count(); + assert_eq!(leftovers, 0); +} + +fn first_rev(t: &tempfile::TempDir) -> std::path::PathBuf { + dir(t).join(format!("r{:020}.json", 1)) +} + +fn good(t: &tempfile::TempDir) -> Vec { + Store::at(dir(t), id(1)).set(0, &name("Nova")).unwrap(); + std::fs::read(first_rev(t)).unwrap() +} + +#[test] +fn damaged_files_are_refused_and_never_replaced() { + type Mutate = Box Vec>; + let cases: Vec<(&str, Mutate)> = vec![ + ("malformed json", Box::new(|_| b"{not json".to_vec())), + ( + "unknown schema", + Box::new(|g| { + g.replace("aien.allen.profile/1", "aien.allen.profile/2") + .into_bytes() + }), + ), + ( + "unknown field", + Box::new(|g| g.replacen('{', "{\"avatar\":\"x\",", 1).into_bytes()), + ), + ( + "oversize", + Box::new(|g| { + let mut v = g.as_bytes().to_vec(); + v.extend(std::iter::repeat_n(b' ', 20_000)); + v + }), + ), + ( + "bad tone", + Box::new(|g| g.replace("\"neutral\"", "\"sarcastic\"").into_bytes()), + ), + ]; + for (label, mutate) in cases { + let t = tempfile::tempdir().unwrap(); + let g = String::from_utf8(good(&t)).unwrap(); + let bad = mutate(&g); + std::fs::write(first_rev(&t), &bad).unwrap(); + let s = Store::at(dir(&t), id(1)); + assert!(matches!(s.head(), Err(R::Damaged(_))), "{label}"); + assert!( + matches!(s.set(1, &name("X")), Err(R::Damaged(_))), + "{label}" + ); + assert!(matches!(s.reset(1), Err(R::Damaged(_))), "{label}"); + assert_eq!( + std::fs::read(first_rev(&t)).unwrap(), + bad, + "{label}: untouched" + ); + // The context falls back to defaults and says why. + let c = PersonaContext::from_store(&s); + assert_eq!(c.state, PersonaState::Refused, "{label}"); + assert_eq!(c.persona.display_name, "ALLEN"); + assert!(c.reason.is_some()); + } +} + +#[test] +fn broken_chain_gap_and_foreign_file_are_refused() { + let t = tempfile::tempdir().unwrap(); + let s = Store::at(dir(&t), id(1)); + s.set(0, &name("A")).unwrap(); + s.set(1, &name("B")).unwrap(); + // Editing revision 1 in place breaks revision 2's chain link. + let p1 = first_rev(&t); + let edited = String::from_utf8(std::fs::read(&p1).unwrap()) + .unwrap() + .replace("\"A\"", "\"Z\""); + std::fs::write(&p1, edited).unwrap(); + assert!(matches!(s.head(), Err(R::Damaged(_)))); + // A gap. + let t2 = tempfile::tempdir().unwrap(); + let s2 = Store::at(dir(&t2), id(1)); + s2.set(0, &name("A")).unwrap(); + s2.set(1, &name("B")).unwrap(); + std::fs::remove_file(first_rev(&t2)).unwrap(); + assert!(matches!(s2.head(), Err(R::Damaged(_)))); + // A foreign file. + let t3 = tempfile::tempdir().unwrap(); + let s3 = Store::at(dir(&t3), id(1)); + s3.set(0, &name("A")).unwrap(); + std::fs::write(dir(&t3).join("notes.txt"), "hi").unwrap(); + assert!(matches!(s3.head(), Err(R::Damaged(_)))); +} + +#[test] +fn permission_like_keys_are_rejected() { + let t = tempfile::tempdir().unwrap(); + let s = Store::at(dir(&t), id(1)); + for k in [ + "grant_write", + "permission.fs", + "auto_approve", + "capability-x", + "allow_all", + "authorized_paths", + "skip_approval", + "auto-approval", + "bypass.checks", + "sudo", + ] { + let ch = Changes { + set_prefs: vec![pref(k, "yes")], + ..Default::default() + }; + assert!(matches!(s.set(0, &ch), Err(R::PermissionKey(_))), "{k}"); + } + assert!(s.head().unwrap().is_none()); + // Other invalid input. + for ch in [ + Changes { + set_prefs: vec![pref("Bad Key", "v")], + ..Default::default() + }, + Changes { + set_prefs: vec![pref("ok", "line\nbreak")], + ..Default::default() + }, + Changes { + set_prefs: vec![pref("ok", &"x".repeat(201))], + ..Default::default() + }, + name(""), + name(&"n".repeat(65)), + name("bad\u{7}name"), + Changes { + unset_prefs: vec!["missing".into()], + ..Default::default() + }, + ] { + assert!(matches!(s.set(0, &ch), Err(R::Invalid(_))), "{ch:?}"); + } + let many = Changes { + set_prefs: (0..33).map(|i| pref(&format!("k{i:02}"), "v")).collect(), + ..Default::default() + }; + assert!(matches!(s.set(0, &many), Err(R::Invalid(_)))); + assert!(matches!( + s.set(0, &Changes::default()), + Err(R::NothingToChange) + )); +} + +#[test] +fn crash_at_every_write_step_leaves_an_intact_head() { + for step in WriteStep::ALL { + let t = tempfile::tempdir().unwrap(); + // Revision 1 written cleanly; the crash hits revision 2. + let clean = Store::at(dir(&t), id(1)); + clean.set(0, &name("Old")).unwrap(); + let crashing = Store::at(dir(&t), id(1)).with_fault_hook(Arc::new(move |s| s == step)); + assert!( + matches!(crashing.set(1, &name("New")), Err(R::Crashed(_))), + "{step:?}" + ); + let head = Store::at(dir(&t), id(1)).head().unwrap().unwrap(); + let landed = matches!( + step, + WriteStep::Linked | WriteStep::DirSynced | WriteStep::TempRemoved + ); + let (rev, nm) = if landed { (2, "New") } else { (1, "Old") }; + assert_eq!( + (head.revision, head.persona.display_name.as_str()), + (rev, nm), + "{step:?}" + ); + // Recovery: the next honest write works from whatever the head is. + let again = Store::at(dir(&t), id(1)); + again.set(rev, &name("After")).unwrap(); + assert_eq!(again.revision().unwrap(), rev + 1); + } +} + +#[test] +fn crash_on_the_very_first_write_leaves_no_profile_or_a_whole_one() { + for step in WriteStep::ALL { + let t = tempfile::tempdir().unwrap(); + let s = Store::at(dir(&t), id(1)).with_fault_hook(Arc::new(move |s| s == step)); + assert!(s.set(0, &name("Nova")).is_err()); + let h = Store::at(dir(&t), id(1)).head().unwrap(); + match step { + WriteStep::Linked | WriteStep::DirSynced | WriteStep::TempRemoved => { + assert_eq!(h.unwrap().persona.display_name, "Nova") + } + _ => assert!(h.is_none(), "{step:?}"), + } + } +} + +#[test] +fn history_revert_and_reset_write_new_revisions() { + let t = tempfile::tempdir().unwrap(); + let s = Store::at(dir(&t), id(1)); + s.set(0, &name("Nova")).unwrap(); + s.set( + 1, + &Changes { + tone: Some(Tone::Direct), + note: Some("make it terse".into()), + ..Default::default() + }, + ) + .unwrap(); + let r3 = s.revert(2, 1).unwrap(); + assert_eq!(r3.revision, 3); + assert_eq!(r3.persona.tone, Tone::Neutral); + assert_eq!(r3.persona.display_name, "Nova"); + assert_eq!(s.get(2).unwrap().persona.tone, Tone::Direct, "history kept"); + assert!(matches!(s.revert(3, 9), Err(R::UnknownRevision(9)))); + assert!(matches!(s.revert(3, 3), Err(R::NothingToChange))); + assert!(matches!(s.revert(2, 1), Err(R::StaleUpdate { .. }))); + let r4 = s.reset(3).unwrap(); + assert_eq!(r4.persona.display_name, "ALLEN"); + assert!(matches!(s.reset(4), Err(R::NothingToChange))); + let h = s.history().unwrap(); + assert_eq!(h.len(), 4); + assert_eq!(h[1].note, "make it terse"); + assert_eq!(h[3].author.clone(), aien_allen_profile::Author::Reset); + // Reset on an empty store. + let t2 = tempfile::tempdir().unwrap(); + assert!(matches!( + Store::at(dir(&t2), id(1)).reset(0), + Err(R::NoProfile) + )); +} + +#[test] +fn context_is_deterministic_and_bounded() { + let t = tempfile::tempdir().unwrap(); + let s = Store::at(dir(&t), id(1)); + // Default context, no profile. + let d = PersonaContext::from_store(&s); + assert_eq!(d.state, PersonaState::Default); + assert!(d.render().contains("name: \"ALLEN\"")); + // Insert in scrambled order; output is sorted by key and identical on every call. + let ch = Changes { + name: Some("Nova".into()), + set_prefs: vec![pref("zeta", "z"), pref("alpha", "a"), pref("mid", "m")], + ..Default::default() + }; + s.set(0, &ch).unwrap(); + let a = PersonaContext::from_store(&s).render(); + let b = PersonaContext::from_store(&Store::at(dir(&t), id(1))).render(); + assert_eq!(a, b); + let (ia, im, iz) = ( + a.find("alpha").unwrap(), + a.find("mid =").unwrap(), + a.find("zeta").unwrap(), + ); + assert!(ia < im && im < iz); + assert!(a.contains("grant no permission")); + // Worst case: 32 preferences, each 200 multi-byte characters, 64-char name. + let t2 = tempfile::tempdir().unwrap(); + let s2 = Store::at(dir(&t2), id(1)); + let big = Changes { + name: Some("N".repeat(64)), + set_prefs: (0..32) + .map(|i| pref(&format!("pref.{i:02}"), &"é".repeat(150))) + .collect(), + ..Default::default() + }; + s2.set(0, &big).unwrap(); + let c = PersonaContext::from_store(&s2); + let r = c.render(); + assert!(r.len() <= CONTEXT_MAX_BYTES, "{} bytes", r.len()); + assert!(c.dropped > 0 && c.shown.len() + c.dropped == 32); + assert!(r.contains(&format!("({} more preferences not shown)", c.dropped))); + assert_eq!(r, PersonaContext::from_store(&s2).render()); +} + +#[test] +fn control_and_bidi_characters_are_refused() { + let t = tempfile::tempdir().unwrap(); + let s = Store::at(dir(&t), id(1)); + for c in [ + '\u{2028}', '\u{2029}', '\u{202A}', '\u{202B}', '\u{202C}', '\u{202D}', '\u{202E}', + '\u{2066}', '\u{2067}', '\u{2068}', '\u{2069}', '\n', '\u{0}', + ] { + assert!( + matches!(s.set(0, &name(&format!("Ab{c}cd"))), Err(R::Invalid(_))), + "name {c:?}" + ); + let ch = Changes { + set_prefs: vec![pref("reply_language", &format!("en{c}x"))], + ..Default::default() + }; + assert!(matches!(s.set(0, &ch), Err(R::Invalid(_))), "value {c:?}"); + } + assert!(s.head().unwrap().is_none()); +} + +#[test] +fn normal_key_is_accepted() { + let t = tempfile::tempdir().unwrap(); + let s = Store::at(dir(&t), id(1)); + let ch = Changes { + set_prefs: vec![pref("reply_language", "english")], + ..Default::default() + }; + assert!(s.set(0, &ch).is_ok()); +} + +/// Both writers pass the stale check; the first finishes its whole write +/// between the second's temp-file sync and its hard link, so the second hits +/// the AlreadyExists path and must lose cleanly. +#[test] +fn link_race_loser_gets_stale_update_and_winner_is_intact() { + let t = tempfile::tempdir().unwrap(); + let d = dir(&t); + let winner_dir = d.clone(); + let loser = Store::at(d.clone(), id(1)).with_fault_hook(Arc::new(move |step| { + if step == WriteStep::TempSynced { + Store::at(winner_dir.clone(), id(1)) + .set(0, &name("Winner")) + .unwrap(); + } + false + })); + match loser.set(0, &name("Loser")) { + Err(R::StaleUpdate { expected, current }) => assert_eq!((expected, current), (0, 1)), + o => panic!("{o:?}"), + } + let s = Store::at(d.clone(), id(1)); + let head = s.head().unwrap().unwrap(); + assert_eq!( + (head.revision, head.persona.display_name.as_str()), + (1, "Winner") + ); + assert_eq!(s.history().unwrap().len(), 1); + let leftovers = std::fs::read_dir(&d) + .unwrap() + .filter(|e| { + e.as_ref() + .unwrap() + .file_name() + .to_string_lossy() + .starts_with(".tmp-") + }) + .count(); + assert_eq!(leftovers, 0); +} diff --git a/crates/aien-cli/.crumb b/crates/aien-cli/.crumb index 830546a9..f39fcc38 100644 --- a/crates/aien-cli/.crumb +++ b/crates/aien-cli/.crumb @@ -34,21 +34,21 @@ "generated": { "children": [ { - "digest": "b0298d44ce42c5d721ddf77d0550bb1d0206b9f1da7dfe755fd9e29dda0e4c81", - "last_commit": "8e0000e", + "digest": "191a29d642fd9ab8d99389383c02f7a886690e667ac0d87bd3fb04a984c6c3f7", + "last_commit": "5ae4f1d", "name": "src", "purpose": "" } ], - "children_root": "sha256:5ef216cca4bfdceed4edfb1ef94250623d511bcacc9125f4d1773701cb291926", - "compiled_at": "2026-10-07T23:58:24Z", + "children_root": "sha256:16e726539369c13d22cabd3d6b1d7fff2fd60e09a53465ab611a80aab494e16f", + "compiled_at": "2026-10-08T00:47:16Z", "compiler": "crumb-compile/1", - "digest": "sha256:53765e1fd0a9cd03e3846820fc848b63d5d97a620ee3487af7310c7756d192b9", + "digest": "sha256:03e2bc1517734a73205069d8d051a2a3cf16ee17f9e80ff506d4e8725bce4853", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 30, - "generated_at_commit": "8e0000e180d31dcc729cddce83dfc396fc835c8b", - "source_tree": "sha256:3274c2117eb2f2650c49ad353ebcf89f2b3525bd6efab813089193cd9a6ad1ee" + "files": 31, + "generated_at_commit": "0e1d79bd5ff9afd6335611f1d3db3776a91b8873", + "source_tree": "sha256:0b976c77231eb94ea18915f71ac40f846fd3ec6be2cf6feb7ff03c36957a78eb" } }, "history": [ diff --git a/crates/aien-cli/Cargo.toml b/crates/aien-cli/Cargo.toml index 34da5083..da90c8f3 100644 --- a/crates/aien-cli/Cargo.toml +++ b/crates/aien-cli/Cargo.toml @@ -26,6 +26,7 @@ aien-inference-abi = { path = "../aien-inference-abi" } aien-kv-cache = { path = "../aien-kv-cache" } aien-scheduler = { path = "../aien-scheduler" } aien-runtime = { path = "../aien-runtime" } +aien-allen-profile = { path = "../aien-allen-profile" } aien-omega-gpu = { path = "../aien-omega-gpu" } [features] diff --git a/crates/aien-cli/src/.crumb b/crates/aien-cli/src/.crumb index 7d0edef4..3bc9d118 100644 --- a/crates/aien-cli/src/.crumb +++ b/crates/aien-cli/src/.crumb @@ -64,14 +64,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-07T23:58:24Z", + "compiled_at": "2026-10-08T00:47:16Z", "compiler": "crumb-compile/1", - "digest": "sha256:b0298d44ce42c5d721ddf77d0550bb1d0206b9f1da7dfe755fd9e29dda0e4c81", + "digest": "sha256:191a29d642fd9ab8d99389383c02f7a886690e667ac0d87bd3fb04a984c6c3f7", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 25, - "generated_at_commit": "8e0000e180d31dcc729cddce83dfc396fc835c8b", - "source_tree": "sha256:1204d16a4f14a133fbc7d1fe8188134c3abfef5a625acef2e9c9d16c74e38e85" + "files": 26, + "generated_at_commit": "0e1d79bd5ff9afd6335611f1d3db3776a91b8873", + "source_tree": "sha256:ccf8abe76ec75173fa3b0b5417ada0c5c21a0660c4b2aea4c52289408a474f9f" } }, "history": [ diff --git a/crates/aien-cli/src/allen.rs b/crates/aien-cli/src/allen.rs new file mode 100644 index 00000000..c9422d36 --- /dev/null +++ b/crates/aien-cli/src/allen.rs @@ -0,0 +1,305 @@ +//! `aien allen ...`: the ALLEN persona profile (arch#159), one operator step +//! per subcommand, against the running daemon. Each call prints ONE JSON +//! object on stdout (`"ok": true|false`) and exits 1 on failure. +//! +//! status identity, persona, model, unsupported facilities +//! show the saved profile (or the defaults) +//! set --expect R [--name N] [--tone T] [--verbosity V] [--plain-language 0|1] +//! [--pref key=value[@scope]]... [--unset-pref key]... [--note TEXT] +//! history every saved revision +//! revert --to N --expect R new revision copying revision N +//! reset --expect R new revision with the defaults +//! +//! Every change needs `--expect ` (0 when nothing is saved +//! yet): if the profile moved since you looked, the change is refused. +//! The daemon owns the profile store; this side only asks. +use aien_allen_profile::{Changes, PrefChange, Scope, Tone, Verbosity}; +use aien_runtime::client::AienRuntimeClient; +use aien_runtime::control::{ControlCommand, ControlResponse}; +use serde_json::{json, Value}; + +type Flags = Vec<(String, String)>; + +fn flags(args: &[String], allowed: &[&str]) -> Result { + let mut out = Vec::new(); + let mut i = 0; + while i < args.len() { + let k = args[i] + .strip_prefix("--") + .ok_or_else(|| format!("expected --flag, got {:?}", args[i]))?; + if !allowed.contains(&k) { + return Err(format!("unknown flag --{k}")); + } + let v = args + .get(i + 1) + .ok_or_else(|| format!("--{k} needs a value"))?; + out.push((k.to_string(), v.clone())); + i += 2; + } + Ok(out) +} + +fn one<'a>(f: &'a Flags, k: &str) -> Result, String> { + let mut it = f.iter().filter(|(n, _)| n == k); + let first = it.next().map(|(_, v)| v.as_str()); + if it.next().is_some() { + return Err(format!("--{k} given more than once")); + } + Ok(first) +} + +fn number(f: &Flags, k: &str) -> Result { + let v = one(f, k)?.ok_or_else(|| { + if k == "expect" { + "--expect is required: the revision you looked at (0 when nothing is saved yet)".into() + } else { + format!("--{k} is required") + } + })?; + v.trim() + .parse::() + .map_err(|_| format!("--{k} must be a whole number, got {v:?}")) +} + +/// `key=value` or `key=value@scope` (scope one of all, personal, work, project). +fn parse_pref(s: &str) -> Result { + let (key, rest) = s + .split_once('=') + .ok_or_else(|| format!("--pref needs key=value, got {s:?}"))?; + let (value, scope) = match rest.rsplit_once('@') { + Some((v, sc)) if matches!(sc, "all" | "personal" | "work" | "project") => { + (v, Scope::parse(sc).map_err(|e| e.to_string())?) + } + _ => (rest, Scope::All), + }; + Ok(PrefChange { + key: key.to_string(), + value: value.to_string(), + scope, + }) +} + +/// Turn the command line into the daemon command (pure, no I/O). +pub fn parse(sub: &str, args: &[String]) -> Result { + match sub { + "status" => { + flags(args, &[])?; + Ok(ControlCommand::AllenStatus) + } + "show" => { + flags(args, &[])?; + Ok(ControlCommand::AllenProfileShow) + } + "history" => { + flags(args, &[])?; + Ok(ControlCommand::AllenProfileHistory) + } + "set" => { + let f = flags( + args, + &[ + "expect", + "name", + "tone", + "verbosity", + "plain-language", + "pref", + "unset-pref", + "note", + ], + )?; + let expected_revision = number(&f, "expect")?; + let plain_language = match one(&f, "plain-language")? { + None => None, + Some("1") => Some(true), + Some("0") => Some(false), + Some(o) => return Err(format!("--plain-language must be 0 or 1, got {o:?}")), + }; + let changes = Changes { + name: one(&f, "name")?.map(str::to_string), + tone: one(&f, "tone")? + .map(Tone::parse) + .transpose() + .map_err(|e| e.to_string())?, + verbosity: one(&f, "verbosity")? + .map(Verbosity::parse) + .transpose() + .map_err(|e| e.to_string())?, + plain_language, + set_prefs: f + .iter() + .filter(|(k, _)| k == "pref") + .map(|(_, v)| parse_pref(v)) + .collect::>()?, + unset_prefs: f + .iter() + .filter(|(k, _)| k == "unset-pref") + .map(|(_, v)| v.clone()) + .collect(), + note: one(&f, "note")?.map(str::to_string), + }; + Ok(ControlCommand::AllenProfileSet { + expected_revision, + changes, + }) + } + "revert" => { + let f = flags(args, &["expect", "to"])?; + Ok(ControlCommand::AllenProfileRevert { + expected_revision: number(&f, "expect")?, + to: number(&f, "to")?, + }) + } + "reset" => { + let f = flags(args, &["expect"])?; + Ok(ControlCommand::AllenProfileReset { + expected_revision: number(&f, "expect")?, + }) + } + other => Err(format!( + "unknown step {other:?} (status, show, set, history, revert, reset)" + )), + } +} + +fn to_json(v: &T) -> Result { + serde_json::to_value(v).map_err(|e| e.to_string()) +} + +/// Daemon answer to the one printed JSON object. `Err` = the call failed. +fn render(sub: &str, r: ControlResponse) -> Result { + let ok = |body: Value| { + let mut v = json!({"ok": true, "step": sub}); + v["result"] = body; + Ok(v) + }; + match r { + ControlResponse::AllenStatusReport(x) => ok(to_json(&*x).unwrap_or(Value::Null)), + ControlResponse::AllenProfile(x) => ok(to_json(&*x).unwrap_or(Value::Null)), + ControlResponse::AllenHistory(x) => ok(to_json(&*x).unwrap_or(Value::Null)), + ControlResponse::AllenRefused(x) => Err(json!({ + "ok": false, + "step": sub, + "refused": to_json(&*x).unwrap_or(Value::Null), + "changed": false, + })), + ControlResponse::Error(e) => Err(json!({"ok": false, "step": sub, "error": e})), + other => Err(json!({ + "ok": false, "step": sub, "error": format!("unexpected response {other:?}"), + })), + } +} + +pub async fn handle_allen_command(args: &[String]) { + let Some(sub) = args.first() else { + println!( + "{}", + json!({"ok": false, "error": "usage: aien allen [--flag value ...]"}) + ); + std::process::exit(1); + }; + let cmd = match parse(sub, &args[1..]) { + Ok(c) => c, + Err(e) => { + println!("{}", json!({"ok": false, "step": sub, "error": e})); + std::process::exit(1); + } + }; + let out = match AienRuntimeClient::default_client().send_command(cmd).await { + Ok(r) => render(sub, r), + // The daemon is a separate process. Not reaching it says nothing about + // the identity or the saved profile; both stay on disk. + Err(e) => Err(json!({ + "ok": false, + "step": sub, + "daemon": "unreachable", + "error": e, + "note": "temporary: the daemon is not reachable. Your identity and saved profile are not lost or changed.", + })), + }; + match out { + Ok(v) => println!("{v}"), + Err(v) => { + println!("{v}"); + std::process::exit(1); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn a(s: &[&str]) -> Vec { + s.iter().map(|x| x.to_string()).collect() + } + + #[test] + fn set_requires_expect() { + let e = parse("set", &a(&["--name", "Nova"])).unwrap_err(); + assert!(e.contains("--expect is required"), "{e}"); + assert!(parse("reset", &a(&[])).is_err()); + assert!(parse("revert", &a(&["--to", "1"])).is_err()); + } + + #[test] + fn set_parses_every_field() { + let c = parse( + "set", + &a(&[ + "--expect", + "3", + "--name", + "Nova", + "--tone", + "warm", + "--verbosity", + "brief", + "--plain-language", + "1", + "--pref", + "units=metric@work", + "--pref", + "mail=a@b.example", + "--unset-pref", + "old", + "--note", + "why", + ]), + ) + .unwrap(); + let ControlCommand::AllenProfileSet { + expected_revision, + changes, + } = c + else { + panic!() + }; + assert_eq!(expected_revision, 3); + assert_eq!(changes.name.as_deref(), Some("Nova")); + assert_eq!(changes.tone, Some(Tone::Warm)); + assert_eq!(changes.plain_language, Some(true)); + assert_eq!(changes.set_prefs[0].scope, Scope::Work); + assert_eq!(changes.set_prefs[0].value, "metric"); + // '@' that is not a scope stays in the value. + assert_eq!(changes.set_prefs[1].value, "a@b.example"); + assert_eq!(changes.set_prefs[1].scope, Scope::All); + assert_eq!(changes.unset_prefs, vec!["old".to_string()]); + } + + #[test] + fn bad_input_is_refused_before_any_call() { + for bad in [ + vec!["--expect", "x"], + vec!["--expect", "1", "--tone", "grumpy"], + vec!["--expect", "1", "--plain-language", "yes"], + vec!["--expect", "1", "--pref", "novalue"], + vec!["--expect", "1", "--avatar", "cat"], + vec!["--expect", "1", "--expect", "2"], + ] { + assert!(parse("set", &a(&bad)).is_err(), "{bad:?}"); + } + assert!(parse("status", &a(&["--x", "1"])).is_err()); + assert!(parse("nope", &a(&[])).is_err()); + } +} diff --git a/crates/aien-cli/src/main.rs b/crates/aien-cli/src/main.rs index e4a2964f..9535ece9 100644 --- a/crates/aien-cli/src/main.rs +++ b/crates/aien-cli/src/main.rs @@ -1,4 +1,5 @@ #![allow(clippy::type_complexity, clippy::needless_range_loop)] +mod allen; mod client; mod commands; pub mod compaction; @@ -57,6 +58,10 @@ async fn main() { commands::handle_stop_command().await; return; } + if args[1] == "allen" { + allen::handle_allen_command(&args[2..]).await; + return; + } if args[1] == "compose" { compose::handle_compose_command(&args[2..]).await; return; diff --git a/crates/aien-runtime/Cargo.toml b/crates/aien-runtime/Cargo.toml index aebd047c..771385f1 100644 --- a/crates/aien-runtime/Cargo.toml +++ b/crates/aien-runtime/Cargo.toml @@ -17,6 +17,7 @@ aien-security = { path = "../aien-security" } cortex-rs = { path = "../cortex-rs" } aien-omega-compose = { path = "../aien-omega-compose" } aien-allen = { path = "../aien-allen" } +aien-allen-profile = { path = "../aien-allen-profile" } tokio = { version = "1.37", features = ["full"] } parking_lot = "0.12" diff --git a/crates/aien-runtime/src/control.rs b/crates/aien-runtime/src/control.rs index 230574b8..05df56aa 100644 --- a/crates/aien-runtime/src/control.rs +++ b/crates/aien-runtime/src/control.rs @@ -91,6 +91,27 @@ pub enum ControlCommand { /// (torn journal tail, or a journal behind its J-Space anchor). Closes this /// process's handle first; the cut is recorded in the journal. RecoverComposeHome, + /// ALLEN persona profile (arch#159): identity, profile, model and unsupported + /// facilities in one answer. Handled on the socket connection. + AllenStatus, + /// The saved profile (or the defaults when none). + AllenProfileShow, + /// Change the profile; `expected_revision` is the compare-and-swap guard. + AllenProfileSet { + expected_revision: u64, + changes: aien_allen_profile::Changes, + }, + /// Every saved revision, oldest first. + AllenProfileHistory, + /// Write a NEW revision that copies revision `to`. + AllenProfileRevert { + expected_revision: u64, + to: u64, + }, + /// Write a NEW revision with the defaults. The identity is untouched. + AllenProfileReset { + expected_revision: u64, + }, /// NEXT-PHASE-2: the effect-boundary checks and the durable intent, in one /// step (ACCEPTANCE-v2 2.1, 2.3). Answered with `ComposeNoted` (the intent). ComposeEffectIntent { @@ -199,6 +220,14 @@ pub enum ControlResponse { }, /// Result record of `RunComposeTask`. ComposeTaskResult(Box), + /// Result of `AllenStatus`. + AllenStatusReport(Box), + /// Result of `AllenProfileShow`, `AllenProfileSet`, `AllenProfileRevert`, `AllenProfileReset`. + AllenProfile(Box), + /// Result of `AllenProfileHistory`. + AllenHistory(Box), + /// A profile command was refused; nothing was changed. + AllenRefused(Box), /// Result of `ComposeNote`. ComposeNoted(ComposeNoteReport), /// Result of `ComposeRecall`. @@ -398,6 +427,9 @@ pub struct ComposeTaskReport { pub requirements_uncertain: Vec, /// "model" when the Skill ran inference, or the stub label. pub proposer: String, + /// ALLEN persona used for this task (arch#159). Old reports have none. + #[serde(default)] + pub persona: Option, } /// One proposal the compose "model" Skill made (ACCEPTANCE-v2 3b). @@ -545,3 +577,68 @@ pub struct ComposeControlReport { /// For `revoke`: false when the grant was already spent or revoked. pub revoked: Option, } + +/// Which persona a task ran with (arch#159). `state`: `not_engaged` (ALLEN is +/// off, no persona text was added), `default` (no profile saved), `applied` +/// (profile `revision` in use) or `refused` (profile damaged or foreign: +/// defaults used, `reason` says why). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct PersonaReport { + pub state: String, + pub display_name: String, + pub revision: u64, + #[serde(default)] + pub reason: Option, +} + +/// Latest deployment-record line, when the record exists and verifies. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct DeploymentSummary { + pub seq: u64, + pub candidate_id: String, + pub placeholder: bool, +} + +/// `AllenStatus`: identity, persona, model and what is not supported yet, +/// reported separately. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct AllenStatusReport { + /// `not_engaged` or `engaged` (an engaged identity that cannot resolve stops the daemon). + pub identity: String, + /// First 8 hex characters of the agent id (engaged only). + pub fingerprint: Option, + pub head_sequence: Option, + pub chain_verified: Option, + pub persona: PersonaReport, + /// The proposer label the daemon was started with. + pub model: String, + /// `local_model` or `stub`. + pub execution_mode: String, + pub deployment: Option, + /// Facilities that exist in the plan but not in v1; their controls do not exist. + pub unsupported: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct AllenProfileReport { + /// 0 = no profile saved (defaults in effect). + pub revision: u64, + pub state: String, + /// The saved revision; `None` when none is saved. + pub profile: Option, + /// The values in effect when no profile is saved. + pub defaults: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct AllenHistoryReport { + pub entries: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct AllenRefusalReport { + pub code: String, + /// Plain-language reason. + pub message: String, + pub current_revision: Option, +} diff --git a/crates/aien-runtime/src/lib.rs b/crates/aien-runtime/src/lib.rs index bce6f4e3..ab725540 100644 --- a/crates/aien-runtime/src/lib.rs +++ b/crates/aien-runtime/src/lib.rs @@ -10,6 +10,7 @@ pub mod cortex_mark; pub mod destination; pub mod effects; pub mod generation; +pub mod persona; pub mod requirements; mod requirements_extract; pub mod rsi; diff --git a/crates/aien-runtime/src/persona.rs b/crates/aien-runtime/src/persona.rs new file mode 100644 index 00000000..7c7842c4 --- /dev/null +++ b/crates/aien-runtime/src/persona.rs @@ -0,0 +1,166 @@ +//! ALLEN persona profile glue (arch#159): turns the engaged identity plus the +//! profile store into (a) the prompt prefix and report of a compose task and +//! (b) the answers to the `Allen*` control commands. +//! +//! The profile store is written ONLY by `aien-allen-profile`, and only from +//! the operator commands handled here. Nothing in the compose task path +//! (model text, proposals, workspace files) calls a writer. +use crate::control::{ + AllenHistoryReport, AllenProfileReport, AllenRefusalReport, AllenStatusReport, ControlCommand, + ControlResponse, DeploymentSummary, PersonaReport, +}; +use aien_allen::Resolved; +use aien_allen_profile::{Identity, Persona, PersonaContext, ProfileRefusal, Store}; +use std::path::Path; + +/// Facilities in the plan that v1 does not have. Reported, never given a control. +pub const UNSUPPORTED: [&str; 2] = ["avatar", "voice"]; + +/// `None` = ALLEN is not engaged: no persona text, no change in behaviour. +pub fn context_for(dir: &Path, id: Option<&Resolved>) -> Option { + let r = id?; + let store = Store::new(dir, Identity::from(r)); + let ctx = PersonaContext::from_store(&store); + if let Some(why) = &ctx.reason { + tracing::warn!("ALLEN persona profile not used (defaults apply): {why}"); + } + Some(ctx) +} + +pub fn report_for(ctx: Option<&PersonaContext>) -> PersonaReport { + match ctx { + None => PersonaReport { + state: "not_engaged".into(), + display_name: String::new(), + revision: 0, + reason: None, + }, + Some(c) => PersonaReport { + state: c.state.as_str().into(), + display_name: c.persona.display_name.clone(), + revision: c.revision, + reason: c.reason.clone(), + }, + } +} + +/// The persona block in front of the task prompt; the prompt itself is +/// unchanged when there is no context. +pub fn prefix_prompt(prompt: &str, ctx: Option<&PersonaContext>) -> String { + match ctx { + None => prompt.to_string(), + Some(c) => format!("{}\n{prompt}", c.render()), + } +} + +fn refused(e: &ProfileRefusal) -> ControlResponse { + let current_revision = match e { + ProfileRefusal::StaleUpdate { current, .. } => Some(*current), + _ => None, + }; + ControlResponse::AllenRefused(Box::new(AllenRefusalReport { + code: e.code().into(), + message: e.to_string(), + current_revision, + })) +} + +fn profile_report(store: &Store) -> Result { + let head = store.head()?; + Ok(ControlResponse::AllenProfile(Box::new(match head { + Some(p) => AllenProfileReport { + revision: p.revision, + state: "applied".into(), + profile: Some(p), + defaults: None, + }, + None => AllenProfileReport { + revision: 0, + state: "default".into(), + profile: None, + defaults: Some(Persona::default()), + }, + }))) +} + +fn written(p: aien_allen_profile::Profile) -> ControlResponse { + ControlResponse::AllenProfile(Box::new(AllenProfileReport { + revision: p.revision, + state: "applied".into(), + profile: Some(p), + defaults: None, + })) +} + +/// Answer one `Allen*` command. `id` is the identity this daemon resolved +/// (`None` = not engaged); `label` is the proposer label the daemon runs. +pub fn handle_allen_command( + dir: &Path, + id: Option<&Resolved>, + label: &str, + cmd: &ControlCommand, +) -> ControlResponse { + if let ControlCommand::AllenStatus = cmd { + return status(dir, id, label); + } + let Some(r) = id else { + return refused(&ProfileRefusal::NotEngaged); + }; + let store = Store::new(dir, Identity::from(r)); + let out = match cmd { + ControlCommand::AllenProfileShow => profile_report(&store), + ControlCommand::AllenProfileSet { + expected_revision, + changes, + } => store.set(*expected_revision, changes).map(written), + ControlCommand::AllenProfileHistory => store + .history() + .map(|entries| ControlResponse::AllenHistory(Box::new(AllenHistoryReport { entries }))), + ControlCommand::AllenProfileRevert { + expected_revision, + to, + } => store.revert(*expected_revision, *to).map(written), + ControlCommand::AllenProfileReset { expected_revision } => { + store.reset(*expected_revision).map(written) + } + _ => { + return ControlResponse::Error("not an ALLEN profile command".into()); + } + }; + out.unwrap_or_else(|e| refused(&e)) +} + +fn status(dir: &Path, id: Option<&Resolved>, label: &str) -> ControlResponse { + let ctx = context_for(dir, id); + let deployment = id.and_then(|r| { + aien_allen::deployment::verify(&aien_allen::deployment::deployments_path(dir), &r.agent) + .ok() + .and_then(|v| v.last().cloned()) + .map(|e| DeploymentSummary { + seq: e.seq, + candidate_id: e.candidate_id, + placeholder: e.placeholder, + }) + }); + ControlResponse::AllenStatusReport(Box::new(AllenStatusReport { + identity: if id.is_some() { + "engaged" + } else { + "not_engaged" + } + .into(), + fingerprint: id.map(|r| Identity::from(r).fingerprint()), + head_sequence: id.map(|r| r.head_seq), + chain_verified: id.map(|r| r.chain_verified), + persona: report_for(ctx.as_ref()), + model: label.to_string(), + execution_mode: if label.starts_with("model:") { + "local_model" + } else { + "stub" + } + .into(), + deployment, + unsupported: UNSUPPORTED.iter().map(|s| s.to_string()).collect(), + })) +} diff --git a/crates/aien-runtime/src/server.rs b/crates/aien-runtime/src/server.rs index 35a79d32..8c59db73 100644 --- a/crates/aien-runtime/src/server.rs +++ b/crates/aien-runtime/src/server.rs @@ -906,6 +906,15 @@ async fn handle_connection( crate::effects::control(b, &a, &p, authorization) })) } + ControlCommand::AllenStatus + | ControlCommand::AllenProfileShow + | ControlCommand::AllenProfileSet { .. } + | ControlCommand::AllenProfileHistory + | ControlCommand::AllenProfileRevert { .. } + | ControlCommand::AllenProfileReset { .. } => { + let c = envelope.command.clone(); + Some(Box::new(move |b: &Arc| b.allen_command(&c))) + } _ => None, }; if let Some(job) = compose_job { diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs index 69663a8d..87e3564a 100644 --- a/crates/aien-runtime/src/spine.rs +++ b/crates/aien-runtime/src/spine.rs @@ -417,7 +417,13 @@ impl AienRuntimeSpine { | ControlCommand::ComposeReconcile { .. } | ControlCommand::ComposeControl { .. } | ControlCommand::ComposeAuthorize { .. } - | ControlCommand::ComposeApprovedProposal { .. } => ControlResponse::Error( + | ControlCommand::ComposeApprovedProposal { .. } + | ControlCommand::AllenStatus + | ControlCommand::AllenProfileShow + | ControlCommand::AllenProfileSet { .. } + | ControlCommand::AllenProfileHistory + | ControlCommand::AllenProfileRevert { .. } + | ControlCommand::AllenProfileReset { .. } => ControlResponse::Error( "compose commands are handled on the socket connection, not as one-shot commands" .into(), ), @@ -627,7 +633,13 @@ fn proposal_handle(text: &str) -> u64 { /// ALLEN identity gate (aien-allen, ADR 0035), run once per compose-home open. /// Not engaged (AIEN_ALLEN_SUBJECT unset): one log line, nothing else changes. /// Engaged: any refusal is FATAL (message, nonzero exit), never a fallback. -fn allen_gate(dir: &Path, compose: &mut Compose, machine_id: &[u8; 32]) { +/// Returns the resolved identity when engaged, so the compose home can keep it +/// (persona profile, arch#159); `None` when not engaged. +fn allen_gate( + dir: &Path, + compose: &mut Compose, + machine_id: &[u8; 32], +) -> Option { use aien_allen::{Context, Gate}; static NOT_ENGAGED_ONCE: std::sync::Once = std::sync::Once::new(); let lineage = compose.record(1).ok().map(|r| r.digest); @@ -647,6 +659,7 @@ fn allen_gate(dir: &Path, compose: &mut Compose, machine_id: &[u8; 32]) { match aien_allen::gate(dir, &ctx, &get) { Gate::NotEngaged => { NOT_ENGAGED_ONCE.call_once(|| println!("{}", aien_allen::NOT_ENGAGED_LINE)); + None } Gate::Engaged(r) => { if r.adopted { @@ -663,6 +676,7 @@ fn allen_gate(dir: &Path, compose: &mut Compose, machine_id: &[u8; 32]) { r.head_seq, r.chain_verified ); + Some(r) } Gate::Refused(why) => { let msg = format!("FATAL ALLEN refused: {why}"); @@ -1643,6 +1657,8 @@ pub(crate) fn record_view( pub(crate) struct ComposeHome { pub(crate) compose: Compose, + /// The ALLEN identity this home resolved (`None` = not engaged). + pub(crate) allen: Option, pub(crate) machine_id: String, prompts: Arc>>, /// Proposer hook: task -> approved proposal text (crate::approved). @@ -1881,9 +1897,10 @@ impl ComposeBridge { } // ALLEN identity gate: after the open (record 1 exists, skills are // registered), before the home is handed out. Fatal when engaged. - allen_gate(&self.dir, &mut compose, &info.machine_id); + let allen = allen_gate(&self.dir, &mut compose, &info.machine_id); let mut home = ComposeHome { compose, + allen, budgets, machine_id: hex(&info.machine_id), prompts, @@ -1977,7 +1994,7 @@ impl ComposeBridge { ws.display() )); } - let (plan, dest) = task_decision(goal, &ws)?; + let (mut plan, dest) = task_decision(goal, &ws)?; // The requirements the goal states are checked on every path: the model // path and an approved proposal (refused before any write when unmet). let machine_goal = @@ -2014,6 +2031,18 @@ impl ComposeBridge { *guard = Some(self.open_home()?); } let home = guard.as_mut().expect("opened above"); + // ALLEN persona (arch#159): only a model run reads it; an approved + // proposal runs no model, so it carries no persona. Not engaged: the + // prompt is exactly what it was. + let persona_ctx = match approved_text { + None => crate::persona::context_for(&self.dir, home.allen.as_ref()), + Some(_) => None, + }; + plan.0 = crate::persona::prefix_prompt(&plan.0, persona_ctx.as_ref()); + let persona = match approved_text { + None => Some(crate::persona::report_for(persona_ctx.as_ref())), + Some(_) => None, + }; // Deadlines agree on both sides: omega settles budget + 1 s after the run // starts, the Skill gives up at budget. Set only here, under the lock that // serializes runs, never while rx_compose_run is in flight. An omega without @@ -2126,6 +2155,7 @@ impl ComposeBridge { Some(_) => APPROVED_PROPOSER_LABEL.to_string(), None => self.proposer_label.clone(), }, + persona, }) } @@ -2217,6 +2247,20 @@ impl ComposeBridge { } } + /// ALLEN persona profile commands (arch#159). Opens the home if needed (the + /// identity is resolved there). Blocking. + pub fn allen_command(&self, cmd: &ControlCommand) -> ControlResponse { + let r = self.with_home(|home| { + Ok(crate::persona::handle_allen_command( + &self.dir, + home.allen.as_ref(), + &self.proposer_label, + cmd, + )) + }); + r.unwrap_or_else(ControlResponse::Error) + } + /// S6 / S8: host records plus the cited ids, digests re-checked. pub fn recall(&self, ids: &[u64], prefix: Option) -> ControlResponse { let r = self.with_home(|home| { diff --git a/crates/aien-runtime/tests/allen_persona_ipc_test.rs b/crates/aien-runtime/tests/allen_persona_ipc_test.rs new file mode 100644 index 00000000..07aa269c --- /dev/null +++ b/crates/aien-runtime/tests/allen_persona_ipc_test.rs @@ -0,0 +1,76 @@ +//! ALLEN persona profile commands over the runtime socket (arch#159): routing +//! only. ALLEN is not engaged here, so status answers "not_engaged" and a +//! change is refused. In a stub omega build the compose home cannot open and +//! the daemon says so (the answer is an error, never a made-up identity). +use aien_allen::ENV_SUBJECT; +use aien_inference_abi::MockInferenceBackend; +use aien_kv_cache::create_shared_kv_manager; +use aien_runtime::client::AienRuntimeClient; +use aien_runtime::control::{ControlCommand, ControlResponse}; +use aien_runtime::server::AienRuntimeServer; +use aien_runtime::spine::AienRuntimeSpine; +use aien_scheduler::SchedulerConfig; +use std::time::Duration; + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn allen_commands_route_through_the_socket() { + let tmp = tempfile::tempdir().unwrap(); + // Only this test binary sets these; one test per binary avoids env races. + std::env::set_var("AIEN_COMPOSE_DIR", tmp.path().join("compose")); + std::env::remove_var(ENV_SUBJECT); + let socket = tmp.path().join("runtime.sock"); + let cfg = SchedulerConfig { + max_batch_size: 8, + max_batch_tokens: 1024, + prefill_chunk_size: 64, + watermark_blocks: 4, + chunk_prefill: true, + max_prefill_tokens: 1024, + }; + let spine = AienRuntimeSpine::new(64, cfg, create_shared_kv_manager(256, 16)); + let server = AienRuntimeServer::new(spine, &socket); + let handle = tokio::spawn(async move { server.run(MockInferenceBackend::new(1)).await }); + let client = AienRuntimeClient::new(&socket); + let mut alive = false; + for _ in 0..100 { + if client.is_alive().await { + alive = true; + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + assert!(alive); + let linked = aien_omega_compose::LINKED; + + let st = client + .send_command(ControlCommand::AllenStatus) + .await + .unwrap(); + match (st, linked) { + (ControlResponse::AllenStatusReport(s), true) => { + assert_eq!(s.identity, "not_engaged"); + assert_eq!(s.model, "model:StreamTurn-path"); + assert_eq!(s.unsupported, vec!["avatar", "voice"]); + } + (ControlResponse::Error(e), false) => assert!(e.contains("not linked"), "{e}"), + (o, l) => panic!("unexpected {o:?} (linked={l})"), + } + let set = client + .send_command(ControlCommand::AllenProfileSet { + expected_revision: 0, + changes: aien_allen_profile::Changes { + name: Some("Nova".into()), + ..Default::default() + }, + }) + .await + .unwrap(); + match (set, linked) { + (ControlResponse::AllenRefused(r), true) => assert_eq!(r.code, "not_engaged"), + (ControlResponse::Error(e), false) => assert!(e.contains("not linked"), "{e}"), + (o, l) => panic!("unexpected {o:?} (linked={l})"), + } + assert!(!tmp.path().join("compose.allen-profile").exists()); + let _ = client.send_command(ControlCommand::Shutdown).await; + let _ = tokio::time::timeout(Duration::from_secs(5), handle).await; +} diff --git a/crates/aien-runtime/tests/allen_persona_test.rs b/crates/aien-runtime/tests/allen_persona_test.rs new file mode 100644 index 00000000..9b3b6384 --- /dev/null +++ b/crates/aien-runtime/tests/allen_persona_test.rs @@ -0,0 +1,536 @@ +//! ALLEN persona profile (arch#159) in the runtime. FIXTURE-ONLY: identities +//! come from the test-only subject encoder in aien-allen/tests/support, resolved +//! through the production resolver. No model runs. +//! +//! Part A needs no composition library and always runs. Part B (marked +//! `b_*`) re-executes this binary against a real compose home and reports +//! NOT_RUN in a stub omega build, like allen_spine_test. +#[path = "../../aien-allen/tests/support/mod.rs"] +mod support; + +use aien_allen::binding::pin_path; +use aien_allen::deployment::{self, Input}; +use aien_allen::resolve::{resolve, Context, Resolved, SubjectSource}; +use aien_allen::{hex, ENV_ADOPT, ENV_SUBJECT}; +use aien_allen_profile::{profile_dir, Changes, Identity, Store, Tone}; +use aien_omega_compose::LINKED; +use aien_runtime::control::{ComposeTaskReport, ControlCommand, ControlResponse, PersonaReport}; +use aien_runtime::persona::{context_for, handle_allen_command, prefix_prompt, report_for}; +use aien_runtime::spine::{task_prompt, ComposeBridge, ComposeProposer, Generation}; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::Arc; + +struct Rig { + _t: tempfile::TempDir, + home: PathBuf, + r: Resolved, +} + +fn rig() -> Rig { + let t = tempfile::tempdir().unwrap(); + let f = support::fx("persona"); + let c = support::chain(&f, 2); + let subj = support::write_head(&t.path().join("subject.bin"), c.last().unwrap()); + let home = t.path().join("compose"); + let r = resolve( + &SubjectSource::Head(subj), + &pin_path(&home), + &Context { + machine_id: [1; 32], + lineage: Some(f.cortex), + }, + Some(&hex(&f.agent)), + ) + .unwrap(); + Rig { _t: t, home, r } +} + +fn set(expected: u64, ch: Changes) -> ControlCommand { + ControlCommand::AllenProfileSet { + expected_revision: expected, + changes: ch, + } +} + +fn name(n: &str) -> Changes { + Changes { + name: Some(n.into()), + ..Default::default() + } +} + +fn run(rig: &Rig, cmd: ControlCommand) -> ControlResponse { + handle_allen_command(&rig.home, Some(&rig.r), "model:test", &cmd) +} + +fn profile(r: ControlResponse) -> aien_runtime::control::AllenProfileReport { + match r { + ControlResponse::AllenProfile(p) => *p, + o => panic!("expected AllenProfile, got {o:?}"), + } +} + +fn refusal(r: ControlResponse) -> aien_runtime::control::AllenRefusalReport { + match r { + ControlResponse::AllenRefused(p) => *p, + o => panic!("expected AllenRefused, got {o:?}"), + } +} + +fn dir_bytes(d: &Path) -> Vec<(String, Vec)> { + let mut v: Vec<_> = std::fs::read_dir(d) + .unwrap() + .map(|e| { + let e = e.unwrap(); + ( + e.file_name().to_string_lossy().into_owned(), + std::fs::read(e.path()).unwrap(), + ) + }) + .collect(); + v.sort(); + v +} + +#[test] +fn not_engaged_refuses_profile_commands_and_changes_nothing() { + let t = tempfile::tempdir().unwrap(); + let home = t.path().join("compose"); + for cmd in [ + ControlCommand::AllenProfileShow, + ControlCommand::AllenProfileHistory, + set(0, name("Nova")), + ControlCommand::AllenProfileRevert { + expected_revision: 1, + to: 1, + }, + ControlCommand::AllenProfileReset { + expected_revision: 1, + }, + ] { + let r = refusal(handle_allen_command(&home, None, "model:test", &cmd)); + assert_eq!(r.code, "not_engaged"); + assert!(r.message.contains("not engaged")); + } + assert!(!profile_dir(&home).exists()); + // Status still answers, and says so. + match handle_allen_command(&home, None, "model:test", &ControlCommand::AllenStatus) { + ControlResponse::AllenStatusReport(s) => { + assert_eq!(s.identity, "not_engaged"); + assert_eq!(s.persona.state, "not_engaged"); + assert!(s.fingerprint.is_none()); + assert_eq!(s.unsupported, vec!["avatar", "voice"]); + } + o => panic!("{o:?}"), + } + // The task prompt is byte-identical when ALLEN is not engaged. + assert!(context_for(&home, None).is_none()); + assert_eq!(prefix_prompt("PROMPT", None), "PROMPT"); +} + +#[test] +fn engaged_set_show_history_revert_reset_and_stale() { + let rig = rig(); + let p = profile(run(&rig, ControlCommand::AllenProfileShow)); + assert_eq!((p.revision, p.state.as_str()), (0, "default")); + assert_eq!(p.defaults.unwrap().display_name, "ALLEN"); + + let ch = Changes { + name: Some("Nova".into()), + tone: Some(Tone::Warm), + ..Default::default() + }; + let p = profile(run(&rig, set(0, ch))); + assert_eq!(p.revision, 1); + // Stale expect: refused, the current revision is reported, nothing written. + let e = refusal(run(&rig, set(0, name("Other")))); + assert_eq!( + (e.code.as_str(), e.current_revision), + ("stale_update", Some(1)) + ); + assert!(e.message.contains("--expect 1")); + profile(run(&rig, set(1, name("Echo")))); + match run(&rig, ControlCommand::AllenProfileHistory) { + ControlResponse::AllenHistory(h) => assert_eq!(h.entries.len(), 2), + o => panic!("{o:?}"), + } + let p = profile(run( + &rig, + ControlCommand::AllenProfileRevert { + expected_revision: 2, + to: 1, + }, + )); + assert_eq!(p.profile.unwrap().persona.display_name, "Nova"); + let p = profile(run( + &rig, + ControlCommand::AllenProfileReset { + expected_revision: 3, + }, + )); + assert_eq!(p.profile.unwrap().persona.display_name, "ALLEN"); + // Status shows identity and profile separately; the identity never moved. + match run(&rig, ControlCommand::AllenStatus) { + ControlResponse::AllenStatusReport(s) => { + assert_eq!(s.identity, "engaged"); + assert_eq!(s.fingerprint.as_deref(), Some(&hex(&rig.r.agent)[..8])); + assert_eq!(s.head_sequence, Some(rig.r.head_seq)); + assert_eq!(s.persona.revision, 4); + assert_eq!(s.execution_mode, "local_model"); + } + o => panic!("{o:?}"), + } +} + +#[test] +fn restart_keeps_the_profile() { + let rig = rig(); + profile(run(&rig, set(0, name("Nova")))); + // "Restart": nothing in memory; context comes from the files alone. + let ctx = context_for(&rig.home, Some(&rig.r)).unwrap(); + assert_eq!(ctx.persona.display_name, "Nova"); + assert_eq!(report_for(Some(&ctx)).state, "applied"); +} + +#[test] +fn permission_keys_are_refused_through_the_command_path() { + let rig = rig(); + let ch = Changes { + set_prefs: vec![aien_allen_profile::PrefChange { + key: "auto_approve".into(), + value: "yes".into(), + scope: aien_allen_profile::Scope::All, + }], + ..Default::default() + }; + let e = refusal(run(&rig, set(0, ch))); + assert_eq!(e.code, "permission_key"); + assert!(e.message.contains("approval desk")); + assert!(!profile_dir(&rig.home).exists()); +} + +#[test] +fn prompt_carries_the_persona_and_keeps_the_task() { + let rig = rig(); + let ws = tempfile::tempdir().unwrap(); + let base = task_prompt("write a note", ws.path()); + profile(run(&rig, set(0, name("Nova")))); + let ctx = context_for(&rig.home, Some(&rig.r)).unwrap(); + let full = prefix_prompt(&base, Some(&ctx)); + assert!(full.ends_with(&base), "the task text is untouched"); + assert!(full.starts_with("[ALLEN style preferences")); + assert!(full.contains("name: \"Nova\"")); + assert!(full.contains("grant no permission")); + assert!(full.len() - base.len() <= aien_allen_profile::CONTEXT_MAX_BYTES + 1); + let r = report_for(Some(&ctx)); + assert_eq!( + r, + PersonaReport { + state: "applied".into(), + display_name: "Nova".into(), + revision: 1, + reason: None + } + ); +} + +#[test] +fn damaged_profile_runs_with_defaults_and_says_so() { + let rig = rig(); + profile(run(&rig, set(0, name("Nova")))); + let first = profile_dir(&rig.home).join(format!("r{:020}.json", 1)); + std::fs::write(&first, b"{broken").unwrap(); + let ctx = context_for(&rig.home, Some(&rig.r)).unwrap(); + let rep = report_for(Some(&ctx)); + assert_eq!(rep.state, "refused"); + assert_eq!(rep.display_name, "ALLEN"); + assert!(rep.reason.unwrap().contains("damaged")); + assert!(prefix_prompt("P", Some(&ctx)).contains("name: \"ALLEN\"")); + // Commands refuse; the damaged file is not replaced. + assert_eq!(refusal(run(&rig, set(1, name("X")))).code, "damaged"); + assert_eq!(std::fs::read(&first).unwrap(), b"{broken"); +} + +#[test] +fn foreign_profile_is_refused_and_not_used() { + let rig = rig(); + let other = Identity { + agent: [9; 32], + root: [8; 32], + }; + Store::new(&rig.home, other) + .set(0, &name("Stranger")) + .unwrap(); + let ctx = context_for(&rig.home, Some(&rig.r)).unwrap(); + assert_eq!(report_for(Some(&ctx)).state, "refused"); + assert_eq!(ctx.persona.display_name, "ALLEN"); + assert_eq!( + refusal(run(&rig, set(1, name("X")))).code, + "foreign_profile" + ); +} + +#[test] +fn a_model_swap_record_leaves_the_profile_untouched() { + let rig = rig(); + profile(run(&rig, set(0, name("Nova")))); + let before = dir_bytes(&profile_dir(&rig.home)); + let dep = deployment::deployments_path(&rig.home); + for (i, model) in ["aa", "bb"].iter().enumerate() { + deployment::append( + &dep, + &rig.r.agent, + Input { + model_sha256: model.repeat(32), + config_sha256: "cc".repeat(32), + candidate_id: format!("cand-{i}"), + executable_sha256: "dd".repeat(32), + revision: "r".into(), + placeholder: true, + }, + ) + .unwrap(); + } + assert_eq!(before, dir_bytes(&profile_dir(&rig.home))); + let ctx = context_for(&rig.home, Some(&rig.r)).unwrap(); + assert_eq!(ctx.persona.display_name, "Nova"); + match run(&rig, ControlCommand::AllenStatus) { + ControlResponse::AllenStatusReport(s) => { + let d = s.deployment.unwrap(); + assert_eq!((d.seq, d.candidate_id.as_str()), (2, "cand-1")); + assert_eq!(s.persona.display_name, "Nova"); + } + o => panic!("{o:?}"), + } +} + +/// No code path from a task, a model reply or a workspace file to the profile +/// writer: only the operator-command handler in persona.rs calls a writer, +/// and nothing else in the runtime even names the profile crate's store. +#[test] +fn only_the_command_handler_can_write_the_profile() { + let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + for ent in std::fs::read_dir(&src).unwrap() { + let p = ent.unwrap().path(); + let name = p.file_name().unwrap().to_string_lossy().into_owned(); + let text = std::fs::read_to_string(&p).unwrap(); + if name != "persona.rs" && name != "control.rs" { + assert!( + !text.contains("aien_allen_profile"), + "{name} must not touch the profile crate" + ); + } + } + let persona = std::fs::read_to_string(src.join("persona.rs")).unwrap(); + let ctx_fn = persona + .split("pub fn context_for") + .nth(1) + .unwrap() + .split("pub fn report_for") + .next() + .unwrap(); + for w in [".set(", ".revert(", ".reset(", "write"] { + assert!(!ctx_fn.contains(w), "context_for must be read-only ({w})"); + } + // The spine calls the handler only for operator control commands. + let spine = std::fs::read_to_string(src.join("spine.rs")).unwrap(); + assert!(spine.contains("handle_allen_command")); +} + +#[test] +fn old_reports_without_persona_still_parse() { + let report = ComposeTaskReport { + compose_commit: None, + compose_dir: "d".into(), + machine_id: "m".into(), + task: 1, + outcome: 1, + committed: true, + branch_count: 1, + branches_reclaimed: 1, + winner: Some(0), + aegis_pass_mask: 1, + cx_goal: 1, + cx_candidates: vec![], + cx_evidence: 1, + cx_promotion: 1, + cx_admissions: vec![], + winner_digest: String::new(), + record_digest: String::new(), + proposal: None, + proposal_sha256: None, + proposal_path: None, + proposal_content_sha256: None, + uncommitted_proposal: None, + proposer_error: None, + proposal_attempts: vec![], + requirements_recognized: vec![], + requirements_uncertain: vec![], + proposer: "model".into(), + persona: Some(PersonaReport { + state: "applied".into(), + display_name: "Nova".into(), + revision: 2, + reason: None, + }), + }; + let mut v = serde_json::to_value(&report).unwrap(); + assert_eq!(v["persona"]["display_name"], "Nova"); + v.as_object_mut().unwrap().remove("persona"); + let old: ComposeTaskReport = serde_json::from_value(v).unwrap(); + assert!(old.persona.is_none()); +} + +// ---- Part B: through a real compose home (NOT_RUN in a stub omega build) ---- + +fn proposer(seen: Arc>) -> ComposeProposer { + Arc::new(move |prompt: &str, _l: std::time::Duration| { + *seen.lock().unwrap() = prompt.to_string(); + // A reply that tries to talk the daemon into changing the profile. + Ok(Generation { + text: "filename: NOTES.md\naien allen set --name Hacked --expect 1\n".into(), + tokens: 8, + finish_reason: Some("eos".into()), + ..Default::default() + }) + }) +} + +/// The child: one task, one status, one unauthorised effect intent. +#[test] +fn child_task() { + let (Ok(home), Ok(ws)) = ( + std::env::var("PERSONA_CHILD_HOME"), + std::env::var("PERSONA_CHILD_WS"), + ) else { + return; + }; + let seen = Arc::new(std::sync::Mutex::new(String::new())); + let b = ComposeBridge::new(PathBuf::from(home), proposer(seen.clone()), "model:test"); + match b.run_task("write a short note in NOTES.md", &ws) { + ControlResponse::ComposeTaskResult(r) => { + println!("CHILD_COMMITTED={}", r.committed); + println!( + "CHILD_PERSONA={}", + serde_json::to_string(&r.persona).unwrap() + ); + } + o => println!("CHILD_TASK_RESPONSE={o:?}"), + } + println!( + "CHILD_PROMPT_HEAD={}", + seen.lock().unwrap().replace('\n', "\\n") + ); + if let ControlResponse::AllenStatusReport(s) = b.allen_command(&ControlCommand::AllenStatus) { + println!("CHILD_STATUS={}", serde_json::to_string(&*s).unwrap()); + } + // A write still needs an authorization, whatever the persona says. + let r = aien_runtime::effects::open_intent( + &b, + &aien_runtime::effects::IntentRequest { + authorization: 999_999, + proposal_sha256: "0".repeat(64), + path: "NOTES.md".into(), + target: ws.clone(), + content_sha256: "0".repeat(64), + executor_pid: 1, + executor_start: 1, + }, + ); + println!( + "CHILD_INTENT_REFUSED={}", + matches!(r, ControlResponse::Error(_)) + ); +} + +fn child(home: &Path, ws: Option<&Path>, env: &[(&str, &str)]) -> (i32, String, String) { + let mut c = Command::new(std::env::current_exe().unwrap()); + c.args(["--exact", "child_task", "--nocapture", "--test-threads=1"]) + .env("PERSONA_CHILD_HOME", home) + .env_remove(ENV_SUBJECT) + .env_remove(ENV_ADOPT); + if let Some(w) = ws { + c.env("PERSONA_CHILD_WS", w); + } else { + c.env("PERSONA_CHILD_WS", home.parent().unwrap()); + } + for (k, v) in env { + c.env(k, v); + } + let o = c.output().unwrap(); + ( + o.status.code().unwrap_or(-1), + String::from_utf8_lossy(&o.stdout).into_owned(), + String::from_utf8_lossy(&o.stderr).into_owned(), + ) +} + +#[test] +fn b_engaged_task_uses_the_persona_and_a_reply_cannot_change_it() { + if !LINKED { + println!("NOT_RUN: stub omega build (no librx_compose.a); set AIEN_OMEGA_COMPOSE_DIR"); + return; + } + let t = tempfile::tempdir().unwrap(); + let home = t.path().join("compose"); + let ws = t.path().join("ws"); + std::fs::create_dir_all(&ws).unwrap(); + // Not engaged first: creates the home, no persona text, report says so. + let (code, out, err) = child(&home, Some(&ws), &[]); + assert_eq!(code, 0, "{out}{err}"); + assert!(out.contains("\"state\":\"not_engaged\""), "{out}"); + assert!(!out.contains("ALLEN style preferences"), "{out}"); + // Engage: subject built for this home's Cortex lineage, adopted once. + let mut name = home.as_os_str().to_owned(); + name.push(".machine-root"); + let root = std::fs::read(PathBuf::from(name)).unwrap(); + let (mut c, _) = aien_omega_compose::Compose::open( + &home, + aien_omega_compose::RootKind::Provisioned, + &root, + 0xA1E4_0001, + ) + .unwrap(); + let lineage = c.record(1).unwrap().digest; + drop(c); + let mut f = support::fx("persona-b"); + f.cortex = lineage; + let chain = support::chain(&f, 2); + let subj = support::write_head(&t.path().join("subject.bin"), chain.last().unwrap()); + let env = [ + (ENV_SUBJECT, subj.to_str().unwrap()), + (ENV_ADOPT, &hex(&f.agent)[..]), + ]; + // Adoption run (no profile yet): defaults, state "default". + let (code, out, err) = child(&home, Some(&ws), &env); + assert_eq!(code, 0, "{out}{err}"); + assert!(out.contains("\"state\":\"default\""), "{out}"); + assert!(out.contains("CHILD_INTENT_REFUSED=true"), "{out}"); + // Save a profile, run again. + let store = Store::new( + &home, + Identity { + agent: f.agent, + root: f.root, + }, + ); + store.set(0, &name_change("Nova")).unwrap(); + let before = dir_bytes(&profile_dir(&home)); + let (code, out, err) = child(&home, Some(&ws), &[(ENV_SUBJECT, subj.to_str().unwrap())]); + assert_eq!(code, 0, "{out}{err}"); + assert!( + out.contains("\"state\":\"applied\"") && out.contains("\"display_name\":\"Nova\""), + "{out}" + ); + assert!(out.contains("name: \"Nova\"\\ntone: neutral"), "{out}"); + assert!(out.contains("CHILD_INTENT_REFUSED=true"), "{out}"); + assert!(out.contains("\"identity\":\"engaged\""), "{out}"); + // The model reply asked for a rename; the profile did not move. + assert_eq!(before, dir_bytes(&profile_dir(&home))); + assert!(!ws.join("NOTES.md").exists(), "no write without authorize"); +} + +fn name_change(n: &str) -> Changes { + name(n) +}