Harness fixes: one wake rule in the heartbeat, the heartbeat's beat, group state in the Projector #80

Merged
eureka merged 2 commits from hands/harness-fixes into main 2026-11-20 03:34:37 +00:00
17 changed files with 1250 additions and 292 deletions

View file

@ -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…

View file

@ -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

View file

@ -17,7 +17,8 @@
//! [--room <fixture.toml>] [--seed N] [--state <file>] [--select-only | --renders K [--through projector|persona]
//! [--judge <state-file>]]` 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.
//!

View file

@ -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<PersonaId>, operators: Vec<String>, beat_s: u32) -> Result<Self> {
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<Name>, Vec<Org
Ok((names, repos))
}
/// Whether a delivery wakes `who` off the beat: the operator or another Mind of
/// the roster addresses her. A Mind naming herself does not; a member does not.
fn wakes(config: &Config, who: &Addressee, delivery: &ChatDelivery) -> 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<WakeCause> {
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<Outcome> {
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))
};

View file

@ -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]

View file

@ -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<RoomLine> = 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,
})

View file

@ -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.

View file

@ -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<Value> {
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<String>,
/// 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<String>,
/// 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<String>,
pub dm: bool,
/// A direct message, to this Matrix id: only its sender and its recipient see it.
pub dm_to: Option<String>,
pub follow_up: bool,
/// The index of the line it replies to.
pub reply_to: Option<usize>,
@ -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<Basis> {
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<TailLine> = 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");

View file

@ -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<String> {
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}");
}

View file

@ -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<char> = 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::<Vec<_>>().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<String> = 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.

View file

@ -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<String>,
pub selected: Vec<Pick>,
/// 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<f64> {
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<String> {
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<String>, 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::<Vec<_>>().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<String>, 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<String> {
fn lines(&self, obj: &str, render: impl Fn(&RoomLine, &str) -> String) -> Vec<String> {
let mut lines: Vec<String> = 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<String> = 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(&section);
}
@ -747,8 +782,9 @@ fn beat_stimulus(inputs: &Inputs, tuning: &Tuning) -> String {
fn reflection_stimulus(inputs: &Inputs, tuning: &Tuning) -> String {
let lines: Vec<String> = 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<String> {
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<String> {
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<String> {
[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<String> {
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<String> = Vec::new();
let mut talk: Vec<String> = 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<String> {
let mut seen: Vec<&str> = Vec::new();
let mut parts: Vec<String> = 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<Utc>, at_ms: u64) -> i64 {
let at = i64::try_from(at_ms).ok().and_then(DateTime::<Utc>::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<String> = 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<String> = [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<String> = 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) }
}

View file

@ -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<Utc>,
rooms: Vec<String>,
#[serde(default)]
operators: Vec<String>,
/// 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<PathBuf>,
cast: Vec<CastEntry>,
#[serde(default, rename = "message")]
script: Vec<Message>,
@ -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<String>,
/// 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<String>,
own_rooms: Vec<String>,
}
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<String>,
}
@ -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<usize> {
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<Value>)> {
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<Value>,
}
/// 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<Woken> {
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<usize> = 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<WakeCause>) -> &'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<String> {
let tagged: Vec<String> = 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<String> {
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<Value> = (0..plan.repeats).map(|repeat| run(harness, &plan, &mut members, repeat)).collect::<Result<_>>()?;
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<Vec<Member>> {
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::<Vec<_>>();
(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<Value> = (0..plan.repeats).map(|repeat| run(harness, &plan, &mut members, repeat)).collect::<Result<_>>()?;
Ok(markdown(plan_path, &plan, &runs))
Ok(members)
}
fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) -> Result<Value> {
@ -216,32 +311,61 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize)
let cast: Vec<String> = 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<Line> = 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<usize> = Vec::new();
let scripted = |round: usize, lines: &mut Vec<Line>, rounds_of: &mut Vec<usize>| -> Result<()> {
let mut causes: Vec<Option<&'static str>> = Vec::new();
let scripted = |round: usize, lines: &mut Vec<Line>, rounds_of: &mut Vec<usize>, causes: &mut Vec<Option<&'static str>>| -> 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<Option<DateTime<Utc>>> = vec![None; members.len()];
let mut last_beat = plan.start;
let mut recent: Vec<Vec<Vec<String>>> = 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<Value>))> = 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<Woken>)> = 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<Standing> = 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<String> = 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<Value> = 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<Value> = 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<String, String>) -> Option<f64> {
/// 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<String, (usize, usize, usize, usize)> = 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<String, Value> = 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<String, String> {
let spoken_by = |keep: Keep| -> BTreeMap<String, String> {
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<String, String> {
let prose_by = |keep: Keep| -> BTreeMap<String, String> {
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<Value> = (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<Value> = 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<Value> = 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<f64> = 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::<f64>() / 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<usize> = (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<bool>, 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::<Vec<_>>().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::<Vec<_>>().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<String> = 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::<Vec<_>>().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::<Vec<_>>().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::<Vec<_>>().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, "<details><summary>round {}, {} (woke: {}, {} turn, {}): {said}</summary>\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, "<details><summary>round {}, {} (woke: {}, {} turn, {}): {}</summary>\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());

View file

@ -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<Member>, 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<Member>, Value) {
let plan: SimFile = toml::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
let base = path.parent().unwrap();
let mut members: Vec<Member> = 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<Answer, Failed> {
if prompt.starts_with("<!-- membrane:") {
Ok(Answer { text: "The room is slow.".into(), usage: None })
} else {
Err(Failed { reason: "the provider failed the call: Overloaded".into(), usage: Some(Spent { model: model.into(), input_tokens: 5, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0, reasoning_tokens: None }) })
}
}
}
#[test]
fn the_report_names_the_state_gap_and_carries_the_transcript_and_usage() {
fn a_failed_call_is_a_failure_and_not_a_silence() {
let dir = tempfile::tempdir().unwrap();
let (_, run) = run_plan(&plan(dir.path(), "\"ruled\"", 2, ""), &FailingPersona);
let metrics = &run["metrics"];
assert_eq!((metrics["failed"].as_u64(), metrics["silence_rate"].is_null()), (Some(2), true), "{metrics}");
assert!(run["turns"].as_array().unwrap().iter().all(|turn| turn["outcome"] == "failed" && turn["failed"].as_str().unwrap().contains("Overloaded")));
}
#[test]
fn a_seed_replays_its_order_and_another_seed_changes_it() {
let items: Vec<usize> = (0..8).collect();
assert_eq!(shuffled(items.clone(), 1), shuffled(items.clone(), 1));
assert_ne!(shuffled(items.clone(), 1), shuffled(items.clone(), 2));
let mut sorted = shuffled(items.clone(), 2);
sorted.sort_unstable();
assert_eq!(sorted, items, "a shuffle, nothing lost");
let dir = tempfile::tempdir().unwrap();
let path = plan(dir.path(), "\"all_messages\"", 4, "");
assert_eq!(turns(&run_plan(&path, &chatty()).1), turns(&run_plan(&path, &chatty()).1));
}
#[test]
fn an_at_handle_in_a_said_line_is_a_mention_and_its_wakes_are_counted_once() {
let dir = tempfile::tempdir().unwrap();
let model = Scripted::new(|prompt| if is_tobiah(prompt) { "\"ask @libby:gamecult.org, and Libby too\"".into() } else { "\"Tobiah?\"".into() });
assert_eq!(explicit_mentions("ask @libby:gamecult.org, and Libby too", &[TOBIAH.into(), LIBBY.into()]), [LIBBY.to_owned()]);
assert_eq!(explicit_mentions("@Libby, tea? Tobiah says hi", &[TOBIAH.into(), LIBBY.into()]), [LIBBY.to_owned()], "an @handle tags, a bare name does not");
let (_, run) = run_plan(&plan(dir.path(), "\"ruled\"", 3, ""), &model);
let addressed = &run["metrics"]["mind_addressed_wakes"];
let libby_mind_wakes = turns(&run).iter().filter(|(_, who, why)| who == "Libby" && why == "addressed_by_mind").count();
assert!(libby_mind_wakes >= 1, "{:?}", turns(&run));
assert_eq!(addressed["total"].as_u64().unwrap() as usize, turns(&run).iter().filter(|(_, _, why)| why == "addressed_by_mind").count());
assert_eq!(addressed["mention_or_reply"].as_u64().unwrap() as usize, libby_mind_wakes, "the stand-in mention is the strongest evidence of each wake, once per wake: {addressed}");
assert_eq!(addressed["id_as_text"].as_u64(), Some(0));
}
#[test]
fn the_report_names_its_gaps_and_carries_representative_lines_and_usage() {
let dir = tempfile::tempdir().unwrap();
let model = chatty();
let harness = Harness { instance: "eureka".into(), persona: None, model: Some(&model), tuning: dir.path().join("persona-tuning.toml") };
let report = simulate(&harness, &plan(dir.path(), "humans_in_rooms", 3, "")).unwrap();
for part in ["# Swarm simulation", "State does not evolve during a run", "## Repeat 1 (seed 11)", "### Transcript", "**Meta (human)**: good afternoon, everyone", "**Tobiah**: what a day", "<details><summary>round 1, ", "### Wakes by round", "| 1 | 2 | 0 | 0 | 0 |", "## Total usage", "| claude-sonnet-5-5 | 4 |"] {
let report = simulate(&harness, &plan(dir.path(), "\"ruled\"", 3, "")).unwrap();
for part in ["# Swarm simulation", "State does not evolve during a run", "Explicit addressee, stand-in", "group state in the Projector's packet: on", "### Representative lines", "**Meta (human)**: good afternoon, everyone", "**Tobiah** _(woke: human)_: what a day", "### Wakes by round", "| 1 | 0 | 2 | 0 | 0 | 0 |", "## Total usage", "| claude-sonnet-5-5 | 4 |"] {
assert!(report.contains(part), "{part}\n{report}");
}
}
@ -148,7 +269,7 @@ fn a_cast_past_eight_or_a_foreign_state_is_refused() {
let dir = tempfile::tempdir().unwrap();
let model = chatty();
let harness = Harness { instance: "eureka".into(), persona: None, model: Some(&model), tuning: dir.path().join("persona-tuning.toml") };
let path = plan(dir.path(), "humans_in_rooms", 2, "");
let path = plan(dir.path(), "\"ruled\"", 2, "");
let text = std::fs::read_to_string(&path).unwrap().replace("state = \"libby.json\"", "state = \"tobiah.json\"");
std::fs::write(&path, text).unwrap();
assert!(format!("{:#}", simulate(&harness, &path).unwrap_err()).contains("refused by a put"), "Libby cannot hold Eureka's state");
@ -158,26 +279,16 @@ fn a_cast_past_eight_or_a_foreign_state_is_refused() {
}
#[test]
fn wake_reason_is_the_ruled_set_and_the_control_widens_it_to_minds() {
let libby = Member { addressee: Addressee::new(LIBBY, ["libby", "Libby"]), entry: CastEntry { id: LIBBY.into(), name: "Libby".into(), state: PathBuf::new(), rooms: vec![], names: vec![] }, state: Value::Null, rooms: vec!["#minds:x".into()] };
let cast = vec![TOBIAH.to_owned(), LIBBY.to_owned()];
let line = |from: &str, room: &str, says: &str| Line { from: from.into(), name: String::new(), room: room.into(), at_ms: 0, says: says.into(), mentions: vec![], dm: false, follow_up: false, reply_to: None, new: false };
let reason = |lines: &[Line], wake: Wake, beat: bool| wake_reason(lines, 0, &libby, &cast, wake, beat).map(|(why, _)| why);
let named = [line(TOBIAH, "#minds:x", "Libby, tea?")];
let unnamed = [line(TOBIAH, "#minds:x", "what a day")];
let human = [line("@deru:x", "#minds:x", "kettle news")];
let elsewhere = [line("@deru:x", "#other:x", "kettle news")];
assert_eq!(reason(&named, Wake::HumansInRooms, false), Some("addressed by a Mind"));
let by_id = [line(TOBIAH, "#minds:x", "ask @libby:gamecult.org about it")];
let (why, by) = wake_reason(&by_id, 0, &libby, &cast, Wake::HumansInRooms, false).unwrap();
assert_eq!((why, by[0]["how"].as_str()), ("addressed by a Mind", Some("id as text")));
assert_eq!(wake_reason(&named, 0, &libby, &cast, Wake::HumansInRooms, false).unwrap().1[0]["how"], "name in text");
let both = [line(TOBIAH, "#minds:x", "Libby, tea?"), line("@deru:x", "#minds:x", "Libby, kettle?")];
assert_eq!(reason(&both, Wake::HumansInRooms, false), Some("addressed by a human"), "a human's address outranks a Mind's");
assert_eq!(reason(&unnamed, Wake::HumansInRooms, false), None, "another Mind's unaddressed line wakes no one");
assert_eq!(reason(&unnamed, Wake::AllMessages, false), Some("a message in her rooms"));
assert_eq!(reason(&human, Wake::HumansInRooms, false), Some("a human in her rooms"));
assert_eq!(reason(&elsewhere, Wake::HumansInRooms, false), None, "not her room");
assert_eq!(reason(&unnamed, Wake::HumansInRooms, true), Some("the beat"));
assert!(wake_reason(&named, 1, &libby, &cast, Wake::HumansInRooms, false).is_none(), "a line she has seen is not new");
fn a_scripted_direct_message_reaches_and_wakes_only_its_recipient() {
let dir = tempfile::tempdir().unwrap();
let path = plan(dir.path(), "\"ruled\"", 2, "");
let dm = "[[message]]\nround = 1\nfrom = \"@meta:gamecult.org\"\nname = \"Meta\"\nroom = \"!dm-libby:gamecult.org\"\ndm = true\nto = \"@libby:gamecult.org\"\nsays = \"just you, how are you?\"\n";
let text = std::fs::read_to_string(&path).unwrap().replace("[[message]]\nfrom = \"@meta:gamecult.org\"\nname = \"Meta\"\nroom = \"#minds:gamecult.org\"\nsays = \"good afternoon, everyone\"\n", dm);
std::fs::write(&path, &text).unwrap();
let (_, run) = run_plan(&path, &silent());
assert_eq!(turns(&run), vec![(1, "Libby".to_owned(), "addressed_by_human".to_owned())], "only the recipient sees it, and it is for her");
std::fs::write(&path, text.replace("to = \"@libby:gamecult.org\"\n", "")).unwrap();
let model = silent();
let harness = Harness { instance: "eureka".into(), persona: None, model: Some(&model), tuning: dir.path().join("persona-tuning.toml") };
assert!(format!("{:#}", simulate(&harness, &path).unwrap_err()).contains("name its recipient"), "a direct message without a recipient is refused");
}

View file

@ -144,8 +144,8 @@ fn the_same_seed_replays_the_same_packet() {
fn present_people_get_their_bond_line_in_words_and_absent_people_none() {
let packet = packet_of(TurnKind::Chat, &state(), &chat_room(), &History::default(), 1);
assert_eq!(packet.present, ["Kiko", "Libby"], "newest first");
assert!(packet.context.contains("- bond [bond-kiko] Kiko, sparring partner: fair trust, heavy friction."), "{}", packet.context);
assert!(packet.context.contains("- bond [bond-libby] Libby, collaborator: fair trust, a little friction."), "{}", packet.context);
assert!(packet.context.contains("- bond [bond-kiko] Kiko \u{2014} sparring partner: fair trust, heavy friction."), "{}", packet.context);
assert!(packet.context.contains("- bond [bond-libby] Libby \u{2014} collaborator: fair trust, a little friction."), "{}", packet.context);
assert!(!packet.context.contains("bond-operator"), "the operator is not here");
assert!(!packet.context.contains("0.6") && !packet.context.contains("0.15"), "numbers reach the packet as words: {}", packet.context);
}
@ -157,21 +157,21 @@ fn two_states_differing_in_one_bonds_tension_give_different_packets() {
let room = chat_room();
let (tense, easy) = (packet_of(TurnKind::Chat, &state(), &room, &History::default(), 3), packet_of(TurnKind::Chat, &eased, &room, &History::default(), 3));
assert_ne!(tense.context, easy.context);
assert!(tense.context.contains("Kiko, sparring partner: fair trust, heavy friction") && easy.context.contains("Kiko, sparring partner: fair trust, easy between them"));
assert!(tense.context.contains("Kiko \u{2014} sparring partner: fair trust, heavy friction") && easy.context.contains("Kiko \u{2014} sparring partner: fair trust, easy between them"));
}
#[test]
fn mood_is_movement_since_her_last_turn() {
let room = chat_room();
let first = packet_of(TurnKind::Chat, &state(), &room, &History::default(), 1);
assert!(first.context.contains("- mood, with no earlier turn to measure from: lighter, more settled than middling"), "{}", first.context);
assert!(first.context.contains("- mood: lighter, more settled than middling"), "{}", first.context);
let mut before = state();
before["activationProfile"]["situationalState"]["valence"]["currentActivation"] = json!(0.5);
before["activationProfile"]["situationalState"]["arousal"]["currentActivation"] = json!(0.41);
let moved = packet_of(TurnKind::Chat, &state(), &room, &History { previous: Some(before), ..History::default() }, 1);
assert!(moved.context.contains("- mood: lighter than at her last turn"), "{}", moved.context);
let none = packet_of(TurnKind::Chat, &json!({ "publicName": "Eureka" }), &room, &History::default(), 1);
assert!(none.context.contains("- mood: none recorded"));
assert!(!none.context.contains("mood"), "a state without a mood has no mood line: {}", none.context);
}
#[test]
@ -1059,8 +1059,8 @@ fn a_bond_line_or_the_crowd_line_that_does_not_fit_gives_way_to_the_mood() {
tuning.select.context_bytes = identity + 200;
let packet = packet_tuned(TurnKind::Chat, &fixed_only, &chat_room(), &History::default(), 1, &tuning);
assert!(packet.context.contains("- mood") && !packet.context.contains("bond ["), "{}", packet.context);
assert!(packet.context.contains("- also here: Kiko, Libby"), "a bond line that does not fit names the person instead: {}", packet.context);
tuning.select.context_bytes = identity + 130;
assert!(packet.context.contains("- also here: Kiko; Libby"), "a bond line that does not fit names the person instead: {}", packet.context);
tuning.select.context_bytes = identity + 100;
let packet = packet_tuned(TurnKind::Chat, &fixed_only, &chat_room(), &History::default(), 1, &tuning);
assert!(packet.context.contains("- mood") && !packet.context.contains("also here"), "{}", packet.context);
assert!(packet.identity.len() + packet.context.len() <= tuning.select.context_bytes);
@ -1298,3 +1298,116 @@ fn the_report_says_how_old_the_addressing_table_is_and_why_it_was_not_used() {
let no_table = run(&Stale(None, Some(written)));
assert!(no_table["why"].as_str().unwrap().contains("holds no addressing table"), "{no_table}");
}
// ---------------------------------------------------------------------------------------------
// What the Projector is shown: absences left out, pronouns, the guidance's rules, the narration checks.
#[test]
fn a_state_without_a_mood_or_with_bare_items_says_nothing_of_records_or_readings() {
let bare = json!({
"publicName": "Eureka",
"affect": {
"socialBonds": [{ "id": "bond-libby", "object": { "id": "libby", "kind": "person", "label": "Libby" }, "status": "active" }],
"needs": [{ "id": "need-empty", "intensity": 0.9, "status": "active" }],
"doctrineStances": [{ "id": "stance-empty", "intensity": 0.9, "status": "active" }],
},
"thoughtMemory": { "memories": [{ "id": "memory-empty", "status": "crystallized", "intensity": 0.9 }], "incubation": [{ "id": "w-empty", "status": "active" }] },
"values": [{ "id": "value-empty", "priority": 0.9 }],
});
for seed in 1..=20 {
let packet = packet_of(TurnKind::Chat, &bare, &chat_room(), &History::default(), seed);
let text = format!("{}\n{}", packet.context, packet.stimulus).to_lowercase();
for word in ["mood", "record", "reading", "measure", "none", "empty"] {
assert!(!text.contains(word), "{word} in: {text}");
}
assert!(packet.context.contains("- bond [bond-libby] Libby\n") || packet.context.ends_with("- bond [bond-libby] Libby"), "a bond with nothing in it names the person and no more: {}", packet.context);
assert!(!packet.context.contains("trust") && !packet.context.contains("friction") && !packet.context.contains("easy between"), "{}", packet.context);
}
}
#[test]
fn every_person_the_packet_names_from_the_room_has_pronouns_and_an_unknown_one_is_they() {
let room = Room {
messages: vec![
message("#swarm:gamecult.org", OPERATOR, "Meta", "Eureka, how are you?", 4, true),
message("#swarm:gamecult.org", "@kiko:gamecult.org", "Kiko", "fine here", 3, false),
message("#swarm:gamecult.org", "@stranger:elsewhere.example", "Stranger", "hello all", 2, false),
],
here: Some("#swarm:gamecult.org".into()),
..Room::default()
};
let packet = packet_of(TurnKind::Chat, &state(), &room, &History::default(), 1);
let line = packet.context.lines().find(|line| line.starts_with("- pronouns:")).unwrap_or_else(|| panic!("{}", packet.context));
assert!(line.contains("Meta, the operator \u{2014} she/her") && line.contains("Kiko \u{2014} she/her"), "{line}");
assert!(line.contains("(@stranger:elsewhere.example) \u{2014} they/them"), "{line}");
assert!(!line.contains("Eureka"), "her own pronouns are in her identity, not here: {line}");
}
#[test]
fn the_projector_is_told_not_to_retell_not_to_offer_options_and_not_to_owe() {
let packet = packet_of(TurnKind::Chat, &state(), &chat_room(), &History::default(), 1);
let prompt = narrate::projector_prompt(&packet, &Tuning::default());
for rule in ["never retell or summarise it", "Do not weigh options", "never as a debt", "an absence is not part of her moment", "pronouns"] {
assert!(prompt.contains(rule), "{rule}");
}
let persona = narrate::persona_prompt(&packet, "The room is warm.", &Tuning::default());
assert!(persona.contains("Continue her inner stream") && persona.contains("This is not a message to the room") && persona.contains("most moments pass with nothing said"), "{persona}");
}
#[test]
fn the_narration_checks_flag_an_option_menu_and_a_retelling_and_pass_a_reaction() {
// Round 1 of the humans_pace run of 2026-11-20, as the Projector wrote it.
let menu = "I owe Zyphos names. I may answer Meta honestly. That could include the Zyphos debt and the sketch, or I could just say how I'm doing. Nothing presses except the open question.";
let idle = "Nothing asks me to act on it now.";
let reaction = "Meta's warmth lands somewhere under her ribs. She likes being asked without a task attached; it makes her want to be honest, and a little playful.";
assert!(narrate::offers_options(menu) && narrate::offers_options(idle));
assert!(!narrate::offers_options(reaction));
let heard = "Kiko, in #minds: \"Two things I'm carrying: the link-target takeover finding is still open, and it's on your door and mine.\"";
let retold = "Kiko named two things she's carrying: the link-target takeover finding is still open, and it's on her door and mine.";
assert!(narrate::heard_overlap(retold, heard) > 0.5, "{}", narrate::heard_overlap(retold, heard));
assert!(narrate::heard_overlap(reaction, heard) < 0.05);
}
#[test]
fn inner_is_her_prose_without_what_she_says_aloud() {
assert_eq!(narrate::inner("She grins. \"Winter, still.\" Then she lets it go."), "She grins. \u{2026} Then she lets it go.");
assert_eq!(narrate::inner("Only thought here."), "Only thought here.");
}
#[test]
fn the_group_state_reads_one_room_and_never_folds_a_direct_message_in() {
let room = Room {
messages: vec![message("#swarm:gamecult.org", "@kiko:gamecult.org", "Kiko", "Eureka, door?", 2, true)],
tail: vec![message("!dm-deru:gamecult.org", "@deru:gamecult.org", "Deru", "SECRET between us", 1, false), message("#swarm:gamecult.org", "@libby:gamecult.org", "Libby", "lunch?", 5, false)],
..Room::default()
};
let packet = packet_of(TurnKind::Chat, &state(), &room, &History::default(), 1);
let line = packet.context.lines().find(|line| line.starts_with("- the conversation")).unwrap_or_else(|| panic!("{}", packet.context)).to_owned();
assert!(line.contains("Kiko with her") && line.contains("Libby"), "{line}");
assert!(!line.contains("Deru") && !packet.context.contains("@deru"), "the direct message is its own room: {}", packet.context);
}
#[test]
fn the_packet_speaks_of_her_in_her_own_pronouns() {
let mut him = state();
him["presentation"]["pronouns"] = json!("he/him");
let packet = packet_of(TurnKind::Chat, &him, &chat_room(), &History::default(), 1);
assert!(packet.stimulus.starts_with("Said to him:") && packet.context.contains("Libby with him"), "{}\n{}", packet.stimulus, packet.context);
let beat = packet_of(TurnKind::Beat, &him, &Room::default(), &History::default(), 1);
assert!(beat.stimulus.starts_with("Nothing addressed him."), "{}", beat.stimulus);
let mut them = state();
them["presentation"]["pronouns"] = json!("any (they for themself)");
let beat = packet_of(TurnKind::Beat, &them, &Room::default(), &History::default(), 1);
assert!(beat.stimulus.starts_with("Nothing addressed them.") && !beat.stimulus.contains(" her ") , "{}", beat.stimulus);
}
#[test]
fn a_room_given_by_its_matrix_id_is_read_by_its_alias() {
let dir = tempfile::tempdir().unwrap();
let stored = Stored(state());
let chat = mouth();
let organs = Organs { persona: Some(&stored), chat: Some(&chat), addressing: None, model: None };
// The mouth's first delivery is in #swarm, room id !1:gamecult.org; its tail line carries the alias.
let report = project(&organs, &Request { room: Some("!1:gamecult.org".into()), ..request(dir.path(), None, None) }, now()).unwrap();
assert_eq!((report["room"]["messages"].as_u64(), report["room"]["tail"].as_u64()), (Some(1), Some(1)), "{}", report["room"]);
}

View file

@ -7,6 +7,7 @@
//! The SHA-256 carried with every packet is of the effective tuning, serialized whole with its defaults: a file that
//! spells out the defaults hashes as no file does, and two builds whose defaults differ hash differently.
use std::collections::BTreeMap;
use std::path::Path;
use anyhow::{Context, Result, bail};
@ -17,12 +18,12 @@ use sha2::{Digest, Sha256};
pub const TUNING_ROOT: &str = "/etc/gamecult/minds";
pub const TUNING_FILE: &str = "persona-tuning.toml";
/// The Persona stage's setting: where her words go, and the one convention that makes them speech (map section 5.5,
/// invariant 5). It licenses nothing: Ghostlight's membrane already says a thin moment gets little or nothing.
const PERSONA_GUIDANCE: &str = "She is in a chat room. Words she says aloud are typed into the room, and appear in her prose inside double quotation marks; nothing else she thinks or does leaves her head.";
/// The Persona stage's setting (map section 2): she continues the Projector's paragraph, her interior, with speech only
/// where her thought moves her to it, quoted (map section 5.5, invariant 5). It is not a reply to the room.
const PERSONA_GUIDANCE: &str = "Continue her inner stream where the paragraph leaves off: her own next thoughts, in the first person. This is not a message to the room. Speech is rare: words she says aloud appear in double quotation marks, and only when something in her thought moves her to say them; anyone else's words she recalls go in single quotation marks. In a busy room most moments pass with nothing said. To make sure someone hears her, she writes @ and their handle in what she says. Nothing else she thinks leaves her head.";
/// The setting the Projector renders for. No task: in the Persona-only shape nothing is work she owes.
const GUIDANCE: &str = "This person is a Mind of the GameCult swarm. She lives in its chat rooms among the operator, the other Minds and whoever drops by, and no task is waiting on her in this moment. Render the moment as she lives it: who is here and how they sit with her, what she carries, what she wants.";
const GUIDANCE: &str = "This person is a Mind of the GameCult swarm. She lives in its chat rooms among the operator, the other Minds and whoever drops by, and no task is waiting on her in this moment. Render the moment as she lives it: who is here and how they sit with her, what she carries, what she wants. What was said reaches her word for word after this stream, so never retell or summarise it: render what it stirs in her and what she makes of the people who said it. Render the conversation as it stands, never as a debt: nobody is owed an answer unless a person is waiting on her by name, and a question others have answered is covered. Do not weigh options or list what she might do or say; what she does is hers to decide. Leave out whatever the context does not carry: an absence is not part of her moment. Use each person's pronouns as given.";
/// The context room the fixed slots need beside the identity: the hour and the mood lines always fit.
const FIXED_ROOM: usize = 256;
@ -36,14 +37,46 @@ const ADDRESSED_RANGE: std::ops::RangeInclusive<usize> = 1024..=64 * 1024;
const PART_BYTES_MAX: usize = 32 * 1024;
/// The most words a lived stream may be given: a thin moment gets a thin stream, and no budget needs a book.
const WORDS_MAX: usize = 2000;
/// The most room lines the group state reads: a recent window, not the room's history.
const GROUP_LINES_MAX: usize = 40;
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Tuning {
pub projector: ProjectorTuning,
pub persona: PersonaTuning,
pub select: SelectTuning,
pub lens: LensWeights,
/// Each person's pronouns by Matrix id, for everyone the packet names: the persona schema has no pronoun field for
/// another person. A file's table replaces this one whole; anyone not listed is they/them.
pub pronouns: BTreeMap<String, String>,
}
/// The swarm's people as of 2026-11-20 (operator's word): she for the operator and five Minds, he for Heimdall and Deru,
/// any for Void, rendered they/them.
const PRONOUNS: [(&str, &str); 10] = [
("@meta:gamecult.org", "she/her"),
("@libby:gamecult.org", "she/her"),
("@kiko:gamecult.org", "she/her"),
("@aqua:gamecult.org", "she/her"),
("@weksa:gamecult.org", "she/her"),
("@nibu:gamecult.org", "she/her"),
("@eureka:gamecult.org", "she/her"),
("@heimdall:gamecult.org", "he/him"),
("@void:gamecult.org", "they/them (any pronouns)"),
("@deru:gamecult.org", "he/him"),
];
impl Default for Tuning {
fn default() -> Self {
Self {
projector: ProjectorTuning::default(),
persona: PersonaTuning::default(),
select: SelectTuning::default(),
lens: LensWeights::default(),
pronouns: PRONOUNS.iter().map(|(id, pronouns)| ((*id).to_owned(), (*pronouns).to_owned())).collect(),
}
}
}
/// The Projector's call: its model, its domain guidance and its word budgets.
@ -97,6 +130,14 @@ pub struct SelectTuning {
pub people_full: usize,
/// The room lines a beat shows.
pub beat_tail_lines: usize,
/// The group-state slot: who has been talking to whom, how long since a human spoke, what is addressed to her or
/// open to anyone, and how long the run of Mind lines is (prior art: group state in the prompt is what lets a
/// participant judge whether to speak).
pub group_state: bool,
/// The room lines the group state reads.
pub group_lines: usize,
/// The group-state slot's bytes.
pub group_bytes: usize,
pub caps: PoolCaps,
}
@ -153,6 +194,9 @@ impl Default for SelectTuning {
freshness_window: 5,
people_full: 2,
beat_tail_lines: 6,
group_state: true,
group_lines: 12,
group_bytes: 360,
caps: PoolCaps::default(),
}
}
@ -203,6 +247,8 @@ impl Tuning {
("select.identity_bytes", select.identity_bytes),
("select.bond_summary_bytes", select.bond_summary_bytes),
("select.item_bytes", select.item_bytes),
("select.group_lines", select.group_lines),
("select.group_bytes", select.group_bytes),
("projector.words", self.projector.words),
("projector.beat_words", self.projector.beat_words),
("persona.words", self.persona.words),
@ -218,13 +264,18 @@ impl Tuning {
("select.identity_bytes", select.identity_bytes),
("select.bond_summary_bytes", select.bond_summary_bytes),
("select.item_bytes", select.item_bytes),
("select.group_bytes", select.group_bytes),
("projector.guidance", self.projector.guidance.len()),
("persona.guidance", self.persona.guidance.len()),
] {
if bytes > PART_BYTES_MAX {
bail!("{name} must be at most {PART_BYTES_MAX} bytes, not {bytes}: the prompt must fit the connector's frame");
}
}
for (name, words) in [("projector.words", self.projector.words), ("projector.beat_words", self.projector.beat_words)] {
if select.group_lines > GROUP_LINES_MAX {
bail!("select.group_lines must be at most {GROUP_LINES_MAX}, not {}", select.group_lines);
}
for (name, words) in [("projector.words", self.projector.words), ("projector.beat_words", self.projector.beat_words), ("persona.words", self.persona.words)] {
if words > WORDS_MAX {
bail!("{name} must be at most {WORDS_MAX}, not {words}");
}

View file

@ -77,7 +77,7 @@ fn project_over_a_room_fixture_and_a_state_file_needs_no_daemon_and_no_mouth() {
let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!((report["state"].as_str(), report["persona_receipt"].is_null()), (Some("given"), true), "{report}");
assert!(report["packet"]["identity"].as_str().unwrap().starts_with("Tobiah Fenn"), "{report}");
assert!(report["packet"]["stimulus"].as_str().unwrap().contains("Said to her"), "Kiko's tagged reply is for her: {report}");
assert!(report["packet"]["stimulus"].as_str().unwrap().contains("Said to him"), "Kiko's tagged reply is for him, in his own pronouns: {report}");
// Without any endpoint at all it runs the same.
let output = Command::new(env!("CARGO_BIN_EXE_mind-persona")).args(args).env_clear().env("MIND_PERSONA_TUNING", "/nonexistent/persona-tuning.toml").output().unwrap();
assert_eq!(output.status.code(), Some(0), "{}", text(&output.stderr));

View file

@ -161,6 +161,7 @@ mind_body::heartbeat: impl HeartbeatView for FileStore
mind_body::heartbeat: impl PersonaId
mind_body::heartbeat: impl PersonaId: fn parse (spec : & str) -> Result < Self >
mind_body::heartbeat: impl Row < '_ >
mind_body::heartbeat: impl Speaker
mind_body::heartbeat: impl Store for FileStore
mind_body::heartbeat: impl fmt :: Display for Outcome
mind_body::heartbeat: impl fmt :: Display for PollTrace
@ -261,7 +262,7 @@ mind_body::projection::harness: impl MouthReader for Fixture
mind_body::projection::harness: pub use super :: simulate :: simulate ;
mind_body::projection::harness: struct Fixture # [derive (Clone , Debug)] pub-fields[her: String, names: Vec < String >, kind: TurnKind, now: DateTime < Utc >, here: Option < String >, operators: Vec < String >, minds: Vec < String >, last_heard: Vec < (String , u64) >]
mind_body::projection::harness: struct Harness< 'a > pub-fields[instance: String, persona: Option < & 'a dyn PersonaSource >, model: Option < & 'a dyn Model >, tuning: PathBuf]
mind_body::projection::harness: struct Message # [derive (Clone , Debug , Deserialize)] pub-fields[from: String, name: String, room: String, ago: Option < String >, round: Option < usize >, says: String, new: bool, tag: bool, mentions: Vec < String >, dm: bool, follow_up: bool, reply_to: Option < usize >]
mind_body::projection::harness: struct Message # [derive (Clone , Debug , Deserialize)] pub-fields[from: String, name: String, room: String, ago: Option < String >, round: Option < usize >, says: String, new: bool, tag: bool, mentions: Vec < String >, dm: bool, to: Option < String >, follow_up: bool, reply_to: Option < usize >]
mind_body::projection::narrate: fn connector_key (credentials : & Path) -> Result < String >
mind_body::projection::narrate: impl Failed
mind_body::projection::narrate: impl KitModel
@ -290,14 +291,15 @@ mind_body::projection::tuning: impl Default for PersonaTuning
mind_body::projection::tuning: impl Default for PoolCaps
mind_body::projection::tuning: impl Default for ProjectorTuning
mind_body::projection::tuning: impl Default for SelectTuning
mind_body::projection::tuning: impl Default for Tuning
mind_body::projection::tuning: impl Tuning
mind_body::projection::tuning: struct LensWeights # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[body_and_hour: f64, person_present: f64, unresolved_want: f64, memory_surfacing: f64, wondering: f64]
mind_body::projection::tuning: struct Loaded # [derive (Clone , Debug , PartialEq , Serialize)] pub-fields[tuning: Tuning, source: & 'static str, sha256: String]
mind_body::projection::tuning: struct PersonaTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, guidance: String, words: usize]
mind_body::projection::tuning: struct PoolCaps # [derive (Clone , Debug , PartialEq , Eq , Serialize , Deserialize)] pub-fields[memories_about_present: usize, other_memories: usize, needs: usize, incubation: usize, stance: usize, value: usize, said: usize]
mind_body::projection::tuning: struct ProjectorTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[model: String, guidance: String, words: usize, beat_words: usize]
mind_body::projection::tuning: struct SelectTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[temperature: f64, inclusion_score: f64, context_bytes: usize, stimulus_bytes: usize, heard_bytes: usize, addressed_bytes: usize, identity_bytes: usize, bond_summary_bytes: usize, item_bytes: usize, memory_tau_h: f64, freshness_base: f64, freshness_window: usize, people_full: usize, beat_tail_lines: usize, caps: PoolCaps]
mind_body::projection::tuning: struct Tuning # [derive (Clone , Debug , Default , PartialEq , Serialize , Deserialize)] pub-fields[projector: ProjectorTuning, persona: PersonaTuning, select: SelectTuning, lens: LensWeights]
mind_body::projection::tuning: struct SelectTuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[temperature: f64, inclusion_score: f64, context_bytes: usize, stimulus_bytes: usize, heard_bytes: usize, addressed_bytes: usize, identity_bytes: usize, bond_summary_bytes: usize, item_bytes: usize, memory_tau_h: f64, freshness_base: f64, freshness_window: usize, people_full: usize, beat_tail_lines: usize, group_state: bool, group_lines: usize, group_bytes: usize, caps: PoolCaps]
mind_body::projection::tuning: struct Tuning # [derive (Clone , Debug , PartialEq , Serialize , Deserialize)] pub-fields[projector: ProjectorTuning, persona: PersonaTuning, select: SelectTuning, lens: LensWeights, pronouns: BTreeMap < String , String >]
mind_body::queue: fn on_hold (mind : & dyn MindPort) -> Result < Held >
mind_body::queue: impl Held
mind_body::queue: impl Held: fn contains (& self , item : & PipelineRef) -> bool