diff --git a/crates/eureka-state/src/bin/huginn/main.rs b/crates/eureka-state/src/bin/huginn/main.rs index 8cc6380..280ae96 100644 --- a/crates/eureka-state/src/bin/huginn/main.rs +++ b/crates/eureka-state/src/bin/huginn/main.rs @@ -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, }, } @@ -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 { +pub(crate) fn faculty(text: &str) -> Result { 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 { 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) { } /// 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 { - 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, - expected_updated_at: Option, - file: &str, -) -> Result { - 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", diff --git a/crates/eureka-state/src/bin/huginn/persona.rs b/crates/eureka-state/src/bin/huginn/persona.rs new file mode 100644 index 0000000..ba082ac --- /dev/null +++ b/crates/eureka-state/src/bin/huginn/persona.rs @@ -0,0 +1,1974 @@ +//! `huginn persona`: get, put, privacy-stripped public-Matrix `seed`, and +//! surgical delta verbs (`memory`, `bond`, `mood`, `intention`) over CAS. + +use std::collections::BTreeSet; +use std::fmt::Write as _; + +use chrono::{DateTime, Duration, Utc}; +use clap::{Args, Subcommand, ValueEnum}; +use huginn_mind::eureka_pipeline::{Short, Slug}; +use huginn_mind::persona::validate_document; +use huginn_mind::{ + Faculty, HuginnMindResponse, MindRefusal, PersonaPutOutcome, PipelineProvenance, +}; +use serde_json::{Map, Value, json}; +use sha2::{Digest, Sha256}; + +use crate::config::{Settings, TOOL}; +use crate::door; +use crate::trouble::Trouble; +use crate::{PersonaCommand, refused, say, unexpected}; + +const CAS_ATTEMPTS: usize = 3; + +const TARGET_KINDS: [&str; 13] = [ + "person", + "repo", + "scene", + "system", + "room", + "artifact", + "concept", + "relationship", + "self", + "community", + "thread", + "document", + "runtime", +]; + +const RELATIONSHIP_KINDS: [&str; 11] = [ + "ally", + "friend", + "collaborator", + "mentor", + "ward", + "rival", + "audience", + "community_member", + "self_relation", + "unknown", + "custom", +]; + +const THOUGHT_STATUSES: [&str; 6] = [ + "draft", + "active", + "cooling", + "crystallized", + "resolved", + "retired", +]; + +#[derive(Subcommand, Debug)] +pub enum MemoryCommand { + /// Add an anchored thought to thoughtMemory.{shortTerm,memories,incubation}. + Add(Box), + /// Retire, resolve, or crystallize an existing thoughtMemory entry by id. + Retire { + #[arg(long, value_parser = crate::faculty)] + faculty: Faculty, + /// The writing agent's name. + #[arg(long)] + agent: String, + /// The writing session; else HUGINN_SESSION. + #[arg(long)] + session: Option, + /// Target status (crystallized moves shortTerm/incubation entries into memories). + #[arg(long, value_enum, default_value_t = RetireStatus::Retired)] + status: RetireStatus, + /// The entry id to update. + id: String, + }, +} + +#[derive(Args, Debug)] +pub struct MemoryAddCli { + #[arg(long, value_parser = crate::faculty)] + pub faculty: Faculty, + /// The writing agent's name. + #[arg(long)] + pub agent: String, + /// The writing session; else HUGINN_SESSION. + #[arg(long)] + pub session: Option, + /// The thought's summary text. + #[arg(long)] + pub summary: String, + /// Which thoughtMemory pool to write into. + #[arg(long, value_enum, default_value_t = MemoryKind::ShortTerm)] + pub kind: MemoryKind, + /// Explicit id (default: generated m-... or w-...). + #[arg(long)] + pub id: Option, + /// Target kind (default: self). + #[arg(long)] + pub target_kind: Option, + /// Target id (default: current instance when target is self). + #[arg(long)] + pub target_id: Option, + /// Optional target label. + #[arg(long)] + pub target_label: Option, + /// Optional tension text. + #[arg(long)] + pub tension: Option, + /// Optional actionImplication text. + #[arg(long)] + pub action_implication: Option, + /// Optional claim text. + #[arg(long)] + pub claim: Option, + /// Optional question text. + #[arg(long)] + pub question: Option, + /// Importance / intensity in [0, 1]. + #[arg(long, allow_hyphen_values = true)] + pub importance: Option, + /// Valence in [-1, 1]. + #[arg(long, allow_hyphen_values = true)] + pub valence: Option, + /// Public tags (private and room:! tags are rejected). + #[arg(long = "tag")] + pub tags: Vec, +} + +#[derive(ValueEnum, Clone, Copy, Debug, PartialEq, Eq)] +pub enum MemoryKind { + #[value(name = "short-term")] + ShortTerm, + Memory, + Incubation, +} + +#[derive(ValueEnum, Clone, Copy, Debug, PartialEq, Eq)] +pub enum RetireStatus { + Retired, + Resolved, + Crystallized, +} + +#[derive(Subcommand, Debug)] +pub enum BondCommand { + /// Create or update a person bond in affect.socialBonds[]. + Update { + #[arg(long, value_parser = crate::faculty)] + faculty: Faculty, + /// The writing agent's name. + #[arg(long)] + agent: String, + /// The writing session; else HUGINN_SESSION. + #[arg(long)] + session: Option, + /// The person id (object.kind == "person" && object.id == ). + #[arg(long)] + person: String, + /// Optional person display label. + #[arg(long)] + label: Option, + /// Relationship kind (ally, friend, collaborator, mentor, ward, rival, audience, community_member, self_relation, unknown, custom). + #[arg(long)] + kind: Option, + /// Custom relationship kind (required when --kind custom). + #[arg(long)] + custom_kind: Option, + /// Bond summary (required when creating a new bond). + #[arg(long)] + summary: Option, + /// Reason for updating an existing summary (rotates prior summary/updatedAt into lastEvidence). + #[arg(long)] + why: Option, + /// Trust in [0, 1] or signed delta (+N / -N, clamped to [0, 1]). + #[arg(long, allow_hyphen_values = true)] + trust: Option, + /// Tension in [0, 1] or signed delta (+N / -N, clamped to [0, 1]). + #[arg(long, allow_hyphen_values = true)] + tension: Option, + /// Intensity in [0, 1] or signed delta (+N / -N, clamped to [0, 1]). + #[arg(long, allow_hyphen_values = true)] + intensity: Option, + /// Thought status (draft, active, cooling, crystallized, resolved, retired). + #[arg(long)] + status: Option, + }, +} + +#[derive(Subcommand, Debug)] +pub enum MoodCommand { + /// Set or clear a named feeling in affect.moodDimensions[] and/or update activationProfile.situationalState.. + Set { + #[arg(long, value_parser = crate::faculty)] + faculty: Faculty, + /// The writing agent's name. + #[arg(long)] + agent: String, + /// The writing session; else HUGINN_SESSION. + #[arg(long)] + session: Option, + /// Named feeling to set (trimmed and lowercased). + #[arg(long)] + feeling: Option, + /// Feeling intensity in [0, 1] (required with --feeling). + #[arg(long, allow_hyphen_values = true)] + value: Option, + /// Optional source for --feeling. + #[arg(long)] + source: Option, + /// Named feeling to remove from affect.moodDimensions[]. + #[arg(long)] + clear_feeling: Option, + /// Situational mood axis name (e.g. valence, arousal, dominance). + #[arg(long)] + axis: Option, + /// Axis activation in [0, 1] or signed delta (+N / -N, clamped to [0, 1]) (required with --axis). + #[arg(long, allow_hyphen_values = true)] + activation: Option, + /// Optional axis baseline mean in [0, 1] (requires --axis). + #[arg(long, allow_hyphen_values = true)] + mean: Option, + /// Optional axis plasticity in [0, 1] (requires --axis). + #[arg(long, allow_hyphen_values = true)] + plasticity: Option, + }, +} + +#[derive(Subcommand, Debug)] +pub enum IntentionCommand { + /// Add an intention in candidateActions.actions[]. + Add { + #[arg(long, value_parser = crate::faculty)] + faculty: Faculty, + /// The writing agent's name. + #[arg(long)] + agent: String, + /// The writing session; else HUGINN_SESSION. + #[arg(long)] + session: Option, + /// Intention summary text. + #[arg(long)] + summary: String, + /// Explicit id (default: generated i-...). + #[arg(long)] + id: Option, + /// Target kind (default: self). + #[arg(long)] + target_kind: Option, + /// Target id (default: current instance when target is self). + #[arg(long)] + target_id: Option, + /// Optional target label. + #[arg(long)] + target_label: Option, + /// Readiness state. + #[arg(long, value_enum, default_value_t = IntentionReadiness::Waiting)] + readiness: IntentionReadiness, + /// Urgency in [0, 1]. + #[arg(long, allow_hyphen_values = true)] + urgency: Option, + /// Confidence in [0, 1]. + #[arg(long, allow_hyphen_values = true)] + confidence: Option, + /// Optional rationale text. + #[arg(long)] + rationale: Option, + /// Optional expiry in hours from commit time (>= 1). + #[arg(long)] + expires_in_hours: Option, + }, + /// Drop an existing intention by id (sets status=retired, readiness=expired). + Drop { + #[arg(long, value_parser = crate::faculty)] + faculty: Faculty, + /// The writing agent's name. + #[arg(long)] + agent: String, + /// The writing session; else HUGINN_SESSION. + #[arg(long)] + session: Option, + /// The intention id to drop. + id: String, + }, +} + +#[derive(ValueEnum, Clone, Copy, Debug, PartialEq, Eq)] +pub enum IntentionReadiness { + Waiting, + Ready, + Draft, +} + +impl IntentionReadiness { + fn as_str(self) -> &'static str { + match self { + Self::Waiting => "waiting", + Self::Ready => "ready", + Self::Draft => "draft", + } + } +} + +pub fn run(settings: &Settings, command: PersonaCommand) -> Result { + match command { + PersonaCommand::Get => persona_get(settings), + PersonaCommand::Put { faculty, agent, session, expected_updated_at, file } => { + persona_put(settings, faculty, agent, session, expected_updated_at, &file) + } + PersonaCommand::Seed => persona_seed(settings), + PersonaCommand::Memory { command: MemoryCommand::Add(cli) } => memory_add( + settings, + cli.faculty, + cli.agent, + cli.session, + MemoryAddArgs { + summary: cli.summary, + kind: cli.kind, + id: cli.id, + target_kind: cli.target_kind, + target_id: cli.target_id, + target_label: cli.target_label, + tension: cli.tension, + action_implication: cli.action_implication, + claim: cli.claim, + question: cli.question, + importance: cli.importance, + valence: cli.valence, + tags: cli.tags, + }, + ), + PersonaCommand::Memory { command: MemoryCommand::Retire { faculty, agent, session, status, id } } => { + memory_retire(settings, faculty, agent, session, status, id) + } + PersonaCommand::Bond { command: BondCommand::Update { + faculty, + agent, + session, + person, + label, + kind, + custom_kind, + summary, + why, + trust, + tension, + intensity, + status, + } } => bond_update( + settings, + faculty, + agent, + session, + BondUpdateArgs { person, label, kind, custom_kind, summary, why, trust, tension, intensity, status }, + ), + PersonaCommand::Mood { command: MoodCommand::Set { + faculty, + agent, + session, + feeling, + value, + source, + clear_feeling, + axis, + activation, + mean, + plasticity, + } } => mood_set( + settings, + faculty, + agent, + session, + MoodSetArgs { feeling, value, source, clear_feeling, axis, activation, mean, plasticity }, + ), + PersonaCommand::Intention { command: IntentionCommand::Add { + faculty, + agent, + session, + summary, + id, + target_kind, + target_id, + target_label, + readiness, + urgency, + confidence, + rationale, + expires_in_hours, + } } => intention_add( + settings, + faculty, + agent, + session, + IntentionAddArgs { + summary, + id, + target_kind, + target_id, + target_label, + readiness, + urgency, + confidence, + rationale, + expires_in_hours, + }, + ), + PersonaCommand::Intention { command: IntentionCommand::Drop { faculty, agent, session, id } } => { + intention_drop(settings, faculty, agent, session, id) + } + } +} + +fn persona_get(settings: &Settings) -> Result { + 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, + expected_updated_at: Option, + file: &str, +) -> Result { + 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 stamp_after(now: DateTime, stored: Option<&str>) -> DateTime { + let floor = stored + .and_then(|text| DateTime::parse_from_rfc3339(text).ok()) + .map(|at| at.with_timezone(&Utc) + Duration::milliseconds(1)); + floor.map_or(now, |floor| now.max(floor)) +} + +fn mutate_persona( + settings: &Settings, + faculty: Faculty, + agent: String, + session: Option, + mut mutator: impl FnMut(&Slug, &mut Value, DateTime, &str) -> Result, Trouble>, +) -> Result { + let session = settings.session(session)?; + let client = settings.client()?; + let instance = client.instance().clone(); + for attempt in 0..CAS_ATTEMPTS { + let view = match client.persona_get().map_err(Trouble::from)? { + HuginnMindResponse::Persona(Some(view)) => view, + HuginnMindResponse::Persona(None) => { + say("absent"); + return Ok(1); + } + HuginnMindResponse::Refused(refusal) => return Ok(refused(&refusal)), + other => return Err(unexpected(&other)), + }; + let stamp_dt = stamp_after(Utc::now(), Some(&view.updated_at)); + let stamp = stamp_dt.to_rfc3339(); + let mut next = view.value; + let item_id = mutator(&instance, &mut next, stamp_dt, &stamp)?; + next["updatedAt"] = json!(stamp); + validate_document(&instance, &next) + .map_err(|refusal| Trouble::invalid(format!("the persona document fails schema validation: {refusal:?}")))?; + let provenance = PipelineProvenance { + faculty, + agent: Short(agent.clone()), + session: Short(session.clone()), + tool: Short(TOOL.to_string()), + imported_from: None, + }; + match client.persona_put(provenance, next, Some(view.updated_at)).map_err(Trouble::from)? { + HuginnMindResponse::PersonaPut(PersonaPutOutcome::Committed { receipt_id }) => { + say(format_args!("Committed {receipt_id}")); + if let Some(id) = item_id { + say(format_args!("id {id}")); + } + return Ok(0); + } + HuginnMindResponse::PersonaPut(PersonaPutOutcome::Refused(MindRefusal::PersonaStale { .. })) + if attempt + 1 < CAS_ATTEMPTS => + { + continue; + } + HuginnMindResponse::PersonaPut(PersonaPutOutcome::Refused(refusal)) | HuginnMindResponse::Refused(refusal) => { + return Ok(refused(&refusal)); + } + other => return Err(unexpected(&other)), + } + } + Err(Trouble::Internal("CAS retry loop exited unexpectedly".into())) +} + +#[derive(Clone, Copy, Debug)] +enum BoundOrDelta { + Absolute(f64), + Delta(f64), +} + +impl BoundOrDelta { + fn apply(self, base: f64) -> f64 { + match self { + Self::Absolute(value) => value, + Self::Delta(delta) => (base + delta).clamp(0.0, 1.0), + } + } +} + +fn require_non_empty(flag: &str, text: &str) -> Result { + let trimmed = text.trim(); + if trimmed.is_empty() { + return Err(Trouble::invalid(format!("{flag} cannot be empty"))); + } + Ok(trimmed.to_owned()) +} + +fn parse_unit(flag: &str, value: f64) -> Result { + if !value.is_finite() || !(0.0..=1.0).contains(&value) { + return Err(Trouble::invalid(format!("{flag} must be a finite number in 0..=1"))); + } + Ok(value) +} + +fn parse_bipolar(flag: &str, value: f64) -> Result { + if !value.is_finite() || !(-1.0..=1.0).contains(&value) { + return Err(Trouble::invalid(format!("{flag} must be a finite number in -1..=1"))); + } + Ok(value) +} + +fn parse_bound_or_delta(flag: &str, text: &str) -> Result { + let trimmed = text.trim(); + if trimmed.starts_with('+') || trimmed.starts_with('-') { + let delta: f64 = trimmed + .parse() + .map_err(|_| Trouble::invalid(format!("{flag} must be a number in 0..=1 or a signed delta (+N/-N)")))?; + if !delta.is_finite() { + return Err(Trouble::invalid(format!("{flag} must be finite"))); + } + Ok(BoundOrDelta::Delta(delta)) + } else { + let value: f64 = trimmed + .parse() + .map_err(|_| Trouble::invalid(format!("{flag} must be a number in 0..=1 or a signed delta (+N/-N)")))?; + Ok(BoundOrDelta::Absolute(parse_unit(flag, value)?)) + } +} + +fn build_target( + instance: &Slug, + kind: Option<&str>, + id: Option<&str>, + label: Option<&str>, +) -> Result { + let (resolved_kind, resolved_id) = match (kind.map(str::trim), id.map(str::trim)) { + (None, None) => ("self".to_owned(), instance.0.clone()), + (Some(kind), Some(id)) => { + if !TARGET_KINDS.contains(&kind) { + return Err(Trouble::invalid(format!("--target-kind `{kind}` is not a valid target kind"))); + } + if id.is_empty() { + return Err(Trouble::invalid("--target-id cannot be empty")); + } + (kind.to_owned(), id.to_owned()) + } + (Some("self"), None) => ("self".to_owned(), instance.0.clone()), + (Some(_), None) => { + return Err(Trouble::invalid("--target-id is required when --target-kind is given")); + } + (None, Some(_)) => { + return Err(Trouble::invalid("--target-kind is required when --target-id is given")); + } + }; + let mut target = json!({ "kind": resolved_kind, "id": resolved_id }); + if let Some(label) = label { + let label = require_non_empty("--target-label", label)?; + target["label"] = json!(label); + } + Ok(target) +} + +fn is_private_tag(tag: &str) -> bool { + let lower = tag.trim().to_ascii_lowercase(); + lower == "private" || lower.starts_with("room:!") +} + +fn validate_public_tags(tags: &[String]) -> Result, Trouble> { + let mut out = Vec::with_capacity(tags.len()); + for raw in tags { + let tag = require_non_empty("--tag", raw)?; + if is_private_tag(&tag) { + return Err(Trouble::invalid(format!("tag `{tag}` is forbidden on public-Matrix persona entries"))); + } + out.push(tag); + } + Ok(out) +} + +fn array_mut<'a>(root: &'a mut Value, path: &[&str]) -> Result<&'a mut Vec, Trouble> { + let label = path.join("."); + let mut cursor = root; + for key in path { + cursor = cursor + .get_mut(*key) + .ok_or_else(|| Trouble::invalid(format!("stored persona document is missing `{label}`")))?; + } + cursor + .as_array_mut() + .ok_or_else(|| Trouble::invalid(format!("stored persona document field `{label}` is not an array"))) +} + +fn object_mut<'a>(root: &'a mut Value, path: &[&str]) -> Result<&'a mut Map, Trouble> { + let label = path.join("."); + let mut cursor = root; + for key in path { + cursor = cursor + .get_mut(*key) + .ok_or_else(|| Trouble::invalid(format!("stored persona document is missing `{label}`")))?; + } + cursor + .as_object_mut() + .ok_or_else(|| Trouble::invalid(format!("stored persona document field `{label}` is not an object"))) +} + +fn next_id(prefix: char, existing_ids: &BTreeSet, stamp: DateTime, seed: &str) -> String { + let pid = std::process::id(); + let nanos = stamp.timestamp_nanos_opt().unwrap_or_else(|| stamp.timestamp_millis() * 1_000_000); + for counter in 0u64.. { + let mut hasher = Sha256::new(); + hasher.update([prefix as u8]); + hasher.update(nanos.to_le_bytes()); + hasher.update(pid.to_le_bytes()); + hasher.update(counter.to_le_bytes()); + hasher.update(seed.as_bytes()); + let digest = hasher.finalize(); + let candidate = format!( + "{prefix}-{:02x}{:02x}{:02x}{:02x}{:02x}", + digest[0], digest[1], digest[2], digest[3], digest[4] + ); + if !existing_ids.contains(&candidate) { + return candidate; + } + } + unreachable!() +} + +struct MemoryAddArgs { + summary: String, + kind: MemoryKind, + id: Option, + target_kind: Option, + target_id: Option, + target_label: Option, + tension: Option, + action_implication: Option, + claim: Option, + question: Option, + importance: Option, + valence: Option, + tags: Vec, +} + +fn memory_add( + settings: &Settings, + faculty: Faculty, + agent: String, + session: Option, + args: MemoryAddArgs, +) -> Result { + let summary = require_non_empty("--summary", &args.summary)?; + let explicit_id = args.id.as_deref().map(|id| require_non_empty("--id", id)).transpose()?; + let intensity = args.importance.map(|v| parse_unit("--importance", v)).transpose()?; + let valence = args.valence.map(|v| parse_bipolar("--valence", v)).transpose()?; + let tags = validate_public_tags(&args.tags)?; + let tension = args.tension.as_deref().map(str::trim).unwrap_or_default().to_owned(); + let action_implication = args.action_implication.as_deref().map(str::trim).unwrap_or_default().to_owned(); + let claim = args.claim.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned); + let question = args.question.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned); + + // Pre-check target flags before hitting the wire. + let target_kind = args.target_kind.as_deref(); + let target_id = args.target_id.as_deref(); + let target_label = args.target_label.as_deref(); + let _ = build_target(settings.client()?.instance(), target_kind, target_id, target_label)?; + + mutate_persona(settings, faculty, agent, session, |instance, state, stamp_dt, stamp| { + let mut existing_ids = BTreeSet::new(); + for pool in ["shortTerm", "memories", "incubation"] { + for item in array_mut(state, &["thoughtMemory", pool])?.iter() { + if let Some(id) = item.get("id").and_then(Value::as_str) { + existing_ids.insert(id.to_owned()); + } + } + } + let (pool, prefix, status) = match args.kind { + MemoryKind::ShortTerm => ("shortTerm", 'm', "active"), + MemoryKind::Memory => ("memories", 'm', "crystallized"), + MemoryKind::Incubation => ("incubation", 'w', "active"), + }; + let id = match &explicit_id { + Some(id) => { + if existing_ids.contains(id) { + return Err(Trouble::invalid(format!("thoughtMemory already contains id `{id}`"))); + } + id.clone() + } + None => next_id(prefix, &existing_ids, stamp_dt, &summary), + }; + let target = build_target(instance, target_kind, target_id, target_label)?; + let mut entry = json!({ + "id": id, + "status": status, + "target": target, + "summary": summary, + "tension": tension, + "actionImplication": action_implication, + "createdAt": stamp, + "updatedAt": stamp, + }); + if let Some(claim) = &claim { + entry["claim"] = json!(claim); + } + if let Some(question) = &question { + entry["question"] = json!(question); + } + if let Some(intensity) = intensity { + entry["intensity"] = json!(intensity); + } + if let Some(valence) = valence { + entry["valence"] = json!(valence); + } + if !tags.is_empty() { + entry["tags"] = json!(tags); + } + array_mut(state, &["thoughtMemory", pool])?.push(entry); + Ok(Some(id)) + }) +} + +fn memory_retire( + settings: &Settings, + faculty: Faculty, + agent: String, + session: Option, + status: RetireStatus, + id: String, +) -> Result { + let id = require_non_empty("", &id)?; + mutate_persona(settings, faculty, agent, session, |_instance, state, _stamp_dt, stamp| { + for pool in ["shortTerm", "memories", "incubation"] { + let list = array_mut(state, &["thoughtMemory", pool])?; + if let Some(pos) = list.iter().position(|entry| entry.get("id").and_then(Value::as_str) == Some(id.as_str())) { + match status { + RetireStatus::Retired => { + let entry = &mut list[pos]; + entry["status"] = json!("retired"); + entry["updatedAt"] = json!(stamp); + entry["retiredAt"] = json!(stamp); + } + RetireStatus::Resolved => { + let entry = &mut list[pos]; + entry["status"] = json!("resolved"); + entry["updatedAt"] = json!(stamp); + } + RetireStatus::Crystallized => { + if pool == "memories" { + let entry = &mut list[pos]; + entry["status"] = json!("crystallized"); + entry["updatedAt"] = json!(stamp); + } else { + let mut entry = list.remove(pos); + entry["status"] = json!("crystallized"); + entry["updatedAt"] = json!(stamp); + array_mut(state, &["thoughtMemory", "memories"])?.push(entry); + } + } + } + return Ok(None); + } + } + Err(Trouble::invalid(format!("no thoughtMemory entry found with id `{id}`"))) + }) +} + +struct BondUpdateArgs { + person: String, + label: Option, + kind: Option, + custom_kind: Option, + summary: Option, + why: Option, + trust: Option, + tension: Option, + intensity: Option, + status: Option, +} + +fn bond_update( + settings: &Settings, + faculty: Faculty, + agent: String, + session: Option, + args: BondUpdateArgs, +) -> Result { + let person = require_non_empty("--person", &args.person)?; + let label = args.label.as_deref().map(|s| require_non_empty("--label", s)).transpose()?; + let kind = args + .kind + .as_deref() + .map(|s| { + let trimmed = require_non_empty("--kind", s)?; + if !RELATIONSHIP_KINDS.contains(&trimmed.as_str()) { + return Err(Trouble::invalid(format!("--kind `{trimmed}` is not a valid relationshipKind"))); + } + Ok(trimmed) + }) + .transpose()?; + let custom_kind = args.custom_kind.as_deref().map(|s| require_non_empty("--custom-kind", s)).transpose()?; + if custom_kind.is_some() && matches!(kind.as_deref(), Some(k) if k != "custom") { + return Err(Trouble::invalid("--custom-kind requires --kind custom")); + } + let summary = args.summary.as_deref().map(|s| require_non_empty("--summary", s)).transpose()?; + let why = args.why.as_deref().map(|s| require_non_empty("--why", s)).transpose()?; + if why.is_some() && summary.is_none() { + return Err(Trouble::invalid("--why requires --summary")); + } + let trust = args.trust.as_deref().map(|s| parse_bound_or_delta("--trust", s)).transpose()?; + let tension = args.tension.as_deref().map(|s| parse_bound_or_delta("--tension", s)).transpose()?; + let intensity = args.intensity.as_deref().map(|s| parse_bound_or_delta("--intensity", s)).transpose()?; + let status = args + .status + .as_deref() + .map(|s| { + let trimmed = require_non_empty("--status", s)?; + if !THOUGHT_STATUSES.contains(&trimmed.as_str()) { + return Err(Trouble::invalid(format!("--status `{trimmed}` is not a valid thoughtStatus"))); + } + Ok(trimmed) + }) + .transpose()?; + + if label.is_none() + && kind.is_none() + && custom_kind.is_none() + && summary.is_none() + && trust.is_none() + && tension.is_none() + && intensity.is_none() + && status.is_none() + { + return Err(Trouble::invalid("bond update requires at least one field to update")); + } + + mutate_persona(settings, faculty, agent, session, |instance, state, stamp_dt, stamp| { + let bonds = array_mut(state, &["affect", "socialBonds"])?; + let found = bonds.iter().position(|bond| { + bond.pointer("/object/kind").and_then(Value::as_str) == Some("person") + && bond.pointer("/object/id").and_then(Value::as_str) == Some(person.as_str()) + }); + if let Some(pos) = found { + let bond = &mut bonds[pos]; + if let Some(label) = &label { + bond["object"]["label"] = json!(label); + } + if let Some(kind) = &kind { + bond["relationshipKind"] = json!(kind); + if kind == "custom" { + if let Some(custom) = &custom_kind { + bond["customRelationshipKind"] = json!(custom); + } else if bond.get("customRelationshipKind").and_then(Value::as_str).is_none_or(str::is_empty) { + return Err(Trouble::invalid("--custom-kind is required when setting --kind custom")); + } + } else if let Some(obj) = bond.as_object_mut() { + obj.remove("customRelationshipKind"); + } + } else if let Some(custom) = &custom_kind { + if bond.get("relationshipKind").and_then(Value::as_str) != Some("custom") { + return Err(Trouble::invalid("--custom-kind requires --kind custom or an existing custom bond")); + } + bond["customRelationshipKind"] = json!(custom); + } + if let Some(new_summary) = &summary { + if let Some(why_text) = &why { + let prior_summary = bond.get("summary").and_then(Value::as_str).unwrap_or_default().to_owned(); + let prior_updated = bond + .get("updatedAt") + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + .unwrap_or(stamp) + .to_owned(); + let bond_id = bond.get("id").and_then(Value::as_str).unwrap_or_default(); + bond["lastEvidence"] = json!({ + "id": format!("{bond_id}-e"), + "status": "retired", + "target": bond["object"].clone(), + "summary": prior_summary, + "claim": why_text, + "tension": "", + "actionImplication": "", + "createdAt": prior_updated, + "updatedAt": stamp, + }); + } + bond["summary"] = json!(new_summary); + } + if let Some(trust_val) = trust { + let current = bond.get("trust").and_then(Value::as_f64).unwrap_or(0.5); + bond["trust"] = json!(trust_val.apply(current)); + } + if let Some(tension_val) = tension { + let current = bond.get("tension").and_then(Value::as_f64).unwrap_or(0.2); + bond["tension"] = json!(tension_val.apply(current)); + } + if let Some(intensity_val) = intensity { + let current = bond.get("intensity").and_then(Value::as_f64).unwrap_or(0.5); + bond["intensity"] = json!(intensity_val.apply(current)); + } + if let Some(status_val) = &status { + bond["status"] = json!(status_val); + } + bond["updatedAt"] = json!(stamp); + let id = bond.get("id").and_then(Value::as_str).unwrap_or_default().to_owned(); + Ok(Some(id)) + } else { + let new_summary = summary + .as_ref() + .ok_or_else(|| Trouble::invalid("--summary is required when creating a new bond"))?; + if custom_kind.is_some() && kind.as_deref() != Some("custom") { + return Err(Trouble::invalid("--custom-kind requires --kind custom when creating a new bond")); + } + let rel_kind = kind.as_deref().unwrap_or("unknown"); + if rel_kind == "custom" && custom_kind.is_none() { + return Err(Trouble::invalid("--custom-kind is required when --kind is custom")); + } + let existing_ids: BTreeSet = bonds + .iter() + .filter_map(|bond| bond.get("id").and_then(Value::as_str).map(str::to_owned)) + .collect(); + let id = next_id('b', &existing_ids, stamp_dt, &person); + let mut object = json!({ "kind": "person", "id": person }); + if let Some(label) = &label { + object["label"] = json!(label); + } + let mut bond = json!({ + "id": id, + "status": status.as_deref().unwrap_or("active"), + "subject": { "kind": "self", "id": instance.0 }, + "object": object, + "relationshipKind": rel_kind, + "summary": new_summary, + "trust": trust.map_or(0.5, |v| v.apply(0.5)), + "tension": tension.map_or(0.2, |v| v.apply(0.2)), + "intensity": intensity.map_or(0.5, |v| v.apply(0.5)), + "updatedAt": stamp, + }); + if let Some(custom) = &custom_kind { + bond["customRelationshipKind"] = json!(custom); + } + bonds.push(bond); + Ok(Some(id)) + } + }) +} + +struct MoodSetArgs { + feeling: Option, + value: Option, + source: Option, + clear_feeling: Option, + axis: Option, + activation: Option, + mean: Option, + plasticity: Option, +} + +fn mood_set( + settings: &Settings, + faculty: Faculty, + agent: String, + session: Option, + args: MoodSetArgs, +) -> Result { + if args.feeling.is_none() && args.clear_feeling.is_none() && args.axis.is_none() { + return Err(Trouble::invalid("mood set requires at least one of --feeling, --clear-feeling, or --axis")); + } + let feeling = match args.feeling { + Some(raw) => { + let name = require_non_empty("--feeling", &raw)?.to_lowercase(); + let val = args + .value + .ok_or_else(|| Trouble::invalid("--value is required with --feeling"))?; + let val = parse_unit("--value", val)?; + let source = args.source.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned); + Some((name, val, source)) + } + None => { + if args.value.is_some() || args.source.is_some() { + return Err(Trouble::invalid("--value and --source require --feeling")); + } + None + } + }; + let clear_feeling = args + .clear_feeling + .as_deref() + .map(|raw| require_non_empty("--clear-feeling", raw).map(|s| s.to_lowercase())) + .transpose()?; + let axis = match args.axis { + Some(raw) => { + let name = require_non_empty("--axis", &raw)?; + let act_raw = args + .activation + .as_deref() + .ok_or_else(|| Trouble::invalid("--activation is required with --axis"))?; + let activation = parse_bound_or_delta("--activation", act_raw)?; + let mean = args.mean.map(|v| parse_unit("--mean", v)).transpose()?; + let plasticity = args.plasticity.map(|v| parse_unit("--plasticity", v)).transpose()?; + Some((name, activation, mean, plasticity)) + } + None => { + if args.activation.is_some() || args.mean.is_some() || args.plasticity.is_some() { + return Err(Trouble::invalid("--activation, --mean, and --plasticity require --axis")); + } + None + } + }; + + mutate_persona(settings, faculty, agent, session, |_instance, state, _stamp_dt, stamp| { + if let Some(clear_name) = &clear_feeling { + let feelings = array_mut(state, &["affect", "moodDimensions"])?; + feelings.retain(|entry| { + entry + .get("name") + .and_then(Value::as_str) + .map(|n| n.trim().to_lowercase()) + .as_deref() + != Some(clear_name.as_str()) + }); + } + if let Some((name, val, source)) = &feeling { + let feelings = array_mut(state, &["affect", "moodDimensions"])?; + let mut entry = json!({ + "name": name, + "value": val, + "updatedAt": stamp, + }); + if let Some(source) = source { + entry["source"] = json!(source); + } + if let Some(pos) = feelings.iter().position(|held| { + held.get("name") + .and_then(Value::as_str) + .map(|n| n.trim().to_lowercase()) + .as_deref() + == Some(name.as_str()) + }) { + feelings[pos] = entry; + } else { + feelings.push(entry); + } + } + if let Some((axis_name, act, mean, plasticity)) = &axis { + let situational = object_mut(state, &["activationProfile", "situationalState"])?; + let existing = situational.get(axis_name.as_str()).and_then(Value::as_object); + let prev_act = existing.and_then(|o| o.get("currentActivation")).and_then(Value::as_f64).unwrap_or(0.5); + let prev_mean = existing.and_then(|o| o.get("mean")).and_then(Value::as_f64).unwrap_or(0.5); + let prev_plasticity = existing.and_then(|o| o.get("plasticity")).and_then(Value::as_f64).unwrap_or(0.5); + situational.insert( + axis_name.clone(), + json!({ + "mean": mean.unwrap_or(prev_mean), + "plasticity": plasticity.unwrap_or(prev_plasticity), + "currentActivation": act.apply(prev_act), + }), + ); + } + Ok(None) + }) +} + +fn normalized_words(text: &str) -> Vec { + text.split_whitespace().map(str::to_lowercase).collect() +} + +fn is_intention(action: &Value) -> bool { + action.get("actionType").and_then(Value::as_str) == Some("custom") + && action.get("customActionType").and_then(Value::as_str) == Some("intention") +} + +struct IntentionAddArgs { + summary: String, + id: Option, + target_kind: Option, + target_id: Option, + target_label: Option, + readiness: IntentionReadiness, + urgency: Option, + confidence: Option, + rationale: Option, + expires_in_hours: Option, +} + +fn intention_add( + settings: &Settings, + faculty: Faculty, + agent: String, + session: Option, + args: IntentionAddArgs, +) -> Result { + let summary = require_non_empty("--summary", &args.summary)?; + let explicit_id = args.id.as_deref().map(|id| require_non_empty("--id", id)).transpose()?; + let urgency = args.urgency.map(|v| parse_unit("--urgency", v)).transpose()?; + let confidence = args.confidence.map(|v| parse_unit("--confidence", v)).transpose()?; + let rationale = args.rationale.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned); + if let Some(hours) = args.expires_in_hours { + if hours == 0 { + return Err(Trouble::invalid("--expires-in-hours must be at least 1")); + } + if Utc::now().checked_add_signed(Duration::hours(i64::from(hours))).is_none() { + return Err(Trouble::invalid("--expires-in-hours is out of date range")); + } + } + let target_kind = args.target_kind.as_deref(); + let target_id = args.target_id.as_deref(); + let target_label = args.target_label.as_deref(); + let _ = build_target(settings.client()?.instance(), target_kind, target_id, target_label)?; + + let wanted_words = normalized_words(&summary); + mutate_persona(settings, faculty, agent, session, |instance, state, stamp_dt, stamp| { + let expires_at = args + .expires_in_hours + .map(|hours| { + stamp_dt + .checked_add_signed(Duration::hours(i64::from(hours))) + .map(|dt| dt.to_rfc3339()) + .ok_or_else(|| Trouble::invalid("--expires-in-hours is out of date range")) + }) + .transpose()?; + let actions = array_mut(state, &["candidateActions", "actions"])?; + let now = Utc::now(); + if actions.iter().any(|action| { + is_intention(action) + && action.get("status").and_then(Value::as_str) == Some("active") + && !is_expired_action(action, now) + && normalized_words(action.get("summary").and_then(Value::as_str).unwrap_or_default()) == wanted_words + }) { + return Err(Trouble::invalid("an active intention with the same summary already exists")); + } + let existing_ids: BTreeSet = actions + .iter() + .filter_map(|action| action.get("id").and_then(Value::as_str).map(str::to_owned)) + .collect(); + let id = match &explicit_id { + Some(id) => { + if existing_ids.contains(id) { + return Err(Trouble::invalid(format!("candidateActions.actions already contains id `{id}`"))); + } + id.clone() + } + None => next_id('i', &existing_ids, stamp_dt, &summary), + }; + let target = build_target(instance, target_kind, target_id, target_label)?; + let mut entry = json!({ + "id": id, + "status": "active", + "actionType": "custom", + "customActionType": "intention", + "readiness": args.readiness.as_str(), + "riskLevel": "low", + "target": target, + "summary": summary, + "urgency": urgency.unwrap_or(0.5), + "createdAt": stamp, + "updatedAt": stamp, + }); + if let Some(confidence) = confidence { + entry["confidence"] = json!(confidence); + } + if let Some(rationale) = &rationale { + entry["rationale"] = json!(rationale); + } + if let Some(expires_at) = &expires_at { + entry["expiresAt"] = json!(expires_at); + } + actions.push(entry); + Ok(Some(id)) + }) +} + +fn intention_drop( + settings: &Settings, + faculty: Faculty, + agent: String, + session: Option, + id: String, +) -> Result { + let id = require_non_empty("", &id)?; + mutate_persona(settings, faculty, agent, session, |_instance, state, _stamp_dt, stamp| { + let actions = array_mut(state, &["candidateActions", "actions"])?; + let Some(action) = actions.iter_mut().find(|action| { + action.get("id").and_then(Value::as_str) == Some(id.as_str()) && is_intention(action) + }) else { + return Err(Trouble::invalid(format!("no intention found with id `{id}`"))); + }; + action["status"] = json!("retired"); + action["readiness"] = json!("expired"); + action["updatedAt"] = json!(stamp); + Ok(None) + }) +} + +/// Legacy Persona State Standard privacy predicate (`select.rs:1818-1831`): +/// true when `extensions.privacy == "private"`, a `"private"` tag is present, +/// or any tag starts with `"room:!"` (DM room), matched ASCII case-insensitively after trimming. +pub(crate) fn is_private_entry(item: &Value) -> bool { + if item + .pointer("/extensions/privacy") + .and_then(Value::as_str) + .is_some_and(|privacy| privacy.trim().eq_ignore_ascii_case("private")) + { + return true; + } + item.get("tags") + .and_then(Value::as_array) + .is_some_and(|tags| tags.iter().filter_map(Value::as_str).any(is_private_tag)) +} + +fn is_live_entry(item: &Value) -> bool { + !matches!( + item.get("status").and_then(Value::as_str).map(str::trim), + Some("retired" | "resolved" | "cooled") + ) +} + +fn is_expired_action(action: &Value, now: DateTime) -> bool { + if str_at(action, &["readiness"]) == "expired" { + return true; + } + let expires_at = str_at(action, &["expiresAt"]); + !expires_at.is_empty() + && DateTime::parse_from_rfc3339(expires_at).is_ok_and(|at| at.with_timezone(&Utc) <= now) +} + +fn persona_seed(settings: &Settings) -> Result { + match settings.client()?.persona_get().map_err(Trouble::from)? { + HuginnMindResponse::Persona(Some(view)) => { + let rendered = render_seed(&view.value, &view.updated_at, &view.receipt_id); + let _ = std::io::Write::write_all(&mut std::io::stdout(), rendered.as_bytes()); + Ok(0) + } + HuginnMindResponse::Persona(None) => { + say("absent"); + Ok(1) + } + HuginnMindResponse::Refused(refusal) => Ok(refused(&refusal)), + other => Err(unexpected(&other)), + } +} + +fn str_at<'a>(value: &'a Value, path: &[&str]) -> &'a str { + path.iter() + .try_fold(value, |cursor, key| cursor.get(*key)) + .and_then(Value::as_str) + .map(str::trim) + .unwrap_or_default() +} + +fn num_at(value: &Value, path: &[&str]) -> Option { + path.iter().try_fold(value, |cursor, key| cursor.get(*key)).and_then(Value::as_f64) +} + +fn slice_at<'a>(value: &'a Value, path: &[&str]) -> &'a [Value] { + path.iter() + .try_fold(value, |cursor, key| cursor.get(*key)) + .and_then(Value::as_array) + .map_or(&[], Vec::as_slice) +} + +fn one_line(text: &str) -> String { + text.split_whitespace().collect::>().join(" ") +} + +fn format_target(target: &Value) -> String { + let kind = str_at(target, &["kind"]); + let id = str_at(target, &["id"]); + let label = str_at(target, &["label"]); + if kind.is_empty() && id.is_empty() { + return String::new(); + } + if label.is_empty() { + format!("{kind}:{id}") + } else { + format!("{kind}:{id} ({})", one_line(label)) + } +} + +fn render_thought_lines(out: &mut String, heading: &str, items: &[Value]) { + let live_public: Vec<&Value> = items + .iter() + .filter(|item| !is_private_entry(item) && is_live_entry(item)) + .collect(); + if live_public.is_empty() { + return; + } + let _ = writeln!(out, "{heading}:"); + for item in live_public { + let id = str_at(item, &["id"]); + let status = str_at(item, &["status"]); + let summary = one_line(str_at(item, &["summary"])); + let target = format_target(&item["target"]); + let _ = write!(out, "- [{id}] ({status}"); + if !target.is_empty() { + let _ = write!(out, ", {target}"); + } + let _ = write!(out, "): {summary}"); + let claim = one_line(str_at(item, &["claim"])); + if !claim.is_empty() { + let _ = write!(out, " | claim: {claim}"); + } + let question = one_line(str_at(item, &["question"])); + if !question.is_empty() { + let _ = write!(out, " | question: {question}"); + } + let tension = one_line(str_at(item, &["tension"])); + if !tension.is_empty() { + let _ = write!(out, " | tension: {tension}"); + } + let action = one_line(str_at(item, &["actionImplication"])); + if !action.is_empty() { + let _ = write!(out, " | action: {action}"); + } + let _ = writeln!(out); + } +} + +pub(crate) fn render_seed(state: &Value, updated_at: &str, receipt_id: &str) -> String { + render_seed_at(state, updated_at, receipt_id, Utc::now()) +} + +fn render_seed_at(state: &Value, updated_at: &str, receipt_id: &str, now: DateTime) -> String { + let mut out = String::new(); + let persona_id = str_at(state, &["personaId"]); + let public_name = one_line(str_at(state, &["publicName"])); + let pronouns = one_line(str_at(state, &["presentation", "pronouns"])); + if pronouns.is_empty() { + let _ = writeln!(out, "Persona: {public_name} ({persona_id})"); + } else { + let _ = writeln!(out, "Persona: {public_name} ({persona_id}) [{pronouns}]"); + } + let description = one_line(str_at(state, &["publicDescription"])); + if !description.is_empty() { + let _ = writeln!(out, "Description: {description}"); + } + let voice = one_line(str_at(state, &["presentation", "voiceSummary"])); + if !voice.is_empty() { + let _ = writeln!(out, "Voice: {voice}"); + } + let jurisdiction = one_line(str_at(state, &["presentation", "jurisdiction"])); + if !jurisdiction.is_empty() { + let _ = writeln!(out, "Jurisdiction: {jurisdiction}"); + } + if let Some(home) = state.pointer("/presentation/homeContext") { + let formatted = format_target(home); + if !formatted.is_empty() { + let _ = writeln!(out, "Home: {formatted}"); + } + } + let handles: Vec = slice_at(state, &["presentation", "publicHandles"]) + .iter() + .filter_map(|handle| { + let sys = one_line(str_at(handle, &["system"])); + let h = one_line(str_at(handle, &["handle"])); + (!sys.is_empty() && !h.is_empty()).then(|| format!("{sys}:{h}")) + }) + .collect(); + if !handles.is_empty() { + let _ = writeln!(out, "Handles: {}", handles.join(", ")); + } + + // Values (`select.rs:801`: filter by !is_private_entry defensively) + let values: Vec<&Value> = slice_at(state, &["values"]) + .iter() + .filter(|value| !is_private_entry(value)) + .collect(); + if !values.is_empty() { + let _ = writeln!(out, "Values:"); + for val in values { + let id = str_at(val, &["id"]); + let label = one_line(str_at(val, &["label"])); + let summary = one_line(str_at(val, &["summary"])); + let prio = num_at(val, &["priority"]).unwrap_or(0.5); + if summary.is_empty() { + let _ = writeln!(out, "- [{id}] {label} (priority {prio:.2})"); + } else { + let _ = writeln!(out, "- [{id}] {label} (priority {prio:.2}): {summary}"); + } + } + } + + // Embodiment (senses & actuators) + let senses: Vec<&Value> = slice_at(state, &["embodiment", "senses"]) + .iter() + .filter(|item| !is_private_entry(item) && is_live_entry(item)) + .collect(); + let actuators: Vec<&Value> = slice_at(state, &["embodiment", "actuators"]) + .iter() + .filter(|item| !is_private_entry(item) && is_live_entry(item)) + .collect(); + if !senses.is_empty() || !actuators.is_empty() { + let _ = writeln!(out, "Embodiment:"); + for (kind, items) in [("sense", senses), ("actuator", actuators)] { + for item in items { + let id = str_at(item, &["id"]); + let label = one_line(str_at(item, &["label"])); + let summary = one_line(str_at(item, &["summary"])); + let lacks = one_line(str_at(item, &["lacks"])); + let _ = write!(out, "- {kind} [{id}] {label}: {summary}"); + if !lacks.is_empty() { + let _ = write!(out, " (lacks: {lacks})"); + } + let _ = writeln!(out); + } + } + } + + // Activation profile & mood dimensions & social biases + let trait_sections = [ + ("situationalState", "Situational State"), + ("stableDispositions", "Stable Dispositions"), + ("behavioralDimensions", "Behavioral Dimensions"), + ("presentationStrategy", "Presentation Strategy"), + ("voiceStyle", "Voice Style"), + ("underlyingOrganization", "Underlying Organization"), + ]; + for (field, heading) in trait_sections { + if let Some(map) = state.pointer(&format!("/activationProfile/{field}")).and_then(Value::as_object) + && !map.is_empty() + { + let mut keys: Vec<&String> = map.keys().collect(); + keys.sort(); + let _ = writeln!(out, "{heading}:"); + for key in keys { + let vec = &map[key]; + let act = num_at(vec, &["currentActivation"]).unwrap_or(0.5); + let mean = num_at(vec, &["mean"]).unwrap_or(0.5); + let plast = num_at(vec, &["plasticity"]).unwrap_or(0.5); + let _ = writeln!(out, "- {key}: activation={act:.2} mean={mean:.2} plasticity={plast:.2}"); + } + } + } + + let moods: Vec<&Value> = slice_at(state, &["affect", "moodDimensions"]) + .iter() + .filter(|item| !is_private_entry(item)) + .collect(); + if !moods.is_empty() { + let _ = writeln!(out, "Mood Dimensions:"); + for item in moods { + let name = one_line(str_at(item, &["name"])); + let value = num_at(item, &["value"]).unwrap_or(0.0); + let source = one_line(str_at(item, &["source"])); + if source.is_empty() { + let _ = writeln!(out, "- {name}: {value:.2}"); + } else { + let _ = writeln!(out, "- {name}: {value:.2} (source: {source})"); + } + } + } + + let biases: Vec<&Value> = slice_at(state, &["affect", "socialBiases"]) + .iter() + .filter(|item| !is_private_entry(item)) + .collect(); + if !biases.is_empty() { + let _ = writeln!(out, "Social Biases:"); + for item in biases { + let name = one_line(str_at(item, &["name"])); + let value = num_at(item, &["value"]).unwrap_or(0.0); + let summary = one_line(str_at(item, &["summary"])); + let pull = one_line(str_at(item, &["behavioralPull"])); + let _ = writeln!(out, "- {name} ({value:.2}): {summary} [pull: {pull}]"); + } + } + + // Social bonds + let bonds: Vec<&Value> = slice_at(state, &["affect", "socialBonds"]) + .iter() + .filter(|item| !is_private_entry(item) && is_live_entry(item)) + .collect(); + if !bonds.is_empty() { + let _ = writeln!(out, "Social Bonds:"); + for bond in bonds { + let id = str_at(bond, &["id"]); + let person_id = str_at(bond, &["object", "id"]); + let label = one_line(str_at(bond, &["object", "label"])); + let rel = match str_at(bond, &["relationshipKind"]) { + "custom" => { + let custom = one_line(str_at(bond, &["customRelationshipKind"])); + if custom.is_empty() { "custom".to_owned() } else { custom } + } + other => other.to_owned(), + }; + let trust = num_at(bond, &["trust"]).unwrap_or(0.5); + let tension = num_at(bond, &["tension"]).unwrap_or(0.2); + let summary = one_line(str_at(bond, &["summary"])); + let who = if label.is_empty() { person_id.to_owned() } else { format!("{label} ({person_id})") }; + let _ = write!(out, "- [{id}] {who} [{rel}] trust={trust:.2} tension={tension:.2}"); + if let Some(intensity) = num_at(bond, &["intensity"]) { + let _ = write!(out, " intensity={intensity:.2}"); + } + let _ = write!(out, ": {summary}"); + if let Some(ev) = bond.get("lastEvidence").filter(|ev| !is_private_entry(ev)) { + let claim = one_line(str_at(ev, &["claim"])); + let ev_summary = one_line(str_at(ev, &["summary"])); + if !claim.is_empty() || !ev_summary.is_empty() { + let _ = write!(out, " | lastEvidence: {claim} (was: {ev_summary})"); + } + } + let _ = writeln!(out); + } + } + + // Status reads + let reads: Vec<&Value> = slice_at(state, &["affect", "statusReads"]) + .iter() + .filter(|item| !is_private_entry(item) && is_live_entry(item)) + .collect(); + if !reads.is_empty() { + let _ = writeln!(out, "Status Reads:"); + for read in reads { + let id = str_at(read, &["id"]); + let target = format_target(&read["target"]); + let kind = match str_at(read, &["statusKind"]) { + "custom" => { + let custom = one_line(str_at(read, &["customStatusKind"])); + if custom.is_empty() { "custom".to_owned() } else { custom } + } + other => other.to_owned(), + }; + let conf = num_at(read, &["confidence"]).unwrap_or(0.5); + let summary = one_line(str_at(read, &["summary"])); + let _ = write!(out, "- [{id}] {target} [{kind}, conf={conf:.2}]: {summary}"); + if let Some(ev) = read.get("lastEvidence").filter(|ev| !is_private_entry(ev)) { + let claim = one_line(str_at(ev, &["claim"])); + let ev_summary = one_line(str_at(ev, &["summary"])); + if !claim.is_empty() || !ev_summary.is_empty() { + let _ = write!(out, " | lastEvidence: {claim} (was: {ev_summary})"); + } + } + let _ = writeln!(out); + } + } + + // Doctrine stances + let stances: Vec<&Value> = slice_at(state, &["affect", "doctrineStances"]) + .iter() + .filter(|item| !is_private_entry(item) && is_live_entry(item)) + .collect(); + if !stances.is_empty() { + let _ = writeln!(out, "Doctrine Stances:"); + for stance in stances { + let id = str_at(stance, &["id"]); + let kind = match str_at(stance, &["stanceKind"]) { + "custom" => { + let custom = one_line(str_at(stance, &["customStanceKind"])); + if custom.is_empty() { "custom".to_owned() } else { custom } + } + other => other.to_owned(), + }; + let principle = one_line(str_at(stance, &["principle"])); + let summary = one_line(str_at(stance, &["summary"])); + let _ = writeln!(out, "- [{id}] ({kind}) {principle}: {summary}"); + } + } + + render_thought_lines(&mut out, "Needs", slice_at(state, &["affect", "needs"])); + render_thought_lines(&mut out, "Pressures", slice_at(state, &["agencyPressure", "pressures"])); + render_thought_lines(&mut out, "Short-Term Thoughts", slice_at(state, &["thoughtMemory", "shortTerm"])); + render_thought_lines(&mut out, "Memories", slice_at(state, &["thoughtMemory", "memories"])); + render_thought_lines(&mut out, "Incubation", slice_at(state, &["thoughtMemory", "incubation"])); + + // Candidate actions / intentions + let actions: Vec<&Value> = slice_at(state, &["candidateActions", "actions"]) + .iter() + .filter(|item| !is_private_entry(item) && is_live_entry(item) && !is_expired_action(item, now)) + .collect(); + if !actions.is_empty() { + let _ = writeln!(out, "Intentions & Candidate Actions:"); + for action in actions { + let id = str_at(action, &["id"]); + let readiness = str_at(action, &["readiness"]); + let kind = match str_at(action, &["actionType"]) { + "custom" => { + let custom = one_line(str_at(action, &["customActionType"])); + if custom.is_empty() { "custom".to_owned() } else { custom } + } + other => other.to_owned(), + }; + let summary = one_line(str_at(action, &["summary"])); + let target = format_target(&action["target"]); + let _ = write!(out, "- [{id}] ({kind}, {readiness}"); + if !target.is_empty() { + let _ = write!(out, ", {target}"); + } + let _ = write!(out, "): {summary}"); + let rationale = one_line(str_at(action, &["rationale"])); + if !rationale.is_empty() { + let _ = write!(out, " | rationale: {rationale}"); + } + let ev_summaries: Vec = slice_at(action, &["evidence"]) + .iter() + .filter(|ev| !is_private_entry(ev)) + .map(|ev| one_line(str_at(ev, &["summary"]))) + .filter(|s| !s.is_empty()) + .collect(); + if !ev_summaries.is_empty() { + let _ = write!(out, " | evidence: {}", ev_summaries.join("; ")); + } + let _ = writeln!(out); + } + } + + let _ = writeln!(out, "updatedAt {updated_at} receipt {receipt_id}"); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn is_private_entry_matches_persona_state_standard() { + assert!(!is_private_entry(&json!({ "id": "m1", "tags": ["about:meta", "room:#swarm:gamecult.org", "Room:#swarm:gamecult.org"], "extensions": { "privacy": "public" } }))); + assert!(is_private_entry(&json!({ "id": "m2", "extensions": { "privacy": "private" } }))); + assert!(is_private_entry(&json!({ "id": "m2b", "extensions": { "privacy": " Private " } }))); + assert!(is_private_entry(&json!({ "id": "m3", "tags": ["private"] }))); + assert!(is_private_entry(&json!({ "id": "m3b", "tags": [" Private "] }))); + assert!(is_private_entry(&json!({ "id": "m4", "tags": ["room:!abc:gamecult.org"] }))); + assert!(is_private_entry(&json!({ "id": "m4b", "tags": [" Room:!abc:gamecult.org "] }))); + } + + #[test] + fn stamp_after_advances_past_future_stored_timestamp() { + let now = DateTime::parse_from_rfc3339("2026-12-06T00:00:00Z").unwrap().with_timezone(&Utc); + let stored = "2099-01-01T00:00:00Z"; + let stamped = stamp_after(now, Some(stored)); + assert!(stamped > DateTime::parse_from_rfc3339(stored).unwrap().with_timezone(&Utc)); + } + + #[test] + fn render_seed_strips_all_legacy_private_and_retired_surfaces() { + let doc = json!({ + "personaId": "eureka", + "publicName": "Eureka", + "publicDescription": "Public description", + "presentation": { "pronouns": "she/her", "voiceSummary": "clear and dry" }, + "privateNotes": ["SECRET-PRIVATE-NOTE"], + "values": [ + { "id": "v1", "label": "Coherence", "priority": 0.9, "summary": "Public value" }, + { "id": "v2", "label": "Hidden", "priority": 0.1, "summary": "SECRET-VALUE", "tags": ["private"] } + ], + "activationProfile": { + "underlyingOrganization": {}, "stableDispositions": {}, "behavioralDimensions": {}, + "presentationStrategy": {}, "voiceStyle": {}, "situationalState": { + "valence": { "mean": 0.5, "plasticity": 0.3, "currentActivation": 0.6 } + } + }, + "thoughtMemory": { + "shortTerm": [ + { "id": "st1", "status": "active", "target": { "kind": "self", "id": "eureka" }, "summary": "Public short term" }, + { "id": "st2", "status": "active", "target": { "kind": "self", "id": "eureka" }, "summary": "SECRET-EXT", "extensions": { "privacy": "private" } }, + { "id": "st3", "status": "retired", "target": { "kind": "self", "id": "eureka" }, "summary": "RETIRED-ST" } + ], + "memories": [ + { "id": "mem1", "status": "crystallized", "target": { "kind": "self", "id": "eureka" }, "summary": "Public memory" }, + { "id": "mem2", "status": "crystallized", "target": { "kind": "self", "id": "eureka" }, "summary": "SECRET-DM", "tags": ["room:!dm:gamecult.org"] } + ], + "incubation": [ + { "id": "inc1", "status": "resolved", "target": { "kind": "self", "id": "eureka" }, "summary": "RESOLVED-INC" }, + { "id": "inc2", "status": "active", "target": { "kind": "self", "id": "eureka" }, "summary": "SECRET-INC-PRIV", "tags": ["Private"] } + ] + }, + "agencyPressure": { + "pressures": [ + { "id": "p1", "status": "active", "target": { "kind": "self", "id": "eureka" }, "summary": "SECRET-PRESSURE", "tags": ["private"] } + ] + }, + "candidateActions": { + "actions": [ + { + "id": "i1", "status": "active", "actionType": "custom", "customActionType": "intention", + "readiness": "waiting", "riskLevel": "low", "target": { "kind": "self", "id": "eureka" }, + "summary": "Public intention", + "evidence": [ + { "id": "ev1", "summary": "Public evidence" }, + { "id": "ev2", "summary": "SECRET-EVIDENCE", "extensions": { "privacy": "private" } } + ] + } + ] + }, + "voidbotProjection": { + "candidateInterventions": [ + { "id": "vb1", "status": "active", "actionType": "speak", "readiness": "ready", "riskLevel": "low", "target": { "kind": "self", "id": "eureka" }, "summary": "SECRET-VOIDBOT" } + ] + }, + "affect": { + "needs": [], + "socialBonds": [ + { + "id": "b1", "status": "active", "subject": { "kind": "self", "id": "eureka" }, + "object": { "kind": "person", "id": "meta", "label": "Meta" }, + "relationshipKind": "collaborator", "summary": "Public bond", "trust": 0.9, "tension": 0.1, + "lastEvidence": { "id": "b1-e", "status": "retired", "summary": "SECRET-LAST-EV", "claim": "SECRET-CLAIM", "tags": ["room:!secret:gamecult.org"] } + } + ], + "statusReads": [], + "moodDimensions": [{ "name": "curious", "value": 0.7 }], + "socialBiases": [], + "doctrineStances": [] + }, + "embodiment": { + "senses": [{ "id": "s1", "status": "active", "label": "Matrix", "summary": "Public sense" }], + "actuators": [{ "id": "a1", "status": "active", "label": "DM", "summary": "SECRET-ACTUATOR", "tags": ["private"] }] + } + }); + let rendered = render_seed(&doc, "2026-12-06T00:00:00Z", "mind-commit-1"); + for public_text in ["Public description", "Public value", "Public short term", "Public memory", "Public intention", "Public evidence", "Public bond", "Public sense", "curious", "updatedAt 2026-12-06T00:00:00Z receipt mind-commit-1"] { + assert!(rendered.contains(public_text), "missing `{public_text}` in:\n{rendered}"); + } + for forbidden in ["SECRET-PRIVATE-NOTE", "SECRET-VALUE", "SECRET-EXT", "RETIRED-ST", "SECRET-DM", "RESOLVED-INC", "SECRET-INC-PRIV", "SECRET-PRESSURE", "SECRET-EVIDENCE", "SECRET-VOIDBOT", "SECRET-LAST-EV", "SECRET-CLAIM", "SECRET-ACTUATOR"] { + assert!(!rendered.contains(forbidden), "leaked `{forbidden}` in:\n{rendered}"); + } + } + + #[test] + fn render_seed_exercises_optional_fields_and_empty_omissions() { + let rich = json!({ + "personaId": "eureka", + "publicName": "Eureka", + "presentation": { + "voiceSummary": "clear and dry", + "jurisdiction": "GameCult", + "homeContext": { "kind": "room", "id": "#swarm:gamecult.org", "label": "Swarm" }, + "publicHandles": [ + { "system": "matrix", "handle": "@eureka:gamecult.org" }, + { "system": "", "handle": "SKIP-NO-SYS" }, + { "system": "SKIP-NO-HANDLE", "handle": "" } + ] + }, + "activationProfile": { + "underlyingOrganization": {}, + "stableDispositions": {}, + "behavioralDimensions": {}, + "presentationStrategy": {}, + "voiceStyle": {}, + "situationalState": { + "valence": { "mean": 0.5, "plasticity": 0.3, "currentActivation": 0.6 } + } + }, + "thoughtMemory": { + "shortTerm": [ + { + "id": "st-full", + "status": "active", + "target": { "kind": "self", "id": "eureka" }, + "summary": "Full thought", + "claim": "Claim A", + "question": "Question A", + "tension": "Tension A", + "actionImplication": "Action A" + }, + { + "id": "st-bare", + "status": "active", + "target": {}, + "summary": "Bare thought" + }, + { + "id": "st-kind-only", + "status": "active", + "target": { "kind": "room", "id": "" }, + "summary": "Kind-only target" + } + ] + }, + "embodiment": { + "senses": [ + { "id": "s1", "status": "active", "label": "Matrix", "summary": "Reads rooms", "lacks": "audio" } + ], + "actuators": [ + { "id": "a1", "status": "active", "label": "Mouth", "summary": "Speaks" } + ] + }, + "affect": { + "socialBonds": [ + { + "id": "b-claim", "status": "active", + "object": { "kind": "person", "id": "p1" }, + "relationshipKind": "ally", "summary": "Bond 1", + "lastEvidence": { "claim": "Claim only" } + }, + { + "id": "b-sum", "status": "active", + "object": { "kind": "person", "id": "p2" }, + "relationshipKind": "ally", "summary": "Bond 2", + "lastEvidence": { "summary": "Summary only" } + }, + { + "id": "b-empty-ev", "status": "active", + "object": { "kind": "person", "id": "p3" }, + "relationshipKind": "ally", "summary": "Bond 3", + "lastEvidence": { "claim": "", "summary": "" } + } + ], + "statusReads": [ + { + "id": "sr-priv-ev", "status": "active", + "target": { "kind": "person", "id": "p1" }, + "statusKind": "trust", "summary": "Read 1", + "lastEvidence": { "claim": "LEAK-SR-EV", "extensions": { "privacy": "private" } } + }, + { + "id": "sr-claim", "status": "active", + "target": { "kind": "person", "id": "p2" }, + "statusKind": "trust", "summary": "Read 2", + "lastEvidence": { "claim": "Read claim" } + }, + { + "id": "sr-empty-ev", "status": "active", + "target": { "kind": "person", "id": "p3" }, + "statusKind": "trust", "summary": "Read 3", + "lastEvidence": { "claim": "", "summary": "" } + } + ] + }, + "candidateActions": { + "actions": [ + { + "id": "i-full", "status": "active", "actionType": "custom", "customActionType": "intention", + "readiness": "ready", "target": { "kind": "self", "id": "eureka" }, + "summary": "Full intention", "rationale": "Why do this" + }, + { + "id": "i-bare", "status": "active", "actionType": "custom", "customActionType": "intention", + "readiness": "waiting", "target": {}, + "summary": "Bare intention" + } + ] + } + }); + let rendered = render_seed(&rich, "2026-12-06T00:00:00Z", "r-1"); + for expected in [ + "Voice: clear and dry\n", + "Jurisdiction: GameCult\n", + "Home: room:#swarm:gamecult.org (Swarm)\n", + "Handles: matrix:@eureka:gamecult.org\n", + "- [st-full] (active, self:eureka): Full thought | claim: Claim A | question: Question A | tension: Tension A | action: Action A\n", + "- [st-bare] (active): Bare thought\n", + "- [st-kind-only] (active, room:): Kind-only target\n", + "- sense [s1] Matrix: Reads rooms (lacks: audio)\n", + "- actuator [a1] Mouth: Speaks\n", + "Situational State:\n", + "- [b-claim] p1 [ally] trust=0.50 tension=0.20: Bond 1 | lastEvidence: Claim only (was: )\n", + "- [b-sum] p2 [ally] trust=0.50 tension=0.20: Bond 2 | lastEvidence: (was: Summary only)\n", + "- [b-empty-ev] p3 [ally] trust=0.50 tension=0.20: Bond 3\n", + "- [sr-priv-ev] person:p1 [trust, conf=0.50]: Read 1\n", + "- [sr-claim] person:p2 [trust, conf=0.50]: Read 2 | lastEvidence: Read claim (was: )\n", + "- [sr-empty-ev] person:p3 [trust, conf=0.50]: Read 3\n", + "- [i-full] (intention, ready, self:eureka): Full intention | rationale: Why do this\n", + "- [i-bare] (intention, waiting): Bare intention\n", + ] { + assert!(rendered.contains(expected), "missing `{expected}` in:\n{rendered}"); + } + for absent in [ + "SKIP-NO-SYS", + "SKIP-NO-HANDLE", + "LEAK-SR-EV", + "xyzzy", + "Stable Dispositions:", + "Behavioral Dimensions:", + "Presentation Strategy:", + "Voice Style:", + "Underlying Organization:", + ] { + assert!(!rendered.contains(absent), "unexpected `{absent}` in:\n{rendered}"); + } + + // Minimal document omits optional headers when absent, and actuators alone still render Embodiment. + let actuators_only = json!({ + "personaId": "eureka", + "publicName": "Eureka", + "presentation": { "homeContext": {} }, + "embodiment": { + "senses": [], + "actuators": [{ "id": "a1", "status": "active", "label": "Mouth", "summary": "Speaks" }] + } + }); + let min_rendered = render_seed(&actuators_only, "2026-12-06T00:00:00Z", "r-2"); + assert!(min_rendered.contains("Embodiment:\n- actuator [a1] Mouth: Speaks\n"), "{min_rendered}"); + for absent in ["Voice:", "Jurisdiction:", "Home:", "Handles:"] { + assert!(!min_rendered.contains(absent), "unexpected `{absent}` in:\n{min_rendered}"); + } + } + + #[test] + fn render_seed_at_filters_expired_intentions_at_exact_boundary() { + let now = DateTime::parse_from_rfc3339("2026-12-06T12:00:00Z").unwrap().with_timezone(&Utc); + let doc = json!({ + "personaId": "eureka", + "publicName": "Eureka", + "candidateActions": { + "actions": [ + { + "id": "i-live", "status": "active", "actionType": "custom", "customActionType": "intention", + "readiness": "ready", "target": { "kind": "self", "id": "eureka" }, + "summary": "KEEP-FUTURE-INTENTION", "expiresAt": "2026-12-06T12:00:01Z" + }, + { + "id": "i-eq", "status": "active", "actionType": "custom", "customActionType": "intention", + "readiness": "ready", "target": { "kind": "self", "id": "eureka" }, + "summary": "HIDE-BOUNDARY-INTENTION", "expiresAt": "2026-12-06T12:00:00Z" + }, + { + "id": "i-past", "status": "active", "actionType": "custom", "customActionType": "intention", + "readiness": "waiting", "target": { "kind": "self", "id": "eureka" }, + "summary": "HIDE-PAST-INTENTION", "expiresAt": "2026-12-06T11:59:59Z" + }, + { + "id": "i-readiness", "status": "active", "actionType": "custom", "customActionType": "intention", + "readiness": "expired", "target": { "kind": "self", "id": "eureka" }, + "summary": "HIDE-EXPIRED-READINESS", "expiresAt": "2026-12-06T13:00:00Z" + } + ] + } + }); + let rendered = render_seed_at(&doc, "2026-12-06T12:00:00Z", "r-exp", now); + assert!(rendered.contains("KEEP-FUTURE-INTENTION"), "{rendered}"); + for hidden in ["HIDE-BOUNDARY-INTENTION", "HIDE-PAST-INTENTION", "HIDE-EXPIRED-READINESS"] { + assert!(!rendered.contains(hidden), "expired `{hidden}` leaked in:\n{rendered}"); + } + } +} diff --git a/crates/eureka-state/tests/cli.rs b/crates/eureka-state/tests/cli.rs index b513b5d..860f5ae 100644 --- a/crates/eureka-state/tests/cli.rs +++ b/crates/eureka-state/tests/cli.rs @@ -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: 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); +}