diff --git a/crates/mind-body/fixtures/harness/golden-chorus.txt b/crates/mind-body/fixtures/harness/golden-chorus.txt new file mode 100644 index 0000000..99c902c --- /dev/null +++ b/crates/mind-body/fixtures/harness/golden-chorus.txt @@ -0,0 +1,6 @@ +responder 3: - the conversation: Meta, who runs the place asked the room a question, and "weksa" (@weksa:gamecult.org); "heimdall" (@heimdall:gamecult.org) answered it; Meta, who runs the place last spoke 5 min ago; the last 2 lines are the Minds' alone +responder 4: - the conversation: Meta, who runs the place asked the room a question, and "weksa" (@weksa:gamecult.org); "heimdall" (@heimdall:gamecult.org); Kiko answered it; Meta, who runs the place last spoke 5 min ago; the last 3 lines are the Minds' alone +responder 5: - the conversation: Meta, who runs the place asked the room a question, and "weksa" (@weksa:gamecult.org); "heimdall" (@heimdall:gamecult.org); Kiko; "libby" (@libby:gamecult.org) answered it; Meta, who runs the place last spoke 5 min ago; the last 4 lines are the Minds' alone +responder 6: - the conversation: Meta, who runs the place asked the room a question, and "weksa" (@weksa:gamecult.org); "heimdall" (@heimdall:gamecult.org); Kiko; "libby" (@libby:gamecult.org); "void" (@void:gamecult.org) answered it; Meta, who runs the place last spoke 5 min ago; the last 5 lines are the Minds' alone +responder 7: - the conversation: Meta, who runs the place asked the room a question, and "weksa" (@weksa:gamecult.org); "heimdall" (@heimdall:gamecult.org); Kiko; "libby" (@libby:gamecult.org); "void" (@void:gamecult.org); "nibu" (@nibu:gamecult.org) answered it; Meta, who runs the place last spoke 5 min ago; the last 6 lines are the Minds' alone +responder 8: - the conversation: Meta, who runs the place asked the room a question, and "weksa" (@weksa:gamecult.org); "heimdall" (@heimdall:gamecult.org); Kiko; "libby" (@libby:gamecult.org); "void" (@void:gamecult.org); "nibu" (@nibu:gamecult.org); "aqua" (@aqua:gamecult.org) answered it; Meta, who runs the place last spoke 5 min ago; the last 7 lines are the Minds… diff --git a/crates/mind-body/fixtures/harness/golden-group.txt b/crates/mind-body/fixtures/harness/golden-group.txt new file mode 100644 index 0000000..2a1f028 --- /dev/null +++ b/crates/mind-body/fixtures/harness/golden-group.txt @@ -0,0 +1,4 @@ +quiet-beat.toml: - the conversation: lately libby to the room; Kiko to the room; the last 3 lines are the Minds' alone +operator-warm.toml: - the conversation: lately Meta, who runs the place with him; Meta, who runs the place last spoke 1 min ago; Meta, who runs the place is waiting on him +mind-teases.toml: - the conversation: lately he to the room; aqua to the room; Kiko with him; the last 3 lines are the Minds' alone +deru-passing.toml: - the conversation: lately weksa to the room; Deru to the room; Deru last spoke 1 min ago diff --git a/crates/mind-body/src/bin/mind-persona.rs b/crates/mind-body/src/bin/mind-persona.rs index ce802ca..6adf7f5 100644 --- a/crates/mind-body/src/bin/mind-persona.rs +++ b/crates/mind-body/src/bin/mind-persona.rs @@ -17,7 +17,8 @@ //! [--room ] [--seed N] [--state ] [--select-only | --renders K [--through projector|persona] //! [--judge ]]` is the experiment tool over the Projector and the Persona stage //! (`mind_body::projection::project`): it prints, as JSON, the packet the Select stage builds from her stored state (or -//! `--state`, checked as a put would check it), and with `--renders` the Projector's narrations of K successive turns; +//! `--state`, checked as a put checks its content, rules P1 to P3; P4 and P5 compare it with the stored document and are +//! not checked), and with `--renders` the Projector's narrations of K successive turns; //! `--through persona` adds her prose and the quoted lines it would say; `--judge` renders a second state too and asks //! the model which narration came from which. It writes nothing and reads no brake. //! diff --git a/crates/mind-body/src/heartbeat.rs b/crates/mind-body/src/heartbeat.rs index 063d216..aa25f75 100644 --- a/crates/mind-body/src/heartbeat.rs +++ b/crates/mind-body/src/heartbeat.rs @@ -32,7 +32,7 @@ use eureka_pipeline::{OrgRepo, PipelineKind, RunTurn, Slug}; use huginn_mind::PipelineFacts; use crate::address::{Addressee, Name, is_for, project_names}; -use crate::chat_client::{Chat, ChatDelivery}; +use crate::chat_client::{Basis, Chat, ChatDelivery}; use crate::control::{ControlSource, Effective, FileSource, HeldReason, SwarmEffective, read_effective, read_envelope, set_mode_world_readable}; use crate::launch::{Clock, Launcher}; use crate::queue::{MindPort, headers, in_force, of_kind}; @@ -98,11 +98,15 @@ pub struct Config { } impl Config { - /// Refuses no Persona, a Persona twice, or a beat of zero seconds. + /// Refuses no Persona, a Persona twice, a beat of zero seconds, or an operator id that is also a Persona's: one + /// sender is either the operator or a Mind, never both, or the wake rule could not tell which it heard. pub fn new(personas: Vec, operators: Vec, beat_s: u32) -> Result { if personas.is_empty() { bail!("no persona is configured"); } + if operators.iter().any(|operator| personas.iter().any(|persona| persona.matrix_id == *operator)) { + bail!("an operator id is also a persona's matrix id"); + } if beat_s == 0 { bail!("the beat is zero seconds"); } @@ -393,12 +397,115 @@ pub(crate) fn stewardships_of(mind: &dyn MindPort) -> Result<(Vec, Vec bool { - let from_operator = config.operators.contains(&delivery.sender); - let from_other_mind = delivery.sender != who.matrix_id() && config.personas.iter().any(|mind| mind.matrix_id == delivery.sender); - (from_operator || from_other_mind) && is_for(who, delivery) +/// A member (anyone not the operator) has a pending delivery that addresses her: the beat's urgency. The one owner of +/// that reading: the poll's rows and the simulator's beat both ask it, over the deliveries the mouth would give her. +pub(crate) fn addressed_by_member(operators: &[String], who: &Addressee, pending: &[ChatDelivery]) -> bool { + pending.iter().any(|delivery| !operators.contains(&delivery.sender) && is_for(who, delivery)) +} + +/// Who sent a line, as the wake rule sees them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Speaker { + Operator, + /// Another Mind of the roster. + Mind, + /// A human who is not the operator: a member. + Member, + /// The Persona herself. + Her, +} + +impl Speaker { + fn human(self) -> bool { + matches!(self, Self::Operator | Self::Member) + } +} + +/// Which lines wake a Persona off the beat. `Live` is the heartbeat's rule today and the only one `poll` uses; the rest +/// are what desk question `po-mind-wakes-mind` weighs, run in `mind-persona project --simulate` until it is answered. +/// The beat is not here: every policy has it, and it wakes one Persona by `tempo::pick`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum WakePolicy { + /// The operator or another Mind addressing her (`is_for`). A member's line does not. + Live, + /// Ruling `persona-only-wake-humans-in-rooms`: a line addressing her, from anyone, and any human line in her rooms. + Ruled, + /// Ruling `persona-only-humans-pace`: a human's line wakes her in her own room (a direct message, or a room that is + /// hers); in a public room only when it addresses her or continues an exchange she is in. A Mind's line wakes her + /// only by an explicit mention (a Matrix mention of her or a reply to her, never a name in prose), in any room, and + /// only while fewer than this many Mind lines in a row came before it in its room: the backstop. + HumansPace(usize), + /// `Ruled`, with at most this many Mind lines in a row in a room before a human must speak again: a Mind's line past + /// the cap wakes no one. + NamesWithCap(usize), + /// The swarm's old loop, a control: any line in her rooms but her own. + AllMessages, +} + +/// Why a line wakes her, strongest first. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum WakeCause { + AddressedByHuman, + Human, + AddressedByMind, + /// A Mind's line that does not address her: only the control wakes on it. + Mind, +} + +/// What the room says about a line, beside the line: the facts a policy may weigh. The live poll knows none of them yet +/// and passes the default; `Live` reads none. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct LineFacts { + /// How many Mind lines in a row came before this one in its room since a human last spoke there. + pub mind_run: usize, + /// The line is in a room of hers: a direct message (the delivery says so) or a room configured as hers. + pub own_room: bool, + /// She has spoken in the room's current exchange: the lines before this one that follow each other without a long gap. + pub in_exchange: bool, +} + +/// Whether a line in her rooms wakes `who` off the beat under `policy`, and why. The one owner of the wake rule: the +/// heartbeat's poll asks it with `Live`, the simulator with the policy under test. +pub(crate) fn wakes(policy: WakePolicy, who: &Addressee, delivery: &ChatDelivery, speaker: Speaker, facts: LineFacts) -> Option { + if speaker == Speaker::Her { + return None; + } + let addressed = is_for(who, delivery); + let human = speaker.human(); + let cause = match (human, addressed) { + (true, true) => WakeCause::AddressedByHuman, + (true, false) => WakeCause::Human, + (false, true) => WakeCause::AddressedByMind, + (false, false) => WakeCause::Mind, + }; + let wakes = match policy { + WakePolicy::Live => addressed && matches!(speaker, Speaker::Operator | Speaker::Mind), + WakePolicy::Ruled => human || addressed, + WakePolicy::HumansPace(cap) => { + let explicit = delivery.mentions.iter().any(|id| id == who.matrix_id()) || matches!(delivery.basis, Some(Basis::Tag | Basis::Reply)); + if human { addressed || delivery.is_direct || facts.own_room || facts.in_exchange } else { explicit && facts.mind_run < cap } + } + WakePolicy::NamesWithCap(cap) => human || (addressed && facts.mind_run < cap), + WakePolicy::AllMessages => true, + }; + wakes.then_some(cause) +} + +impl Config { + /// Who sent a delivery, as `wakes` sees them. + fn speaker(&self, who: &Addressee, delivery: &ChatDelivery) -> Speaker { + if delivery.sender == who.matrix_id() { + Speaker::Her + } else if self.operators.contains(&delivery.sender) { + Speaker::Operator + } else if self.personas.iter().any(|mind| mind.matrix_id == delivery.sender) { + Speaker::Mind + } else { + Speaker::Member + } + } } /// The mouth pages a pending answer, so fewer deliveries may come than wait. @@ -443,7 +550,7 @@ impl Row<'_> { /// A member (not the operator) has a pending message that names or tags her. fn addressed_by_member(&self, config: &Config) -> bool { - self.pending.iter().any(|delivery| !config.operators.contains(&delivery.sender) && is_for(&self.addressee, delivery)) + addressed_by_member(&config.operators, &self.addressee, &self.pending) } } @@ -528,7 +635,7 @@ pub fn poll(organs: &Organs, config: &Config) -> Result { pending.sort_by_key(|delivery| delivery.seq); pending .into_iter() - .filter(|delivery| wakes(config, &row.addressee, delivery)) + .filter(|delivery| wakes(WakePolicy::Live, &row.addressee, delivery, config.speaker(&row.addressee, delivery), LineFacts::default()).is_some()) .map(|delivery| format!("{}:{}", slug.0, delivery.event_id)) .find(|key| !state.handled_mentions.contains(key)) }; diff --git a/crates/mind-body/src/heartbeat/tests.rs b/crates/mind-body/src/heartbeat/tests.rs index 2038ad0..2af1b89 100644 --- a/crates/mind-body/src/heartbeat/tests.rs +++ b/crates/mind-body/src/heartbeat/tests.rs @@ -293,7 +293,9 @@ fn each_persona_carries_her_own_huginn_and_a_missing_or_malformed_one_refuses_th for bad in ["ann,ann,Ann,@ann:chat", "ann,ann,Ann,@ann:chat,", "ann,ann,Ann,@ann:chat,127.0.0.1:4101", "ann,ann,Ann,@ann:chat,rudp://localhost:4101"] { assert!(PersonaId::parse(bad).is_err(), "{bad}"); } - assert!(Config::new(personas, vec![], 0).is_err(), "a beat of zero seconds is refused"); + assert!(Config::new(personas.clone(), vec![], 0).is_err(), "a beat of zero seconds is refused"); + let refused = Config::new(personas, vec!["@bob:chat".into()], 60).map(|_| ()).unwrap_err(); + assert!(format!("{refused:#}").contains("operator id is also a persona"), "a sender is the operator or a Mind, never both"); } #[test] diff --git a/crates/mind-body/src/projection.rs b/crates/mind-body/src/projection.rs index 2fbd449..669feb8 100644 --- a/crates/mind-body/src/projection.rs +++ b/crates/mind-body/src/projection.rs @@ -39,7 +39,7 @@ pub use narrate::{Answer, Failed, KitModel, Model, Spent, connector_key}; pub use select::TurnKind; pub use tuning::{TUNING_FILE, TUNING_ROOT}; -use narrate::{cap_words, distinct_2, field_names, judge_prompt, judged, persona_prompt, projector_prompt, word_budget, words, would_say}; +use narrate::{cap_words, distinct_2, field_names, heard_overlap, inner, judge_prompt, judged, offers_options, persona_prompt, projector_prompt, word_budget, words, would_say}; use select::{History, Inputs, Packet, People, Room, RoomLine, select}; /// The agent name on the connector's request ids. @@ -180,7 +180,9 @@ fn read_room(chat: &dyn MouthReader, request: &Request, own: &Addressee) -> (Roo Ok(pending) => pending, Err(fault) => return (Room { here: request.room.clone(), last_heard: request.last_heard.clone(), ..Room::default() }, json!({ "read": false, "why": format!("{fault:#}") })), }; - let wanted = |room: &str, id: &str| request.room.as_deref().is_none_or(|here| here == room || here == id); + // The turn's room by its alias, the name every line of the tail carries, when it was given by its Matrix id. + let here = request.room.as_ref().map(|here| pending.deliveries.iter().find(|delivery| delivery.room_id == *here).map_or_else(|| here.clone(), |delivery| delivery.room_alias.clone())); + let wanted = |room: &str, id: &str| here.as_deref().is_none_or(|here| here == room || here == id); let messages: Vec = pending .deliveries .iter() @@ -203,7 +205,7 @@ fn read_room(chat: &dyn MouthReader, request: &Request, own: &Addressee) -> (Roo .map(|line| RoomLine { room: line.room.clone(), sender: line.sender.clone(), display: String::new(), text: line.body.clone(), at_ms: line.at_unix_ms, to_her: false }) .collect(); let report = json!({ "read": true, "messages": messages.len(), "tail": tail.len(), "tail_gaps": pending.tail_gaps }); - (Room { messages, tail, here: request.room.clone(), last_heard: request.last_heard.clone() }, report) + (Room { messages, tail, here, last_heard: request.last_heard.clone() }, report) } fn packet_json(packet: &Packet) -> Value { @@ -247,6 +249,8 @@ fn narrate_one(model: &dyn Model, instance: &str, packet: &Packet, tuning: &tuni "words": words(&narration), "cut_at_budget": words(&raw) > budget, "field_names": field_names(&narration, &named), + "heard_overlap": heard_overlap(&narration, &packet.heard), + "offers_options": offers_options(&narration), "usage": answer.usage, "narration": narration, }); @@ -258,6 +262,7 @@ fn narrate_one(model: &dyn Model, instance: &str, packet: &Packet, tuning: &tuni "words": words(&prose), "cut_at_budget": words(&spoke.text) > tuning.persona.words, "would_say": would_say(&prose), + "inner": inner(&prose), "usage": spoke.usage, "prose": prose, }) diff --git a/crates/mind-body/src/projection/fixtures/golden-chat.txt b/crates/mind-body/src/projection/fixtures/golden-chat.txt index 59ede06..b7b0f9a 100644 --- a/crates/mind-body/src/projection/fixtures/golden-chat.txt +++ b/crates/mind-body/src/projection/fixtures/golden-chat.txt @@ -5,9 +5,11 @@ present: Kiko, Libby Eureka (she/her). Dry, direct, almost feral; zeal aimed at revealing. --- context - now: Thursday 19 November, 14:05 UTC -- mood, with no earlier turn to measure from: lighter, more settled than middling -- bond [bond-kiko] Kiko, sparring partner: fair trust, heavy friction. Kiko pokes her to stop massaging the pipeline. -- bond [bond-libby] Libby, collaborator: fair trust, a little friction. Libby holds the sounds and teases her about the pipeline. +- mood: lighter, more settled than middling +- bond [bond-kiko] Kiko — sparring partner: fair trust, heavy friction. Kiko pokes her to stop massaging the pipeline. +- bond [bond-libby] Libby — collaborator: fair trust, a little friction. Libby holds the sounds and teases her about the pipeline. +- the conversation: lately Libby with her; Kiko to the room; the last 2 lines are the Minds' alone +- pronouns: Libby — she/her; Kiko — she/her - memory [libby-sounds]: Libby laughed at the door fix. - memory [t1-m0]: The heartbeat stalled at noon. - memory [curse]: Her curse is the knife. The same drive makes her good and will lead her wrong. diff --git a/crates/mind-body/src/projection/harness.rs b/crates/mind-body/src/projection/harness.rs index 797d929..da0aeb7 100644 --- a/crates/mind-body/src/projection/harness.rs +++ b/crates/mind-body/src/projection/harness.rs @@ -29,11 +29,14 @@ use crate::heartbeat::{Addressing, HeartbeatView}; pub use super::simulate::simulate; +/// A narration whose word trigrams overlap what she heard past this share is marked as retelling it. +pub(crate) const RETELL_FLAG: f64 = 0.15; /// The most room lines a view's tail carries, as a mouth's tail is bounded. const TAIL_LINES: usize = 40; /// A persona state file, checked as a put would check its content (huginn-mind's rules P1 to P3: the published schema, /// `personaId` is the instance, canonical provenance). A file this accepts is one a put would not refuse for what it says. +/// P4 and P5 are not checked: they compare `updatedAt` with the stored document, and no store is read here. pub fn state_file(path: &Path, instance: &str) -> Result { let text = std::fs::read_to_string(path).with_context(|| format!("{} could not be read", path.display()))?; let state: Value = serde_json::from_str(&text).with_context(|| format!("{} is not JSON", path.display()))?; @@ -89,9 +92,12 @@ pub struct Message { /// Other Matrix ids it tags. #[serde(default)] pub mentions: Vec, - /// A direct message to her. + /// A direct message: to her in a room fixture; to `to` in a simulation script. #[serde(default)] pub dm: bool, + /// The recipient of a direct message, by Matrix id. A room fixture's defaults to her; a script must name one. + #[serde(default)] + pub to: Option, /// A reply in a conversation she opened (the mouth's follow-up basis). #[serde(default)] pub follow_up: bool, @@ -110,7 +116,8 @@ pub(crate) struct Line { pub at_ms: u64, pub says: String, pub mentions: Vec, - pub dm: bool, + /// A direct message, to this Matrix id: only its sender and its recipient see it. + pub dm_to: Option, pub follow_up: bool, /// The index of the line it replies to. pub reply_to: Option, @@ -127,18 +134,25 @@ impl Line { if message.tag { mentions.push(her.ok_or_else(|| anyhow!("message {} tags her, and a simulation has no one \"her\": name the ids in mentions", index + 1))?.to_owned()); } + let dm_to = match (message.dm, &message.to) { + (true, Some(to)) if matrix_id(to) => Some(to.clone()), + (true, Some(to)) => bail!("message {} is a direct message to \"{to}\", which is not a Matrix id", index + 1), + (true, None) => Some(her.ok_or_else(|| anyhow!("message {} is a direct message to no one: a script names its recipient in `to`", index + 1))?.to_owned()), + (false, Some(_)) => bail!("message {} names a recipient but is not a direct message", index + 1), + (false, None) => None, + }; let reply_to = match message.reply_to { Some(number) if number >= 1 && number <= index => Some(number - 1), Some(number) => bail!("message {} replies to message {number}, which is not an earlier one", index + 1), None => None, }; - Ok(Self { from: message.from.clone(), name: message.name.clone(), room: message.room.clone(), at_ms: unix_ms(at), says: message.says.clone(), mentions, dm: message.dm, follow_up: message.follow_up, reply_to, new: message.new }) + Ok(Self { from: message.from.clone(), name: message.name.clone(), room: message.room.clone(), at_ms: unix_ms(at), says: message.says.clone(), mentions, dm_to, follow_up: message.follow_up, reply_to, new: message.new }) } /// What Matrix would say about this line to `viewer`: a direct message, a tag, a reply to a line of hers, or a /// follow-up. fn basis(&self, viewer: &str, lines: &[Line]) -> Option { - if self.dm { + if self.dm_to.as_deref() == Some(viewer) { Some(Basis::Direct) } else if self.mentions.iter().any(|id| id == viewer) { Some(Basis::Tag) @@ -151,6 +165,15 @@ impl Line { } } + /// Whether `viewer` sees the line: a direct message only its sender and recipient; any other line every member of its + /// room (no rooms named is every room). + pub(crate) fn visible_to(&self, viewer: &str, rooms: &[String]) -> bool { + match &self.dm_to { + Some(to) => to == viewer || self.from == viewer, + None => rooms.is_empty() || rooms.contains(&self.room), + } + } + pub(crate) fn delivery(&self, index: usize, viewer: &str, lines: &[Line]) -> ChatDelivery { ChatDelivery { seq: index as u64 + 1, @@ -163,7 +186,7 @@ impl Line { at_unix_ms: self.at_ms, context: vec![], mentions: self.mentions.clone(), - is_direct: self.dm, + is_direct: self.dm_to.is_some(), image: None, basis: self.basis(viewer, lines), form: Form::Message, @@ -175,7 +198,7 @@ impl Line { /// The mouth's pending read as `viewer` would get it from `lines`: the lines `new` says she has not had, from others, /// in her rooms, as deliveries; and every line of her rooms, hers included, as the tail. pub(crate) fn pending_for(lines: &[Line], viewer: &str, rooms: &[String], new: impl Fn(usize) -> bool) -> ChatPending { - let hers = |line: &Line| rooms.is_empty() || rooms.contains(&line.room) || line.dm; + let hers = |line: &Line| line.visible_to(viewer, rooms); let deliveries = lines.iter().enumerate().filter(|(at, line)| new(*at) && hers(line) && line.from != viewer).map(|(at, line)| line.delivery(at, viewer, lines)).collect(); let tail: Vec = lines .iter() @@ -461,6 +484,13 @@ Usage: {} if let Some(names) = render["field_names"].as_array().filter(|names| !names.is_empty()) { let _ = writeln!(out, "**Field names leaked:** {}\n", Value::Array(names.clone())); } + let _ = writeln!( + out, + "Narration checks: overlap with what she heard {}{}{}\n", + render["heard_overlap"].as_f64().map_or_else(|| "n/a".to_owned(), |overlap| format!("{overlap:.2}")), + if render["heard_overlap"].as_f64().is_some_and(|overlap| overlap > RETELL_FLAG) { " (retells)" } else { "" }, + if render["offers_options"] == true { "; offers her options" } else { "" } + ); let persona = &render["persona"]; if let Some(failed) = persona["failed"].as_str() { let _ = writeln!(out, "**Persona call failed:** {failed} @@ -468,6 +498,8 @@ Usage: {} } else if !persona.is_null() { let _ = writeln!(out, "**Her prose** ({} words{}):\n", persona["words"], if persona["cut_at_budget"] == true { ", cut at budget" } else { "" }); quoted(out, persona["prose"].as_str().unwrap_or_default()); + let _ = writeln!(out, "**Inner** (her prose with what she says aloud taken out):\n"); + quoted(out, persona["inner"].as_str().unwrap_or_default()); match persona["would_say"].as_array().filter(|said| !said.is_empty()) { Some(said) => { let _ = writeln!(out, "**Would say:**\n"); diff --git a/crates/mind-body/src/projection/harness/tests.rs b/crates/mind-body/src/projection/harness/tests.rs index b11a727..58b61dd 100644 --- a/crates/mind-body/src/projection/harness/tests.rs +++ b/crates/mind-body/src/projection/harness/tests.rs @@ -218,3 +218,69 @@ fn a_batch_state_without_a_file_is_her_stored_state() { let report = batch(&harness(dir.path(), Some(&Stored), Some(&model)), &plan).unwrap(); assert!(report.contains("## stored × quiet, sample 1") && !report.contains("failed"), "{report}"); } + +fn group_line_of(dir: &Path, name: &str) -> Option { + let fixture = room(name); + let harness = harness(dir, None, None); + let organs = Organs { persona: None, chat: Some(&fixture), addressing: fixture.addressee(), model: None }; + let report = project(&organs, &fixture_request(&harness, &fixture, Some(control()), 1, None, Through::Projector), fixture.now).unwrap(); + report["packet"]["context"].as_str().unwrap().lines().find(|line| line.starts_with("- the conversation")).map(str::to_owned) +} + +#[test] +fn the_group_state_reads_each_scenario_room_as_the_golden_file_says() { + let dir = tempfile::tempdir().unwrap(); + let mut rendered = String::new(); + for name in ["quiet-beat.toml", "operator-warm.toml", "mind-teases.toml", "deru-passing.toml"] { + let line = group_line_of(dir.path(), name).unwrap_or_else(|| "(none)".into()); + assert!(line.len() <= 360, "the slot holds its byte budget: {line}"); + rendered.push_str(&format!("{name}: {line} +")); + } + let golden = include_str!("../../../fixtures/harness/golden-group.txt").replace(" +", " +"); + assert_eq!(rendered, golden, "the group state moved; if deliberately, the new golden file is: +{rendered}"); +} + +#[test] +fn the_group_state_is_off_when_the_tuning_says_so() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("persona-tuning.toml"), "[select] +group_state = false +").unwrap(); + assert!(group_line_of(dir.path(), "mind-teases.toml").is_none()); +} + +/// Round 1 of a crowded room: the operator asks everyone, and `answered` Minds have answered before this one's turn. +fn chorus(answered: usize) -> Fixture { + let minds = ["@weksa:gamecult.org", "@heimdall:gamecult.org", "@kiko:gamecult.org", "@libby:gamecult.org", "@void:gamecult.org", "@nibu:gamecult.org", "@aqua:gamecult.org"]; + let mut text = String::from("her = \"@eureka:gamecult.org\"\nkind = \"chat\"\nnow = \"2026-11-20T15:05:00Z\"\nrooms = [\"#minds:gamecult.org\"]\nhere = \"#minds:gamecult.org\"\noperators = [\"@meta:gamecult.org\"]\nminds = [\"@eureka:gamecult.org\", \"@weksa:gamecult.org\", \"@heimdall:gamecult.org\", \"@kiko:gamecult.org\", \"@libby:gamecult.org\", \"@void:gamecult.org\", \"@nibu:gamecult.org\", \"@aqua:gamecult.org\"]\n"); + text.push_str("[[message]]\nfrom = \"@meta:gamecult.org\"\nname = \"Meta\"\nroom = \"#minds:gamecult.org\"\nago = \"5m\"\nnew = true\nsays = \"afternoon, all of you. no tasks today. how's everyone doing?\"\n"); + for (at, mind) in minds.iter().take(answered).enumerate() { + text.push_str(&format!("[[message]]\nfrom = \"{mind}\"\nname = \"{}\"\nroom = \"#minds:gamecult.org\"\nago = \"{}s\"\nnew = true\nsays = \"afternoon, Meta. doing well, thanks.\"\n", crate::address::localpart(mind), 240 - at * 20)); + } + Fixture::parse(&text).unwrap() +} + +#[test] +fn the_third_to_eighth_responder_sees_a_covered_question_and_no_duty() { + let dir = tempfile::tempdir().unwrap(); + let harness = harness(dir.path(), None, None); + let mut rendered = String::new(); + for answered in 2..=7 { + let fixture = chorus(answered); + let organs = Organs { persona: None, chat: Some(&fixture), addressing: None, model: None }; + let report = project(&organs, &fixture_request(&harness, &fixture, Some(control()), 1, None, Through::Projector), fixture.now).unwrap(); + let context = report["packet"]["context"].as_str().unwrap().to_owned(); + let line = context.lines().find(|line| line.starts_with("- the conversation")).unwrap_or_else(|| panic!("{context}")).to_owned(); + assert!(line.contains("asked the room a question, and") && line.contains("answered it"), "{line}"); + for duty in ["owe", "haven't", "have not", "open", "still", "waiting on her", "to her", "unanswered"] { + assert!(!line.contains(duty), "responder {}: {duty} in {line}", answered + 1); + } + rendered.push_str(&format!("responder {}: {line}\n", answered + 1)); + } + let golden = include_str!("../../../fixtures/harness/golden-chorus.txt").replace("\r\n", "\n"); + assert_eq!(rendered, golden, "the chorus's group state moved; if deliberately, the new golden file is:\n{rendered}"); +} diff --git a/crates/mind-body/src/projection/narrate.rs b/crates/mind-body/src/projection/narrate.rs index a3387fe..9dfcedb 100644 --- a/crates/mind-body/src/projection/narrate.rs +++ b/crates/mind-body/src/projection/narrate.rs @@ -138,7 +138,7 @@ pub(crate) fn word_budget(kind: TurnKind, tuning: &Tuning) -> usize { /// The Projector's prompt: Ghostlight's membrane over the packet, with the lens as where to begin. pub(crate) fn projector_prompt(packet: &Packet, tuning: &Tuning) -> String { - let guidance = format!("{}\n\nBegin from {}.", tuning.projector.guidance.trim(), packet.lens.words()); + let guidance = format!("{}\n\nBegin from {}.", tuning.projector.guidance.trim(), packet.lens.words(&packet.forms)); build_projector_prompt(&ProjectorPrompt { identity: &packet.identity, typed_context: &packet.context, visible_stimulus: &packet.stimulus, domain_guidance: &guidance, word_budget: word_budget(packet.kind, tuning) }) } @@ -189,6 +189,50 @@ pub(crate) fn persona_prompt(packet: &Packet, narration: &str, tuning: &Tuning) build_persona_prompt(&PersonaPrompt { identity: &packet.identity, lived_stream: &lived_stream(narration, &packet.heard), domain_guidance: tuning.persona.guidance.trim(), word_budget: tuning.persona.words }) } +/// Her prose with what she says aloud taken out: her interior, which never leaves her head. +pub(crate) fn inner(prose: &str) -> String { + let mut out = String::with_capacity(prose.len()); + let mut open: Option = None; + for c in prose.chars() { + match (open, c) { + (None, '"') => open = Some('"'), + (None, '\u{201C}') => open = Some('\u{201D}'), + (Some(close), c) if c == close => { + open = None; + out.push('\u{2026}'); + } + (Some(_), _) => {} + (None, c) => out.push(c), + } + } + out.split_whitespace().collect::>().join(" ") +} + +/// The share of the narration's word trigrams that also appear in what she heard: how much of the stream retells the +/// messages the Persona is shown word for word anyway. A judge metric, never a filter: 0 is no retelling. +pub(crate) fn heard_overlap(narration: &str, heard: &str) -> f64 { + let trigrams = |text: &str| -> Vec<(String, String, String)> { + let words: Vec = text.split(|c: char| !c.is_alphanumeric() && c != '\'').filter(|word| !word.is_empty()).map(str::to_lowercase).collect(); + words.windows(3).map(|three| (three[0].clone(), three[1].clone(), three[2].clone())).collect() + }; + let told = trigrams(narration); + if told.is_empty() { + return 0.0; + } + let heard: BTreeSet<(String, String, String)> = trigrams(heard).into_iter().collect(); + told.iter().filter(|three| heard.contains(three)).count() as f64 / told.len() as f64 +} + +/// Whether a narration lays out options for her: "I may…", "I could…", "she might…", "nothing asks me to…". The Projector +/// renders the moment and the Persona decides; a menu of choices is the Projector deciding. A lexical flag on a narrow +/// form, reported as a metric, never a filter. +pub(crate) fn offers_options(narration: &str) -> bool { + let lower = format!(" {} ", narration.to_lowercase().replace('\u{2019}', "'")); + ["i may ", "i could ", "i might ", "she may ", "she could ", "she might ", "nothing asks me", "nothing asks her", "or i could", "or she could"] + .iter() + .any(|form| lower.contains(&format!(" {form}")) || lower.contains(&format!(". {form}")) || lower.contains(&format!(", {form}"))) +} + /// The words her prose says aloud: each span inside straight or curly double quotation marks, in prose order (map /// section 5.5: speech needs quoted spoken words). A preview of what the Interpreter (C3b) will be asked to quote, not /// its decision: a quotation she only recalls reads here as said. An unclosed quote says nothing. diff --git a/crates/mind-body/src/projection/select.rs b/crates/mind-body/src/projection/select.rs index c4635aa..7bc0d1f 100644 --- a/crates/mind-body/src/projection/select.rs +++ b/crates/mind-body/src/projection/select.rs @@ -5,7 +5,7 @@ //! here; reaching into it is the Interpreter's, through its read tools, when wondering leads to reading. //! //! Every packet carries its fixed slots: identity, the hour, her mood as change, a bond line for each person -//! present, and the stimulus. The rest comes from her state's pools. Each candidate is ordered by +//! present, the group state (who has been talking to whom, `group_line`), and the stimulus. The rest comes from her state's pools. Each candidate is ordered by //! `log(score) / T` plus Gumbel noise and included with probability `1 - exp(-score / inclusion_score)`, where //! `score = salience × recency × touch × relevance × unresolved × freshness`; then each pool's cap and the context //! budget bound what is kept. A cap is a maximum, never a target: a pool with fewer candidates than its cap still @@ -47,6 +47,29 @@ const NAME_BYTES: usize = 80; /// The most bytes the line naming the unbonded people present takes. const ALSO_HERE_BYTES: usize = 300; +/// Her pronouns as the packet speaks of her (from `presentation.pronouns`: he, she, or they for anything else, "any" +/// included), with the verb forms that agree with them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Forms { + pub subj: &'static str, + pub cap_subj: &'static str, + pub obj: &'static str, + pub poss: &'static str, + pub be: &'static str, + pub has: &'static str, + /// The present tense's third-person `s`: "wants" or "want". + pub s: &'static str, +} + +pub(crate) fn forms(state: &Value) -> Forms { + let pronouns = text(state, &["presentation", "pronouns"]).to_lowercase(); + match pronouns.split(|c: char| !c.is_alphabetic()).find(|word| !word.is_empty()).unwrap_or_default() { + "he" => Forms { subj: "he", cap_subj: "He", obj: "him", poss: "his", be: "is", has: "has", s: "s" }, + "she" => Forms { subj: "she", cap_subj: "She", obj: "her", poss: "her", be: "is", has: "has", s: "s" }, + _ => Forms { subj: "they", cap_subj: "They", obj: "them", poss: "their", be: "are", has: "have", s: "" }, + } +} + /// What kind of turn the packet is for. The stimulus and nothing else differs between them. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] @@ -146,14 +169,14 @@ pub(crate) enum Lens { } impl Lens { - /// The lens as the domain guidance's "begin from …". - pub(crate) fn words(&self) -> String { + /// The lens as the domain guidance's "begin from …", in her pronouns. + pub(crate) fn words(&self, forms: &Forms) -> String { match self { - Self::BodyAndHour => "how she is, here, at this hour".into(), + Self::BodyAndHour => format!("how {} {}, here, at this hour", forms.subj, forms.be), Self::PersonPresent(name) => format!("{name}, who is here"), - Self::UnresolvedWant => "something she still wants and has not got".into(), - Self::MemorySurfacing => "a memory coming back to her".into(), - Self::Wondering => "something she has been wondering about".into(), + Self::UnresolvedWant => format!("something {} still want{} and {} not got", forms.subj, forms.s, forms.has), + Self::MemorySurfacing => format!("a memory coming back to {}", forms.obj), + Self::Wondering => format!("something {} {} been wondering about", forms.subj, forms.has), } } } @@ -196,6 +219,9 @@ pub(crate) struct Packet { /// Every typed id the packet's lines name: the selected items' and the bonds' of the people present. pub ids: Vec, pub selected: Vec, + /// Her pronouns, for the words the prompts speak of her in. + #[serde(skip)] + pub forms: Forms, } /// What the messages to her cost past the caps: bytes over the stimulus and heard caps, the older messages to her the @@ -310,11 +336,12 @@ fn activation(state: &Value, axis: &str) -> Option { number(state, &["activationProfile", "situationalState", axis, "currentActivation"]) } -/// Mood as change since her last turn; as a level only when there is no last turn to measure from. -fn mood_line(state: &Value, previous: Option<&Value>) -> String { +/// Mood as change since her last turn; as a level only when there is no last turn to measure from. None when her state +/// carries no mood: an absence is left out of the packet, never narrated. +fn mood_line(state: &Value, previous: Option<&Value>) -> Option { let now: Vec<(usize, f64)> = MOOD_AXES.iter().enumerate().filter_map(|(at, (axis, ..))| activation(state, axis).map(|value| (at, value))).collect(); if now.is_empty() { - return "- mood: none recorded".into(); + return None; } let Some(previous) = previous else { let words: Vec<&str> = now @@ -324,7 +351,7 @@ fn mood_line(state: &Value, previous: Option<&Value>) -> String { if *value >= 0.5 { up } else { down } }) .collect(); - return format!("- mood, with no earlier turn to measure from: {} than middling", words.join(", ")); + return Some(format!("- mood: {} than middling", words.join(", "))); }; let moves: Vec<&str> = now .iter() @@ -338,15 +365,16 @@ fn mood_line(state: &Value, previous: Option<&Value>) -> String { } }) .collect(); - if moves.is_empty() { "- mood: where it was at her last turn".into() } else { format!("- mood: {} than at her last turn", moves.join(", ")) } + let poss = forms(state).poss; + Some(if moves.is_empty() { format!("- mood: where it was at {poss} last turn") } else { format!("- mood: {} than at {poss} last turn", moves.join(", ")) }) } -fn need_movement(need: &Value, previous: Option<&Value>) -> String { +fn need_movement(need: &Value, previous: Option<&Value>, poss: &str) -> String { let intensity = number(need, &["intensity"]).unwrap_or(SALIENCE_UNSTATED); let before = previous.and_then(|previous| items(previous, &["affect", "needs"]).iter().find(|old| text(old, &["id"]) == text(need, &["id"])).and_then(|old| number(old, &["intensity"]))); match before.map(|before| intensity - before) { - Some(change) if change >= MOVE_MIN => "growing since her last turn".into(), - Some(change) if change <= -MOVE_MIN => "easing since her last turn".into(), + Some(change) if change >= MOVE_MIN => format!("growing since {poss} last turn"), + Some(change) if change <= -MOVE_MIN => format!("easing since {poss} last turn"), Some(_) => "where it was".into(), None => strength_words(intensity).into(), } @@ -445,10 +473,9 @@ fn candidates(inputs: &Inputs, tuning: &Tuning, present: &BTreeSet, touc let about = about_present(memory, present); let pool = if about { Pool::MemoriesAboutPresent } else { Pool::OtherMemories }; let touch = if about { TOUCH_PRESENT } else if in_room(memory, here) { TOUCH_ROOM } else { TOUCH_ELSE }; - let mut body = text(memory, &["summary"]).to_owned(); - let tension = text(memory, &["tension"]); - if !tension.is_empty() { - body = format!("{body} {tension}"); + let body = [text(memory, &["summary"]), text(memory, &["tension"])].into_iter().filter(|part| !part.is_empty()).collect::>().join(" "); + if body.is_empty() { + continue; } let line = format!("- memory [{}]: {}", text(memory, &["id"]), clip(&one_line(&body), item_bytes)); let salience = number(memory, &["intensity"]).unwrap_or(SALIENCE_UNSTATED); @@ -459,33 +486,39 @@ fn candidates(inputs: &Inputs, tuning: &Tuning, present: &BTreeSet, touc for need in items(state, &["affect", "needs"]).iter().filter(|need| live(need)) { let intensity = number(need, &["intensity"]).unwrap_or(SALIENCE_UNSTATED); - let name = [text(need, &["label"]), text(need, &["summary"]), text(need, &["id"])].into_iter().find(|name| !name.is_empty()).unwrap_or_default(); - let line = format!("- need [{}]: {}, {}", text(need, &["id"]), clip(&one_line(name), item_bytes), need_movement(need, inputs.history.previous.as_ref())); + let Some(name) = [text(need, &["label"]), text(need, &["summary"])].into_iter().find(|name| !name.is_empty()) else { continue }; + let line = format!("- need [{}]: {}, {}", text(need, &["id"]), clip(&one_line(name), item_bytes), need_movement(need, inputs.history.previous.as_ref(), forms(state).poss)); push(text(need, &["id"]), Pool::Needs, line, intensity, 0.0, TOUCH_ELSE, 1.0 + intensity); } - for wondering in items(state, &["thoughtMemory", "incubation"]).iter().filter(|item| live(item) && !private_elsewhere(item, here)) { + for wondering in items(state, &["thoughtMemory", "incubation"]).iter().filter(|item| live(item) && !private_elsewhere(item, here) && !text(item, &["summary"]).is_empty()) { let days = time(wondering).map_or(0.0, |at| (inputs.now - at).num_seconds().max(0) as f64 / 86_400.0); let touch = if about_present(wondering, present) { TOUCH_PRESENT } else { TOUCH_ELSE }; let line = format!("- wondering [{}]: {}", text(wondering, &["id"]), clip(&one_line(text(wondering, &["summary"])), item_bytes)); push(text(wondering, &["id"]), Pool::Incubation, line, number(wondering, &["intensity"]).unwrap_or(SALIENCE_UNSTATED), 0.0, touch, (1.0 + days / 7.0).min(INCUBATION_UNRESOLVED_MAX)); } - for stance in items(state, &["affect", "doctrineStances"]).iter().filter(|stance| live(stance)) { + for stance in items(state, &["affect", "doctrineStances"]).iter().filter(|stance| live(stance) && !text(stance, &["summary"]).is_empty()) { let touch = if about_present(stance, present) { TOUCH_PRESENT } else { TOUCH_ELSE }; let line = format!("- stance [{}]: {}", text(stance, &["id"]), clip(&one_line(text(stance, &["summary"])), item_bytes)); push(text(stance, &["id"]), Pool::Stance, line, number(stance, &["intensity"]).unwrap_or(SALIENCE_UNSTATED), relevance_log(text(stance, &["summary"]), touching), touch, 1.0); } - for value in items(state, &["values"]) { - let line = format!("- value [{}] {}: {}", text(value, &["id"]), clip(text(value, &["label"]), NAME_BYTES), clip(&one_line(text(value, &["summary"])), item_bytes)); + for value in items(state, &["values"]).iter().filter(|value| !text(value, &["label"]).is_empty() || !text(value, &["summary"]).is_empty()) { + let summary = clip(&one_line(text(value, &["summary"])), item_bytes); + let label = clip(text(value, &["label"]), NAME_BYTES); + let line = match (label.is_empty(), summary.is_empty()) { + (false, false) => format!("- value [{}] {label}: {summary}", text(value, &["id"])), + (false, true) => format!("- value [{}] {label}", text(value, &["id"])), + _ => format!("- value [{}]: {summary}", text(value, &["id"])), + }; let relevance = relevance_log(&format!("{} {}", text(value, &["label"]), text(value, &["summary"])), touching); push(text(value, &["id"]), Pool::Value, line, number(value, &["priority"]).unwrap_or(SALIENCE_UNSTATED), relevance, TOUCH_ELSE, 1.0); } for said in &inputs.history.said { let touch = if Some(said.room.as_str()) == here { TOUCH_ROOM } else { TOUCH_ELSE }; - let line = format!("- she said [{}] in {}: {}", said.id, said.room, spoken(&clip(&said.text, item_bytes))); + let line = format!("- {} said [{}] in {}: {}", forms(state).subj, said.id, said.room, spoken(&clip(&said.text, item_bytes))); push(&said.id, Pool::Said, line, SALIENCE_UNSTATED, recency_log(Some(said.at), inputs.now, tuning.select.memory_tau_h), touch, 1.0); } out @@ -592,10 +625,10 @@ struct Addressed<'a> { } impl Addressed<'_> { - fn lines(&self, render: impl Fn(&RoomLine, &str) -> String) -> Vec { + fn lines(&self, obj: &str, render: impl Fn(&RoomLine, &str) -> String) -> Vec { let mut lines: Vec = Vec::new(); if self.left_out > 0 { - lines.push(format!("({} more said to her, not shown)", self.left_out)); + lines.push(format!("({} more said to {obj}, not shown)", self.left_out)); } lines.extend(self.shown.iter().map(|(line, cut)| match cut { None => render(line, &spoken(&line.text)), @@ -645,12 +678,13 @@ fn chat_stimulus(inputs: &Inputs, tuning: &Tuning) -> (String, String, Overflow) // One selection, rendered twice: the stimulus and the heard lines show the same messages to her and the same count. let addressed = said_to_her(&to_her, typed, ceiling); let (left_out, clipped) = (addressed.left_out, addressed.clipped); - let typed_to_her = addressed.lines(typed); - let heard_to_her = addressed.lines(heard); + let obj = forms(inputs.state).obj; + let typed_to_her = addressed.lines(obj, typed); + let heard_to_her = addressed.lines(obj, heard); let mut stimulus = String::new(); if !typed_to_her.is_empty() { - stimulus.push_str("Said to her:"); + stimulus.push_str(&format!("Said to {obj}:")); for line in &typed_to_her { stimulus.push('\n'); stimulus.push_str(line); @@ -718,12 +752,13 @@ fn beat_stimulus(inputs: &Inputs, tuning: &Tuning) -> String { let last = heard.filter(|(sender, _)| inputs.people.person_of(sender) == person).map(|(_, at)| at).max(); contacts.push((last, match last { Some(at) => format!("- last heard from {label} {} h ago", hours(inputs.now, at)), - None => format!("- nothing from {label} in her rooms lately"), + None => format!("- nothing from {label} in {} rooms lately", forms(inputs.state).poss), })); } contacts.sort_by_key(|(last, _)| std::cmp::Reverse(*last)); let mut out = Lines::new(cap); - out.push("Nothing addressed her."); + let her = forms(inputs.state); + out.push(&format!("Nothing addressed {}.", her.obj)); let note_room = 48; let contact_cap = cap * 2 / 3; let mut left_out = 0; @@ -733,12 +768,12 @@ fn beat_stimulus(inputs: &Inputs, tuning: &Tuning) -> String { } } if left_out > 0 { - out.push(&format!("({left_out} more people she is bound to not shown)")); + out.push(&format!("({left_out} more people {} {} bound to not shown)", her.subj, her.be)); } let others: Vec<&RoomLine> = inputs.room.tail.iter().filter(|line| line.sender != inputs.people.own_sender).collect(); let shown = &others[others.len().saturating_sub(tuning.select.beat_tail_lines)..]; let lines: Vec = shown.iter().map(|line| format!("- {} in {}, {} h ago: {}", name_of(line, inputs), line.room, hours(inputs.now, line.at_ms), spoken(&clip(&line.text, tuning.select.item_bytes / 2)))).collect(); - let section = newest_section("Lately in her rooms:", &lines, cap.saturating_sub(out.out.len() + 2)); + let section = newest_section(&format!("Lately in {} rooms:", her.poss), &lines, cap.saturating_sub(out.out.len() + 2)); if !section.is_empty() && out.push("") { out.push(§ion); } @@ -747,8 +782,9 @@ fn beat_stimulus(inputs: &Inputs, tuning: &Tuning) -> String { fn reflection_stimulus(inputs: &Inputs, tuning: &Tuning) -> String { let lines: Vec = items(inputs.state, &["thoughtMemory", "shortTerm"]).iter().filter(|item| live(item)).map(|item| format!("- {}", clip(&one_line(text(item, &["summary"])), tuning.select.item_bytes))).collect(); - let section = newest_section("Since she last took stock:", &lines, tuning.select.stimulus_bytes); - if section.is_empty() { clip("Since she last took stock: nothing new.", tuning.select.stimulus_bytes) } else { section } + let subj = forms(inputs.state).subj; + let section = newest_section(&format!("Since {subj} last took stock:"), &lines, tuning.select.stimulus_bytes); + if section.is_empty() { clip(&format!("Since {subj} last took stock: nothing new."), tuning.select.stimulus_bytes) } else { section } } /// The people present, newest first: who spoke to her or in her room this turn, or in the beat's lines. @@ -771,14 +807,30 @@ fn present_people(inputs: &Inputs, tuning: &Tuning) -> Vec<(String, String)> { out } +/// A bond line: the person, the kind of bond after a dash (a label may hold a comma: "Meta, the operator"), trust and +/// friction as words when the bond carries them, and its summary. What the bond does not carry is left out. fn bond_line(bond: &Value, name: &str, tuning: &Tuning) -> String { - let mut feel = vec![friction_words(number(bond, &["tension"]).unwrap_or(0.0))]; - if let Some(trust) = number(bond, &["trust"]) { - feel.insert(0, trust_words(trust)); + let feel: Vec<&str> = [number(bond, &["trust"]).map(trust_words), number(bond, &["tension"]).map(friction_words)].into_iter().flatten().collect(); + let custom = text(bond, &["customRelationshipKind"]); + let kind = clip(&one_line(if custom.is_empty() { text(bond, &["relationshipKind"]) } else { custom }), NAME_BYTES); + let mut line = format!("- bond [{}] {name}", text(bond, &["id"])); + if !kind.is_empty() { + let _ = write!(line, " \u{2014} {kind}"); } - let kind = clip(&one_line(text(bond, &["relationshipKind"])), NAME_BYTES); - let kind = if kind.is_empty() { String::new() } else { format!(", {kind}") }; - format!("- bond [{}] {name}{kind}: {}. {}", text(bond, &["id"]), feel.join(", "), clip(&one_line(text(bond, &["summary"])), tuning.select.bond_summary_bytes)) + let summary = clip(&one_line(text(bond, &["summary"])), tuning.select.bond_summary_bytes); + match (feel.is_empty(), summary.is_empty()) { + (true, true) => {} + (true, false) => { + let _ = write!(line, ": {summary}"); + } + (false, true) => { + let _ = write!(line, ": {}.", feel.join(", ")); + } + (false, false) => { + let _ = write!(line, ": {}. {summary}", feel.join(", ")); + } + } + line } fn identity_of(state: &Value, tuning: &Tuning) -> String { @@ -803,17 +855,161 @@ fn also_here(named: &[String]) -> Option { break; } if shown > 0 { - line.push_str(", "); + line.push_str("; "); } line.push_str(name); shown += 1; } if shown < named.len() { - let _ = write!(line, "{}{} more", if shown > 0 { ", and " } else { "" }, named.len() - shown); + let _ = write!(line, "{}{} more", if shown > 0 { "; and " } else { "" }, named.len() - shown); } Some(line) } +// --------------------------------------------------------------------------------------------- +// The group state: what the room's recent lines say about who is talking to whom. + +/// Whether a sender is a Mind of the swarm (she is one); anyone else is a human. +fn is_mind(inputs: &Inputs, sender: &str) -> bool { + sender == inputs.people.own_sender || inputs.people.minds.iter().any(|mind| mind == sender) +} + +/// The label her bond with a sender gives them, when she has a live one. +fn bond_label(inputs: &Inputs, sender: &str) -> Option { + let person = inputs.people.person_of(sender); + items(inputs.state, &["affect", "socialBonds"]).iter().find(|bond| live(bond) && text(bond, &["object", "id"]).to_lowercase() == person).map(|bond| text(bond, &["object", "label"]).to_owned()).filter(|label| !label.is_empty()) +} + +/// The words a line may call its sender by: the Matrix localpart, the display name, and the bond's label when she has one. +fn names_of(line: &RoomLine, inputs: &Inputs) -> Vec { + [Some(localpart(&line.sender).to_owned()), Some(line.display.trim().to_owned()), bond_label(inputs, &line.sender)].into_iter().flatten().filter(|name| !name.is_empty()).collect() +} + +/// The recent lines of one room, the one the group state and the pronouns describe: messages and tail together, each +/// once, oldest first. The room is the turn's when it is one room; otherwise the room of the newest message to her, else +/// of the newest message, else of the newest tail line. Never several rooms folded into one, so a direct message is +/// only ever read as its own room. +fn recent_lines<'a>(inputs: &'a Inputs) -> Vec<&'a RoomLine> { + let newest = |lines: &'a [RoomLine], keep: &dyn Fn(&RoomLine) -> bool| lines.iter().filter(|line| keep(line)).max_by_key(|line| line.at_ms).map(|line| line.room.as_str()); + let Some(room) = inputs.room.here.as_deref().or_else(|| newest(&inputs.room.messages, &|line| line.to_her)).or_else(|| newest(&inputs.room.messages, &|_| true)).or_else(|| newest(&inputs.room.tail, &|_| true)) else { + return Vec::new(); + }; + let mut lines: Vec<&RoomLine> = Vec::new(); + for line in inputs.room.messages.iter().chain(&inputs.room.tail) { + if line.room != room || lines.iter().any(|seen| seen.sender == line.sender && seen.at_ms == line.at_ms && seen.text == line.text) { + continue; + } + lines.push(line); + } + lines.sort_by_key(|line| line.at_ms); + lines +} + +/// How a sender reads in the group-state and pronoun lines: "she" for her; the bond's label; the display name; or, for a +/// tail line that carries none, the handle in the Matrix id. +fn label_of(line: &RoomLine, inputs: &Inputs) -> String { + if line.sender == inputs.people.own_sender { + forms(inputs.state).subj.to_owned() + } else if line.display.trim().is_empty() && bond_label(inputs, &line.sender).is_none() { + localpart(&line.sender).to_owned() + } else { + name_of(line, inputs) + } +} + +/// The group-state slot (`select.group_state`): the conversation as it stands over the room's last `group_lines` lines. +/// Who has been talking with whom; a human's question to the room that others have answered, as covered (one nobody +/// answered is not mentioned); when a human last spoke; how many Mind lines in a row; and a human waiting on her by name +/// since she last spoke. Never what she owes: the room's state, not her duty. Whom a line is to is read from the names in +/// it and Matrix's word, a cue the Interpreter (C3b) will replace. None when the room shows no line. +fn group_line(inputs: &Inputs, tuning: &Tuning) -> Option { + let lines = recent_lines(inputs); + if lines.is_empty() { + return None; + } + let own = inputs.people.own_sender; + let names_her = |line: &RoomLine| line.sender != own && (line.to_her || [localpart(own), text(inputs.state, &["publicName"])].iter().any(|name| crate::address::names_whole_word(&line.text, name, false))); + // Everything the line says is over these lines: its last `group_lines`. + let window = &lines[lines.len().saturating_sub(tuning.select.group_lines)..]; + let named_in = |line: &RoomLine| window.iter().filter(|other| other.sender != line.sender).find(|other| names_of(other, inputs).iter().any(|name| crate::address::names_whole_word(&line.text, name, false))).copied(); + // A human's last line, when it is a question to the room (no one named), and who has answered it since. + let question = window.iter().rposition(|line| !is_mind(inputs, &line.sender)).filter(|at| { + let line = window[*at]; + line.text.trim_end().ends_with('?') && !names_her(line) && named_in(line).is_none() + }); + let mut answered: Vec = Vec::new(); + let mut talk: Vec = Vec::new(); + for (at, line) in window.iter().enumerate() { + let speaker = label_of(line, inputs); + let target = if names_her(line) { Some(forms(inputs.state).obj.to_owned()) } else { named_in(line).map(|other| label_of(other, inputs)) }; + let answers = question.is_some_and(|asked| at > asked && line.sender != window[asked].sender && target.as_ref().is_none_or(|target| *target == label_of(window[asked], inputs))); + if answers { + if !answered.contains(&speaker) { + answered.push(speaker); + } + continue; + } + if question == Some(at) { + continue; + } + let pair = match target { + Some(target) => format!("{speaker} with {target}"), + None => format!("{speaker} to the room"), + }; + if !talk.contains(&pair) { + talk.push(pair); + } + } + let mut parts = Vec::new(); + if let Some(asked) = question + && !answered.is_empty() + { + parts.push(format!("{} asked the room a question, and {} answered it", label_of(window[asked], inputs), answered.join("; "))); + } + if !talk.is_empty() { + parts.push(format!("lately {}", talk.join("; "))); + } + if let Some(line) = window.iter().rev().find(|line| !is_mind(inputs, &line.sender)) { + parts.push(format!("{} last spoke {} min ago", label_of(line, inputs), minutes(inputs.now, line.at_ms))); + } + let minds_in_a_row = window.iter().rev().take_while(|line| is_mind(inputs, &line.sender)).count(); + if minds_in_a_row >= 2 { + parts.push(format!("the last {minds_in_a_row} lines are the Minds' alone")); + } + // A human waiting on her by name: a line of a human's that names or tags her, after her own last line. + let her_last = window.iter().rposition(|line| line.sender == own); + if let Some(line) = window.iter().enumerate().rev().find(|(at, line)| her_last.is_none_or(|last| *at > last) && !is_mind(inputs, &line.sender) && names_her(line)).map(|(_, line)| line) { + parts.push(format!("{} is waiting on {}", label_of(line, inputs), forms(inputs.state).obj)); + } + (!parts.is_empty()).then(|| clip(&format!("- the conversation: {}", parts.join("; ")), tuning.select.group_bytes)) +} + +/// The pronouns of everyone the packet names from the room: `tuning.pronouns` by Matrix id (the persona state has no +/// pronoun field for another person; `presentation.pronouns` is hers alone), and they/them for anyone it does not list. +fn pronoun_line(inputs: &Inputs, tuning: &Tuning) -> Option { + let mut seen: Vec<&str> = Vec::new(); + let mut parts: Vec = Vec::new(); + let messages = inputs.room.messages.iter(); + let shown_tail = recent_lines(inputs).into_iter().rev().take(tuning.select.group_lines.max(tuning.select.beat_tail_lines)); + for line in messages.chain(shown_tail) { + if line.sender == inputs.people.own_sender || seen.contains(&line.sender.as_str()) { + continue; + } + seen.push(&line.sender); + let pronouns = tuning.pronouns.get(&line.sender).map_or(UNKNOWN_PRONOUNS, String::as_str); + parts.push(format!("{} \u{2014} {pronouns}", label_of(line, inputs))); + } + (!parts.is_empty()).then(|| clip(&format!("- pronouns: {}", parts.join("; ")), ALSO_HERE_BYTES)) +} + +/// The pronouns of a person nobody listed. +const UNKNOWN_PRONOUNS: &str = "they/them"; + +fn minutes(now: DateTime, at_ms: u64) -> i64 { + let at = i64::try_from(at_ms).ok().and_then(DateTime::::from_timestamp_millis).unwrap_or(now); + (now - at).num_minutes().max(0) +} + // --------------------------------------------------------------------------------------------- // The packet. @@ -823,7 +1019,7 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet { let (stimulus, heard, overflow) = match inputs.kind { TurnKind::Chat => chat_stimulus(inputs, tuning), TurnKind::Beat => (beat_stimulus(inputs, tuning), String::new(), Overflow::default()), - TurnKind::FollowUp => (clip(&format!("She just found: {}", inputs.observation.unwrap_or("nothing")), tuning.select.stimulus_bytes), String::new(), Overflow::default()), + TurnKind::FollowUp => (clip(&format!("{} just found: {}", forms(inputs.state).cap_subj, inputs.observation.unwrap_or("nothing")), tuning.select.stimulus_bytes), String::new(), Overflow::default()), TurnKind::Reflection => (reflection_stimulus(inputs, tuning), String::new(), Overflow::default()), }; @@ -833,7 +1029,7 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet { let present = present_people(inputs, tuning); let present_ids: BTreeSet = present.iter().map(|(id, _)| id.clone()).collect(); let bonds = items(inputs.state, &["affect", "socialBonds"]); - let mut fixed = vec![format!("- now: {}", inputs.now.format("%A %-d %B, %H:%M UTC")), mood_line(inputs.state, inputs.history.previous.as_ref())]; + let mut fixed: Vec = [Some(format!("- now: {}", inputs.now.format("%A %-d %B, %H:%M UTC"))), mood_line(inputs.state, inputs.history.previous.as_ref())].into_iter().flatten().collect(); let mut used: usize = fixed.iter().map(|line| line.len() + 1).sum(); let mut ids = Vec::new(); let mut named = Vec::new(); @@ -858,6 +1054,16 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet { used += line.len() + 1; fixed.push(line); } + if tuning.select.group_state + && let Some(line) = group_line(inputs, tuning).filter(|line| used + line.len() < budget) + { + used += line.len() + 1; + fixed.push(line); + } + if let Some(line) = pronoun_line(inputs, tuning).filter(|line| used + line.len() < budget) { + used += line.len() + 1; + fixed.push(line); + } // What the room is touching: the content words of what was said there, and of a follow-up's finding. let touching: BTreeSet = inputs.room.messages.iter().chain(&inputs.room.tail).map(|line| line.text.as_str()).chain(inputs.observation).flat_map(content_words).collect(); @@ -894,5 +1100,5 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet { lines.extend(taken.iter().map(|candidate| candidate.line.clone())); ids.extend(taken.iter().map(|candidate| candidate.id.clone())); let selected = taken.into_iter().map(|candidate| Pick { id: candidate.id, pool: candidate.pool, log_score: candidate.log_score }).collect(); - Packet { kind: inputs.kind, seed: inputs.seed, lens, identity, context: lines.join("\n"), stimulus, heard, overflow, present: present_names, ids, selected } + Packet { kind: inputs.kind, seed: inputs.seed, lens, identity, context: lines.join("\n"), stimulus, heard, overflow, present: present_names, ids, selected, forms: forms(inputs.state) } } diff --git a/crates/mind-body/src/projection/simulate.rs b/crates/mind-body/src/projection/simulate.rs index a2c35b2..cc7ff3c 100644 --- a/crates/mind-body/src/projection/simulate.rs +++ b/crates/mind-body/src/projection/simulate.rs @@ -2,13 +2,14 @@ //! one `project` through the Persona stage, and each one's quoted lines join the room as from her Matrix id, so the //! next one hears them. //! -//! Who wakes is the real rule: `address::is_for` over each persona's names, plus ruling -//! `persona-only-wake-humans-in-rooms` (an addressed message, any human message in her rooms, the beat). Another Mind's -//! unaddressed message wakes no one, unless the plan asks for the swarm's old loop (`wake = "all_messages"`), kept as a -//! control. Those woken in one round go in an order drawn from the seed, each against the room as it stands at her turn. +//! Who wakes is the heartbeat's: `heartbeat::wakes` under the plan's `WakePolicy`, over each persona's addressee as the +//! heartbeat's addressing table holds it (her stewarded projects' names included) when the plan names the table. The +//! beat is the heartbeat's too: when it falls, one Persona wakes, the winner of `tempo::pick`. Those woken in one round +//! go in an order drawn from the seed, each against the room as it stands at her turn. //! //! Her state does not move during a run: the Interpreter (C3b) and the commit (C3c) are not built. `state_after_turn` -//! is the seam where they will. +//! is the seam where they will. An explicit addressee (the Interpreter naming whom she speaks to) cannot be simulated +//! until then either: a spoken line addresses another persona only by the names in its text. use std::collections::BTreeMap; use std::fmt::Write as _; @@ -19,26 +20,19 @@ use chrono::{DateTime, Duration, Utc}; use serde::Deserialize; use serde_json::{Value, json}; -use super::harness::{Harness, Line, Message, cosine, pending_for, state_file, turn_markdown, usage_markdown, usage_total}; +use super::harness::{Harness, Line, Message, RETELL_FLAG, cosine, pending_for, state_file, turn_markdown, usage_markdown, usage_total}; use super::select::Draw; +use super::tuning; use super::{MouthReader, Organs, Request, Through, TurnKind, project}; use crate::address::{Addressee, is_for, localpart}; use crate::chat_client::ChatPending; -use crate::heartbeat::{Addressing, HeartbeatView}; +use crate::heartbeat::{Addressing, DEFAULT_BEAT_S, FileStore, HeartbeatView, LineFacts, Speaker, WakeCause, WakePolicy, addressed_by_member, wakes}; +use crate::tempo::{Standing, pick}; /// The most personas a simulation holds: the swarm. const CAST_MAX: usize = 8; - -/// Who a message wakes. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)] -#[serde(rename_all = "snake_case")] -enum Wake { - /// The ruled set: a message for her, any human message in her rooms, the beat. - #[default] - HumansInRooms, - /// The swarm's old loop, as a control: any message in her rooms, a Mind's too. - AllMessages, -} +/// How many transcript lines the report quotes as representative. +const REPRESENTATIVE_LINES: usize = 18; #[derive(Deserialize)] #[serde(deny_unknown_fields)] @@ -48,17 +42,25 @@ struct SimFile { repeats: usize, #[serde(default)] seed: u64, - #[serde(default)] - wake: Wake, - /// Every this many rounds the beat wakes everyone who was not woken otherwise; 0 is no beat. - #[serde(default)] - beat_every: usize, + #[serde(default = "ruled")] + wake: WakePolicy, + /// The heartbeat's beat, in seconds of simulated time; 0 is no beat. + #[serde(default = "beat_s")] + beat_s: u32, #[serde(default = "two")] round_minutes: i64, + /// An exchange in a room is its run of lines with no gap longer than this between one and the next; she is in it when + /// one of them is hers (`humans_pace`). + #[serde(default = "exchange_gap")] + exchange_gap_minutes: i64, start: DateTime, rooms: Vec, #[serde(default)] operators: Vec, + /// The heartbeat's store (`heartbeat.cc`), read without a lock or a write, for its addressing table: each persona's + /// names and her stewarded projects' names. None addresses each by her own names. + #[serde(default)] + addressing: Option, cast: Vec, #[serde(default, rename = "message")] script: Vec, @@ -72,6 +74,18 @@ fn two() -> i64 { 2 } +fn exchange_gap() -> i64 { + 20 +} + +fn ruled() -> WakePolicy { + WakePolicy::Ruled +} + +fn beat_s() -> u32 { + DEFAULT_BEAT_S +} + #[derive(Clone, Deserialize)] #[serde(deny_unknown_fields)] struct CastEntry { @@ -82,15 +96,18 @@ struct CastEntry { /// Her rooms; none is every room of the plan. #[serde(default)] rooms: Vec, - /// More names she answers to, beside her handle and display name. + /// The rooms that are hers, where any human line wakes her under `humans_pace`. Neither the heartbeat's table nor + /// `persona.env` records which rooms a Mind owns, so the plan says; a direct message is always hers. #[serde(default)] - names: Vec, + own_rooms: Vec, } struct Member { entry: CastEntry, state: Value, addressee: Addressee, + /// Where her addressee came from: the heartbeat's table, or her own names. + names_from: &'static str, rooms: Vec, } @@ -122,8 +139,33 @@ fn state_after_turn(state: Value, _turn: &Value) -> Value { state } -/// How a Mind's line addressed her, by the evidence `is_for` had: a Matrix tag or a reply to her (`mention or reply`), -/// her Matrix id written as plain text (`id as text`), or one of her names in the text (`name in text`). +fn speaker(line: &Line, member: &Member, operators: &[String], cast: &[String]) -> Speaker { + if line.from == member.entry.id { + Speaker::Her + } else if operators.contains(&line.from) { + Speaker::Operator + } else if cast.contains(&line.from) { + Speaker::Mind + } else { + Speaker::Member + } +} + +/// For each line, how many Mind lines in a row came before it in its room since a human last spoke there. +fn mind_runs(lines: &[Line], cast: &[String]) -> Vec { + let mut run: BTreeMap<&str, usize> = BTreeMap::new(); + lines + .iter() + .map(|line| { + let before = run.get(line.room.as_str()).copied().unwrap_or(0); + run.insert(&line.room, if cast.contains(&line.from) { before + 1 } else { 0 }); + before + }) + .collect() +} + +/// How a Mind's line addressed her, by the evidence `is_for` had, strongest first: a Matrix tag or a reply to her, her +/// Matrix id written as plain text, or one of her names in the text. fn how_addressed(line: &Line, at: usize, member: &Member, lines: &[Line]) -> &'static str { let delivery = line.delivery(at, &member.entry.id, lines); if delivery.mentions.contains(&member.entry.id) || delivery.basis.is_some() { @@ -135,39 +177,71 @@ fn how_addressed(line: &Line, at: usize, member: &Member, lines: &[Line]) -> &'s } } -/// Why she wakes this round, by the plan's rule, and the Minds' lines that addressed her; none leaves her asleep. A -/// human outranks a Mind: a wake a human's line would cause is counted as the human's, so the Mind-addressed wakes are -/// exactly those no human caused. -fn wake_reason(lines: &[Line], seen: usize, member: &Member, cast: &[String], wake: Wake, beat: bool) -> Option<(&'static str, Vec)> { - let (mut human_addressed, mut human, mut mind) = (false, false, false); - let mut by_minds = Vec::new(); +/// One wake: why (the strongest cause among her new lines, under the plan's policy) and, when only Minds' lines caused +/// it, the strongest evidence that addressed her and the lines that did. +struct Woken { + cause: WakeCause, + how: Option<&'static str>, + by: Vec, +} + +/// Whether she spoke in the exchange a line continues: walking back through the lines of its room while each is within +/// `gap` of the one after it. +fn in_exchange(lines: &[Line], at: usize, her: &str, gap: Duration) -> bool { + let room = &lines[at].room; + let mut after = lines[at].at_ms; + for line in lines[..at].iter().rev().filter(|line| line.room == *room) { + if after.saturating_sub(line.at_ms) > u64::try_from(gap.num_milliseconds()).unwrap_or(0) { + return false; + } + if line.from == her { + return true; + } + after = line.at_ms; + } + false +} + +#[allow(clippy::too_many_arguments, reason = "one wake decision's inputs, each a plan or room fact")] +fn woken(lines: &[Line], runs: &[usize], seen: usize, member: &Member, operators: &[String], cast: &[String], policy: WakePolicy, gap: Duration) -> Option { + let mut found: Vec<(usize, WakeCause)> = Vec::new(); for (at, line) in lines.iter().enumerate().skip(seen) { - if line.from == member.entry.id || !(member.rooms.contains(&line.room) || line.dm) { + if !line.visible_to(&member.entry.id, &member.rooms) { continue; } - let is_human = !cast.contains(&line.from); - let addressed = is_for(&member.addressee, &line.delivery(at, &member.entry.id, lines)); - match (is_human, addressed) { - (true, true) => human_addressed = true, - (true, false) => human = true, - (false, true) => by_minds.push(json!({ "from": line.from, "how": how_addressed(line, at, member, lines), "says": line.says })), - (false, false) => mind = true, + let delivery = line.delivery(at, &member.entry.id, lines); + let facts = LineFacts { mind_run: runs[at], own_room: member.entry.own_rooms.contains(&line.room), in_exchange: in_exchange(lines, at, &member.entry.id, gap) }; + if let Some(cause) = wakes(policy, &member.addressee, &delivery, speaker(line, member, operators, cast), facts) { + found.push((at, cause)); } } - let why = if human_addressed { - "addressed by a human" - } else if human { - "a human in her rooms" - } else if !by_minds.is_empty() { - "addressed by a Mind" - } else if wake == Wake::AllMessages && mind { - "a message in her rooms" - } else if beat { - "the beat" - } else { - return None; - }; - Some((why, if why == "addressed by a Mind" { by_minds } else { Vec::new() })) + let cause = found.iter().map(|(_, cause)| *cause).min()?; + if cause != WakeCause::AddressedByMind { + return Some(Woken { cause, how: None, by: vec![] }); + } + let addressing: Vec = found.iter().filter(|(_, cause)| *cause == WakeCause::AddressedByMind).map(|(at, _)| *at).collect(); + let rank = |how: &str| ["mention or reply", "id as text", "name in text"].iter().position(|one| *one == how).unwrap_or(3); + let how = addressing.iter().map(|at| how_addressed(&lines[*at], *at, member, lines)).min_by_key(|how| rank(how)); + let by = addressing.iter().map(|at| json!({ "from": lines[*at].from, "how": how_addressed(&lines[*at], *at, member, lines), "says": lines[*at].says })).collect(); + Some(Woken { cause, how, by }) +} + +/// The wire spelling of a cause, and of the beat. +fn cause_word(cause: Option) -> &'static str { + match cause { + Some(WakeCause::AddressedByHuman) => "addressed_by_human", + Some(WakeCause::Human) => "human", + Some(WakeCause::AddressedByMind) => "addressed_by_mind", + Some(WakeCause::Mind) => "mind", + None => "beat", + } +} + +/// The cast members a said line tags: an `@handle` of theirs in the text. The stand-in for the Interpreter's explicit +/// addressee (C3b), which will carry a Matrix mention; a name without the `@` tags no one. +fn explicit_mentions(says: &str, cast: &[String]) -> Vec { + let tagged: Vec = says.split(|c: char| !(c.is_alphanumeric() || c == '@' || c == '_' || c == '-' || c == '.')).filter_map(|word| word.strip_prefix('@')).map(|handle| handle.trim_end_matches('.').to_lowercase()).collect(); + cast.iter().filter(|id| tagged.iter().any(|handle| handle == &localpart(id).to_lowercase() || id.to_lowercase() == format!("@{handle}"))).cloned().collect() } /// A seeded shuffle, so the order of those woken together is drawn, and replays. @@ -191,24 +265,45 @@ pub fn simulate(harness: &Harness, plan_path: &Path) -> Result { bail!("a simulation needs rounds, repeats, a room and a positive round_minutes"); } let base = plan_path.parent().unwrap_or(Path::new(".")); + let mut members = cast_of(&plan, base)?; + let group_state = tuning::load(&harness.tuning).map(|loaded| loaded.tuning.select.group_state).ok(); + let runs: Vec = (0..plan.repeats).map(|repeat| run(harness, &plan, &mut members, repeat)).collect::>()?; + Ok(markdown(plan_path, &plan, &members, group_state, &runs)) +} + +/// The plan's cast: each persona's state, checked as a put would check it, and her addressee, from the heartbeat's +/// table when the plan names it and the table holds her; and the script checked against the rooms. +fn cast_of(plan: &SimFile, base: &Path) -> Result> { + let table = match &plan.addressing { + Some(path) => FileStore::new(base.join(path)).addressing().with_context(|| format!("the heartbeat store {} could not be read", path.display()))?.unwrap_or_default(), + None => Addressing::default(), + }; let mut members = Vec::new(); for entry in &plan.cast { let state = state_file(&base.join(&entry.state), localpart(&entry.id))?; let rooms = if entry.rooms.is_empty() { plan.rooms.clone() } else { entry.rooms.clone() }; - let public = state["publicName"].as_str().unwrap_or_default().to_owned(); - let names = [localpart(&entry.id), entry.name.as_str(), public.as_str()].into_iter().chain(entry.names.iter().map(String::as_str)).filter(|name| !name.is_empty()); - members.push(Member { addressee: Addressee::new(&entry.id, names), entry: entry.clone(), state, rooms }); + let (addressee, names_from) = match table.minds.iter().find(|row| row.matrix_id() == entry.id) { + Some(row) => (row.clone(), "the heartbeat's table"), + None => { + let public = state["publicName"].as_str().unwrap_or_default().to_owned(); + let names = [localpart(&entry.id), entry.name.as_str(), public.as_str()].into_iter().filter(|name| !name.is_empty()).map(str::to_owned).collect::>(); + (Addressee::new(&entry.id, names.iter().map(String::as_str)), "her own names") + } + }; + members.push(Member { addressee, names_from, entry: entry.clone(), state, rooms }); } for (at, message) in plan.script.iter().enumerate() { if message.ago.is_some() || message.new || message.tag { bail!("script message {} uses a room fixture's ago, new or tag: a script names its round and its mentions", at + 1); } - if !plan.rooms.contains(&message.room) { + if !message.dm && !plan.rooms.contains(&message.room) { bail!("script message {} is in {}, which is not one of the rooms", at + 1, message.room); } + if message.dm && message.to.as_ref().is_none_or(|to| !plan.cast.iter().any(|entry| entry.id == *to)) { + bail!("script message {} is a direct message: name its recipient, a cast member, in `to`", at + 1); + } } - let runs: Vec = (0..plan.repeats).map(|repeat| run(harness, &plan, &mut members, repeat)).collect::>()?; - Ok(markdown(plan_path, &plan, &runs)) + Ok(members) } fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) -> Result { @@ -216,32 +311,61 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) let cast: Vec = members.iter().map(|member| member.entry.id.clone()).collect(); let at_round = |round: usize| plan.start + Duration::minutes(plan.round_minutes * round as i64); let mut lines: Vec = Vec::new(); + // Per line: the round, and the cause of the turn that spoke it (none for a script line). let mut rounds_of: Vec = Vec::new(); - let scripted = |round: usize, lines: &mut Vec, rounds_of: &mut Vec| -> Result<()> { + let mut causes: Vec> = Vec::new(); + let scripted = |round: usize, lines: &mut Vec, rounds_of: &mut Vec, causes: &mut Vec>| -> Result<()> { for (at, message) in plan.script.iter().enumerate().filter(|(_, message)| message.round.unwrap_or(0) == round) { lines.push(Line::of(message, at_round(round) + Duration::seconds(at as i64), None, at)?); rounds_of.push(round); + causes.push(None); } Ok(()) }; - scripted(0, &mut lines, &mut rounds_of)?; + scripted(0, &mut lines, &mut rounds_of, &mut causes)?; let opening = lines.len(); let mut seen = vec![0usize; members.len()]; + let mut last_turn: Vec>> = vec![None; members.len()]; + let mut last_beat = plan.start; let mut recent: Vec>> = vec![Vec::new(); members.len()]; let mut turns = Vec::new(); let mut counter = 0u64; for round in 1..=plan.rounds { - scripted(round, &mut lines, &mut rounds_of)?; - let beat = plan.beat_every > 0 && round % plan.beat_every == 0; - let woken: Vec<(usize, (&'static str, Vec))> = members.iter().enumerate().filter_map(|(at, member)| wake_reason(&lines, seen[at], member, &cast, plan.wake, beat).map(|why| (at, why))).collect(); - for (at, (why, addressed_by)) in shuffled(woken, seed ^ (round as u64).wrapping_mul(0x9E37_79B9)) { + scripted(round, &mut lines, &mut rounds_of, &mut causes)?; + let round_at = at_round(round); + let runs = mind_runs(&lines, &cast); + let mut woke: Vec<(usize, Option)> = members.iter().enumerate().filter_map(|(at, member)| woken(&lines, &runs, seen[at], member, &plan.operators, &cast, plan.wake, Duration::minutes(plan.exchange_gap_minutes)).map(|why| (at, Some(why)))).collect(); + // The beat, as the heartbeat's: when it has fallen, one more wake for the winner of `tempo::pick` among those + // not already woken. + if plan.beat_s > 0 && (round_at - last_beat).num_seconds() >= i64::from(plan.beat_s) { + let standings: Vec = members + .iter() + .enumerate() + .map(|(at, member)| Standing { + slug: localpart(&member.entry.id).to_owned(), + eligible: !woke.iter().any(|(woken, _)| *woken == at), + waited_s: last_turn[at].map(|turn| u64::try_from((round_at - turn).num_seconds()).unwrap_or(0)), + last_turn_ms: last_turn[at].map(|turn| turn.timestamp_millis()), + topic_permille: 0, + addressed_by_member: addressed_by_member(&plan.operators, &member.addressee, &pending_for(&lines, &member.entry.id, &member.rooms, |index| index >= seen[at]).deliveries), + }) + .collect(); + if let Some(winner) = pick(&standings, plan.beat_s) { + woke.push((winner, None)); + last_beat = round_at; + } + } + for (at, why) in shuffled(woke, seed ^ (round as u64).wrapping_mul(0x9E37_79B9)) { counter += 1; let member = &members[at]; let id = member.entry.id.clone(); - let fresh: Vec<&Line> = lines[seen[at]..].iter().filter(|line| line.from != id && (member.rooms.contains(&line.room) || line.dm)).collect(); - let here = fresh.iter().rev().find(|line| line.mentions.contains(&id)).or(fresh.last()).map_or_else(|| member.rooms[0].clone(), |line| line.room.clone()); + let fresh: Vec<&Line> = lines[seen[at]..].iter().filter(|line| line.from != id && line.visible_to(&id, &member.rooms)).collect(); + let woke_on = fresh.iter().rev().find(|line| line.mentions.contains(&id) || line.dm_to.as_deref() == Some(id.as_str())).or(fresh.last()).copied(); + let here = woke_on.map_or_else(|| member.rooms[0].clone(), |line| line.room.clone()); + // Woken by a direct message, she answers in it: to its sender alone. + let dm_to = woke_on.filter(|line| line.dm_to.as_deref() == Some(id.as_str())).map(|line| line.from.clone()); let kind = if fresh.is_empty() { TurnKind::Beat } else { TurnKind::Chat }; - let now = at_round(round) + Duration::seconds(30 + counter as i64); + let now = round_at + Duration::seconds(30 + counter as i64); let request = Request { instance: localpart(&id).to_owned(), kind, @@ -263,24 +387,32 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) let organs = Organs { persona: None, chat: Some(&view), addressing: Some(&names), model: harness.model }; let report = project(&organs, &request, now).unwrap_or_else(|fault| json!({ "error": format!("{fault:#}") })); seen[at] = lines.len(); + last_turn[at] = Some(now); let render = &report["renders"][0]; if let Some(selected) = render["selected"].as_array() { recent[at].push(selected.iter().filter_map(Value::as_str).map(str::to_owned).collect()); } + // A failed call is a failure, never a silence. + let failed = report.get("error").or_else(|| render.get("failed")).or_else(|| render["persona"].get("failed")).map(|fault| fault.as_str().unwrap_or_default().to_owned()); let said: Vec = render["persona"]["would_say"].as_array().map(|said| said.iter().filter_map(Value::as_str).map(str::to_owned).collect()).unwrap_or_default(); let line = (!said.is_empty()).then(|| said.join(" ")); + let cause = cause_word(why.as_ref().map(|why| why.cause)); if let Some(says) = &line { - lines.push(Line { from: id.clone(), name: member.entry.name.clone(), room: here.clone(), at_ms: u64::try_from(now.timestamp_millis()).unwrap_or_default(), says: says.clone(), mentions: vec![], dm: false, follow_up: false, reply_to: None, new: false }); + let mentions = explicit_mentions(says, &cast); + lines.push(Line { from: id.clone(), name: member.entry.name.clone(), room: here.clone(), at_ms: u64::try_from(now.timestamp_millis()).unwrap_or_default(), says: says.clone(), mentions, dm_to: dm_to.clone(), follow_up: false, reply_to: None, new: false }); rounds_of.push(round); + causes.push(Some(cause)); } - let turn = json!({ "round": round, "persona": member.entry.name, "id": id, "woke": why, "addressed_by": addressed_by, "kind": kind, "room": here, "said": line, "report": report }); + let outcome = if failed.is_some() { "failed" } else if line.is_some() { "spoke" } else { "silent" }; + let (how, by) = why.map_or((None, vec![]), |why| (why.how, why.by)); + let turn = json!({ "round": round, "persona": member.entry.name, "id": id, "woke": cause, "how": how, "addressed_by": by, "kind": kind, "room": here, "outcome": outcome, "failed": failed, "said": line, "report": report }); let member = &mut members[at]; member.state = state_after_turn(std::mem::take(&mut member.state), &turn); turns.push(turn); } } - let metrics = metrics(members, &lines, &rounds_of, opening, &turns, plan.rounds); - let transcript: Vec = lines.iter().zip(&rounds_of).map(|(line, round)| json!({ "round": round, "room": line.room, "from": line.from, "name": line.name, "says": line.says, "mind": cast.contains(&line.from) })).collect(); + let metrics = metrics(members, &lines, &rounds_of, &causes, opening, &turns, plan.rounds); + let transcript: Vec = lines.iter().zip(&rounds_of).zip(&causes).map(|((line, round), cause)| json!({ "round": round, "room": line.room, "from": line.from, "name": line.name, "says": line.says, "mind": cast.contains(&line.from), "woke": cause })).collect(); Ok(json!({ "repeat": repeat + 1, "seed": seed, "transcript": transcript, "turns": turns, "metrics": metrics })) } @@ -311,12 +443,39 @@ fn mean_pairwise(texts: &BTreeMap) -> Option { /// Which rounds a measure keeps. type Keep<'a> = &'a dyn Fn(usize) -> bool; -fn metrics(members: &[Member], lines: &[Line], rounds_of: &[usize], opening: usize, turns: &[Value], rounds: usize) -> Value { +/// A Mind-to-Mind reply: a Mind's line spoken in a turn another Mind's line woke. +fn mind_reply(cause: Option<&str>) -> bool { + matches!(cause, Some("addressed_by_mind" | "mind")) +} + +/// Per room: Mind-to-Mind replies in a row with no human line and no human-woken answer between them. +fn reply_chains(lines: &[Line], causes: &[Option<&str>], opening: usize, cast: &[&str]) -> Value { + let mut rooms: BTreeMap = BTreeMap::new(); + for (line, cause) in lines.iter().zip(causes).skip(opening) { + let (longest, chains, total, run) = rooms.entry(line.room.clone()).or_default(); + if cast.contains(&line.from.as_str()) && mind_reply(*cause) { + *run += 1; + *total += 1; + *longest = (*longest).max(*run); + } else { + *chains += usize::from(*run >= 3); + *run = 0; + } + } + let out: BTreeMap = rooms + .into_iter() + .map(|(room, (longest, chains, total, run))| (room, json!({ "longest": longest, "chains_of_3_or_more": chains + usize::from(run >= 3), "mind_to_mind_replies": total }))) + .collect(); + json!(out) +} + +fn metrics(members: &[Member], lines: &[Line], rounds_of: &[usize], causes: &[Option<&str>], opening: usize, turns: &[Value], rounds: usize) -> Value { let cast: Vec<&str> = members.iter().map(|member| member.entry.id.as_str()).collect(); + let outcome = |turn: &&Value, what: &str| turn["outcome"] == what; let mut per = BTreeMap::new(); for member in members { let mine: Vec<&Value> = turns.iter().filter(|turn| turn["id"] == member.entry.id.as_str()).collect(); - let spoke = mine.iter().filter(|turn| !turn["said"].is_null()).count(); + let (spoke, silent, failed) = (mine.iter().filter(|turn| outcome(turn, "spoke")).count(), mine.iter().filter(|turn| outcome(turn, "silent")).count(), mine.iter().filter(|turn| outcome(turn, "failed")).count()); let mut addressed = BTreeMap::new(); for (at, line) in lines.iter().enumerate().skip(opening).filter(|(_, line)| line.from == member.entry.id) { for other in members.iter().filter(|other| other.entry.id != member.entry.id) { @@ -325,22 +484,11 @@ fn metrics(members: &[Member], lines: &[Line], rounds_of: &[usize], opening: usi } } } - per.insert(member.entry.name.clone(), json!({ "turns": mine.len(), "messages": spoke, "silence_rate": if mine.is_empty() { Value::Null } else { json!(1.0 - spoke as f64 / mine.len() as f64) }, "addressed": addressed })); + let answered = spoke + silent; + per.insert(member.entry.name.clone(), json!({ "turns": mine.len(), "messages": spoke, "failed": failed, "silence_rate": if answered == 0 { Value::Null } else { json!(silent as f64 / answered as f64) }, "addressed": addressed })); } - // Mind-to-Mind chains: runs of Mind lines with no human line between them. - let (mut longest, mut long_chains, mut run) = (0usize, 0usize, 0usize); - for line in &lines[opening..] { - if cast.contains(&line.from.as_str()) { - run += 1; - longest = longest.max(run); - } else { - long_chains += usize::from(run >= 3); - run = 0; - } - } - long_chains += usize::from(run >= 3); let half = rounds.div_ceil(2); - let spoken_by = |keep: &dyn Fn(usize) -> bool| -> BTreeMap { + let spoken_by = |keep: Keep| -> BTreeMap { let mut texts = BTreeMap::new(); for (line, _) in lines.iter().zip(rounds_of).skip(opening).filter(|(line, round)| cast.contains(&line.from.as_str()) && keep(**round)) { let text: &mut String = texts.entry(line.from.clone()).or_default(); @@ -349,7 +497,7 @@ fn metrics(members: &[Member], lines: &[Line], rounds_of: &[usize], opening: usi } texts }; - let prose_by = |keep: &dyn Fn(usize) -> bool| -> BTreeMap { + let prose_by = |keep: Keep| -> BTreeMap { let mut texts = BTreeMap::new(); for turn in turns.iter().filter(|turn| turn["round"].as_u64().is_some_and(|round| keep(round as usize))) { let text: &mut String = texts.entry(turn["id"].as_str().unwrap_or_default().to_owned()).or_default(); @@ -360,31 +508,42 @@ fn metrics(members: &[Member], lines: &[Line], rounds_of: &[usize], opening: usi }; let (all, early, late): (Keep, Keep, Keep) = (&|_| true, &|round| round <= half, &|round| round > half); let mind_lines: Vec<&Line> = lines[opening..].iter().filter(|line| cast.contains(&line.from.as_str())).collect(); + const CAUSES: [&str; 5] = ["addressed_by_human", "human", "addressed_by_mind", "mind", "beat"]; + let count_causes = |these: &[&Value]| -> BTreeMap<&str, usize> { CAUSES.iter().map(|cause| (*cause, these.iter().filter(|turn| turn["woke"] == *cause).count())).collect() }; let wakes_by_round: Vec = (1..=rounds) .map(|round| { let these: Vec<&Value> = turns.iter().filter(|turn| turn["round"] == round).collect(); - let count = |whys: &[&str]| these.iter().filter(|turn| whys.contains(&turn["woke"].as_str().unwrap_or_default())).count(); - json!({ "round": round, "human": count(&["addressed by a human", "a human in her rooms"]), "mind_addressed": count(&["addressed by a Mind"]), "mind_unaddressed": count(&["a message in her rooms"]), "beat": count(&["the beat"]) }) + json!({ "round": round, "causes": count_causes(&these) }) }) .collect(); - let mind_addressed: Vec = turns - .iter() - .filter(|turn| turn["woke"] == "addressed by a Mind") - .flat_map(|turn| turn["addressed_by"].as_array().into_iter().flatten().map(move |by| json!({ "round": turn["round"], "persona": turn["persona"], "from": by["from"], "how": by["how"], "says": by["says"] }))) - .collect(); + let every: Vec<&Value> = turns.iter().collect(); + let mind_woken: Vec<&Value> = turns.iter().filter(|turn| turn["woke"] == "addressed_by_mind").collect(); + let by_how = |how: &str| mind_woken.iter().filter(|turn| turn["how"] == how).count(); + let id_as_text: Vec = mind_woken.iter().filter(|turn| turn["how"] == "id as text").map(|turn| json!({ "round": turn["round"], "persona": turn["persona"], "by": turn["addressed_by"] })).collect(); + let (silent, failed) = (turns.iter().filter(|turn| turn["outcome"] == "silent").count(), turns.iter().filter(|turn| turn["outcome"] == "failed").count()); + let answered = turns.len() - failed; let work = mind_lines.iter().filter(|line| work_talk(&line.says)).count(); + let overlaps: Vec = turns.iter().filter_map(|turn| turn["report"]["renders"][0]["heard_overlap"].as_f64()).collect(); + let narration = json!({ + "mean_heard_overlap": if overlaps.is_empty() { Value::Null } else { json!(overlaps.iter().sum::() / overlaps.len() as f64) }, + "retelling": overlaps.iter().filter(|overlap| **overlap > RETELL_FLAG).count(), + "offers_options": turns.iter().filter(|turn| turn["report"]["renders"][0]["offers_options"] == true).count(), + "narrations": overlaps.len(), + }); json!({ + "narration": narration, "personas": per, "turns": turns.len(), + "wakes": count_causes(&every), + "failed": failed, "mind_messages": mind_lines.len(), - "silence_rate": if turns.is_empty() { Value::Null } else { json!(turns.iter().filter(|turn| turn["said"].is_null()).count() as f64 / turns.len() as f64) }, - "mind_chain_longest": longest, - "mind_chains_of_3_or_more": long_chains, + "silence_rate": if answered == 0 { Value::Null } else { json!(silent as f64 / answered as f64) }, + "reply_chains": reply_chains(lines, causes, opening, &cast), "convergence_lines": { "all": mean_pairwise(&spoken_by(all)), "first_half": mean_pairwise(&spoken_by(early)), "second_half": mean_pairwise(&spoken_by(late)) }, "convergence_prose": { "all": mean_pairwise(&prose_by(all)), "first_half": mean_pairwise(&prose_by(early)), "second_half": mean_pairwise(&prose_by(late)) }, "work_talk_share": if mind_lines.is_empty() { Value::Null } else { json!(work as f64 / mind_lines.len() as f64) }, "wakes_by_round": wakes_by_round, - "mind_addressed": mind_addressed, + "mind_addressed_wakes": { "total": mind_woken.len(), "mention_or_reply": by_how("mention or reply"), "id_as_text": by_how("id as text"), "name_in_text": by_how("name in text"), "id_as_text_wakes": id_as_text }, }) } @@ -397,57 +556,104 @@ fn number(value: &Value) -> String { value.as_f64().map_or_else(|| "n/a".into(), |number| format!("{number:.3}")) } -fn markdown(plan_path: &Path, plan: &SimFile, runs: &[Value]) -> String { +fn policy_words(policy: WakePolicy) -> String { + match policy { + WakePolicy::Live => "live: the operator or another Mind addressing her (the heartbeat's rule today)".into(), + WakePolicy::Ruled => "ruled: a line addressing her, from anyone, and any human line in her rooms".into(), + WakePolicy::HumansPace(cap) => format!("humans_pace (cap {cap}): a human's line wakes a Mind in her own room always, and in a public room when it addresses her or continues an exchange she is in; a Mind's line wakes another only by an explicit mention or a reply, while fewer than {cap} Mind lines in a row came before it in its room, never by a name in prose"), + WakePolicy::NamesWithCap(cap) => format!("names_with_cap {cap}: ruled, but a Mind's line past {cap} Mind lines in a row in its room wakes no one until a human speaks"), + WakePolicy::AllMessages => "all_messages: any line in her rooms, a Mind's too (the old loop, the control)".into(), + } +} + +/// `count` lines spread evenly over the transcript, the first and the last included. +fn representative(transcript: &[Value], count: usize) -> Vec<&Value> { + if transcript.len() <= count { + return transcript.iter().collect(); + } + let mut at: Vec = (0..count).map(|index| index * (transcript.len() - 1) / (count - 1)).collect(); + at.dedup(); + at.into_iter().map(|index| &transcript[index]).collect() +} + +fn transcript_line(line: &Value) -> String { + let who = if line["mind"] == true { line["name"].as_str().unwrap_or_default().to_owned() } else { format!("{} (human)", line["name"].as_str().unwrap_or_default()) }; + let woke = line["woke"].as_str().map_or_else(String::new, |cause| format!(" _(woke: {cause})_")); + format!("- r{} {} **{who}**{woke}: {}", line["round"], line["room"].as_str().unwrap_or_default(), one_line(line["says"].as_str().unwrap_or_default())) +} + +fn markdown(plan_path: &Path, plan: &SimFile, members: &[Member], group_state: Option, runs: &[Value]) -> String { let mut out = String::new(); let _ = writeln!(out, "# Swarm simulation\n"); let _ = writeln!(out, "> **State does not evolve during a run.** The Interpreter (C3b) and the commit (C3c) are not built, so every persona starts each turn from the state the plan gave her. `state_after_turn` in `projection/simulate.rs` is the seam where they will move it between rounds. Freshness carries over: each persona's earlier packets in the run count against repeating an item.\n"); + let _ = writeln!(out, "> **Explicit addressee, stand-in.** Whom a line is to is the Interpreter's to say (C3b). Until then a said line that holds `@handle` of a cast member counts as a Matrix mention of that member; any other name in it is prose and tags no one.\n"); let _ = writeln!(out, "- plan: `{}`", plan_path.display()); - let _ = writeln!(out, "- cast: {}", plan.cast.iter().map(|entry| format!("{} (`{}`, `{}`)", entry.name, entry.id, entry.state.display())).collect::>().join(", ")); - let _ = writeln!(out, "- rooms: {}; rounds: {}; repeats: {}; seed: {}; minutes a round: {}", plan.rooms.join(", "), plan.rounds, plan.repeats, plan.seed, plan.round_minutes); - let _ = writeln!(out, "- wake: {}; beat: {}", match plan.wake { Wake::HumansInRooms => "ruled set (addressed, any human message in her rooms, the beat; another Mind's unaddressed message wakes no one)", Wake::AllMessages => "control: any message in her rooms wakes her, a Mind's too (the old loop)" }, if plan.beat_every == 0 { "off".to_owned() } else { format!("every {} rounds", plan.beat_every) }); + let _ = writeln!(out, "- cast: {}", members.iter().map(|member| format!("{} (`{}`, `{}`, names from {})", member.entry.name, member.entry.id, member.entry.state.display(), member.names_from)).collect::>().join(", ")); + let _ = writeln!(out, "- rooms: {}; rounds: {}; repeats: {}; seed: {}; minutes a round: {}; an exchange ends at a gap over {} min", plan.rooms.join(", "), plan.rounds, plan.repeats, plan.seed, plan.round_minutes, plan.exchange_gap_minutes); + let owners: Vec = members.iter().filter(|member| !member.entry.own_rooms.is_empty()).map(|member| format!("{}: {}", member.entry.name, member.entry.own_rooms.join(", "))).collect(); + let _ = writeln!(out, "- own rooms (from the plan: neither the heartbeat's table nor `persona.env` records room ownership): {}", if owners.is_empty() { "none".to_owned() } else { owners.join("; ") }); + let _ = writeln!(out, "- wake: {}; beat: {}", policy_words(plan.wake), if plan.beat_s == 0 { "off".to_owned() } else { format!("every {} s of simulated time, one Persona by `tempo::pick`", plan.beat_s) }); + let _ = writeln!(out, "- group state in the Projector's packet: {}", match group_state { Some(true) => "on", Some(false) => "off", None => "unknown (the tuning did not load)" }); let _ = writeln!(out, "- speech: the double-quoted spans of her prose, joined, posted to the room she woke in; none is silence. A preview of the Interpreter's speech, not its decision"); - let _ = writeln!(out, "- wakes: a human-caused wake is counted as the human's even when a Mind also addressed her; Mind-addressed wakes are split by evidence (Matrix mention or reply, her id written as text, a name in the text). Spoken lines here carry no Matrix mention, so a Mind addresses another only through text -- convergence is the mean pairwise cosine of speakers' word counts (lexical, cheap); work-talk share is a lexical heuristic over a fixed word list, not a classifier"); + let _ = writeln!(out, "- wakes are counted per wake, by its strongest cause: addressed by a human, a human line, addressed by a Mind, a Mind's line (control only), the beat. A Mind-addressed wake's evidence is its strongest: a Matrix mention or reply, her id written as text, a name in the text"); + let _ = writeln!(out, "- silence rate is per woken turn that did not fail; a failed call is counted apart. Reply chains are per room: Mind lines spoken in turns another Mind's line woke, in a row"); + let _ = writeln!(out, "- convergence is the mean pairwise cosine of speakers' word counts (lexical, cheap); work-talk share is a lexical heuristic over a fixed word list, not a classifier"); let _ = writeln!(out, "- read-only: nothing is posted, no state is put, no Mind is asked\n"); for run in runs { let metrics = &run["metrics"]; + let wakes = &metrics["wakes"]; let _ = writeln!(out, "## Repeat {} (seed {})\n", run["repeat"], run["seed"]); let _ = writeln!(out, "### Metrics\n"); - let _ = writeln!(out, "- turns: {}; Mind messages: {}; silence rate: {}", metrics["turns"], metrics["mind_messages"], number(&metrics["silence_rate"])); - let _ = writeln!(out, "- longest Mind-to-Mind chain with no human between: {}; chains of 3 or more: {}", metrics["mind_chain_longest"], metrics["mind_chains_of_3_or_more"]); + let _ = writeln!( + out, + "- wakes: {} (addressed by a human {}, a human line {}, addressed by a Mind {}, a Mind's line {}, the beat {}); failed {}", + metrics["turns"], wakes["addressed_by_human"], wakes["human"], wakes["addressed_by_mind"], wakes["mind"], wakes["beat"], metrics["failed"] + ); + let _ = writeln!(out, "- Mind messages: {}; silence rate per woken turn: {}", metrics["mind_messages"], number(&metrics["silence_rate"])); + if let Some(rooms) = metrics["reply_chains"].as_object() { + for (room, chain) in rooms { + let _ = writeln!(out, "- reply chains in {room}: longest {}, chains of 3 or more {}, Mind-to-Mind replies {}", chain["longest"], chain["chains_of_3_or_more"], chain["mind_to_mind_replies"]); + } + } + let addressed = &metrics["mind_addressed_wakes"]; + let _ = writeln!(out, "- Mind-addressed wakes: {} (Matrix mention or reply {}, her id written as text {}, a name in the text {})", addressed["total"], addressed["mention_or_reply"], addressed["id_as_text"], addressed["name_in_text"]); let _ = writeln!(out, "- convergence of spoken lines: all {}, first half {}, second half {}", number(&metrics["convergence_lines"]["all"]), number(&metrics["convergence_lines"]["first_half"]), number(&metrics["convergence_lines"]["second_half"])); let _ = writeln!(out, "- convergence of prose: all {}, first half {}, second half {}", number(&metrics["convergence_prose"]["all"]), number(&metrics["convergence_prose"]["first_half"]), number(&metrics["convergence_prose"]["second_half"])); - let _ = writeln!(out, "- work-talk share of Mind lines (heuristic): {}\n", number(&metrics["work_talk_share"])); - let _ = writeln!(out, "| persona | turns | messages | silence rate | addressed |\n|---|---|---|---|---|"); + let _ = writeln!(out, "- work-talk share of Mind lines (heuristic): {}", number(&metrics["work_talk_share"])); + let narration = &metrics["narration"]; + let _ = writeln!(out, "- narrations: {}; mean overlap with what she heard {}; retelling (over {RETELL_FLAG}) {}; offering her options {}\n", narration["narrations"], number(&narration["mean_heard_overlap"]), narration["retelling"], narration["offers_options"]); + let _ = writeln!(out, "| persona | wakes | messages | failed | silence rate | addressed |\n|---|---|---|---|---|---|"); if let Some(personas) = metrics["personas"].as_object() { for (name, row) in personas { - let addressed = row["addressed"].as_object().map(|map| map.iter().map(|(who, count)| format!("{who} {count}")).collect::>().join(", ")).unwrap_or_default(); - let _ = writeln!(out, "| {name} | {} | {} | {} | {addressed} |", row["turns"], row["messages"], number(&row["silence_rate"])); + let named = row["addressed"].as_object().map(|map| map.iter().map(|(who, count)| format!("{who} {count}")).collect::>().join(", ")).unwrap_or_default(); + let _ = writeln!(out, "| {name} | {} | {} | {} | {} | {named} |", row["turns"], row["messages"], row["failed"], number(&row["silence_rate"])); } } - let _ = writeln!(out, "\n### Wakes by round\n\nA wake a human's line would cause is counted as the human's; Mind-addressed wakes are those only a Mind's line caused.\n\n| round | human | Mind-addressed | Mind, unaddressed (control) | beat |\n|---|---|---|---|---|"); + let _ = writeln!(out, "\n### Wakes by round\n\n| round | addressed by a human | a human line | addressed by a Mind | a Mind's line | beat |\n|---|---|---|---|---|---|"); for row in metrics["wakes_by_round"].as_array().into_iter().flatten() { - let _ = writeln!(out, "| {} | {} | {} | {} | {} |", row["round"], row["human"], row["mind_addressed"], row["mind_unaddressed"], row["beat"]); + let causes = &row["causes"]; + let _ = writeln!(out, "| {} | {} | {} | {} | {} | {} |", row["round"], causes["addressed_by_human"], causes["human"], causes["addressed_by_mind"], causes["mind"], causes["beat"]); } - let addressed = metrics["mind_addressed"].as_array().cloned().unwrap_or_default(); - let by_how = |how: &str| addressed.iter().filter(|one| one["how"] == how).count(); - let _ = writeln!(out, "\nMind-addressed wake evidence: {} lines; a Matrix mention or reply {}, her Matrix id written as text {}, a name in the text {}.\n", addressed.len(), by_how("mention or reply"), by_how("id as text"), by_how("name in text")); - let as_text: Vec<&Value> = addressed.iter().filter(|one| one["how"] == "id as text").collect(); + let as_text = addressed["id_as_text_wakes"].as_array().cloned().unwrap_or_default(); if !as_text.is_empty() { - let _ = writeln!(out, "Wakes where the only address was an id written as text (no mention, no reply):\n"); + let _ = writeln!(out, "\nWakes whose only address was an id written as text (no mention, no reply):\n"); for one in as_text { - let _ = writeln!(out, "- r{} {} woken by {}: {}", one["round"], one["persona"].as_str().unwrap_or_default(), one["from"].as_str().unwrap_or_default(), one_line(one["says"].as_str().unwrap_or_default())); + let by = one["by"].as_array().into_iter().flatten().map(|by| format!("{}: {}", by["from"].as_str().unwrap_or_default(), one_line(by["says"].as_str().unwrap_or_default()))).collect::>().join("; "); + let _ = writeln!(out, "- r{} {}: {by}", one["round"], one["persona"].as_str().unwrap_or_default()); } } + let transcript = run["transcript"].as_array().cloned().unwrap_or_default(); + let _ = writeln!(out, "\n### Representative lines\n"); + for line in representative(&transcript, REPRESENTATIVE_LINES) { + let _ = writeln!(out, "{}", transcript_line(line)); + } let _ = writeln!(out, "\n### Transcript\n"); - for line in run["transcript"].as_array().into_iter().flatten() { - let who = if line["mind"] == true { line["name"].as_str().unwrap_or_default().to_owned() } else { format!("{} (human)", line["name"].as_str().unwrap_or_default()) }; - let _ = writeln!(out, "- r{} {} **{who}**: {}", line["round"], line["room"].as_str().unwrap_or_default(), one_line(line["says"].as_str().unwrap_or_default())); + for line in &transcript { + let _ = writeln!(out, "{}", transcript_line(line)); } let _ = writeln!(out, "\n### Turns\n"); for turn in run["turns"].as_array().into_iter().flatten() { - let said = if turn["said"].is_null() { "silent".to_owned() } else { "spoke".to_owned() }; - let _ = writeln!(out, "
round {}, {} (woke: {}, {} turn, {}): {said}\n", turn["round"], turn["persona"].as_str().unwrap_or_default(), turn["woke"].as_str().unwrap_or_default(), turn["kind"].as_str().unwrap_or_default(), turn["room"].as_str().unwrap_or_default()); + let _ = writeln!(out, "
round {}, {} (woke: {}, {} turn, {}): {}\n", turn["round"], turn["persona"].as_str().unwrap_or_default(), turn["woke"].as_str().unwrap_or_default(), turn["kind"].as_str().unwrap_or_default(), turn["room"].as_str().unwrap_or_default(), turn["outcome"].as_str().unwrap_or_default()); let report = &turn["report"]; if let Some(error) = report.get("error") { let _ = writeln!(out, "**failed:** {}\n", error.as_str().unwrap_or_default()); diff --git a/crates/mind-body/src/projection/simulate/tests.rs b/crates/mind-body/src/projection/simulate/tests.rs index eb97908..579b831 100644 --- a/crates/mind-body/src/projection/simulate/tests.rs +++ b/crates/mind-body/src/projection/simulate/tests.rs @@ -4,6 +4,7 @@ use serde_json::Value; use super::*; use crate::projection::harness::tests::{Scripted, control}; +use crate::projection::{Answer, Failed, Model, Spent}; const TOBIAH: &str = "@eureka:gamecult.org"; const LIBBY: &str = "@libby:gamecult.org"; @@ -18,18 +19,21 @@ fn cast(dir: &Path) { std::fs::write(dir.join("libby.json"), libby.to_string()).unwrap(); } +/// A plan over the two, the operator opening; `wake` is the TOML value of the policy; no beat unless `extra` sets one. fn plan(dir: &Path, wake: &str, rounds: usize, extra: &str) -> PathBuf { cast(dir); let path = dir.join("plan.toml"); + let beat = if extra.contains("beat_s") { "" } else { "beat_s = 0\n" }; std::fs::write( &path, format!( r##"rounds = {rounds} seed = 11 -wake = "{wake}" +wake = {wake} start = "2026-11-20T15:00:00Z" rooms = ["#minds:gamecult.org"] operators = ["@meta:gamecult.org"] +{beat}{extra} [[cast]] id = "{TOBIAH}" name = "Tobiah" @@ -43,33 +47,38 @@ from = "@meta:gamecult.org" name = "Meta" room = "#minds:gamecult.org" says = "good afternoon, everyone" -{extra}"## +"## ), ) .unwrap(); path } -/// Both speak every turn, neither naming the other: a Mind line wakes no one under the ruled set. -fn chatty() -> Scripted { - Scripted::new(|prompt| if prompt.contains("Who you are:\nTobiah") { "\"what a day\" he says".into() } else { "\"mm, the deploy went fine\" she says".into() }) +fn is_tobiah(prompt: &str) -> bool { + prompt.contains("Who you are:\nTobiah") } -fn run_plan(path: &Path, model: &Scripted) -> (SimFile, Vec, Value) { +/// Both speak every turn, neither naming the other. +fn chatty() -> Scripted { + Scripted::new(|prompt| if is_tobiah(prompt) { "\"what a day\" he says".into() } else { "\"mm, the deploy went fine\" she says".into() }) +} + +/// Both speak every turn, each naming the other. +fn namers() -> Scripted { + Scripted::new(|prompt| if is_tobiah(prompt) { "\"Libby, tea?\"".into() } else { "\"Tobiah, yes please.\"".into() }) +} + +fn silent() -> Scripted { + Scripted::new(|_| "Nobody needs anything from her.".into()) +} + +fn run_plan(path: &Path, model: &dyn Model) -> (Vec, Value) { let plan: SimFile = toml::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); let base = path.parent().unwrap(); - let mut members: Vec = plan - .cast - .iter() - .map(|entry| { - let state = state_file(&base.join(&entry.state), localpart(&entry.id)).unwrap(); - let public = state["publicName"].as_str().unwrap().to_owned(); - Member { addressee: Addressee::new(&entry.id, [localpart(&entry.id), entry.name.as_str(), public.as_str()]), entry: entry.clone(), state, rooms: plan.rooms.clone() } - }) - .collect(); + let mut members = cast_of(&plan, base).unwrap(); let harness = Harness { instance: "eureka".into(), persona: None, model: Some(model), tuning: base.join("persona-tuning.toml") }; let run = run(&harness, &plan, &mut members, 0).unwrap(); - (plan, members, run) + (members, run) } fn turns(run: &Value) -> Vec<(u64, String, String)> { @@ -77,68 +86,180 @@ fn turns(run: &Value) -> Vec<(u64, String, String)> { } #[test] -fn under_the_ruled_wake_set_a_minds_unaddressed_line_wakes_no_one() { +fn the_wake_policies_are_the_heartbeats_one_function() { + let libby = Addressee::new(LIBBY, ["libby", "Libby"]); + let line = |from: &str, says: &str| Line { from: from.into(), name: String::new(), room: "#minds:x".into(), at_ms: 0, says: says.into(), mentions: vec![], dm_to: None, follow_up: false, reply_to: None, new: false }; + let ask = |policy: WakePolicy, from: &str, says: &str, speaker: Speaker, run: usize| wakes(policy, &libby, &line(from, says).delivery(0, LIBBY, &[]), speaker, LineFacts { mind_run: run, ..LineFacts::default() }); + let paced = |says: &str, own_room: bool, in_exchange: bool| wakes(WakePolicy::HumansPace(4), &libby, &line("@meta:x", says).delivery(0, LIBBY, &[]), Speaker::Operator, LineFacts { mind_run: 0, own_room, in_exchange }); + let (named, unnamed) = ("Libby, tea?", "what a day"); + use WakeCause::*; + // Ruled: anyone addressing her, any human line. + assert_eq!(ask(WakePolicy::Ruled, TOBIAH, named, Speaker::Mind, 0), Some(AddressedByMind)); + assert_eq!(ask(WakePolicy::Ruled, TOBIAH, unnamed, Speaker::Mind, 0), None, "another Mind's unaddressed line wakes no one"); + assert_eq!(ask(WakePolicy::Ruled, "@deru:x", unnamed, Speaker::Member, 0), Some(Human)); + assert_eq!(ask(WakePolicy::Ruled, "@deru:x", named, Speaker::Member, 0), Some(AddressedByHuman)); + // Live, the heartbeat's today: a member's line does not wake her, the operator's or a Mind's address does. + assert_eq!(ask(WakePolicy::Live, "@deru:x", named, Speaker::Member, 0), None); + assert_eq!(ask(WakePolicy::Live, "@meta:x", named, Speaker::Operator, 0), Some(AddressedByHuman)); + assert_eq!(ask(WakePolicy::Live, TOBIAH, named, Speaker::Mind, 0), Some(AddressedByMind)); + assert_eq!(ask(WakePolicy::Live, "@meta:x", unnamed, Speaker::Operator, 0), None); + // Humans pace: a Mind's line never wakes a Mind; a human's wakes her in her own room, or in a public room when it + // addresses her or continues an exchange she is in. + assert_eq!(ask(WakePolicy::HumansPace(4), TOBIAH, named, Speaker::Mind, 0), None, "a name in prose wakes no one"); + let tagged = Line { mentions: vec![LIBBY.into()], ..line(TOBIAH, unnamed) }; + let explicit = |run: usize| wakes(WakePolicy::HumansPace(4), &libby, &tagged.delivery(0, LIBBY, &[]), Speaker::Mind, LineFacts { mind_run: run, ..LineFacts::default() }); + assert_eq!(explicit(3), Some(AddressedByMind), "a Matrix mention by a Mind wakes her, in any room"); + assert_eq!(explicit(4), None, "the backstop: past the cap of Mind lines in a row, no Mind wakes another"); + assert_eq!(paced(unnamed, false, false), None, "a public room's human line that is not hers to answer"); + assert_eq!(paced(unnamed, true, false), Some(Human)); + assert_eq!(paced(unnamed, false, true), Some(Human)); + assert_eq!(paced(named, false, false), Some(AddressedByHuman)); + // The cap: a Mind's address wakes her only while the Mind run before the line is under it. + assert_eq!(ask(WakePolicy::NamesWithCap(2), TOBIAH, named, Speaker::Mind, 1), Some(AddressedByMind)); + assert_eq!(ask(WakePolicy::NamesWithCap(2), TOBIAH, named, Speaker::Mind, 2), None); + assert_eq!(ask(WakePolicy::NamesWithCap(2), "@meta:x", unnamed, Speaker::Operator, 9), Some(Human), "a human always may"); + // The control, and her own line never. + assert_eq!(ask(WakePolicy::AllMessages, TOBIAH, unnamed, Speaker::Mind, 0), Some(Mind)); + assert_eq!(ask(WakePolicy::AllMessages, LIBBY, named, Speaker::Her, 0), None); +} + +#[test] +fn under_the_ruled_set_unaddressed_mind_lines_wake_no_one() { let dir = tempfile::tempdir().unwrap(); - let (_, _, run) = run_plan(&plan(dir.path(), "humans_in_rooms", 6, ""), &chatty()); + let (_, run) = run_plan(&plan(dir.path(), "\"ruled\"", 6, ""), &chatty()); let turns = turns(&run); assert_eq!(turns.len(), 2, "the operator's opening wakes both in round 1, and then nothing does: {turns:?}"); - assert!(turns.iter().all(|(round, _, why)| *round == 1 && why == "a human in her rooms"), "{turns:?}"); - let transcript = run["transcript"].as_array().unwrap(); - assert_eq!(transcript.len(), 3); - assert!(transcript.iter().any(|line| line["from"] == TOBIAH && line["says"] == "what a day" && line["mind"] == true), "her quoted words join the room as from her id: {transcript:?}"); + assert!(turns.iter().all(|(round, _, why)| *round == 1 && why == "human"), "{turns:?}"); + assert!(run["transcript"].as_array().unwrap().iter().any(|line| line["from"] == TOBIAH && line["says"] == "what a day" && line["woke"] == "human"), "her quoted words join the room as from her id"); } #[test] -fn the_old_loop_control_lets_minds_wake_each_other_into_a_chain() { +fn the_control_lets_minds_wake_each_other_into_a_reply_chain_counted_per_room() { let dir = tempfile::tempdir().unwrap(); - let (_, _, run) = run_plan(&plan(dir.path(), "all_messages", 6, ""), &chatty()); - let turns = turns(&run); - assert!(turns.len() >= 6, "every round someone answers a Mind: {turns:?}"); - assert!(turns.iter().any(|(_, _, why)| why == "a message in her rooms")); + let (_, run) = run_plan(&plan(dir.path(), "\"all_messages\"", 6, ""), &chatty()); let metrics = &run["metrics"]; - assert!(metrics["mind_chain_longest"].as_u64().unwrap() >= 5, "{metrics}"); - assert!(metrics["mind_chains_of_3_or_more"].as_u64().unwrap() >= 1); - assert_eq!(metrics["silence_rate"].as_f64(), Some(0.0)); + assert!(metrics["wakes"]["mind"].as_u64().unwrap() >= 5, "{metrics}"); + let chain = &metrics["reply_chains"]["#minds:gamecult.org"]; + // The two round-1 answers are to the operator; every later line is a reply to a Mind. + assert_eq!(chain["mind_to_mind_replies"].as_u64(), Some(metrics["mind_messages"].as_u64().unwrap() - 2), "{metrics}"); + assert!(chain["longest"].as_u64().unwrap() >= 5 && chain["chains_of_3_or_more"] == 1, "{chain}"); let work = metrics["work_talk_share"].as_f64().unwrap(); assert!(work > 0.3 && work < 0.7, "Libby's lines name the deploy, Tobiah's do not: {work}"); - assert!(metrics["convergence_lines"]["all"].as_f64().unwrap() < 0.5, "two different lines are not one voice: {metrics}"); } #[test] -fn a_scripted_interjection_wakes_everyone_in_her_room_and_addressing_is_counted() { +fn naming_runs_away_under_the_ruled_set_and_stops_at_the_cap() { let dir = tempfile::tempdir().unwrap(); - let interjection = "[[message]]\nround = 4\nfrom = \"@deru:gamecult.org\"\nname = \"Deru\"\nroom = \"#minds:gamecult.org\"\nsays = \"kettle news\"\n"; - let model = Scripted::new(|prompt| if prompt.contains("Who you are:\nTobiah") { "\"Libby, tea?\"".into() } else { "She does not answer.".into() }); - let (_, members, run) = run_plan(&plan(dir.path(), "humans_in_rooms", 5, interjection), &model); + let (_, ruled) = run_plan(&plan(dir.path(), "\"ruled\"", 6, ""), &namers()); + assert!(turns(&ruled).iter().filter(|(_, _, why)| why == "addressed_by_mind").count() >= 5, "{:?}", turns(&ruled)); + assert_eq!(ruled["metrics"]["mind_addressed_wakes"]["name_in_text"], ruled["metrics"]["mind_addressed_wakes"]["total"]); + let dir = tempfile::tempdir().unwrap(); + let (_, capped) = run_plan(&plan(dir.path(), "{ names_with_cap = 2 }", 6, ""), &namers()); + let capped = turns(&capped); + assert!(capped.iter().all(|(round, _, _)| *round <= 2), "after two Mind lines in a row no Mind's address wakes anyone: {capped:?}"); + let dir = tempfile::tempdir().unwrap(); + let (_, paced) = run_plan(&plan(dir.path(), "{ humans_pace = 4 }", 6, ""), &namers()); + assert!(turns(&paced).is_empty(), "under humans_pace an unaddressed public line wakes no one, and no Mind's line ever does"); +} + +#[test] +fn under_humans_pace_her_own_room_wakes_her_and_a_public_room_only_by_address_or_her_exchange() { + let dir = tempfile::tempdir().unwrap(); + cast(dir.path()); + let path = dir.path().join("plan.toml"); + let line = |round: usize, room: &str, says: &str| format!("[[message]]\nround = {round}\nfrom = \"@meta:gamecult.org\"\nname = \"Meta\"\nroom = \"{room}\"\nsays = \"{says}\"\n"); + std::fs::write( + &path, + format!( + "rounds = 4\nseed = 11\nwake = {{ humans_pace = 4 }}\nbeat_s = 0\nstart = \"2026-11-20T15:00:00Z\"\nrooms = [\"#minds:gamecult.org\", \"#tobiah:gamecult.org\"]\noperators = [\"@meta:gamecult.org\"]\n[[cast]]\nid = \"{TOBIAH}\"\nname = \"Tobiah\"\nstate = \"tobiah.json\"\nown_rooms = [\"#tobiah:gamecult.org\"]\n[[cast]]\nid = \"{LIBBY}\"\nname = \"Libby\"\nstate = \"libby.json\"\n{}{}{}", + line(0, "#minds:gamecult.org", "Libby, how was the gig?"), + line(2, "#minds:gamecult.org", "and the rest of you?"), + line(3, "#tobiah:gamecult.org", "quiet in here today") + ), + ) + .unwrap(); + let (members, run) = run_plan(&path, &namers()); let turns = turns(&run); - let fourth: Vec<&String> = turns.iter().filter(|(round, _, _)| *round == 4).map(|(_, who, _)| who).collect(); - assert_eq!(fourth.len(), 2, "Deru's line at round 4 wakes both: {turns:?}"); - assert_eq!(run["metrics"]["personas"]["Tobiah"]["addressed"]["Libby"].as_u64().unwrap(), run["metrics"]["personas"]["Tobiah"]["messages"].as_u64().unwrap()); - let rounds = run["metrics"]["wakes_by_round"].as_array().unwrap(); - assert_eq!((rounds[0]["human"].as_u64(), rounds[3]["human"].as_u64()), (Some(2), Some(2)), "the opening and Deru wake both: {rounds:?}"); - let by_minds: u64 = rounds.iter().map(|row| row["mind_addressed"].as_u64().unwrap()).sum(); - assert_eq!(by_minds as usize, run["metrics"]["mind_addressed"].as_array().unwrap().len(), "one line addressed each Mind-addressed wake"); - assert_eq!(run["metrics"]["personas"]["Libby"]["silence_rate"].as_f64(), Some(1.0)); - // The seam: no state moved. - assert_eq!(members[0].state, control()); + assert_eq!( + turns, + vec![(1, "Libby".to_owned(), "addressed_by_human".to_owned()), (2, "Libby".to_owned(), "human".to_owned()), (3, "Tobiah".to_owned(), "human".to_owned())], + "named in #minds, then her exchange there, then his own room; Libby's naming Tobiah wakes no one" + ); + assert_eq!(members[0].state, control(), "the seam: no state moved"); } #[test] -fn the_same_seed_replays_the_same_order() { +fn the_beat_wakes_one_persona_by_the_heartbeats_pick() { let dir = tempfile::tempdir().unwrap(); - let path = plan(dir.path(), "all_messages", 4, ""); - let (_, _, first) = run_plan(&path, &chatty()); - let (_, _, second) = run_plan(&path, &chatty()); - assert_eq!(turns(&first), turns(&second)); + let (_, run) = run_plan(&plan(dir.path(), "\"ruled\"", 4, "beat_s = 120"), &silent()); + let turns = turns(&run); + for round in 2..=4 { + let beats: Vec<&(u64, String, String)> = turns.iter().filter(|(at, _, _)| *at == round).collect(); + assert_eq!(beats.len(), 1, "one wake a beat: {turns:?}"); + assert_eq!(beats[0].2, "beat"); + } + // The pick takes whoever waited longest: the two alternate. + assert_ne!(turns[2].1, turns[3].1, "{turns:?}"); + assert_eq!(run["metrics"]["silence_rate"].as_f64(), Some(1.0)); +} + +/// A model whose Persona stage fails: a failure, never a silence. +struct FailingPersona; + +impl Model for FailingPersona { + fn ask(&self, _request_id: &str, model: &str, prompt: &str) -> std::result::Result { + if prompt.starts_with("