diff --git a/crates/mind-body/README.md b/crates/mind-body/README.md index f64eaa5..207a022 100644 --- a/crates/mind-body/README.md +++ b/crates/mind-body/README.md @@ -14,7 +14,7 @@ wrong or the mind cannot be reached. `mind-heartbeat` is the one process that decides who wakes and when. It starts a Persona's unit and writes no Mind: the beat (`HEARTBEAT_BEAT_S`, default 1800 s) goes to the idle, released Mind that has waited longest, bent by a member addressing her, and the operator or another Mind naming a Persona wakes her at once, once per message. `mind-heartbeat timeline` prints its latest record. -`mind-persona` is inert: it reads the brakes and exits `dead` or `no organ`. It writes nothing. Nothing launches `mind-self-run`. +`mind-persona` reads the brakes and exits `dead`, or drains: one turn in each room with a waking line (at most three), one put of her state and one trace record per turn, one ack. `mind-persona trace --instance [--last N]` prints her trace. Nothing launches `mind-self-run`. The actuator has its own ignored test, `the_real_bin_finds_her_run_...` in `tests/self_run.rs`: the real `mind-self-run` against the real daemon with a diff --git a/crates/mind-body/src/bin/mind-persona.rs b/crates/mind-body/src/bin/mind-persona.rs index 01c7b2e..103af74 100644 --- a/crates/mind-body/src/bin/mind-persona.rs +++ b/crates/mind-body/src/bin/mind-persona.rs @@ -1,17 +1,23 @@ //! `mind-persona --instance [--endpoint rudp://:]`: //! one start of the Persona organ (`mind_body::persona::carry`) inside //! `mind-persona@`. This reads the process's arguments and -//! environment, the things the library never reads, and prints the outcome: -//! `dead` when a brake is held, `no organ` when they allow a turn, since she has -//! none until the three-stage turn lands. It exits 0 for both, and 2 when the -//! arguments or the environment are wrong. +//! environment, the things the library never reads, builds the organs once the brakes allow a turn, and prints the +//! outcome: `dead` when a brake is held; else the drain (`drained: N turns, acked through S, K puts refused`), which takes +//! a turn in each room holding a waking line and acks once (`persona-turn-drains-deliveries`); or `failed: ` for a +//! start that read nothing, exit 1. It exits 0 for `dead` and `drained`, and 2 when the arguments or the environment +//! are wrong. //! //! The persona flags (`--rooms`, `--operator`, `--minds`, `--self-sender`, or //! `MIND_PERSONA_ROOMS`, `MIND_PERSONA_OPERATOR`, `MIND_PERSONA_MINDS`, //! `MIND_PERSONA_SELF_SENDER` and `MIND_PERSONA_MODEL` from the unit's -//! `persona.env`) are still parsed, so a start refuses the configuration the turn -//! will need. Without `--endpoint` the daemon is `HUGINN_ENDPOINT`; no call is made -//! to it. +//! `persona.env`) are parsed first, so a start refuses a configuration the turn will not run on. A released start needs +//! the daemon (`--endpoint` or `HUGINN_ENDPOINT`, her persona door), the mouth (`BIFROST_CHAT_ENDPOINT`, +//! `BIFROST_CHAT_KEY_FILE`), the connector (`MIND_PERSONA_CONNECTOR_ENDPOINT` and the `connector-key` credential) and +//! `STATE_DIRECTORY`, where her trace is `persona-trace.cc`; it reads `MIND_PERSONA_FORGE_URL`, `MIND_PERSONA_TUNING` +//! and `MIND_HEARTBEAT_STATE` as `project` does. Without the connector or the mouth it ends `failed`, touching nothing. +//! +//! `mind-persona trace --instance [--last N]` prints the newest N (default 20) records of her trace as JSON lines, +//! oldest first. It is read-only. //! //! `mind-persona project --instance [--endpoint rudp://:] [--kind chat|beat|reflection] [--in ] //! [--room ] [--seed N] [--state ] [--last-outcome ] [--select-only | --renders K @@ -51,16 +57,18 @@ use std::path::{Path, PathBuf}; use std::time::Duration; use anyhow::{Context, Result, anyhow, bail}; +use eureka_pipeline::Slug; use eureka_state::HuginnClient; use mind_body::chat_rudp::{RudpChat, connection_id}; use mind_body::cli::{instance_and_endpoint, instance_and_maybe_endpoint}; use mind_body::control::{CONTROL_ROOT, FileSource, control_path, swarm_path}; -use mind_body::persona::{Config, carry}; +use mind_body::persona::{Config, FileTrace, Outcome, Start, carry, trace_lines}; use mind_body::heartbeat::{FileStore, HeartbeatView, own_rooms}; use mind_body::projection::harness::{Fixture, Harness, batch, fixture_request, simulate, state_file}; use mind_body::projection::{DomainSource, HttpForge, HuginnPersonaSource, KitModel, LiveReads, MindDomain, Model, MouthReader, ReadSource, Organs as ProjectOrgans, PersonaSource, Request as ProjectRequest, TUNING_FILE, TUNING_ROOT, Through, TurnKind, connector_key, project}; const USAGE: &str = "usage: mind-persona --instance [--endpoint rudp://:] [--rooms a,b] [--operator id[,id]] [--minds id[,id]] [--self-sender id]"; +const TRACE_USAGE: &str = "usage: mind-persona trace --instance [--last N]"; const PROJECT_USAGE: &str = "usage: mind-persona project --instance [--endpoint rudp://:] [--kind chat|beat|reflection] [--in ] [--room ] [--seed N] [--state ] [--last-outcome ] [--select-only | --renders K [--through projector|persona|interpreter] [--judge ]] | (--batch | --simulate ) --out "; /// How long one call to the mind may take. const TIMEOUT: Duration = Duration::from_secs(15); @@ -77,13 +85,73 @@ fn setting(name: &str) -> Option { } #[allow(clippy::disallowed_methods, reason = "the binary reads its own arguments and environment, and hands them to the library")] -fn run() -> Result { +fn run() -> Result { let args: Vec = std::env::args().skip(1).collect(); - let (_config, rest) = Config::from_args_and_env(&args, setting, USAGE)?; - let (instance, _endpoint) = instance_and_endpoint(&rest, setting("HUGINN_ENDPOINT"), USAGE)?; + let (config, rest) = Config::from_args_and_env(&args, setting, USAGE)?; + let (instance, endpoint) = instance_and_endpoint(&rest, setting("HUGINN_ENDPOINT"), USAGE)?; let control = FileSource::new(control_path(Path::new(CONTROL_ROOT), &instance)?); let swarm = FileSource::new(swarm_path(Path::new(CONTROL_ROOT))); - Ok(carry(&control, &swarm, &instance).to_string()) + Ok(carry(&control, &swarm, &instance, || start(config, &instance, endpoint))) +} + +/// The organs of a released start: built only when the brakes allow a turn, each from the unit's environment. +fn start(config: Config, instance: &Slug, endpoint: SocketAddr) -> Result> { + let chat = chat(instance)?.ok_or_else(|| anyhow!("BIFROST_CHAT_ENDPOINT and BIFROST_CHAT_KEY_FILE are not set"))?; + let connector: SocketAddr = required("MIND_PERSONA_CONNECTOR_ENDPOINT")?.parse().map_err(|_| anyhow!("MIND_PERSONA_CONNECTOR_ENDPOINT is not :"))?; + let model = KitModel::open(connector, connector_key(&credentials_directory()?)?, &instance.0, MODEL_TIMEOUT)?; + let client = || HuginnClient::new(endpoint, instance.clone(), TIMEOUT); + let forge = setting("MIND_PERSONA_FORGE_URL"); + Ok(Start { + config, + persona: Box::new(HuginnPersonaSource::new(client())), + chat, + trace: Box::new(trace_of()?), + addressing: setting("MIND_HEARTBEAT_STATE").map(|path| Box::new(FileStore::new(path)) as Box), + model: Box::new(model), + domain: forge.as_deref().map(|forge| Box::new(MindDomain::new(client(), HttpForge::new(forge))) as Box), + reads: Some(Box::new(LiveReads::new(client(), forge.as_deref().map(HttpForge::new)))), + tuning: tuning_of(instance), + clock: Box::new(chrono::Utc::now), + }) +} + +/// Her trace: the unit's state directory, `persona-trace.cc`. +#[allow(clippy::disallowed_methods, reason = "the binary reads its own environment, and hands it to the library")] +fn trace_of() -> Result { + let directory = required("STATE_DIRECTORY")?; + Ok(FileTrace::new(Path::new(directory.split(':').next().unwrap_or_default()).join("persona-trace.cc"))) +} + +/// The tuning file: `MIND_PERSONA_TUNING`, else the installed one. +fn tuning_of(instance: &Slug) -> PathBuf { + setting("MIND_PERSONA_TUNING").map_or_else(|| Path::new(TUNING_ROOT).join(&instance.0).join(TUNING_FILE), PathBuf::from) +} + +/// The mouth, when the environment names it. +fn chat(instance: &Slug) -> Result> { + match (setting("BIFROST_CHAT_ENDPOINT"), setting("BIFROST_CHAT_KEY_FILE")) { + (Some(endpoint), Some(_)) => { + let endpoint: SocketAddr = endpoint.strip_prefix("rudp://").and_then(|address| address.parse().ok()).ok_or_else(|| anyhow!("BIFROST_CHAT_ENDPOINT is not rudp://:"))?; + Ok(Some(RudpChat::new(endpoint, connection_id(&credential("BIFROST_CHAT_KEY_FILE")?), instance.0.clone(), CHAT_TIMEOUT))) + } + _ => Ok(None), + } +} + +/// `trace --instance [--last N]`: the newest records of her trace, as JSON lines. +fn run_trace(args: &[String]) -> Result { + let (mut instance, mut last) = (None, 20usize); + let mut given = args.iter(); + while let Some(flag) = given.next() { + let mut value = || given.next().cloned().ok_or_else(|| anyhow!("{TRACE_USAGE}")); + match flag.as_str() { + "--instance" => instance = Some(value()?), + "--last" => last = value()?.parse().map_err(|_| anyhow!("{TRACE_USAGE}"))?, + _ => bail!("{TRACE_USAGE}"), + } + } + instance.ok_or_else(|| anyhow!("{TRACE_USAGE}"))?; + Ok(trace_lines(&trace_of()?, last)?.join("\n")) } fn required(name: &str) -> Result { @@ -156,7 +224,7 @@ fn run_project(args: &[String]) -> Result { bail!("{PROJECT_USAGE}"); } let (instance, address) = instance_and_maybe_endpoint(&rest, setting("HUGINN_ENDPOINT"), PROJECT_USAGE)?; - let tuning = setting("MIND_PERSONA_TUNING").map_or_else(|| Path::new(TUNING_ROOT).join(&instance.0).join(TUNING_FILE), PathBuf::from); + let tuning = tuning_of(&instance); // Her stored state is asked only when no state is given; with a state file no daemon is needed or reached. let persona = address.map(|address| HuginnPersonaSource::new(HuginnClient::new(address, instance.clone(), TIMEOUT))); let renders = if select_only || planned { None } else { Some(renders.unwrap_or(1)) }; @@ -186,13 +254,7 @@ fn run_project(args: &[String]) -> Result { let request = ProjectRequest { judge_against: judge, last_outcome, ..fixture_request(&harness, fixture, state, seed.unwrap_or(seed_now), renders, through) }; return Ok(serde_json::to_string_pretty(&project(&organs, &request, fixture.now)?)?); } - let chat = match (setting("BIFROST_CHAT_ENDPOINT"), setting("BIFROST_CHAT_KEY_FILE")) { - (Some(endpoint), Some(_)) => { - let endpoint: SocketAddr = endpoint.strip_prefix("rudp://").and_then(|address| address.parse().ok()).ok_or_else(|| anyhow!("BIFROST_CHAT_ENDPOINT is not rudp://:"))?; - Some(RudpChat::new(endpoint, connection_id(&credential("BIFROST_CHAT_KEY_FILE")?), instance.0.clone(), CHAT_TIMEOUT)) - } - _ => None, - }; + let chat = chat(&instance)?; let heartbeat = setting("MIND_HEARTBEAT_STATE").map(FileStore::new); // Her domain: her mind through the endpoint given (her read door, for a Persona) and the forge, both read-only. let domain = match (address, setting("MIND_PERSONA_FORGE_URL")) { @@ -262,8 +324,23 @@ fn main() { } return; } + if args.first().map(String::as_str) == Some("trace") { + match run_trace(&args[1..]) { + Ok(lines) => println!("{lines}"), + Err(error) => { + eprintln!("mind-persona trace: {error:#}"); + std::process::exit(2); + } + } + return; + } match run() { - Ok(outcome) => println!("{outcome}"), + Ok(outcome) => { + println!("{outcome}"); + if matches!(outcome, Outcome::Failed(_)) { + std::process::exit(1); + } + } Err(error) => { eprintln!("mind-persona: {error:#}"); std::process::exit(2); diff --git a/crates/mind-body/src/persona.rs b/crates/mind-body/src/persona.rs index 824643d..a331006 100644 --- a/crates/mind-body/src/persona.rs +++ b/crates/mind-body/src/persona.rs @@ -1,12 +1,22 @@ -//! The Persona organ: one start of `mind-persona@`. +//! The Persona organ: one start of `mind-persona@`, and it is a drain (ruling +//! `eureka-body:ruling:persona-turn-drains-deliveries`, map section 16.36.2). //! //! A start reads the instance brake and the swarm brake once. A held brake ends it `Dead` before anything else is -//! touched. A released one ends it `NoOrgan`: she has no turn until the three-stage turn (Projector, Persona, -//! Interpreter) lands (ruling `eureka-body:ruling:persona-only-heartbeat`, map -//! `docs/persona-only-heartbeat-map.md`, cut C3). A start writes nothing: not her Mind, not her persona state, not the -//! chat, not a trace. +//! touched. A released one reads her persona state and her pending deliveries once, takes one turn in each room that +//! holds a waking line (`heartbeat::wakes`, the one rule), oldest waking line first, at most `TURNS_PER_START` of them +//! (a start the beat woke, with no waking line, takes one turn in the room of the newest pending line, else her first +//! room), and acks once. Each turn is `projection::take`, the simulator's turn: the Interpreter's decision through the +//! mouth, the commit's application of her proposals, one put of her state, one record appended to her trace. //! -//! What the module holds for that turn is what a chat line is made of: her `Config`, who a sender is to her +//! The put is `persona_put` under the `updatedAt` she was read at. A stale one (Self or Life put between) reads her +//! again, applies the same record again and puts once more; a second refusal is `put_refused` in the record and on +//! stderr, and her lines have already gone out. The record is appended after the put, refused or not. +//! +//! The ack rule: after the turns, ack through the highest seq below the first waking delivery whose room's turn did not +//! record a decision (it failed, or was not taken); every line below it is acked, the ones that woke no one as ambient. +//! A failed turn leaves its room's waking lines pending, so her next wake shows them again. The heartbeat never acks. +//! +//! What the module holds besides the drain is what a chat line is made of: her `Config`, who a sender is to her //! (`sender_role`), whom a message addresses (`addressees`, `addressing_of`), the framed `message` line, the tail of //! her rooms (`render_tail`) and the turn records' store (`FileTrace`). Items no start calls yet carry an //! `allow(dead_code)` that the first caller removes. @@ -19,12 +29,13 @@ use anyhow::{Result, anyhow, bail}; use chrono::{DateTime, Utc}; use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore}; use eureka_pipeline::{MemoryOrigin, Slug}; -use serde_json::Value; +use serde_json::{Value, json}; use crate::address::{Addressee, addresses, is_for, localpart}; -use crate::chat_client::{Basis, ChatDelivery, TailLine}; +use crate::chat_client::{Basis, Chat, ChatDelivery, TailLine}; use crate::control::{ControlSource, Effective, HeldReason, derive}; -use crate::heartbeat::HeartbeatView; +use crate::heartbeat::{HeartbeatView, Speaker, own_rooms, pending_facts, wakes}; +use crate::projection::{DomainSource, Model, Mouth, Organs, PersonaStore, Put, ReadSource, Request, Taken, Through, TurnKind, apply_commit, history, own_addressee, take}; /// The admitting agent's name on what her Persona admitted; `self_run::inbox` still reads her briefs by it. pub const AGENT: &str = "mind-persona"; @@ -181,15 +192,21 @@ impl Trace for FileTrace { pub enum Outcome { /// The brake did not allow it; nothing was touched. Dead(HeldReason), - /// The brakes allow a turn and she has none to take: the three-stage turn has not landed. - NoOrgan, + /// The drain ran: the turns taken, the seq the start acked through (none when it acked nothing), and the puts that + /// were refused twice. + Drained { turns: usize, acked_through: Option, put_refused: usize }, + /// The start read nothing (the organs could not be built, the daemon or the mouth was down): nothing acked, nothing put. + Failed(String), } impl fmt::Display for Outcome { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Dead(reason) => write!(f, "dead: {reason:?}"), - Self::NoOrgan => f.write_str("no organ: the brakes allow a turn and she has none"), + Self::Drained { turns, acked_through, put_refused } => { + write!(f, "drained: {turns} turns, acked through {}, {put_refused} puts refused", acked_through.map_or_else(|| "nothing".to_owned(), |seq| seq.to_string())) + } + Self::Failed(why) => write!(f, "failed: {why}"), } } } @@ -199,14 +216,199 @@ pub(crate) fn read(control: &impl ControlSource, swarm: &impl ControlSource, ins derive(control, swarm, instance) } -/// One start. `control` is the instance's control store and `swarm` the swarm's. Brakes first, and nothing after them. -pub fn carry(control: &impl ControlSource, swarm: &impl ControlSource, instance: &Slug) -> Outcome { +/// How many rooms one start takes a turn in. +pub const TURNS_PER_START: usize = 3; + +/// What a released start acts through: her organs, built only after the brakes allow it. +pub struct Start { + pub config: Config, + pub persona: Box, + pub chat: C, + pub trace: Box, + /// The heartbeat's addressing table, read-only. + pub addressing: Option>, + pub model: Box, + pub domain: Option>, + pub reads: Option>, + pub tuning: PathBuf, + pub clock: Box DateTime>, +} + +/// One start. `control` is the instance's control store and `swarm` the swarm's. Brakes first, and nothing after them: +/// `build` makes the organs only when they allow a turn. +pub fn carry(control: &impl ControlSource, swarm: &impl ControlSource, instance: &Slug, build: impl FnOnce() -> Result>) -> Outcome { match read(control, swarm, instance) { Effective::Held { reason } => Outcome::Dead(reason), - Effective::Released(_) => Outcome::NoOrgan, + Effective::Released(_) => match build() { + Ok(start) => drain(instance, &start), + Err(fault) => Outcome::Failed(format!("{fault:#}")), + }, } } +/// One turn's standing for the ack: the room it was in, whether she decided and it is in her trace, and whether the put +/// was refused twice. +struct Turn { + room: String, + decided: bool, + put_refused: bool, +} + +fn drain(instance: &Slug, start: &Start) -> Outcome { + let began = (start.clock)(); + let began_ms = u64::try_from(began.timestamp_millis()).unwrap_or_default(); + let config = &start.config; + let failed = |what: &str, fault: anyhow::Error| Outcome::Failed(format!("{what}: {fault:#}")); + let mut state = match start.persona.persona() { + Ok((state, _)) => state, + Err(fault) => return failed("her persona state was not read", fault), + }; + let pending = match start.chat.pending(0) { + Ok(pending) => pending, + Err(fault) => return failed("the mouth was not read", fault), + }; + let mut deliveries: Vec<&ChatDelivery> = pending.deliveries.iter().collect(); + deliveries.sort_by_key(|delivery| delivery.seq); + // Her rooms and her addressee, as the heartbeat reads them: the rooms named for the repos she stewards (a failed read + // leaves her none), and the heartbeat's table row for her. + let repos = start.domain.as_ref().and_then(|domain| domain.stewarded().ok()).unwrap_or_default(); + let own = own_rooms(repos.iter().map(String::as_str), deliveries.iter().map(|delivery| delivery.room_alias.as_str())); + let public_name = state.get("publicName").and_then(Value::as_str).unwrap_or_default().to_owned(); + let (her, _) = own_addressee(start.addressing.as_deref(), &config.own_sender, &public_name, began); + let facts = pending_facts(&deliveries, &config.own_sender, &config.minds, &own); + let waking: Vec<(u64, &str)> = deliveries + .iter() + .zip(&facts) + .filter(|(delivery, facts)| wakes(&her, delivery, speaker(config, delivery), **facts).is_some()) + .map(|(delivery, _)| (delivery.seq, delivery.room_alias.as_str())) + .collect(); + // The rooms to take a turn in, oldest waking line first; a start with no waking line is the beat's. + let mut rooms: Vec<&str> = Vec::new(); + for (_, room) in &waking { + if !rooms.contains(room) { + rooms.push(room); + } + } + rooms.truncate(TURNS_PER_START); + let kind = if rooms.is_empty() { TurnKind::Beat } else { TurnKind::Chat }; + if rooms.is_empty() { + rooms.extend(deliveries.last().map(|delivery| delivery.room_alias.as_str()).or(config.rooms.first().map(String::as_str))); + } + // The newest event of each room her input held: a send is refused if another sender reached the room after it. + let mut newest: BTreeMap<&str, (u64, &str)> = BTreeMap::new(); + let lines = deliveries.iter().map(|delivery| (delivery.room_alias.as_str(), delivery.at_unix_ms, delivery.event_id.as_str())).chain(pending.tail.iter().flatten().map(|line| (line.room.as_str(), line.at_unix_ms, line.event_id.as_str()))); + for (room, at, event) in lines { + if newest.get(room).is_none_or(|(held, _)| *held <= at) { + newest.insert(room, (at, event)); + } + } + let seen = newest.into_iter().map(|(room, (_, event))| (room.to_owned(), event.to_owned())).collect(); + let mouth = Mouth { chat: &start.chat, persona: instance.0.clone(), seen, since_unix_ms: began_ms }; + let organs = Organs { persona: None, chat: Some(&start.chat), addressing: start.addressing.as_deref(), model: Some(start.model.as_ref()), domain: start.domain.as_deref(), reads: start.reads.as_deref() }; + let mut taken: Vec = Vec::new(); + for (index, room) in rooms.iter().enumerate() { + let key = format!("{began_ms}-t{index}"); + let now = (start.clock)(); + let past = match start.trace.records() { + Ok(records) => history(&records), + Err(fault) => return failed("her trace was not read", fault), + }; + let request = Request { + instance: instance.0.clone(), + kind, + state: Some(state.clone()), + room: Some((*room).to_owned()), + seed: began_ms.wrapping_add(index as u64), + renders: Some(1), + judge_against: None, + operators: config.operators.clone(), + minds: config.minds.clone(), + own_sender: config.own_sender.clone(), + tuning: start.tuning.clone(), + through: Through::Interpreter, + last_heard: vec![], + recent: past.recent, + own_rooms: own.clone(), + last_outcome: past.last_outcome, + last_wake: past.last_wake, + records: past.records, + }; + let mut turn = take(&organs, &request, &mouth, &key, now); + let mut put_refused = false; + if turn.record.get("failed").is_none() && turn.state != state { + match put_applied(start.persona.as_ref(), &state, &turn, &key, now) { + Ok(landed) => state = landed, + Err((fresh, why)) => { + put_refused = true; + turn.record["put_refused"] = json!(why); + eprintln!("mind-persona: the put of turn {key} was refused twice: {why}"); + state = fresh; + } + } + } + let recorded = start.trace.record(&key, &turn.record); + if let Err(fault) = &recorded { + eprintln!("mind-persona: the record of turn {key} was not appended: {fault:#}"); + } + taken.push(Turn { room: (*room).to_owned(), decided: turn.record.get("failed").is_none() && recorded.is_ok(), put_refused }); + } + // The ack: through the highest seq below the first waking line whose room has no decision. + let blocked = waking.iter().find(|(_, room)| !taken.iter().any(|turn| turn.decided && turn.room == *room)).map(|(seq, _)| *seq); + let acked_through = deliveries.iter().map(|delivery| delivery.seq).filter(|seq| blocked.is_none_or(|limit| *seq < limit)).max().filter(|seq| match start.chat.ack(*seq) { + Ok(()) => true, + Err(fault) => { + eprintln!("mind-persona: the ack through {seq} failed: {fault:#}"); + false + } + }); + Outcome::Drained { turns: taken.len(), acked_through, put_refused: taken.iter().filter(|turn| turn.put_refused).count() } +} + +/// Who sent a delivery, as the wake rule sees them. +fn speaker(config: &Config, delivery: &ChatDelivery) -> Speaker { + if delivery.sender == config.own_sender { + Speaker::Her + } else if config.operators.contains(&delivery.sender) { + Speaker::Operator + } else if config.minds.contains(&delivery.sender) { + Speaker::Mind + } else { + Speaker::Member + } +} + +/// `turn`'s state put under the `updatedAt` she was read at (`read`, the state the turn began from). A stale put reads +/// her again, applies the same record to the state as it stands and puts once more. The state as stored is the answer; +/// when the second put is refused too, the state as it then stands, and why. +fn put_applied(store: &dyn PersonaStore, read: &Value, turn: &Taken, key: &str, now: DateTime) -> std::result::Result { + let stamped = |mut state: Value| { + state["updatedAt"] = json!(now.to_rfc3339()); + state + }; + let next = stamped(turn.state.clone()); + match store.put(&next, read.get("updatedAt").and_then(Value::as_str), key) { + Ok(Put::Committed) => return Ok(next), + Ok(Put::Stale) => {} + Ok(Put::Refused(why)) => return Err((read.clone(), why)), + Err(fault) => return Err((read.clone(), format!("{fault:#}"))), + } + let (fresh, _) = store.persona().map_err(|fault| (read.clone(), format!("her state was not read again: {fault:#}")))?; + let (applied, _) = apply_commit(&fresh, &turn.record, key, now); + let next = stamped(applied); + match store.put(&next, fresh.get("updatedAt").and_then(Value::as_str), key) { + Ok(Put::Committed) => Ok(next), + Ok(Put::Stale) => Err((fresh, "stale again".to_owned())), + Ok(Put::Refused(why)) => Err((fresh, why)), + Err(fault) => Err((fresh, format!("{fault:#}"))), + } +} + +/// The newest `last` records of her trace as JSON lines, oldest first. Read-only. +pub fn trace_lines(trace: &dyn Trace, last: usize) -> Result> { + let records = trace.records()?; + Ok(records[records.len().saturating_sub(last)..].iter().map(Value::to_string).collect()) +} + /// A conversation: the public rooms together, or one direct message room alone. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum Conversation { @@ -419,5 +621,7 @@ fn render_tail(config: &Config, addressing: &[Addressee], tail: Option>>; + +fn room(n: u64) -> String { + format!("!dm-{n}:gamecult.org") +} + +/// A line the mouth holds, the `seq`th: in a direct message from the operator unless `room` is a public one. +fn line(seq: u64, room: &str, sender: &str, text: &str) -> ChatDelivery { + ChatDelivery { + seq, + room_alias: room.into(), + room_id: room.into(), + event_id: format!("$e{seq}"), + sender: sender.into(), + sender_display: String::new(), + text: text.into(), + at_unix_ms: BASE_MS - 120_000 + seq * 1000, + context: vec![], + mentions: vec![], + is_direct: room.starts_with('!'), + image: None, + basis: None, + form: Form::Message, + reply_to: Default::default(), + } +} + +/// The mouth: it holds deliveries until they are acked, records its sends and acks, and counts reads. +struct FakeMouth { + held: RefCell>, + sent: RefCell>, + acks: RefCell>, + reads: Cell, + log: Log, +} + +impl Chat for Rc { + fn pending(&self, _: u64) -> Result { + self.reads.set(self.reads.get() + 1); + Ok(ChatPending { persona: "eureka".into(), deliveries: self.held.borrow().clone(), tail: Some(vec![]), tail_gaps: vec![] }) + } + fn send(&self, request: &ChatSendRequest) -> Result { + self.sent.borrow_mut().push(request.clone()); + self.log.borrow_mut().push("send".into()); + Ok(ChatSendReceipt { request_id: request.request_id.clone(), event_id: Some(format!("$sent-{}", self.sent.borrow().len())), refusal: None, newer: vec![] }) + } + fn open_direct(&self, _: &ChatOpenDirectRequest) -> Result { + bail!("a drain opens no conversation") + } + fn fetch(&self, _: &ChatFetchRequest) -> Result { + bail!("a drain fetches nothing") + } + fn ack(&self, through_seq: u64) -> Result<()> { + self.log.borrow_mut().push("ack".into()); + self.acks.borrow_mut().push(through_seq); + self.held.borrow_mut().retain(|delivery| delivery.seq > through_seq); + Ok(()) + } + fn read(&self, _: &ChatRead) -> Result<()> { + bail!("a drain reports no read") + } +} + +/// Her persona document as the mind holds it: a put under the stored `updatedAt` commits, any other is stale. `outside` +/// is Self or Life's put landing between her read and her put: it edits the stored document once per put, as long as it lasts. +struct FakeStore { + stored: RefCell, + puts: RefCell>, + outside: Cell, + log: Log, +} + +impl PersonaSource for Rc { + fn persona(&self) -> Result<(Value, String)> { + Ok((self.stored.borrow().clone(), "receipt".into())) + } +} + +impl PersonaStore for Rc { + fn put(&self, state: &Value, expected_updated_at: Option<&str>, _session: &str) -> Result { + self.log.borrow_mut().push("put".into()); + if self.outside.get() > 0 { + self.outside.set(self.outside.get() - 1); + let mut stored = self.stored.borrow_mut(); + stored["outside"] = json!("kept"); + stored["updatedAt"] = json!(format!("2026-11-26T00:0{}:00Z", self.puts.borrow().len() + self.outside.get())); + } + if self.stored.borrow().get("updatedAt").and_then(Value::as_str) != expected_updated_at { + return Ok(Put::Stale); + } + *self.stored.borrow_mut() = state.clone(); + self.puts.borrow_mut().push(state.clone()); + Ok(Put::Committed) + } +} + +struct MemTrace { + rows: RefCell>, + log: Log, +} + +impl Trace for Rc { + fn record(&self, key: &str, record: &Value) -> Result<()> { + self.log.borrow_mut().push("trace".into()); + self.rows.borrow_mut().push((key.to_owned(), record.clone())); + Ok(()) + } + fn records(&self) -> Result> { + Ok(self.rows.borrow().iter().map(|(_, record)| record.clone()).collect()) + } +} + +/// The recorded model, failing any call whose prompt carries `marker`: a turn that holds the marked line fails. +struct Flaky { + inner: Scripted, + marker: &'static str, +} + +impl Model for Flaky { + fn ask(&self, request_id: &str, model: &str, prompt: &str, schema: Option<&str>) -> std::result::Result { + if prompt.contains(self.marker) { + return Err(Failed { reason: "the provider failed the call".into(), usage: None }); + } + self.inner.ask(request_id, model, prompt, schema) + } +} + +/// She says one line, and (with `remembering`) keeps one note of it. +fn scripted(remembering: bool) -> Scripted { + Scripted::new(|_| "He nods at the screen. Hello there, friend.".into()).interpreting(move |prompt| { + let mut answer: Value = serde_json::from_str(&drafted_lines(prompt)).unwrap(); + if remembering { + answer["remember"] = json!([{ "text": "He was glad to hear from Meta.", "about": [META], "importance": 0.6, "private": false }]); + } + answer.to_string() + }) +} + +struct Rig { + mouth: Rc, + store: Rc, + trace: Rc, + log: Log, + dir: TempDir, +} + +impl Rig { + fn new(deliveries: Vec) -> Self { + let log = Log::default(); + let dir = TempDir::new().unwrap(); + ControlWriter::open(&dir.path().join("control.cc")).unwrap().set_brake(true, at(0), "op").unwrap(); + SwarmWriter::open(&dir.path().join("swarm.cc")).unwrap().set_brake(true, at(0), "op").unwrap(); + let mouth = Rc::new(FakeMouth { held: RefCell::new(deliveries), sent: RefCell::default(), acks: RefCell::default(), reads: Cell::new(0), log: log.clone() }); + let store = Rc::new(FakeStore { stored: RefCell::new(control()), puts: RefCell::default(), outside: Cell::new(0), log: log.clone() }); + let trace = Rc::new(MemTrace { rows: RefCell::default(), log: log.clone() }); + Self { mouth, store, trace, log, dir } + } + + fn run(&self, model: impl Model + 'static) -> Outcome { + let ticks = Cell::new(0i64); + let start = || { + Ok(Start { + config: Config { rooms: vec![MINDS.into()], operators: vec![META.into()], minds: vec!["@eureka:gamecult.org".into(), LIBBY.into()], own_sender: "@eureka:gamecult.org".into(), model: "test-model".into() }, + persona: Box::new(self.store.clone()), + chat: self.mouth.clone(), + trace: Box::new(self.trace.clone()), + addressing: None, + model: Box::new(model), + domain: None, + reads: None, + tuning: self.dir.path().join("persona-tuning.toml"), + clock: Box::new(move || { + ticks.set(ticks.get() + 1); + Utc.timestamp_millis_opt(i64::try_from(BASE_MS).unwrap()).unwrap() + Duration::seconds(ticks.get()) + }), + }) + }; + carry(&FileSource::new(self.dir.path().join("control.cc")), &FileSource::new(self.dir.path().join("swarm.cc")), &Slug("eureka".into()), start) + } + + fn log(&self) -> Vec { + self.log.borrow().clone() + } + + fn held_seqs(&self) -> Vec { + self.mouth.held.borrow().iter().map(|delivery| delivery.seq).collect() + } +} + +#[test] +fn t_l2_drain_acks_after_decision() { + let rig = Rig::new(vec![line(1, &room(1), META, "morning"), line(2, &room(2), META, "evening"), line(3, &room(1), META, "again")]); + assert_eq!(rig.run(scripted(false)), Outcome::Drained { turns: 2, acked_through: Some(3), put_refused: 0 }); + assert_eq!(*rig.mouth.acks.borrow(), [3], "one ack through the highest pending seq"); + let log = rig.log(); + assert_eq!(log.last().map(String::as_str), Some("ack"), "the ack comes last: {log:?}"); + assert_eq!(log.iter().filter(|event| *event == "trace").count(), 2, "{log:?}"); + assert!(log.iter().position(|event| event == "ack") > log.iter().rposition(|event| event == "trace"), "after both trace appends: {log:?}"); + let ids: Vec = rig.mouth.sent.borrow().iter().map(|request| request.request_id.clone()).collect(); + assert_eq!(ids.len(), 2); + assert!(ids[0].ends_with("-t0:s0") && ids[1].ends_with("-t1:s0"), "one key per turn, one id per send: {ids:?}"); + let keys: Vec = rig.trace.rows.borrow().iter().map(|(key, _)| key.clone()).collect(); + assert_eq!(keys.iter().map(|key| format!("{key}:s0")).collect::>(), ids, "the key of the record is the key of the send"); + assert!(rig.held_seqs().is_empty()); +} + +#[test] +fn t_l2_failed_room_stays_pending() { + let rig = Rig::new(vec![line(1, &room(1), META, "alpha is fine"), line(2, &room(2), META, "FAILME bravo"), line(3, &room(1), META, "alpha again")]); + let model = Flaky { inner: scripted(false), marker: "FAILME" }; + assert_eq!(rig.run(model), Outcome::Drained { turns: 2, acked_through: Some(1), put_refused: 0 }); + assert_eq!(rig.held_seqs(), [2, 3], "the ack stops below the failed room's first waking line, and the later line stays with it"); + let rows = rig.trace.rows.borrow(); + assert!(rows[0].1.get("failed").is_none() && rows[1].1.get("failed").is_some(), "the failed turn is in her trace too: {rows:?}"); +} + +#[test] +fn t_l2_ambient_lines_acked() { + let rig = Rig::new(vec![line(1, MINDS, LIBBY, "the deploy went fine"), line(2, &room(1), META, "hello"), line(3, MINDS, LIBBY, "lunch anyone")]); + assert_eq!(rig.run(scripted(false)), Outcome::Drained { turns: 1, acked_through: Some(3), put_refused: 0 }); + assert!(rig.mouth.sent.borrow().iter().all(|request| request.room_alias == room(1)), "no turn in the room that only held a Mind's unaddressed lines"); + assert!(rig.held_seqs().is_empty()); +} + +#[test] +fn t_l2_65_mentions_do_not_storm() { + let lines = (1..=65).map(|seq| line(seq, &room(seq % 3), META, &format!("are you there {seq}"))).collect(); + let rig = Rig::new(lines); + assert_eq!(rig.run(scripted(false)), Outcome::Drained { turns: 3, acked_through: Some(65), put_refused: 0 }); + assert_eq!(rig.mouth.reads.get(), 4, "the drain read pending once, and each of its three turns read the room"); + assert!(Chat::pending(&rig.mouth, 0).unwrap().deliveries.is_empty(), "a poll after the start finds nothing pending"); +} + +#[test] +fn t_l2_stale_put_reapplies_once() { + let rig = Rig::new(vec![line(1, &room(1), META, "hello")]); + rig.store.outside.set(1); + assert_eq!(rig.run(scripted(true)), Outcome::Drained { turns: 1, acked_through: Some(1), put_refused: 0 }); + let stored = rig.store.stored.borrow(); + assert_eq!(stored["outside"], "kept", "the outside value survives"); + let notes = stored["thoughtMemory"]["shortTerm"].as_array().unwrap(); + assert!(notes.iter().any(|note| note["text"].as_str().is_some_and(|text| text.contains("glad to hear from Meta"))), "the same record is applied again to the fresh state: {notes:?}"); + assert_eq!(rig.log().iter().filter(|event| *event == "put").count(), 2, "one stale put, one retry"); + assert!(rig.trace.rows.borrow()[0].1.get("put_refused").is_none()); +} + +#[test] +fn t_l2_second_stale_put_is_put_refused_in_the_record() { + let rig = Rig::new(vec![line(1, &room(1), META, "hello")]); + rig.store.outside.set(2); + assert_eq!(rig.run(scripted(true)), Outcome::Drained { turns: 1, acked_through: Some(1), put_refused: 1 }); + assert_eq!(rig.log().iter().filter(|event| *event == "put").count(), 2, "never a third put"); + let rows = rig.trace.rows.borrow(); + assert_eq!(rows.len(), 1, "the record is appended though the put was refused"); + assert!(rows[0].1["put_refused"].is_string(), "{:?}", rows[0].1); + assert_eq!(rig.log().iter().position(|event| event == "trace"), Some(rig.log().len() - 2), "the append comes after the puts: {:?}", rig.log()); + assert!(rig.store.puts.borrow().is_empty(), "nothing of hers landed"); +} + +#[test] +fn t_l2_turn_cap() { + let rig = Rig::new((1..=5).map(|seq| line(seq, &room(seq), META, "hello")).collect()); + assert_eq!(rig.run(scripted(false)), Outcome::Drained { turns: TURNS_PER_START, acked_through: Some(3), put_refused: 0 }); + let rooms: Vec = rig.mouth.sent.borrow().iter().map(|request| request.room_alias.clone()).collect(); + assert_eq!(rooms, [room(1), room(2), room(3)], "oldest waking line first"); + assert_eq!(rig.held_seqs(), [4, 5], "the other two rooms stay pending"); +} + +#[test] +fn t_l2_held_brake_touches_nothing() { + let rig = Rig::new(vec![line(1, &room(1), META, "hello")]); + SwarmWriter::open(&rig.dir.path().join("swarm.cc")).unwrap().set_brake(false, at(1), "op").unwrap(); + assert!(matches!(rig.run(scripted(true)), Outcome::Dead(_))); + assert_eq!((rig.mouth.reads.get(), rig.log().len(), rig.store.puts.borrow().len(), rig.held_seqs()), (0, 0, 0, vec![1]), "no read, no put, no trace, no ack, no send"); +} + +#[test] +fn t_l2_a_start_that_cannot_build_its_organs_is_failed_and_touches_nothing() { + let rig = Rig::new(vec![line(1, &room(1), META, "hello")]); + let outcome = carry::>(&FileSource::new(rig.dir.path().join("control.cc")), &FileSource::new(rig.dir.path().join("swarm.cc")), &Slug("eureka".into()), || bail!("MIND_PERSONA_CONNECTOR_ENDPOINT is not set")); + assert_eq!(outcome, Outcome::Failed("MIND_PERSONA_CONNECTOR_ENDPOINT is not set".into())); + assert_eq!((rig.log().len(), rig.held_seqs()), (0, vec![1])); +} + +#[test] +fn t_l2_trace_print() { + let dir = TempDir::new().unwrap(); + let trace = FileTrace::new(dir.path().join("persona-trace.cc")); + for (key, at) in [("a", "2026-11-27T10:00:00Z"), ("b", "2026-11-27T11:00:00Z"), ("c", "2026-11-27T12:00:00Z")] { + trace.record(key, &json!({ "at": at, "posted": [] })).unwrap(); + } + let before = std::fs::read(dir.path().join("persona-trace.cc")).unwrap(); + let printed = trace_lines(&trace, 2).unwrap(); + assert_eq!(printed, [json!({ "at": "2026-11-27T11:00:00Z", "posted": [] }).to_string(), json!({ "at": "2026-11-27T12:00:00Z", "posted": [] }).to_string()]); + assert_eq!(std::fs::read(dir.path().join("persona-trace.cc")).unwrap(), before, "printing writes nothing"); + assert_eq!(trace_lines(&trace, 10).unwrap().len(), 3); +} diff --git a/crates/mind-body/src/persona/tests.rs b/crates/mind-body/src/persona/tests.rs index 3b5a986..8050e27 100644 --- a/crates/mind-body/src/persona/tests.rs +++ b/crates/mind-body/src/persona/tests.rs @@ -67,17 +67,24 @@ fn no_one() -> Addressees { } #[test] -fn a_held_brake_is_dead_and_a_released_one_has_no_organ() { +fn a_held_brake_is_dead_and_a_released_one_builds_its_organs_only_then() { let dir = TempDir::new().unwrap(); let (control, swarm) = (dir.path().join(INSTANCE).join("control.cc"), dir.path().join("swarm.cc")); let instance = Slug(INSTANCE.into()); + let built = std::cell::Cell::new(0); + let build = || -> Result> { + built.set(built.get() + 1); + bail!("no organs in this test") + }; ControlWriter::open(&control).unwrap().set_brake(true, at(0), "op").unwrap(); SwarmWriter::open(&swarm).unwrap().set_brake(true, at(0), "op").unwrap(); - assert_eq!(carry(&FileSource::new(&control), &FileSource::new(&swarm), &instance), Outcome::NoOrgan); + assert_eq!(carry(&FileSource::new(&control), &FileSource::new(&swarm), &instance, build), Outcome::Failed("no organs in this test".into())); + assert_eq!(built.get(), 1); SwarmWriter::open(&swarm).unwrap().set_brake(false, at(1), "op").unwrap(); - assert!(matches!(carry(&FileSource::new(&control), &FileSource::new(&swarm), &instance), Outcome::Dead(_)), "the swarm brake held stops her"); + assert!(matches!(carry(&FileSource::new(&control), &FileSource::new(&swarm), &instance, build), Outcome::Dead(_)), "the swarm brake held stops her"); let missing = dir.path().join("absent.cc"); - assert!(matches!(carry(&FileSource::new(&missing), &FileSource::new(&missing), &instance), Outcome::Dead(_)), "an unreadable brake is held"); + assert!(matches!(carry(&FileSource::new(&missing), &FileSource::new(&missing), &instance, build), Outcome::Dead(_)), "an unreadable brake is held"); + assert_eq!(built.get(), 1, "a held brake built nothing"); } #[test] diff --git a/crates/mind-body/src/projection.rs b/crates/mind-body/src/projection.rs index ce509af..7dddfb7 100644 --- a/crates/mind-body/src/projection.rs +++ b/crates/mind-body/src/projection.rs @@ -38,7 +38,7 @@ use std::path::PathBuf; use anyhow::{Result, anyhow, bail}; use chrono::{DateTime, Utc}; use eureka_state::HuginnClient; -use huginn_mind::HuginnMindResponse; +use huginn_mind::{Faculty, HuginnMindResponse, MindRefusal, PersonaPutOutcome, PipelineProvenance}; use serde_json::{Value, json}; use crate::address::{Addressee, is_for, localpart}; @@ -49,6 +49,8 @@ pub use domain::{DomainFacts, DomainSource, HttpForge, MindDomain}; pub use narrate::{Answer, Continued, Failed, KitModel, Model, Reasoning, Spent, Turn, connector_key}; pub use read::{LiveReads, ReadFailure, ReadFixture, ReadRequest, ReadSource}; pub use select::TurnKind; +pub(crate) use commit::apply as apply_commit; +pub(crate) use turn::{Mouth, Taken, history, take}; pub use tuning::{TUNING_FILE, TUNING_ROOT}; use narrate::{cap_prose, cap_words, distinct_2, field_names, heard_overlap, judge_prompt, judged, offers_options, persona_prompt, projector_prompt, word_budget, words}; @@ -86,6 +88,35 @@ impl PersonaSource for HuginnPersonaSource { } } +/// How a put of her persona state was answered. +#[derive(Debug, PartialEq, Eq)] +pub enum Put { + Committed, + /// The stored document is not the one she was read at. + Stale, + /// Refused for another reason, named. + Refused(String), +} + +/// Her persona state, read and put: what a drain acts through. `project` holds `PersonaSource` alone and cannot put. +pub trait PersonaStore: PersonaSource { + /// Replace her persona document whole under the `updatedAt` she was read at; `session` names the turn. + fn put(&self, state: &Value, expected_updated_at: Option<&str>, session: &str) -> Result; +} + +impl PersonaStore for HuginnPersonaSource { + fn put(&self, state: &Value, expected_updated_at: Option<&str>, session: &str) -> Result { + let short = |text: &str| eureka_pipeline::Short(text.to_owned()); + let provenance = PipelineProvenance { faculty: Faculty::Member, agent: short(AGENT), session: short(session), tool: short(AGENT), imported_from: None }; + match self.client.persona_put(provenance, state.clone(), expected_updated_at.map(str::to_owned)).map_err(|_| anyhow!("the mind could not be asked to put the persona"))? { + HuginnMindResponse::PersonaPut(PersonaPutOutcome::Committed { .. }) => Ok(Put::Committed), + HuginnMindResponse::PersonaPut(PersonaPutOutcome::Refused(MindRefusal::PersonaStale { .. })) | HuginnMindResponse::Refused(MindRefusal::PersonaStale { .. }) => Ok(Put::Stale), + HuginnMindResponse::PersonaPut(PersonaPutOutcome::Refused(refusal)) | HuginnMindResponse::Refused(refusal) => Ok(Put::Refused(format!("{refusal:?}"))), + _ => bail!("the mind answered the persona put with something else"), + } + } +} + /// The mouth, read: pending deliveries and the room tail, which acks nothing. The only chat port `project` holds. pub trait MouthReader { fn pending(&self) -> Result; @@ -236,7 +267,7 @@ pub struct Request { /// holds one; else her own names (handle and public name), with why: no store configured, no heartbeat file, a file /// that could not be read, or a table without her row. The table's age is the store's last write: under a held swarm /// brake the heartbeat does not poll, so an old table is a stale one. -fn own_addressee(addressing: Option<&dyn HeartbeatView>, own_sender: &str, public_name: &str, now: DateTime) -> (Addressee, Value) { +pub(crate) fn own_addressee(addressing: Option<&dyn HeartbeatView>, own_sender: &str, public_name: &str, now: DateTime) -> (Addressee, Value) { let written_at = addressing.and_then(HeartbeatView::written_at); let age = written_at.map(|at| (now - at).num_minutes()); let report = |source: &str, why: &str| json!({ "source": source, "why": why, "written_at": written_at.map(|at| at.to_rfc3339()), "age_minutes": age }); diff --git a/crates/mind-body/src/projection/domain.rs b/crates/mind-body/src/projection/domain.rs index 36473a9..9d9056a 100644 --- a/crates/mind-body/src/projection/domain.rs +++ b/crates/mind-body/src/projection/domain.rs @@ -170,6 +170,10 @@ pub(crate) enum Skip { pub trait DomainSource { /// What moved in her domain from `since` to `now`. fn read(&self, since: DateTime, now: DateTime) -> Result; + /// The repos she stewards in force (`Org/Repo`): the drain's input to `heartbeat::own_rooms`. A source with no mind behind it names none. + fn stewarded(&self) -> Result> { + Ok(Vec::new()) + } } impl DomainSource for DomainFacts { @@ -199,17 +203,16 @@ impl MindDomain { _ => bail!("her mind answered a read with something else"), } } - - /// The repos she stewards in force (`Org/Repo`), through her read door: the drain's input to `heartbeat::own_rooms`. - pub fn stewarded(&self) -> Result> { - stewarded(&|selection| self.ask(selection), &self.client.instance().0) - } } impl DomainSource for MindDomain { fn read(&self, since: DateTime, now: DateTime) -> Result { read(&|selection| self.ask(selection), &self.client.instance().0, &self.forge, since, now) } + + fn stewarded(&self) -> Result> { + stewarded(&|selection| self.ask(selection), &self.client.instance().0) + } } /// One GET on the forge: the status and the body.