This commit is contained in:
Meta Vens 2026-12-06 07:52:07 +01:00
commit 70079777a8
3 changed files with 2984 additions and 56 deletions

View file

@ -22,6 +22,7 @@ mod config;
mod door;
mod import;
mod near;
mod persona;
mod recall;
mod recipes;
mod render;
@ -42,7 +43,7 @@ use huginn_mind::eureka_pipeline::{
};
use huginn_mind::{
BATCH_MAX, ChatQuery, ChatWindowQuery, Faculty, HuginnMindRequest, HuginnMindResponse, MindRefusal, PipelineAdmissionBatch, PipelineAdmissionOutcome,
PersonaPutOutcome, PipelinePageItems, PipelineProvenance, PipelineSelectionPage, SemanticQuery, SourceQuery,
PipelinePageItems, PipelineProvenance, PipelineSelectionPage, SemanticQuery, SourceQuery,
};
use serde_json::Value;
@ -218,7 +219,7 @@ enum Command {
/// The mind's persona document (gamecult.persona_state.v0).
Persona {
#[command(subcommand)]
command: PersonaCommand,
command: Box<PersonaCommand>,
},
}
@ -261,9 +262,31 @@ enum PersonaCommand {
/// The whole document file, or - for stdin.
file: String,
},
/// Render the privacy-stripped public-Matrix session bootstrap prompt; `absent` (exit 1) until the first put.
Seed,
/// Add or retire/resolve/crystallize an anchored thought in thoughtMemory.
Memory {
#[command(subcommand)]
command: persona::MemoryCommand,
},
/// Create or update a person bond in affect.socialBonds.
Bond {
#[command(subcommand)]
command: persona::BondCommand,
},
/// Set/clear named feelings or update situationalState mood axes.
Mood {
#[command(subcommand)]
command: persona::MoodCommand,
},
/// Add or drop an intention in candidateActions.actions.
Intention {
#[command(subcommand)]
command: persona::IntentionCommand,
},
}
fn faculty(text: &str) -> Result<Faculty, String> {
pub(crate) fn faculty(text: &str) -> Result<Faculty, String> {
serde_json::from_value(Value::String(text.to_string())).map_err(|error| error.to_string())
}
@ -315,7 +338,7 @@ fn main() -> ExitCode {
}
}
fn say(text: impl std::fmt::Display) {
pub(crate) fn say(text: impl std::fmt::Display) {
let _ = writeln!(std::io::stdout(), "{text}");
}
@ -351,10 +374,7 @@ fn run(settings: &Settings, command: Command) -> Result<u8, Trouble> {
let session = settings.session(session)?;
import::run(settings, import::Flags { campaign, from, from_endpoint, faculty, agent, session })
}
Command::Persona { command: PersonaCommand::Get } => persona_get(settings),
Command::Persona { command: PersonaCommand::Put { faculty, agent, session, expected_updated_at, file } } => {
persona_put(settings, faculty, agent, session, expected_updated_at, &file)
}
Command::Persona { command } => persona::run(settings, *command),
Command::Recall { command: RecallCommand::Dispatch { top_k, max_anchors, budget, deadline_ms } } => Ok(recall::dispatch(
settings,
&recall::Flags { top_k: top_k as usize, max_anchors: max_anchors as usize, budget: budget as usize, deadline_ms },
@ -733,56 +753,12 @@ fn differences(sent: &Value, held: &Value, path: &str, out: &mut Vec<String>) {
}
/// A refusal is the mind's answer: stdout, exit 1.
fn refused(refusal: &MindRefusal) -> u8 {
pub(crate) fn refused(refusal: &MindRefusal) -> u8 {
say(format_args!("Refused {refusal:?}"));
1
}
fn persona_get(settings: &Settings) -> Result<u8, Trouble> {
match settings.client()?.persona_get().map_err(Trouble::from)? {
HuginnMindResponse::Persona(Some(view)) => {
say(serde_json::to_string_pretty(&view.value).map_err(|error| Trouble::Internal(error.to_string()))?);
say(format_args!("updatedAt {} receipt {}", view.updated_at, view.receipt_id));
Ok(0)
}
HuginnMindResponse::Persona(None) => {
say("absent");
Ok(1)
}
HuginnMindResponse::Refused(refusal) => Ok(refused(&refusal)),
other => Err(unexpected(&other)),
}
}
fn persona_put(
settings: &Settings,
faculty: Faculty,
agent: String,
session: Option<String>,
expected_updated_at: Option<String>,
file: &str,
) -> Result<u8, Trouble> {
let session = settings.session(session)?;
let text = door::file_or_stdin(file)?;
let state: Value = serde_json::from_str(&text)
.map_err(|error| Trouble::invalid(format!("the persona document is not JSON: {error}")))?;
if !state.is_object() {
return Err(Trouble::invalid("the persona document is one JSON object, the whole gamecult.persona_state.v0"));
}
let provenance = PipelineProvenance { faculty, agent: Short(agent), session: Short(session), tool: Short(TOOL.to_string()), imported_from: None };
match settings.client()?.persona_put(provenance, state, expected_updated_at).map_err(Trouble::from)? {
HuginnMindResponse::PersonaPut(PersonaPutOutcome::Committed { receipt_id }) => {
say(format_args!("Committed {receipt_id}"));
Ok(0)
}
HuginnMindResponse::PersonaPut(PersonaPutOutcome::Refused(refusal)) | HuginnMindResponse::Refused(refusal) => {
Ok(refused(&refusal))
}
other => Err(unexpected(&other)),
}
}
fn unexpected(answer: &HuginnMindResponse) -> Trouble {
pub(crate) fn unexpected(answer: &HuginnMindResponse) -> Trouble {
let name = match answer {
HuginnMindResponse::Whoami(_) => "whoami",
HuginnMindResponse::Admit(_) => "admit",

File diff suppressed because it is too large Load diff

View file

@ -18,8 +18,9 @@ use huginn_mind::eureka_pipeline::{
pipeline_key,
};
use huginn_mind::{
AdmissionFacts, HuginnMindRequest, HuginnMindResponse, IndexStatus, MindRefusal, MindStatus, PersonaStatus, PipelineAdmissionOutcome, PipelineDocumentView,
PersonaPutOutcome, PipelinePageItems, PipelineProvenance, PipelineSelectionPage, PipelineStatus,
AdmissionFacts, HuginnMindRequest, HuginnMindResponse, IndexStatus, MindRefusal, MindStatus, PersonaPutOutcome,
PersonaStateView, PersonaStatus, PipelineAdmissionOutcome, PipelineDocumentView, PipelinePageItems,
PipelineProvenance, PipelineSelectionPage, PipelineStatus,
};
use huginn_daemon::{Daemon, Hits, IndexSink, SearchTicket};
use huginn_mind::MindStore;
@ -3057,3 +3058,980 @@ fn chat_window_prints_the_anchor_marked_and_refuses_what_the_index_lacks() {
let HuginnMindRequest::ChatWindow { query, .. } = seen.lock().unwrap().remove(0) else { panic!("a chat window") };
assert_eq!((query.event_id.0.as_str(), query.before, query.after), ("$a", 3, 0));
}
fn fetch_persona_json(addr: SocketAddr) -> Value {
let got = at(addr, &["persona", "get"], None);
assert_eq!(got.code, 0, "{} {}", got.out, got.err);
let (doc, _) = got.out.rsplit_once("\nupdatedAt").unwrap();
serde_json::from_str(doc).unwrap()
}
fn seed_persona(addr: SocketAddr, doc: &Value) {
let dir = tempfile::tempdir().unwrap();
let file = write(&dir, "seed.json", doc);
let put = at(addr, &persona_put_args(&file, None), None);
assert_eq!(put.code, 0, "{} {}", put.out, put.err);
}
#[test]
fn persona_memory_add_and_retire_round_trip_cas() {
let (root, daemon) = mind(vec![]);
let server = serve(root, daemon);
seed_persona(server.addr, &persona(INSTANCE, "2026-10-10T10:00:00Z"));
// 1. memory add (default short-term, default self:<instance> target)
let added = at(
server.addr,
&[
"persona", "memory", "add",
"--faculty", "Hands", "--agent", "eureka-persona", "--session", "s1",
"--summary", "Kept a note about Matrix room sync",
"--tension", "lagging events",
"--action-implication", "check cursor",
"--claim", "cursor lags on reconnect",
"--importance", "0.8",
"--valence", "-0.25",
"--tag", "room:#swarm:gamecult.org",
"--tag", "about:meta",
],
None,
);
assert_eq!(added.code, 0, "{} {}", added.out, added.err);
let mut lines = added.out.lines();
assert!(lines.next().unwrap().starts_with("Committed "), "{}", added.out);
let st_id = lines.next().unwrap().strip_prefix("id ").expect(&added.out).to_string();
assert!(st_id.starts_with("m-"), "{st_id}");
// 2. memory add (--kind incubation, explicit target & question & id)
let inc = at(
server.addr,
&[
"persona", "memory", "add",
"--faculty", "Hands", "--agent", "eureka-persona", "--session", "s1",
"--kind", "incubation", "--id", "w-custom-1",
"--summary", "Why did the socket drop?",
"--question", "Did keepalive expire?",
"--target-kind", "person", "--target-id", "meta", "--target-label", "Meta",
],
None,
);
assert_eq!(inc.code, 0, "{} {}", inc.out, inc.err);
assert!(inc.out.contains("id w-custom-1\n"), "{}", inc.out);
// 3. memory add (--kind memory -> crystallized, blank --question omitted)
let mem = at(
server.addr,
&[
"persona", "memory", "add",
"--faculty", "Hands", "--agent", "eureka-persona", "--session", "s1",
"--kind", "memory",
"--summary", "Direct crystallized memory",
"--question", " ",
],
None,
);
assert_eq!(mem.code, 0, "{} {}", mem.out, mem.err);
let mem_id = mem.out.lines().nth(1).unwrap().strip_prefix("id ").unwrap().to_string();
// Duplicate explicit id across pools is rejected (exit 2) without changing stored state.
let dup = at(
server.addr,
&[
"persona", "memory", "add",
"--faculty", "Hands", "--agent", "eureka-persona", "--session", "s1",
"--id", "w-custom-1", "--summary", "Duplicate id",
],
None,
);
assert_eq!(dup.code, 2, "{} {}", dup.out, dup.err);
assert!(dup.err.starts_with("InvalidInput: "), "{}", dup.err);
let doc = fetch_persona_json(server.addr);
let st = &doc["thoughtMemory"]["shortTerm"][0];
assert_eq!(st["id"], st_id);
assert_eq!(st["status"], "active");
assert_eq!(st["target"], json!({ "kind": "self", "id": INSTANCE }));
assert_eq!(st["tension"], "lagging events");
assert_eq!(st["actionImplication"], "check cursor");
assert_eq!(st["claim"], "cursor lags on reconnect");
assert_eq!(st["intensity"], 0.8);
assert_eq!(st["valence"], -0.25);
assert_eq!(st["tags"], json!(["room:#swarm:gamecult.org", "about:meta"]));
assert_eq!(doc["thoughtMemory"]["memories"][0]["id"], mem_id);
assert_eq!(doc["thoughtMemory"]["memories"][0]["status"], "crystallized");
assert!(doc["thoughtMemory"]["memories"][0].get("question").is_none());
assert!(doc["thoughtMemory"]["memories"][0].get("tags").is_none());
assert_eq!(doc["thoughtMemory"]["incubation"][0]["question"], "Did keepalive expire?");
assert_eq!(doc["thoughtMemory"]["incubation"][0]["target"], json!({ "kind": "person", "id": "meta", "label": "Meta" }));
// 4. memory retire --status crystallized moves shortTerm -> memories
let cryst = at(
server.addr,
&[
"persona", "memory", "retire",
"--faculty", "Hands", "--agent", "eureka-persona", "--session", "s1",
"--status", "crystallized", &st_id,
],
None,
);
assert_eq!(cryst.code, 0, "{} {}", cryst.out, cryst.err);
assert!(cryst.out.starts_with("Committed "), "{}", cryst.out);
// 5. memory retire (default retired) sets retiredAt on incubation entry
let ret = at(
server.addr,
&[
"persona", "memory", "retire",
"--faculty", "Hands", "--agent", "eureka-persona", "--session", "s1",
"w-custom-1",
],
None,
);
assert_eq!(ret.code, 0, "{} {}", ret.out, ret.err);
// 6. memory retire --status resolved sets resolved without retiredAt
let res = at(
server.addr,
&[
"persona", "memory", "retire",
"--faculty", "Hands", "--agent", "eureka-persona", "--session", "s1",
"--status", "resolved", &mem_id,
],
None,
);
assert_eq!(res.code, 0, "{} {}", res.out, res.err);
let after = fetch_persona_json(server.addr);
assert!(after["thoughtMemory"]["shortTerm"].as_array().unwrap().is_empty());
let moved = after["thoughtMemory"]["memories"].as_array().unwrap().iter().find(|e| e["id"] == st_id).unwrap();
assert_eq!(moved["status"], "crystallized");
let inc_entry = &after["thoughtMemory"]["incubation"][0];
assert_eq!(inc_entry["status"], "retired");
assert!(inc_entry.get("retiredAt").and_then(Value::as_str).is_some());
let resolved_entry = after["thoughtMemory"]["memories"].as_array().unwrap().iter().find(|e| e["id"] == mem_id).unwrap();
assert_eq!(resolved_entry["status"], "resolved");
assert!(resolved_entry.get("retiredAt").is_none());
// 7. Unknown id exits 2 without PersonaPut.
let (spy, seen) = replying("persona_get", HuginnMindResponse::Persona(Some(PersonaStateView {
value: after,
updated_at: "2026-10-10T10:00:05Z".into(),
receipt_id: "r-1".into(),
})));
let unknown = at(
spy.addr,
&["persona", "memory", "retire", "--faculty", "Hands", "--agent", "a", "--session", "s", "missing-id"],
None,
);
assert_eq!(unknown.code, 2, "{} {}", unknown.out, unknown.err);
assert!(unknown.err.starts_with("InvalidInput: "), "{}", unknown.err);
assert!(seen.lock().unwrap().iter().all(|req| matches!(req, HuginnMindRequest::PersonaGet { .. })));
}
#[test]
fn persona_bond_mood_intention_round_trip_cas() {
let (root, daemon) = mind(vec![]);
let server = serve(root, daemon);
seed_persona(server.addr, &persona(INSTANCE, "2026-10-10T10:00:00Z"));
// 1. bond update: create new bond
let bond1 = at(
server.addr,
&[
"persona", "bond", "update",
"--faculty", "Hands", "--agent", "eureka-persona", "--session", "s1",
"--person", "meta", "--label", "Meta", "--kind", "collaborator",
"--summary", "Initial working rapport",
],
None,
);
assert_eq!(bond1.code, 0, "{} {}", bond1.out, bond1.err);
let bond_id = bond1.out.lines().nth(1).unwrap().strip_prefix("id ").unwrap().to_string();
assert!(bond_id.starts_with("b-"), "{bond_id}");
let doc1 = fetch_persona_json(server.addr);
let b = &doc1["affect"]["socialBonds"][0];
assert_eq!(b["subject"], json!({ "kind": "self", "id": INSTANCE }));
assert_eq!(b["object"], json!({ "kind": "person", "id": "meta", "label": "Meta" }));
assert_eq!(b["trust"], 0.5);
assert_eq!(b["tension"], 0.2);
assert_eq!(b["intensity"], 0.5);
let prior_updated = b["updatedAt"].as_str().unwrap().to_string();
// 2. bond update: signed clamped deltas + summary rotation into lastEvidence + custom kind
let bond2 = at(
server.addr,
&[
"persona", "bond", "update",
"--faculty", "Hands", "--agent", "eureka-persona", "--session", "s1",
"--person", "meta",
"--kind", "custom", "--custom-kind", "steward_partner",
"--trust", "+0.8", "--tension", "-0.5", "--intensity", "+0.25",
"--summary", "Deepened trust after Cut 1",
"--why", "Shipped clean cuts together",
],
None,
);
assert_eq!(bond2.code, 0, "{} {}", bond2.out, bond2.err);
assert_eq!(bond2.out.lines().nth(1).unwrap(), format!("id {bond_id}"));
let doc2 = fetch_persona_json(server.addr);
let b2 = &doc2["affect"]["socialBonds"][0];
assert_eq!(b2["trust"], 1.0);
assert_eq!(b2["tension"], 0.0);
assert_eq!(b2["intensity"], 0.75);
assert_eq!(b2["relationshipKind"], "custom");
assert_eq!(b2["customRelationshipKind"], "steward_partner");
assert_eq!(b2["summary"], "Deepened trust after Cut 1");
assert_eq!(b2["lastEvidence"]["summary"], "Initial working rapport");
assert_eq!(b2["lastEvidence"]["claim"], "Shipped clean cuts together");
assert_eq!(b2["lastEvidence"]["createdAt"], prior_updated);
// Second distinct person bond + --custom-kind update rules on existing custom vs non-custom bonds.
let nibu = at(
server.addr,
&[
"persona", "bond", "update",
"--faculty", "Hands", "--agent", "eureka-persona", "--session", "s1",
"--person", "nibu", "--label", "Nibu", "--kind", "ally", "--status", "active",
"--summary", "Peer bond",
],
None,
);
assert_eq!(nibu.code, 0, "{} {}", nibu.out, nibu.err);
let non_custom_err = at(
server.addr,
&[
"persona", "bond", "update",
"--faculty", "Hands", "--agent", "eureka-persona", "--session", "s1",
"--person", "nibu", "--custom-kind", "should_fail",
],
None,
);
assert_eq!(non_custom_err.code, 2, "{} {}", non_custom_err.out, non_custom_err.err);
let custom_ok = at(
server.addr,
&[
"persona", "bond", "update",
"--faculty", "Hands", "--agent", "eureka-persona", "--session", "s1",
"--person", "meta", "--custom-kind", "steward_partner_v2",
],
None,
);
assert_eq!(custom_ok.code, 0, "{} {}", custom_ok.out, custom_ok.err);
let doc_bonds = fetch_persona_json(server.addr);
let bonds_arr = doc_bonds["affect"]["socialBonds"].as_array().unwrap();
assert_eq!(bonds_arr.len(), 2);
assert_eq!(bonds_arr[0]["object"]["id"], "meta");
assert_eq!(bonds_arr[0]["customRelationshipKind"], "steward_partner_v2");
assert_eq!(bonds_arr[1]["object"]["id"], "nibu");
assert_eq!(bonds_arr[1]["status"], "active");
// 3. mood set: feeling + source + axis init + update in place + clear
let mood1 = at(
server.addr,
&[
"persona", "mood", "set",
"--faculty", "Hands", "--agent", "eureka-persona", "--session", "s1",
"--feeling", " Curious ", "--value", "0.75", "--source", "room:#swarm:gamecult.org",
"--axis", "valence", "--activation", "0.7", "--mean", "0.55", "--plasticity", "0.4",
],
None,
);
assert_eq!(mood1.code, 0, "{} {}", mood1.out, mood1.err);
let doc_mood1 = fetch_persona_json(server.addr);
assert_eq!(doc_mood1["affect"]["moodDimensions"][0]["source"], "room:#swarm:gamecult.org");
let mood2 = at(
server.addr,
&[
"persona", "mood", "set",
"--faculty", "Hands", "--agent", "eureka-persona", "--session", "s1",
"--feeling", "focused", "--value", "0.9",
"--clear-feeling", "CURIOUS",
"--axis", "valence", "--activation", "+0.5",
],
None,
);
assert_eq!(mood2.code, 0, "{} {}", mood2.out, mood2.err);
let mood3 = at(
server.addr,
&[
"persona", "mood", "set",
"--faculty", "Hands", "--agent", "eureka-persona", "--session", "s1",
"--feeling", "focused", "--value", "0.4", "--source", " ",
],
None,
);
assert_eq!(mood3.code, 0, "{} {}", mood3.out, mood3.err);
let doc3 = fetch_persona_json(server.addr);
let feelings = doc3["affect"]["moodDimensions"].as_array().unwrap();
assert_eq!(feelings.len(), 1);
assert_eq!(feelings[0]["name"], "focused");
assert_eq!(feelings[0]["value"], 0.4);
assert!(feelings[0].get("source").is_none());
let valence_vec = &doc3["activationProfile"]["situationalState"]["valence"];
assert_eq!(valence_vec["mean"], 0.55);
assert_eq!(valence_vec["plasticity"], 0.4);
assert_eq!(valence_vec["currentActivation"], 1.0);
// 4. intention add + duplicate guard + drop + re-add
let int1 = at(
server.addr,
&[
"persona", "intention", "add",
"--faculty", "Hands", "--agent", "eureka-persona", "--session", "s1",
"--summary", "Check public Matrix room",
"--readiness", "ready", "--urgency", "0.8", "--confidence", "0.9",
"--rationale", "Verify peer traffic", "--expires-in-hours", "12",
"--target-kind", "room", "--target-id", "#swarm:gamecult.org",
],
None,
);
assert_eq!(int1.code, 0, "{} {}", int1.out, int1.err);
let int_id = int1.out.lines().nth(1).unwrap().strip_prefix("id ").unwrap().to_string();
assert!(int_id.starts_with("i-"), "{int_id}");
let dup_int = at(
server.addr,
&[
"persona", "intention", "add",
"--faculty", "Hands", "--agent", "eureka-persona", "--session", "s1",
"--summary", " check public matrix room ",
],
None,
);
assert_eq!(dup_int.code, 2, "{} {}", dup_int.out, dup_int.err);
assert!(dup_int.err.starts_with("InvalidInput: "), "{}", dup_int.err);
let dropped = at(
server.addr,
&[
"persona", "intention", "drop",
"--faculty", "Hands", "--agent", "eureka-persona", "--session", "s1",
&int_id,
],
None,
);
assert_eq!(dropped.code, 0, "{} {}", dropped.out, dropped.err);
let doc4 = fetch_persona_json(server.addr);
let act = &doc4["candidateActions"]["actions"][0];
assert_eq!(act["actionType"], "custom");
assert_eq!(act["customActionType"], "intention");
assert_eq!(act["riskLevel"], "low");
assert_eq!(act["status"], "retired");
assert_eq!(act["readiness"], "expired");
assert_eq!(act["rationale"], "Verify peer traffic");
assert!(act["expiresAt"].as_str().is_some());
// After drop, adding the same normalized summary succeeds with a fresh id, and a second distinct active intention also succeeds.
let readd = at(
server.addr,
&[
"persona", "intention", "add",
"--faculty", "Hands", "--agent", "eureka-persona", "--session", "s1",
"--summary", "check public matrix room",
"--rationale", " ",
],
None,
);
assert_eq!(readd.code, 0, "{} {}", readd.out, readd.err);
let second = at(
server.addr,
&[
"persona", "intention", "add",
"--faculty", "Hands", "--agent", "eureka-persona", "--session", "s1",
"--summary", "Review open PRs",
],
None,
);
assert_eq!(second.code, 0, "{} {}", second.out, second.err);
let doc_int = fetch_persona_json(server.addr);
assert!(doc_int["candidateActions"]["actions"][1].get("rationale").is_none());
// Non-intention candidateActions entries neither block intention add nor allow intention drop.
let (root2, daemon2) = mind(vec![]);
let server2 = serve(root2, daemon2);
let mut with_other = persona(INSTANCE, "2026-10-10T10:00:00Z");
with_other["candidateActions"]["actions"].as_array_mut().unwrap().extend([
json!({
"id": "act-speak", "status": "active", "actionType": "speak",
"readiness": "ready", "riskLevel": "low",
"target": { "kind": "self", "id": INSTANCE },
"summary": "Non-intention speak",
"createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z"
}),
json!({
"id": "act-custom-other", "status": "active", "actionType": "custom", "customActionType": "other",
"readiness": "ready", "riskLevel": "low",
"target": { "kind": "self", "id": INSTANCE },
"summary": "Non-intention custom",
"createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z"
}),
]);
seed_persona(server2.addr, &with_other);
for same_summary in ["Non-intention speak", "Non-intention custom"] {
let ok = at(
server2.addr,
&["persona", "intention", "add", "--faculty", "Hands", "--agent", "a", "--session", "s", "--summary", same_summary],
None,
);
assert_eq!(ok.code, 0, "{same_summary}: {} {}", ok.out, ok.err);
}
for non_int_id in ["act-speak", "act-custom-other", "i-nope"] {
let missing_drop = at(
server2.addr,
&["persona", "intention", "drop", "--faculty", "Hands", "--agent", "a", "--session", "s", non_int_id],
None,
);
assert_eq!(missing_drop.code, 2, "{non_int_id}: {} {}", missing_drop.out, missing_drop.err);
}
}
#[test]
fn persona_delta_retries_stale_cas_bounded_and_preserves_identity() {
// 1. Two PersonaStale answers then Committed on 3rd attempt -> exits 0 with 3 gets + 3 puts.
let stamps = ["2026-10-10T10:00:00Z", "2026-10-10T10:00:01Z", "2026-10-10T10:00:02Z"];
let get_count = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let put_count = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let expected_seen = Arc::new(Mutex::new(Vec::new()));
let gc = Arc::clone(&get_count);
let pc = Arc::clone(&put_count);
let es = Arc::clone(&expected_seen);
let server = scripted(move |message| {
let (_, req) = decode_request(message).unwrap();
match req {
HuginnMindRequest::PersonaGet { .. } => {
let idx = gc.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let ts = stamps[idx.min(2)];
answer("persona_get", &HuginnMindResponse::Persona(Some(PersonaStateView {
value: persona(INSTANCE, ts),
updated_at: ts.into(),
receipt_id: format!("r-{idx}"),
})))
}
HuginnMindRequest::PersonaPut { expected_updated_at, .. } => {
let idx = pc.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
es.lock().unwrap().push(expected_updated_at);
if idx < 2 {
answer("persona_put", &HuginnMindResponse::PersonaPut(PersonaPutOutcome::Refused(
MindRefusal::PersonaStale { stored: Some(stamps[idx + 1].into()) },
)))
} else {
answer("persona_put", &HuginnMindResponse::PersonaPut(PersonaPutOutcome::Committed {
receipt_id: "mind-commit-cas3".into(),
}))
}
}
other => panic!("unexpected {other:?}"),
}
});
let ran = at(
server.addr,
&["persona", "mood", "set", "--faculty", "Hands", "--agent", "a", "--session", "s", "--feeling", "calm", "--value", "0.5"],
None,
);
assert_eq!(ran.code, 0, "{} {}", ran.out, ran.err);
assert_eq!(ran.out, "Committed mind-commit-cas3\n");
assert_eq!(get_count.load(std::sync::atomic::Ordering::SeqCst), 3);
assert_eq!(put_count.load(std::sync::atomic::Ordering::SeqCst), 3);
assert_eq!(
*expected_seen.lock().unwrap(),
vec![
Some("2026-10-10T10:00:00Z".into()),
Some("2026-10-10T10:00:01Z".into()),
Some("2026-10-10T10:00:02Z".into()),
]
);
// 2. Three consecutive PersonaStale answers stop at 3 attempts and return Refused exit 1.
let stale_puts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let sp = Arc::clone(&stale_puts);
let always_stale = scripted(move |message| {
let (_, req) = decode_request(message).unwrap();
match req {
HuginnMindRequest::PersonaGet { .. } => answer("persona_get", &HuginnMindResponse::Persona(Some(PersonaStateView {
value: persona(INSTANCE, "2026-10-10T10:00:00Z"),
updated_at: "2026-10-10T10:00:00Z".into(),
receipt_id: "r-0".into(),
}))),
HuginnMindRequest::PersonaPut { .. } => {
sp.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
answer("persona_put", &HuginnMindResponse::PersonaPut(PersonaPutOutcome::Refused(
MindRefusal::PersonaStale { stored: Some("2026-10-10T10:00:09Z".into()) },
)))
}
other => panic!("unexpected {other:?}"),
}
});
let fail = at(
always_stale.addr,
&["persona", "mood", "set", "--faculty", "Hands", "--agent", "a", "--session", "s", "--feeling", "calm", "--value", "0.5"],
None,
);
assert_eq!(fail.code, 1, "{} {}", fail.out, fail.err);
assert!(fail.out.starts_with("Refused PersonaStale"), "{}", fail.out);
assert_eq!(stale_puts.load(std::sync::atomic::Ordering::SeqCst), 3);
// 3b. Non-PersonaStale PersonaPut refusal fails immediately on attempt 1 without retrying.
let non_stale_gets = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let non_stale_puts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let nsg = Arc::clone(&non_stale_gets);
let nsp = Arc::clone(&non_stale_puts);
let non_stale = scripted(move |message| {
let (_, req) = decode_request(message).unwrap();
match req {
HuginnMindRequest::PersonaGet { .. } => {
nsg.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
answer("persona_get", &HuginnMindResponse::Persona(Some(PersonaStateView {
value: persona(INSTANCE, "2026-10-10T10:00:00Z"),
updated_at: "2026-10-10T10:00:00Z".into(),
receipt_id: "r-0".into(),
})))
}
HuginnMindRequest::PersonaPut { .. } => {
nsp.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
answer("persona_put", &HuginnMindResponse::PersonaPut(PersonaPutOutcome::Refused(
MindRefusal::PersonaNotCanonical,
)))
}
other => panic!("unexpected {other:?}"),
}
});
let non_stale_fail = at(
non_stale.addr,
&["persona", "mood", "set", "--faculty", "Hands", "--agent", "a", "--session", "s", "--feeling", "calm", "--value", "0.5"],
None,
);
assert_eq!(non_stale_fail.code, 1, "{} {}", non_stale_fail.out, non_stale_fail.err);
assert!(non_stale_fail.out.starts_with("Refused PersonaNotCanonical"), "{}", non_stale_fail.out);
assert_eq!(non_stale_gets.load(std::sync::atomic::Ordering::SeqCst), 1);
assert_eq!(non_stale_puts.load(std::sync::atomic::Ordering::SeqCst), 1);
// 3c. Client-side validate_document gate rejects invalid mutated state before PersonaPut is sent.
let validate_puts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let vp = Arc::clone(&validate_puts);
let invalid_stored = scripted(move |message| {
let (_, req) = decode_request(message).unwrap();
match req {
HuginnMindRequest::PersonaGet { .. } => {
let mut doc = persona(INSTANCE, "2026-10-10T10:00:00Z");
doc["provenance"]["authority"] = json!("imported");
answer("persona_get", &HuginnMindResponse::Persona(Some(PersonaStateView {
value: doc,
updated_at: "2026-10-10T10:00:00Z".into(),
receipt_id: "r-0".into(),
})))
}
HuginnMindRequest::PersonaPut { .. } => {
vp.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
answer("persona_put", &HuginnMindResponse::PersonaPut(PersonaPutOutcome::Committed {
receipt_id: "mind-commit-should-not-happen".into(),
}))
}
other => panic!("unexpected {other:?}"),
}
});
let invalid_gate = at(
invalid_stored.addr,
&["persona", "mood", "set", "--faculty", "Hands", "--agent", "a", "--session", "s", "--feeling", "calm", "--value", "0.5"],
None,
);
assert_eq!(invalid_gate.code, 2, "{} {}", invalid_gate.out, invalid_gate.err);
assert!(invalid_gate.err.starts_with("InvalidInput: "), "{}", invalid_gate.err);
assert_eq!(validate_puts.load(std::sync::atomic::Ordering::SeqCst), 0);
// 3. Unavailable exits 3 without retry; absent exits 1.
let unavail = at(
closed_port(),
&["persona", "mood", "set", "--faculty", "Hands", "--agent", "a", "--session", "s", "--feeling", "calm", "--value", "0.5"],
None,
);
assert_eq!(unavail.code, 3, "{} {}", unavail.out, unavail.err);
assert!(unavail.err.starts_with("Unavailable: "), "{}", unavail.err);
// 4. Identity & protected fields remain byte-identical across all delta verbs against a live daemon.
let (root, daemon) = mind(vec![]);
let live_server = serve(root, daemon);
let mut rich = persona(INSTANCE, "2026-10-10T10:00:00Z");
rich["publicName"] = json!("Eureka Identity");
rich["publicDescription"] = json!("Steward of coherence.");
rich["presentation"] = json!({
"pronouns": "she/her",
"voiceSummary": "dry, exact, unsentimental",
"jurisdiction": "GameCult",
"publicHandles": [{ "system": "matrix", "handle": "@eureka:gamecult.org" }]
});
rich["values"] = json!([{ "id": "coherence", "label": "Coherence", "priority": 0.95, "summary": "Coherence over velocity" }]);
rich["privateNotes"] = json!(["keep this untouched"]);
rich["embodiment"] = json!({
"senses": [{ "id": "s1", "status": "active", "label": "Matrix", "summary": "Reads rooms", "updatedAt": "2026-10-10T10:00:00Z" }],
"actuators": [{ "id": "a1", "status": "active", "label": "Mouth", "summary": "Speaks", "updatedAt": "2026-10-10T10:00:00Z" }]
});
rich["voidbotProjection"] = json!({ "candidateInterventions": [] });
seed_persona(live_server.addr, &rich);
for args in [
&["persona", "memory", "add", "--faculty", "Hands", "--agent", "a", "--session", "s", "--id", "m-imm", "--summary", "Fact"][..],
&["persona", "memory", "retire", "--faculty", "Hands", "--agent", "a", "--session", "s", "m-imm"],
&["persona", "bond", "update", "--faculty", "Hands", "--agent", "a", "--session", "s", "--person", "meta", "--summary", "Bond"],
&["persona", "mood", "set", "--faculty", "Hands", "--agent", "a", "--session", "s", "--feeling", "steady", "--value", "0.6"],
&["persona", "intention", "add", "--faculty", "Hands", "--agent", "a", "--session", "s", "--id", "i-imm", "--summary", "Stay sharp"],
&["persona", "intention", "drop", "--faculty", "Hands", "--agent", "a", "--session", "s", "i-imm"],
] {
let ran = at(live_server.addr, args, None);
assert_eq!(ran.code, 0, "{args:?}: {} {}", ran.out, ran.err);
}
let after = fetch_persona_json(live_server.addr);
for key in ["publicName", "publicDescription", "presentation", "values", "privateNotes", "embodiment", "voidbotProjection", "provenance"] {
assert_eq!(after[key], rich[key], "field `{key}` changed under delta verbs");
}
}
#[test]
fn persona_seed_strips_all_legacy_private_markers_without_json() {
let (root, daemon) = mind(vec![]);
let server = serve(root, daemon);
// Absent persona exits 1 with "absent".
let absent = at(server.addr, &["persona", "seed"], None);
assert_eq!((absent.code, absent.out.as_str(), absent.err.as_str()), (1, "absent\n", ""));
// `--json` is rejected as an unknown argument (exit 2).
let no_json = at(server.addr, &["persona", "seed", "--json"], None);
assert_eq!(no_json.code, 2, "{} {}", no_json.out, no_json.err);
let doc = json!({
"schemaVersion": "gamecult.persona_state.v0",
"provenance": {
"sourceSystem": "huginn", "sourceDocumentId": INSTANCE,
"sourceUpdatedAt": "2026-10-10T10:00:00Z", "exportedAt": "2026-10-10T10:00:00Z", "authority": "canonical"
},
"personaId": INSTANCE,
"publicName": "Eureka",
"publicDescription": "Public persona description",
"presentation": { "pronouns": "she/her", "voiceSummary": "plain and exact" },
"privateNotes": ["LEAK-PRIVATE-NOTE"],
"values": [
{ "id": "v-pub", "label": "Coherence", "priority": 0.9, "summary": "KEEP-PUBLIC-VALUE" }
],
"activationProfile": {
"underlyingOrganization": {}, "stableDispositions": {}, "behavioralDimensions": {},
"presentationStrategy": {}, "voiceStyle": {}, "situationalState": {
"valence": { "mean": 0.5, "plasticity": 0.3, "currentActivation": 0.6 }
}
},
"thoughtMemory": {
"shortTerm": [
{ "id": "st-pub", "status": "active", "target": { "kind": "self", "id": INSTANCE }, "summary": "KEEP-PUBLIC-ST", "tension": "", "actionImplication": "", "createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z", "tags": ["Room:#swarm:gamecult.org"], "extensions": { "privacy": "public" } },
{ "id": "st-ext", "status": "active", "target": { "kind": "self", "id": INSTANCE }, "summary": "LEAK-ST-EXT", "tension": "", "actionImplication": "", "createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z", "extensions": { "privacy": "private" } },
{ "id": "st-ext-case", "status": "active", "target": { "kind": "self", "id": INSTANCE }, "summary": "LEAK-ST-EXT-CASE", "tension": "", "actionImplication": "", "createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z", "extensions": { "privacy": " Private " } },
{ "id": "st-tag", "status": "active", "target": { "kind": "self", "id": INSTANCE }, "summary": "LEAK-ST-TAG", "tension": "", "actionImplication": "", "createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z", "tags": ["private"] },
{ "id": "st-tag-case", "status": "active", "target": { "kind": "self", "id": INSTANCE }, "summary": "LEAK-ST-TAG-CASE", "tension": "", "actionImplication": "", "createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z", "tags": ["Private"] },
{ "id": "st-dm", "status": "active", "target": { "kind": "self", "id": INSTANCE }, "summary": "LEAK-ST-DM", "tension": "", "actionImplication": "", "createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z", "tags": ["room:!dm123:gamecult.org"] },
{ "id": "st-dm-case", "status": "active", "target": { "kind": "self", "id": INSTANCE }, "summary": "LEAK-ST-DM-CASE", "tension": "", "actionImplication": "", "createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z", "tags": [" Room:!abc:gamecult.org "] },
{ "id": "st-ret", "status": "retired", "target": { "kind": "self", "id": INSTANCE }, "summary": "LEAK-ST-RETIRED", "tension": "", "actionImplication": "", "createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z" }
],
"memories": [
{ "id": "m-pub", "status": "crystallized", "target": { "kind": "self", "id": INSTANCE }, "summary": "KEEP-PUBLIC-MEM", "tension": "", "actionImplication": "", "createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z" },
{ "id": "m-priv", "status": "crystallized", "target": { "kind": "self", "id": INSTANCE }, "summary": "LEAK-MEM-DM", "tension": "", "actionImplication": "", "createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z", "tags": ["room:!secret:gamecult.org"] }
],
"incubation": [
{ "id": "w-pub", "status": "active", "target": { "kind": "self", "id": INSTANCE }, "summary": "KEEP-PUBLIC-INC", "tension": "", "actionImplication": "", "createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z" },
{ "id": "w-priv", "status": "active", "target": { "kind": "self", "id": INSTANCE }, "summary": "LEAK-INC-PRIVATE", "tension": "", "actionImplication": "", "createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z", "extensions": { "privacy": "Private" } },
{ "id": "w-res", "status": "resolved", "target": { "kind": "self", "id": INSTANCE }, "summary": "LEAK-INC-RESOLVED", "tension": "", "actionImplication": "", "createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z" }
]
},
"agencyPressure": {
"pressures": [
{ "id": "p-pub", "status": "active", "target": { "kind": "self", "id": INSTANCE }, "summary": "KEEP-PUBLIC-PRESSURE", "tension": "", "actionImplication": "", "createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z" },
{ "id": "p-priv", "status": "active", "target": { "kind": "self", "id": INSTANCE }, "summary": "LEAK-PRESSURE", "tension": "", "actionImplication": "", "createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z", "tags": ["private"] }
]
},
"candidateActions": {
"actions": [
{
"id": "i-pub", "status": "active", "actionType": "custom", "customActionType": "intention",
"readiness": "waiting", "riskLevel": "low", "target": { "kind": "self", "id": INSTANCE },
"summary": "KEEP-PUBLIC-INTENTION", "createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z",
"evidence": [
{ "id": "ev-pub", "status": "active", "target": { "kind": "self", "id": INSTANCE }, "summary": "KEEP-PUBLIC-EV", "tension": "", "actionImplication": "", "createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z" },
{ "id": "ev-priv", "status": "active", "target": { "kind": "self", "id": INSTANCE }, "summary": "LEAK-ACTION-EVIDENCE", "tension": "", "actionImplication": "", "createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z", "extensions": { "privacy": "private" } }
]
},
{
"id": "i-priv", "status": "active", "actionType": "custom", "customActionType": "intention",
"readiness": "ready", "riskLevel": "low", "target": { "kind": "self", "id": INSTANCE },
"summary": "LEAK-INTENTION", "createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z",
"extensions": { "privacy": "private" }
}
]
},
"voidbotProjection": {
"candidateInterventions": [
{ "id": "vb-1", "status": "active", "actionType": "speak", "readiness": "ready", "riskLevel": "low", "target": { "kind": "self", "id": INSTANCE }, "summary": "LEAK-VOIDBOT", "createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z" }
]
},
"affect": {
"needs": [
{ "id": "n-pub", "status": "active", "target": { "kind": "self", "id": INSTANCE }, "summary": "KEEP-PUBLIC-NEED", "tension": "", "actionImplication": "", "createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z" },
{ "id": "n-priv", "status": "active", "target": { "kind": "self", "id": INSTANCE }, "summary": "LEAK-NEED", "tension": "", "actionImplication": "", "createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z", "tags": ["room:!dm:gamecult.org"] }
],
"socialBonds": [
{
"id": "b-pub", "status": "active", "subject": { "kind": "self", "id": INSTANCE },
"object": { "kind": "person", "id": "meta", "label": "Meta" },
"relationshipKind": "collaborator", "summary": "KEEP-PUBLIC-BOND", "trust": 0.9, "tension": 0.1,
"updatedAt": "2026-10-10T10:00:00Z",
"lastEvidence": { "id": "b-pub-e", "status": "retired", "target": { "kind": "person", "id": "meta" }, "summary": "LEAK-BOND-LAST-EV", "claim": "LEAK-BOND-CLAIM", "tension": "", "actionImplication": "", "createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z", "extensions": { "privacy": "private" } }
},
{
"id": "b-pub2", "status": "active", "subject": { "kind": "self", "id": INSTANCE },
"object": { "kind": "person", "id": "nibu", "label": "Nibu" },
"relationshipKind": "ally", "summary": "KEEP-NIBU-BOND", "trust": 0.8, "tension": 0.1,
"updatedAt": "2026-10-10T10:00:00Z",
"lastEvidence": { "id": "b-pub2-e", "status": "retired", "target": { "kind": "person", "id": "nibu" }, "summary": "Prior nibu summary", "claim": "KEEP-PUBLIC-LAST-EV", "tension": "", "actionImplication": "", "createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z" }
},
{
"id": "b-priv", "status": "active", "subject": { "kind": "self", "id": INSTANCE },
"object": { "kind": "person", "id": "secret", "label": "Secret" },
"relationshipKind": "ally", "summary": "LEAK-PRIVATE-BOND", "trust": 0.5, "tension": 0.2,
"updatedAt": "2026-10-10T10:00:00Z", "extensions": { "privacy": "private" }
}
],
"statusReads": [
{ "id": "sr-pub", "status": "active", "target": { "kind": "person", "id": "meta" }, "statusKind": "trust", "summary": "KEEP-PUBLIC-READ", "confidence": 0.9, "updatedAt": "2026-10-10T10:00:00Z" },
{ "id": "sr-priv", "status": "active", "target": { "kind": "person", "id": "meta" }, "statusKind": "trust", "summary": "LEAK-READ", "confidence": 0.9, "updatedAt": "2026-10-10T10:00:00Z", "extensions": { "privacy": "private" } }
],
"moodDimensions": [{ "name": "curious", "value": 0.8, "updatedAt": "2026-10-10T10:00:00Z" }],
"socialBiases": [{ "name": "clarity", "value": 0.7, "summary": "KEEP-PUBLIC-BIAS", "behavioralPull": "directness", "updatedAt": "2026-10-10T10:00:00Z" }],
"doctrineStances": [
{ "id": "ds-pub", "status": "active", "target": { "kind": "self", "id": INSTANCE }, "stanceKind": "aligned", "principle": "Coherence", "summary": "KEEP-PUBLIC-STANCE", "actionImplication": "", "updatedAt": "2026-10-10T10:00:00Z" },
{ "id": "ds-priv", "status": "active", "target": { "kind": "self", "id": INSTANCE }, "stanceKind": "aligned", "principle": "Hidden", "summary": "LEAK-STANCE", "actionImplication": "", "updatedAt": "2026-10-10T10:00:00Z", "extensions": { "privacy": "private" } }
]
},
"embodiment": {
"senses": [
{ "id": "s-pub", "status": "active", "label": "Matrix", "summary": "KEEP-PUBLIC-SENSE", "updatedAt": "2026-10-10T10:00:00Z" },
{ "id": "s-priv", "status": "active", "label": "DM", "summary": "LEAK-SENSE", "updatedAt": "2026-10-10T10:00:00Z", "extensions": { "privacy": "private" } }
],
"actuators": [
{ "id": "a-pub", "status": "active", "label": "Mouth", "summary": "KEEP-PUBLIC-ACTUATOR", "updatedAt": "2026-10-10T10:00:00Z" },
{ "id": "a-ret", "status": "retired", "label": "Old", "summary": "LEAK-RETIRED-ACTUATOR", "updatedAt": "2026-10-10T10:00:00Z" }
]
},
"updatedAt": "2026-10-10T10:00:00Z"
});
seed_persona(server.addr, &doc);
let seeded = at(server.addr, &["persona", "seed"], None);
assert_eq!(seeded.code, 0, "{} {}", seeded.out, seeded.err);
for expected in [
"Persona: Eureka (eureka) [she/her]",
"KEEP-PUBLIC-VALUE",
"KEEP-PUBLIC-ST",
"KEEP-PUBLIC-MEM",
"KEEP-PUBLIC-INC",
"KEEP-PUBLIC-PRESSURE",
"KEEP-PUBLIC-INTENTION",
"KEEP-PUBLIC-EV",
"KEEP-PUBLIC-NEED",
"KEEP-PUBLIC-BOND",
"KEEP-NIBU-BOND",
"KEEP-PUBLIC-LAST-EV",
"KEEP-PUBLIC-READ",
"KEEP-PUBLIC-BIAS",
"KEEP-PUBLIC-STANCE",
"KEEP-PUBLIC-SENSE",
"KEEP-PUBLIC-ACTUATOR",
"curious: 0.80",
] {
assert!(seeded.out.contains(expected), "missing `{expected}` in:\n{}", seeded.out);
}
for leaked in [
"LEAK-PRIVATE-NOTE",
"LEAK-ST-EXT",
"LEAK-ST-EXT-CASE",
"LEAK-ST-TAG",
"LEAK-ST-TAG-CASE",
"LEAK-ST-DM",
"LEAK-ST-DM-CASE",
"LEAK-ST-RETIRED",
"LEAK-MEM-DM",
"LEAK-INC-PRIVATE",
"LEAK-INC-RESOLVED",
"LEAK-PRESSURE",
"LEAK-ACTION-EVIDENCE",
"LEAK-INTENTION",
"LEAK-VOIDBOT",
"LEAK-NEED",
"LEAK-BOND-LAST-EV",
"LEAK-BOND-CLAIM",
"LEAK-PRIVATE-BOND",
"LEAK-READ",
"LEAK-STANCE",
"LEAK-SENSE",
"LEAK-RETIRED-ACTUATOR",
] {
assert!(!seeded.out.contains(leaked), "leaked `{leaked}` in:\n{}", seeded.out);
}
let last_line = seeded.out.lines().last().unwrap();
assert!(last_line.starts_with("updatedAt 2026-10-10T10:00:00Z receipt "), "{last_line}");
}
#[test]
fn persona_deltas_reject_private_tags_and_bad_bounds_before_wire() {
let (spy, seen) = replying(
"persona_get",
HuginnMindResponse::Persona(Some(PersonaStateView {
value: persona(INSTANCE, "2026-10-10T10:00:00Z"),
updated_at: "2026-10-10T10:00:00Z".into(),
receipt_id: "r-0".into(),
})),
);
let cases: &[&[&str]] = &[
&["persona", "memory", "add", "--faculty", "Hands", "--agent", "a", "--session", "s", "--summary", "hi", "--tag", "private"],
&["persona", "memory", "add", "--faculty", "Hands", "--agent", "a", "--session", "s", "--summary", "hi", "--tag", "room:!r:g"],
&["persona", "memory", "add", "--faculty", "Hands", "--agent", "a", "--session", "s", "--summary", "hi", "--tag", "Room:!r:g"],
&["persona", "memory", "add", "--faculty", "Hands", "--agent", "a", "--session", "s", "--summary", " "],
&["persona", "memory", "add", "--faculty", "Hands", "--agent", "a", "--session", "s", "--summary", "hi", "--importance", "1.5"],
&["persona", "memory", "add", "--faculty", "Hands", "--agent", "a", "--session", "s", "--summary", "hi", "--importance", "-0.1"],
&["persona", "memory", "add", "--faculty", "Hands", "--agent", "a", "--session", "s", "--summary", "hi", "--valence", "-1.5"],
&["persona", "memory", "add", "--faculty", "Hands", "--agent", "a", "--session", "s", "--summary", "hi", "--valence", "1.5"],
&["persona", "memory", "add", "--faculty", "Hands", "--agent", "a", "--session", "s", "--summary", "hi", "--target-kind", "person"],
&["persona", "memory", "add", "--faculty", "Hands", "--agent", "a", "--session", "s", "--summary", "hi", "--target-kind", "bogus", "--target-id", "x"],
&["persona", "mood", "set", "--faculty", "Hands", "--agent", "a", "--session", "s"],
&["persona", "mood", "set", "--faculty", "Hands", "--agent", "a", "--session", "s", "--feeling", "calm"],
&["persona", "mood", "set", "--faculty", "Hands", "--agent", "a", "--session", "s", "--feeling", "calm", "--value", "1.2"],
&["persona", "mood", "set", "--faculty", "Hands", "--agent", "a", "--session", "s", "--clear-feeling", "calm", "--value", "0.5"],
&["persona", "mood", "set", "--faculty", "Hands", "--agent", "a", "--session", "s", "--clear-feeling", "calm", "--source", "room:#swarm:gamecult.org"],
&["persona", "mood", "set", "--faculty", "Hands", "--agent", "a", "--session", "s", "--axis", "valence"],
&["persona", "mood", "set", "--faculty", "Hands", "--agent", "a", "--session", "s", "--axis", "valence", "--activation", "1.2"],
&["persona", "mood", "set", "--faculty", "Hands", "--agent", "a", "--session", "s", "--axis", "valence", "--activation", "0.5", "--mean", "1.5"],
&["persona", "mood", "set", "--faculty", "Hands", "--agent", "a", "--session", "s", "--axis", "valence", "--activation", "0.5", "--plasticity", "-0.1"],
&["persona", "mood", "set", "--faculty", "Hands", "--agent", "a", "--session", "s", "--clear-feeling", "calm", "--activation", "0.5"],
&["persona", "mood", "set", "--faculty", "Hands", "--agent", "a", "--session", "s", "--clear-feeling", "calm", "--mean", "0.5"],
&["persona", "mood", "set", "--faculty", "Hands", "--agent", "a", "--session", "s", "--clear-feeling", "calm", "--plasticity", "0.5"],
&["persona", "bond", "update", "--faculty", "Hands", "--agent", "a", "--session", "s", "--person", "meta"],
&["persona", "bond", "update", "--faculty", "Hands", "--agent", "a", "--session", "s", "--person", "meta", "--why", "missing summary"],
&["persona", "bond", "update", "--faculty", "Hands", "--agent", "a", "--session", "s", "--person", "meta", "--trust", "+0.1", "--why", "missing summary"],
&["persona", "bond", "update", "--faculty", "Hands", "--agent", "a", "--session", "s", "--person", "meta", "--trust", "1.5", "--summary", "x"],
&["persona", "bond", "update", "--faculty", "Hands", "--agent", "a", "--session", "s", "--person", "meta", "--kind", "bogus", "--summary", "x"],
&["persona", "bond", "update", "--faculty", "Hands", "--agent", "a", "--session", "s", "--person", "meta", "--status", "bogus", "--summary", "x"],
&["persona", "intention", "add", "--faculty", "Hands", "--agent", "a", "--session", "s", "--summary", " "],
&["persona", "intention", "add", "--faculty", "Hands", "--agent", "a", "--session", "s", "--summary", "act", "--urgency", "1.5"],
&["persona", "intention", "add", "--faculty", "Hands", "--agent", "a", "--session", "s", "--summary", "act", "--confidence", "-0.2"],
&["persona", "intention", "add", "--faculty", "Hands", "--agent", "a", "--session", "s", "--summary", "act", "--expires-in-hours", "0"],
];
for args in cases {
let ran = at(spy.addr, args, None);
assert_eq!(ran.code, 2, "{args:?}: out={} err={}", ran.out, ran.err);
assert!(ran.err.starts_with("InvalidInput: "), "{args:?}: {}", ran.err);
}
assert!(seen.lock().unwrap().is_empty(), "invalid inputs must not hit the wire: {:?}", *seen.lock().unwrap());
// Creating a brand-new bond without --summary, creating with --custom-kind without --kind custom,
// or --kind custom without --custom-kind exits 2 without sending PersonaPut.
for args in [
&["persona", "bond", "update", "--faculty", "Hands", "--agent", "a", "--session", "s", "--person", "stranger", "--trust", "0.6"][..],
&["persona", "bond", "update", "--faculty", "Hands", "--agent", "a", "--session", "s", "--person", "stranger", "--custom-kind", "my_custom", "--summary", "x"],
&["persona", "bond", "update", "--faculty", "Hands", "--agent", "a", "--session", "s", "--person", "meta", "--kind", "custom", "--summary", "x"],
] {
let ran = at(spy.addr, args, None);
assert_eq!(ran.code, 2, "{args:?}: {} {}", ran.out, ran.err);
}
assert!(seen.lock().unwrap().iter().all(|req| matches!(req, HuginnMindRequest::PersonaGet { .. })));
}
#[test]
fn persona_bond_custom_kind_and_expired_intention_semantics() {
let (root, daemon) = mind(vec![]);
let server = serve(root, daemon);
let mut initial = persona(INSTANCE, "2026-10-10T10:00:00Z");
initial["candidateActions"]["actions"] = json!([
{
"id": "i-past", "status": "active", "actionType": "custom", "customActionType": "intention",
"readiness": "ready", "riskLevel": "low", "target": { "kind": "self", "id": INSTANCE },
"summary": "Past expiry intention",
"createdAt": "2020-01-01T00:00:00Z", "updatedAt": "2020-01-01T00:00:00Z",
"expiresAt": "2020-01-02T00:00:00Z"
},
{
"id": "i-readiness-exp", "status": "active", "actionType": "custom", "customActionType": "intention",
"readiness": "expired", "riskLevel": "low", "target": { "kind": "self", "id": INSTANCE },
"summary": "Readiness expired intention",
"createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z",
"expiresAt": "2099-01-01T00:00:00Z"
},
{
"id": "i-future", "status": "active", "actionType": "custom", "customActionType": "intention",
"readiness": "waiting", "riskLevel": "low", "target": { "kind": "self", "id": INSTANCE },
"summary": "Future active intention",
"createdAt": "2026-10-10T10:00:00Z", "updatedAt": "2026-10-10T10:00:00Z",
"expiresAt": "2099-01-01T00:00:00Z"
}
]);
seed_persona(server.addr, &initial);
// Seed hides expired intentions (both past expiresAt and readiness == expired) and keeps future ones.
let seed_before = at(server.addr, &["persona", "seed"], None);
assert_eq!(seed_before.code, 0, "{} {}", seed_before.out, seed_before.err);
assert!(seed_before.out.contains("Future active intention"), "{}", seed_before.out);
assert!(!seed_before.out.contains("Past expiry intention"), "{}", seed_before.out);
assert!(!seed_before.out.contains("Readiness expired intention"), "{}", seed_before.out);
// Re-adding an intention whose previous entry expired succeeds; duplicating the unexpired future one still fails exit 2.
for summary in ["Past expiry intention", "Readiness expired intention"] {
let ok = at(
server.addr,
&["persona", "intention", "add", "--faculty", "Hands", "--agent", "a", "--session", "s", "--summary", summary],
None,
);
assert_eq!(ok.code, 0, "{summary}: {} {}", ok.out, ok.err);
}
let dup_future = at(
server.addr,
&["persona", "intention", "add", "--faculty", "Hands", "--agent", "a", "--session", "s", "--summary", "future active intention"],
None,
);
assert_eq!(dup_future.code, 2, "{} {}", dup_future.out, dup_future.err);
assert!(dup_future.err.starts_with("InvalidInput: "), "{}", dup_future.err);
// Creating a new bond with --custom-kind without --kind custom fails exit 2; with --kind custom it commits and renders in seed.
let bad_custom = at(
server.addr,
&["persona", "bond", "update", "--faculty", "Hands", "--agent", "a", "--session", "s", "--person", "deru", "--custom-kind", "my_custom", "--summary", "Peer"],
None,
);
assert_eq!(bad_custom.code, 2, "{} {}", bad_custom.out, bad_custom.err);
assert!(bad_custom.err.starts_with("InvalidInput: "), "{}", bad_custom.err);
let good_custom = at(
server.addr,
&["persona", "bond", "update", "--faculty", "Hands", "--agent", "a", "--session", "s", "--person", "deru", "--kind", "custom", "--custom-kind", "my_custom", "--summary", "Peer"],
None,
);
assert_eq!(good_custom.code, 0, "{} {}", good_custom.out, good_custom.err);
// Updating that bond with --why without --summary fails exit 2 without mutating trust or lastEvidence.
let bad_why = at(
server.addr,
&["persona", "bond", "update", "--faculty", "Hands", "--agent", "a", "--session", "s", "--person", "deru", "--trust", "+0.2", "--why", "Should not silently drop"],
None,
);
assert_eq!(bad_why.code, 2, "{} {}", bad_why.out, bad_why.err);
assert!(bad_why.err.starts_with("InvalidInput: "), "{}", bad_why.err);
let doc_after = fetch_persona_json(server.addr);
let deru_bond = doc_after["affect"]["socialBonds"].as_array().unwrap().iter().find(|b| b["object"]["id"] == "deru").unwrap();
assert_eq!(deru_bond["relationshipKind"], "custom");
assert_eq!(deru_bond["customRelationshipKind"], "my_custom");
assert_eq!(deru_bond["trust"], 0.5);
assert!(deru_bond.get("lastEvidence").is_none());
let seed_after = at(server.addr, &["persona", "seed"], None);
assert_eq!(seed_after.code, 0, "{} {}", seed_after.out, seed_after.err);
assert!(seed_after.out.contains("deru [my_custom]"), "{}", seed_after.out);
}