Projector and Persona after the operator's reading; humans_pace per ruling; Soul's hold on #80

Projector (the operator: "Sounds like a Projector issue"):
- The group state is the conversation as it stands, in one room: who is talking with whom, a human's question to the
  room that others answered as covered (one nobody answered goes unmentioned), when a human last spoke, Mind lines in a
  row, and a human waiting on her by name. Never what she owes. Every count covers the window the line describes (S4);
  never several rooms folded together, never a direct message into a public room (S3). Default group_lines 12.
- Absent state is left out: no "mood: none recorded"; a bond, need, memory, stance, wondering or value without content
  is not rendered, and a bond without trust or tension says neither.
- Guidance: never retell what she heard (it reaches her verbatim), render what it stirs; never a debt; no options; leave
  out what the context does not carry; use pronouns as given. Metrics, not filters: heard_overlap (word trigrams shared
  with the heard lines) and offers_options (a narrow lexical flag), per render and per run.
- Pronouns: `[pronouns]` in the tuning by Matrix id, the swarm's people as the default, they/them for anyone else; the
  persona schema has no pronoun field for another person. A pronoun line names everyone the packet shows from the room.
  The packet speaks of her in her own pronouns throughout ("Said to him:") (S5).
- Bond lines put the kind after a dash and lists use semicolons: a label may hold a comma ("Meta, the operator").

Persona stage: continues her inner stream in the first person; speech only where her thought moves her to it, in double
quotes; others' words she recalls in single quotes; @handle tags someone. The report shows her inner prose apart from
what she would say.

humans_pace (ruling persona-only-humans-pace; the operator's words that Minds' explicit mentions wake too):
`HumansPace(cap)`: a human's line wakes her in her own room or a direct message always, and in a public room when it
addresses her or continues an exchange she is in (an exchange ends at a gap over exchange_gap_minutes, default 20); a
Mind's line wakes her only by a Matrix mention or a reply, in any room, while fewer than `cap` Mind lines in a row came
before it. Own rooms come from the plan: neither the heartbeat's table nor persona.env records ownership. Live is
unchanged. In the simulation a said line's @handle of a cast member stands in for a Matrix mention.

Soul's hold:
- S1: Config::new refuses an operator id that is also a persona's.
- S2: the simulator's beat asks heartbeat::addressed_by_member over the deliveries the mouth would give her.
- S3: --in given as a room id is read by its alias.
- S6: a scripted direct message names its recipient (`to`), is seen by sender and recipient alone, and wakes only her.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-20 04:23:06 +01:00
commit 63606efddd
16 changed files with 674 additions and 174 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

@ -1,4 +1,4 @@
quiet-beat.toml: - the room lately: libby to the room, Kiko to the room, libby to the room; no human has spoken here lately; the last 3 lines are the Minds' alone 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 room lately: Meta, who runs the place to her; a human, Meta, who runs the place, last spoke 1 min ago; 1 line is to her 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 room lately: she to the room, aqua to the room, Kiko to her; no human has spoken here lately; the last 3 lines are the Minds' alone; 1 line is to her 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 room lately: weksa to the room, Deru to the room; a human, Deru, last spoke 1 min ago deru-passing.toml: - the conversation: lately weksa to the room; Deru to the room; Deru last spoke 1 min ago

View file

@ -32,7 +32,7 @@ use eureka_pipeline::{OrgRepo, PipelineKind, RunTurn, Slug};
use huginn_mind::PipelineFacts; use huginn_mind::PipelineFacts;
use crate::address::{Addressee, Name, is_for, project_names}; 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::control::{ControlSource, Effective, FileSource, HeldReason, SwarmEffective, read_effective, read_envelope, set_mode_world_readable};
use crate::launch::{Clock, Launcher}; use crate::launch::{Clock, Launcher};
use crate::queue::{MindPort, headers, in_force, of_kind}; use crate::queue::{MindPort, headers, in_force, of_kind};
@ -98,11 +98,15 @@ pub struct Config {
} }
impl 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> { pub fn new(personas: Vec<PersonaId>, operators: Vec<String>, beat_s: u32) -> Result<Self> {
if personas.is_empty() { if personas.is_empty() {
bail!("no persona is configured"); 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 { if beat_s == 0 {
bail!("the beat is zero seconds"); bail!("the beat is zero seconds");
} }
@ -393,6 +397,12 @@ pub(crate) fn stewardships_of(mind: &dyn MindPort) -> Result<(Vec<Name>, Vec<Org
Ok((names, repos)) Ok((names, repos))
} }
/// 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. /// Who sent a line, as the wake rule sees them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Speaker { pub(crate) enum Speaker {
@ -421,8 +431,11 @@ pub(crate) enum WakePolicy {
Live, Live,
/// Ruling `persona-only-wake-humans-in-rooms`: a line addressing her, from anyone, and any human line in her rooms. /// Ruling `persona-only-wake-humans-in-rooms`: a line addressing her, from anyone, and any human line in her rooms.
Ruled, Ruled,
/// Human lines only: each wakes every Mind in the room once; a Mind's line never wakes a Mind. /// Ruling `persona-only-humans-pace`: a human's line wakes her in her own room (a direct message, or a room that is
HumansPace, /// 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 /// `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. /// the cap wakes no one.
NamesWithCap(usize), NamesWithCap(usize),
@ -441,10 +454,21 @@ pub(crate) enum WakeCause {
Mind, Mind,
} }
/// Whether a line in her rooms wakes `who` off the beat under `policy`, and why. `mind_run` is how many Mind lines in a /// What the room says about a line, beside the line: the facts a policy may weigh. The live poll knows none of them yet
/// row came before this one in its room since a human last spoke there. The one owner of the wake rule: the heartbeat's /// and passes the default; `Live` reads none.
/// poll asks it with `Live`, the simulator with the policy under test. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) fn wakes(policy: WakePolicy, who: &Addressee, delivery: &ChatDelivery, speaker: Speaker, mind_run: usize) -> Option<WakeCause> { 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 { if speaker == Speaker::Her {
return None; return None;
} }
@ -459,8 +483,11 @@ pub(crate) fn wakes(policy: WakePolicy, who: &Addressee, delivery: &ChatDelivery
let wakes = match policy { let wakes = match policy {
WakePolicy::Live => addressed && matches!(speaker, Speaker::Operator | Speaker::Mind), WakePolicy::Live => addressed && matches!(speaker, Speaker::Operator | Speaker::Mind),
WakePolicy::Ruled => human || addressed, WakePolicy::Ruled => human || addressed,
WakePolicy::HumansPace => human, WakePolicy::HumansPace(cap) => {
WakePolicy::NamesWithCap(cap) => human || (addressed && mind_run < 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, WakePolicy::AllMessages => true,
}; };
wakes.then_some(cause) wakes.then_some(cause)
@ -523,7 +550,7 @@ impl Row<'_> {
/// A member (not the operator) has a pending message that names or tags her. /// A member (not the operator) has a pending message that names or tags her.
fn addressed_by_member(&self, config: &Config) -> bool { 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)
} }
} }
@ -608,7 +635,7 @@ pub fn poll(organs: &Organs, config: &Config) -> Result<Outcome> {
pending.sort_by_key(|delivery| delivery.seq); pending.sort_by_key(|delivery| delivery.seq);
pending pending
.into_iter() .into_iter()
.filter(|delivery| wakes(WakePolicy::Live, &row.addressee, delivery, config.speaker(&row.addressee, delivery), 0).is_some()) .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)) .map(|delivery| format!("{}:{}", slug.0, delivery.event_id))
.find(|key| !state.handled_mentions.contains(key)) .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"] { 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!(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] #[test]

View file

@ -39,7 +39,7 @@ pub use narrate::{Answer, Failed, KitModel, Model, Spent, connector_key};
pub use select::TurnKind; pub use select::TurnKind;
pub use tuning::{TUNING_FILE, TUNING_ROOT}; 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}; use select::{History, Inputs, Packet, People, Room, RoomLine, select};
/// The agent name on the connector's request ids. /// 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, 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:#}") })), 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 let messages: Vec<RoomLine> = pending
.deliveries .deliveries
.iter() .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 }) .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(); .collect();
let report = json!({ "read": true, "messages": messages.len(), "tail": tail.len(), "tail_gaps": pending.tail_gaps }); 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 { 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), "words": words(&narration),
"cut_at_budget": words(&raw) > budget, "cut_at_budget": words(&raw) > budget,
"field_names": field_names(&narration, &named), "field_names": field_names(&narration, &named),
"heard_overlap": heard_overlap(&narration, &packet.heard),
"offers_options": offers_options(&narration),
"usage": answer.usage, "usage": answer.usage,
"narration": narration, "narration": narration,
}); });
@ -258,6 +262,7 @@ fn narrate_one(model: &dyn Model, instance: &str, packet: &Packet, tuning: &tuni
"words": words(&prose), "words": words(&prose),
"cut_at_budget": words(&spoke.text) > tuning.persona.words, "cut_at_budget": words(&spoke.text) > tuning.persona.words,
"would_say": would_say(&prose), "would_say": would_say(&prose),
"inner": inner(&prose),
"usage": spoke.usage, "usage": spoke.usage,
"prose": prose, "prose": prose,
}) })

View file

@ -5,10 +5,11 @@ present: Kiko, Libby
Eureka (she/her). Dry, direct, almost feral; zeal aimed at revealing. Eureka (she/her). Dry, direct, almost feral; zeal aimed at revealing.
--- context --- context
- now: Thursday 19 November, 14:05 UTC - now: Thursday 19 November, 14:05 UTC
- mood, with no earlier turn to measure from: lighter, more settled than middling - 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-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. - bond [bond-libby] Libby — collaborator: fair trust, a little friction. Libby holds the sounds and teases her about the pipeline.
- the room lately: Libby to her, Kiko to the room; no human has spoken here lately; the last 2 lines are the Minds' alone; 1 line is to her - 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 [libby-sounds]: Libby laughed at the door fix.
- memory [t1-m0]: The heartbeat stalled at noon. - 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. - memory [curse]: Her curse is the knife. The same drive makes her good and will lead her wrong.

View file

@ -29,6 +29,8 @@ use crate::heartbeat::{Addressing, HeartbeatView};
pub use super::simulate::simulate; 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. /// The most room lines a view's tail carries, as a mouth's tail is bounded.
const TAIL_LINES: usize = 40; const TAIL_LINES: usize = 40;
@ -90,9 +92,12 @@ pub struct Message {
/// Other Matrix ids it tags. /// Other Matrix ids it tags.
#[serde(default)] #[serde(default)]
pub mentions: Vec<String>, 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)] #[serde(default)]
pub dm: bool, 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). /// A reply in a conversation she opened (the mouth's follow-up basis).
#[serde(default)] #[serde(default)]
pub follow_up: bool, pub follow_up: bool,
@ -111,7 +116,8 @@ pub(crate) struct Line {
pub at_ms: u64, pub at_ms: u64,
pub says: String, pub says: String,
pub mentions: Vec<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, pub follow_up: bool,
/// The index of the line it replies to. /// The index of the line it replies to.
pub reply_to: Option<usize>, pub reply_to: Option<usize>,
@ -128,18 +134,25 @@ impl Line {
if message.tag { 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()); 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 { let reply_to = match message.reply_to {
Some(number) if number >= 1 && number <= index => Some(number - 1), 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), Some(number) => bail!("message {} replies to message {number}, which is not an earlier one", index + 1),
None => None, 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 /// 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. /// follow-up.
fn basis(&self, viewer: &str, lines: &[Line]) -> Option<Basis> { fn basis(&self, viewer: &str, lines: &[Line]) -> Option<Basis> {
if self.dm { if self.dm_to.as_deref() == Some(viewer) {
Some(Basis::Direct) Some(Basis::Direct)
} else if self.mentions.iter().any(|id| id == viewer) { } else if self.mentions.iter().any(|id| id == viewer) {
Some(Basis::Tag) Some(Basis::Tag)
@ -152,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 { pub(crate) fn delivery(&self, index: usize, viewer: &str, lines: &[Line]) -> ChatDelivery {
ChatDelivery { ChatDelivery {
seq: index as u64 + 1, seq: index as u64 + 1,
@ -164,7 +186,7 @@ impl Line {
at_unix_ms: self.at_ms, at_unix_ms: self.at_ms,
context: vec![], context: vec![],
mentions: self.mentions.clone(), mentions: self.mentions.clone(),
is_direct: self.dm, is_direct: self.dm_to.is_some(),
image: None, image: None,
basis: self.basis(viewer, lines), basis: self.basis(viewer, lines),
form: Form::Message, form: Form::Message,
@ -176,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, /// 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. /// 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 { 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 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 let tail: Vec<TailLine> = lines
.iter() .iter()
@ -462,6 +484,13 @@ Usage: {}
if let Some(names) = render["field_names"].as_array().filter(|names| !names.is_empty()) { 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, "**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"]; let persona = &render["persona"];
if let Some(failed) = persona["failed"].as_str() { if let Some(failed) = persona["failed"].as_str() {
let _ = writeln!(out, "**Persona call failed:** {failed} let _ = writeln!(out, "**Persona call failed:** {failed}
@ -469,6 +498,8 @@ Usage: {}
} else if !persona.is_null() { } else if !persona.is_null() {
let _ = writeln!(out, "**Her prose** ({} words{}):\n", persona["words"], if persona["cut_at_budget"] == true { ", cut at budget" } else { "" }); 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()); 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()) { match persona["would_say"].as_array().filter(|said| !said.is_empty()) {
Some(said) => { Some(said) => {
let _ = writeln!(out, "**Would say:**\n"); let _ = writeln!(out, "**Would say:**\n");

View file

@ -224,7 +224,7 @@ fn group_line_of(dir: &Path, name: &str) -> Option<String> {
let harness = harness(dir, None, None); let harness = harness(dir, None, None);
let organs = Organs { persona: None, chat: Some(&fixture), addressing: fixture.addressee(), model: 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(); 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 room lately")).map(str::to_owned) report["packet"]["context"].as_str().unwrap().lines().find(|line| line.starts_with("- the conversation")).map(str::to_owned)
} }
#[test] #[test]
@ -252,3 +252,35 @@ group_state = false
").unwrap(); ").unwrap();
assert!(group_line_of(dir.path(), "mind-teases.toml").is_none()); 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. /// 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 { 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) }) 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 }) 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 /// 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 /// 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. /// its decision: a quotation she only recalls reads here as said. An unclosed quote says nothing.

View file

@ -47,6 +47,29 @@ const NAME_BYTES: usize = 80;
/// The most bytes the line naming the unbonded people present takes. /// The most bytes the line naming the unbonded people present takes.
const ALSO_HERE_BYTES: usize = 300; 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. /// 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)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]
@ -146,14 +169,14 @@ pub(crate) enum Lens {
} }
impl Lens { impl Lens {
/// The lens as the domain guidance's "begin from …". /// The lens as the domain guidance's "begin from …", in her pronouns.
pub(crate) fn words(&self) -> String { pub(crate) fn words(&self, forms: &Forms) -> String {
match self { 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::PersonPresent(name) => format!("{name}, who is here"),
Self::UnresolvedWant => "something she still wants and has not got".into(), Self::UnresolvedWant => format!("something {} still want{} and {} not got", forms.subj, forms.s, forms.has),
Self::MemorySurfacing => "a memory coming back to her".into(), Self::MemorySurfacing => format!("a memory coming back to {}", forms.obj),
Self::Wondering => "something she has been wondering about".into(), 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. /// Every typed id the packet's lines name: the selected items' and the bonds' of the people present.
pub ids: Vec<String>, pub ids: Vec<String>,
pub selected: Vec<Pick>, 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 /// 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"]) 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. /// Mood as change since her last turn; as a level only when there is no last turn to measure from. None when her state
fn mood_line(state: &Value, previous: Option<&Value>) -> String { /// 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(); 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() { if now.is_empty() {
return "- mood: none recorded".into(); return None;
} }
let Some(previous) = previous else { let Some(previous) = previous else {
let words: Vec<&str> = now 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 } if *value >= 0.5 { up } else { down }
}) })
.collect(); .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 let moves: Vec<&str> = now
.iter() .iter()
@ -338,15 +365,16 @@ fn mood_line(state: &Value, previous: Option<&Value>) -> String {
} }
}) })
.collect(); .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 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"]))); 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) { match before.map(|before| intensity - before) {
Some(change) if change >= MOVE_MIN => "growing since her last turn".into(), Some(change) if change >= MOVE_MIN => format!("growing since {poss} last turn"),
Some(change) if change <= -MOVE_MIN => "easing since her last turn".into(), Some(change) if change <= -MOVE_MIN => format!("easing since {poss} last turn"),
Some(_) => "where it was".into(), Some(_) => "where it was".into(),
None => strength_words(intensity).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 about = about_present(memory, present);
let pool = if about { Pool::MemoriesAboutPresent } else { Pool::OtherMemories }; 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 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 body = [text(memory, &["summary"]), text(memory, &["tension"])].into_iter().filter(|part| !part.is_empty()).collect::<Vec<_>>().join(" ");
let tension = text(memory, &["tension"]); if body.is_empty() {
if !tension.is_empty() { continue;
body = format!("{body} {tension}");
} }
let line = format!("- memory [{}]: {}", text(memory, &["id"]), clip(&one_line(&body), item_bytes)); let line = format!("- memory [{}]: {}", text(memory, &["id"]), clip(&one_line(&body), item_bytes));
let salience = number(memory, &["intensity"]).unwrap_or(SALIENCE_UNSTATED); 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)) { for need in items(state, &["affect", "needs"]).iter().filter(|need| live(need)) {
let intensity = number(need, &["intensity"]).unwrap_or(SALIENCE_UNSTATED); 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 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())); 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); 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 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 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)); 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)); 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 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)); 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); 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"]) { for value in items(state, &["values"]).iter().filter(|value| !text(value, &["label"]).is_empty() || !text(value, &["summary"]).is_empty()) {
let line = format!("- value [{}] {}: {}", text(value, &["id"]), clip(text(value, &["label"]), NAME_BYTES), clip(&one_line(text(value, &["summary"])), item_bytes)); 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); 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); 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 { for said in &inputs.history.said {
let touch = if Some(said.room.as_str()) == here { TOUCH_ROOM } else { TOUCH_ELSE }; 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); push(&said.id, Pool::Said, line, SALIENCE_UNSTATED, recency_log(Some(said.at), inputs.now, tuning.select.memory_tau_h), touch, 1.0);
} }
out out
@ -592,10 +625,10 @@ struct Addressed<'a> {
} }
impl Addressed<'_> { 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(); let mut lines: Vec<String> = Vec::new();
if self.left_out > 0 { 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 { lines.extend(self.shown.iter().map(|(line, cut)| match cut {
None => render(line, &spoken(&line.text)), 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. // 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 addressed = said_to_her(&to_her, typed, ceiling);
let (left_out, clipped) = (addressed.left_out, addressed.clipped); let (left_out, clipped) = (addressed.left_out, addressed.clipped);
let typed_to_her = addressed.lines(typed); let obj = forms(inputs.state).obj;
let heard_to_her = addressed.lines(heard); let typed_to_her = addressed.lines(obj, typed);
let heard_to_her = addressed.lines(obj, heard);
let mut stimulus = String::new(); let mut stimulus = String::new();
if !typed_to_her.is_empty() { 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 { for line in &typed_to_her {
stimulus.push('\n'); stimulus.push('\n');
stimulus.push_str(line); 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(); let last = heard.filter(|(sender, _)| inputs.people.person_of(sender) == person).map(|(_, at)| at).max();
contacts.push((last, match last { contacts.push((last, match last {
Some(at) => format!("- last heard from {label} {} h ago", hours(inputs.now, at)), 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)); contacts.sort_by_key(|(last, _)| std::cmp::Reverse(*last));
let mut out = Lines::new(cap); 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 note_room = 48;
let contact_cap = cap * 2 / 3; let contact_cap = cap * 2 / 3;
let mut left_out = 0; let mut left_out = 0;
@ -733,12 +768,12 @@ fn beat_stimulus(inputs: &Inputs, tuning: &Tuning) -> String {
} }
} }
if left_out > 0 { 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 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 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 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("") { if !section.is_empty() && out.push("") {
out.push(&section); out.push(&section);
} }
@ -747,8 +782,9 @@ fn beat_stimulus(inputs: &Inputs, tuning: &Tuning) -> String {
fn reflection_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 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); let subj = forms(inputs.state).subj;
if section.is_empty() { clip("Since she last took stock: nothing new.", tuning.select.stimulus_bytes) } else { section } 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. /// 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 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 { fn bond_line(bond: &Value, name: &str, tuning: &Tuning) -> String {
let mut feel = vec![friction_words(number(bond, &["tension"]).unwrap_or(0.0))]; let feel: Vec<&str> = [number(bond, &["trust"]).map(trust_words), number(bond, &["tension"]).map(friction_words)].into_iter().flatten().collect();
if let Some(trust) = number(bond, &["trust"]) { let custom = text(bond, &["customRelationshipKind"]);
feel.insert(0, trust_words(trust)); 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 summary = clip(&one_line(text(bond, &["summary"])), tuning.select.bond_summary_bytes);
let kind = if kind.is_empty() { String::new() } else { format!(", {kind}") }; match (feel.is_empty(), summary.is_empty()) {
format!("- bond [{}] {name}{kind}: {}. {}", text(bond, &["id"]), feel.join(", "), clip(&one_line(text(bond, &["summary"])), tuning.select.bond_summary_bytes)) (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 { fn identity_of(state: &Value, tuning: &Tuning) -> String {
@ -803,13 +855,13 @@ fn also_here(named: &[String]) -> Option<String> {
break; break;
} }
if shown > 0 { if shown > 0 {
line.push_str(", "); line.push_str("; ");
} }
line.push_str(name); line.push_str(name);
shown += 1; shown += 1;
} }
if shown < named.len() { 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) Some(line)
} }
@ -833,71 +885,126 @@ 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() [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 group-state slot (`select.group_state`): over the room's last `group_lines` lines, who spoke to whom (to her, to /// The recent lines of one room, the one the group state and the pronouns describe: messages and tail together, each
/// someone else present by name, or to the room); when a human last spoke; how many lines in a row are the Minds' alone; /// once, oldest first. The room is the turn's when it is one room; otherwise the room of the newest message to her, else
/// how many lines are to her; and whether a human's question to everyone stands open. Code reads names and question marks, /// of the newest message, else of the newest tail line. Never several rooms folded into one, so a direct message is
/// not meaning: whom a line is to by the names in it is a cue, and the Interpreter (C3b) will know better. None when the /// only ever read as its own room.
/// room shows no line. fn recent_lines<'a>(inputs: &'a Inputs) -> Vec<&'a RoomLine> {
fn group_line(inputs: &Inputs, tuning: &Tuning) -> Option<String> { 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 here = inputs.room.here.as_deref(); 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(); let mut lines: Vec<&RoomLine> = Vec::new();
for line in inputs.room.messages.iter().chain(&inputs.room.tail) { for line in inputs.room.messages.iter().chain(&inputs.room.tail) {
if here.is_some_and(|here| line.room != here) || lines.iter().any(|seen| seen.sender == line.sender && seen.at_ms == line.at_ms && seen.text == line.text) { if line.room != room || lines.iter().any(|seen| seen.sender == line.sender && seen.at_ms == line.at_ms && seen.text == line.text) {
continue; continue;
} }
lines.push(line); lines.push(line);
} }
lines.sort_by_key(|line| line.at_ms); 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() { if lines.is_empty() {
return None; return None;
} }
let to_her = |line: &RoomLine| line.sender != inputs.people.own_sender && (line.to_her || [localpart(inputs.people.own_sender), text(inputs.state, &["publicName"])].iter().any(|name| crate::address::names_whole_word(&line.text, name, false))); 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 window = &lines[lines.len().saturating_sub(tuning.select.group_lines)..];
// A tail line carries no display name: an unbonded sender there goes by the handle in her Matrix id. 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();
let label = |line: &RoomLine| { // A human's last line, when it is a question to the room (no one named), and who has answered it since.
if line.sender == inputs.people.own_sender { let question = window.iter().rposition(|line| !is_mind(inputs, &line.sender)).filter(|at| {
"she".to_owned() let line = window[*at];
} else if line.display.trim().is_empty() && bond_label(inputs, &line.sender).is_none() { line.text.trim_end().ends_with('?') && !names_her(line) && named_in(line).is_none()
localpart(&line.sender).to_owned()
} else {
name_of(line, inputs)
}
};
let talk: Vec<String> = window
.iter()
.map(|line| {
let target = if to_her(line) {
"her".to_owned()
} else {
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))).map_or_else(|| "the room".to_owned(), |other| label(other))
};
format!("{} to {target}", label(line))
})
.collect();
let mut parts = vec![format!("the room lately: {}", talk.join(", "))];
let last_human = lines.iter().rev().find(|line| !is_mind(inputs, &line.sender));
parts.push(match last_human {
Some(line) => format!("a human, {}, last spoke {} min ago", label(line), minutes(inputs.now, line.at_ms)),
None => "no human has spoken here lately".to_owned(),
}); });
let minds_in_a_row = lines.iter().rev().take_while(|line| is_mind(inputs, &line.sender)).count(); 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 { if minds_in_a_row >= 2 {
parts.push(format!("the last {minds_in_a_row} lines are the Minds' alone")); parts.push(format!("the last {minds_in_a_row} lines are the Minds' alone"));
} }
let addressed = lines.iter().filter(|line| to_her(line)).count(); // A human waiting on her by name: a line of a human's that names or tags her, after her own last line.
if addressed > 0 { let her_last = window.iter().rposition(|line| line.sender == own);
parts.push(format!("{addressed} {} to her", if addressed == 1 { "line is" } else { "lines are" })); 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));
} }
if let Some(line) = last_human (!parts.is_empty()).then(|| clip(&format!("- the conversation: {}", parts.join("; ")), tuning.select.group_bytes))
&& line.text.trim_end().ends_with('?')
&& !to_her(line)
&& !window.iter().filter(|other| other.sender != line.sender).any(|other| names_of(other, inputs).iter().any(|name| crate::address::names_whole_word(&line.text, name, false)))
{
parts.push(format!("{}'s question to everyone is open", label(line)));
}
Some(clip(&format!("- {}", 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 { 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); let at = i64::try_from(at_ms).ok().and_then(DateTime::<Utc>::from_timestamp_millis).unwrap_or(now);
(now - at).num_minutes().max(0) (now - at).num_minutes().max(0)
@ -912,7 +1019,7 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet {
let (stimulus, heard, overflow) = match inputs.kind { let (stimulus, heard, overflow) = match inputs.kind {
TurnKind::Chat => chat_stimulus(inputs, tuning), TurnKind::Chat => chat_stimulus(inputs, tuning),
TurnKind::Beat => (beat_stimulus(inputs, tuning), String::new(), Overflow::default()), 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()), TurnKind::Reflection => (reflection_stimulus(inputs, tuning), String::new(), Overflow::default()),
}; };
@ -922,7 +1029,7 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet {
let present = present_people(inputs, tuning); let present = present_people(inputs, tuning);
let present_ids: BTreeSet<String> = present.iter().map(|(id, _)| id.clone()).collect(); let present_ids: BTreeSet<String> = present.iter().map(|(id, _)| id.clone()).collect();
let bonds = items(inputs.state, &["affect", "socialBonds"]); 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 used: usize = fixed.iter().map(|line| line.len() + 1).sum();
let mut ids = Vec::new(); let mut ids = Vec::new();
let mut named = Vec::new(); let mut named = Vec::new();
@ -953,6 +1060,10 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet {
used += line.len() + 1; used += line.len() + 1;
fixed.push(line); 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. // 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(); 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();
@ -989,5 +1100,5 @@ pub(crate) fn select(inputs: &Inputs, tuning: &Tuning) -> Packet {
lines.extend(taken.iter().map(|candidate| candidate.line.clone())); lines.extend(taken.iter().map(|candidate| candidate.line.clone()));
ids.extend(taken.iter().map(|candidate| candidate.id.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(); 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

@ -20,13 +20,13 @@ use chrono::{DateTime, Duration, Utc};
use serde::Deserialize; use serde::Deserialize;
use serde_json::{Value, json}; 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::select::Draw;
use super::tuning; use super::tuning;
use super::{MouthReader, Organs, Request, Through, TurnKind, project}; use super::{MouthReader, Organs, Request, Through, TurnKind, project};
use crate::address::{Addressee, is_for, localpart}; use crate::address::{Addressee, is_for, localpart};
use crate::chat_client::ChatPending; use crate::chat_client::ChatPending;
use crate::heartbeat::{Addressing, DEFAULT_BEAT_S, FileStore, HeartbeatView, Speaker, WakeCause, WakePolicy, wakes}; use crate::heartbeat::{Addressing, DEFAULT_BEAT_S, FileStore, HeartbeatView, LineFacts, Speaker, WakeCause, WakePolicy, addressed_by_member, wakes};
use crate::tempo::{Standing, pick}; use crate::tempo::{Standing, pick};
/// The most personas a simulation holds: the swarm. /// The most personas a simulation holds: the swarm.
@ -49,6 +49,10 @@ struct SimFile {
beat_s: u32, beat_s: u32,
#[serde(default = "two")] #[serde(default = "two")]
round_minutes: i64, 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>, start: DateTime<Utc>,
rooms: Vec<String>, rooms: Vec<String>,
#[serde(default)] #[serde(default)]
@ -70,6 +74,10 @@ fn two() -> i64 {
2 2
} }
fn exchange_gap() -> i64 {
20
}
fn ruled() -> WakePolicy { fn ruled() -> WakePolicy {
WakePolicy::Ruled WakePolicy::Ruled
} }
@ -88,6 +96,10 @@ struct CastEntry {
/// Her rooms; none is every room of the plan. /// Her rooms; none is every room of the plan.
#[serde(default)] #[serde(default)]
rooms: Vec<String>, rooms: Vec<String>,
/// 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)]
own_rooms: Vec<String>,
} }
struct Member { struct Member {
@ -173,14 +185,33 @@ struct Woken {
by: Vec<Value>, by: Vec<Value>,
} }
fn woken(lines: &[Line], runs: &[usize], seen: usize, member: &Member, operators: &[String], cast: &[String], policy: WakePolicy) -> Option<Woken> { /// 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(); let mut found: Vec<(usize, WakeCause)> = Vec::new();
for (at, line) in lines.iter().enumerate().skip(seen) { for (at, line) in lines.iter().enumerate().skip(seen) {
if !(member.rooms.contains(&line.room) || line.dm) { if !line.visible_to(&member.entry.id, &member.rooms) {
continue; continue;
} }
let delivery = line.delivery(at, &member.entry.id, lines); let delivery = line.delivery(at, &member.entry.id, lines);
if let Some(cause) = wakes(policy, &member.addressee, &delivery, speaker(line, member, operators, cast), runs[at]) { 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)); found.push((at, cause));
} }
} }
@ -206,6 +237,13 @@ fn cause_word(cause: Option<WakeCause>) -> &'static str {
} }
} }
/// 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. /// A seeded shuffle, so the order of those woken together is drawn, and replays.
fn shuffled<T>(mut items: Vec<T>, seed: u64) -> Vec<T> { fn shuffled<T>(mut items: Vec<T>, seed: u64) -> Vec<T> {
let mut draw = Draw(seed); let mut draw = Draw(seed);
@ -258,9 +296,12 @@ fn cast_of(plan: &SimFile, base: &Path) -> Result<Vec<Member>> {
if message.ago.is_some() || message.new || message.tag { 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); 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); 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);
}
} }
Ok(members) Ok(members)
} }
@ -293,7 +334,7 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize)
scripted(round, &mut lines, &mut rounds_of, &mut causes)?; scripted(round, &mut lines, &mut rounds_of, &mut causes)?;
let round_at = at_round(round); let round_at = at_round(round);
let runs = mind_runs(&lines, &cast); 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).map(|why| (at, Some(why)))).collect(); 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 // The beat, as the heartbeat's: when it has fallen, one more wake for the winner of `tempo::pick` among those
// not already woken. // not already woken.
if plan.beat_s > 0 && (round_at - last_beat).num_seconds() >= i64::from(plan.beat_s) { if plan.beat_s > 0 && (round_at - last_beat).num_seconds() >= i64::from(plan.beat_s) {
@ -306,7 +347,7 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize)
waited_s: last_turn[at].map(|turn| u64::try_from((round_at - turn).num_seconds()).unwrap_or(0)), 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()), last_turn_ms: last_turn[at].map(|turn| turn.timestamp_millis()),
topic_permille: 0, topic_permille: 0,
addressed_by_member: lines.iter().enumerate().skip(seen[at]).any(|(index, line)| !plan.operators.contains(&line.from) && line.from != member.entry.id && is_for(&member.addressee, &line.delivery(index, &member.entry.id, &lines))), addressed_by_member: addressed_by_member(&plan.operators, &member.addressee, &pending_for(&lines, &member.entry.id, &member.rooms, |index| index >= seen[at]).deliveries),
}) })
.collect(); .collect();
if let Some(winner) = pick(&standings, plan.beat_s) { if let Some(winner) = pick(&standings, plan.beat_s) {
@ -318,8 +359,11 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize)
counter += 1; counter += 1;
let member = &members[at]; let member = &members[at];
let id = member.entry.id.clone(); 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 fresh: Vec<&Line> = lines[seen[at]..].iter().filter(|line| line.from != id && line.visible_to(&id, &member.rooms)).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 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 kind = if fresh.is_empty() { TurnKind::Beat } else { TurnKind::Chat };
let now = round_at + Duration::seconds(30 + counter as i64); let now = round_at + Duration::seconds(30 + counter as i64);
let request = Request { let request = Request {
@ -354,7 +398,8 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize)
let line = (!said.is_empty()).then(|| said.join(" ")); let line = (!said.is_empty()).then(|| said.join(" "));
let cause = cause_word(why.as_ref().map(|why| why.cause)); let cause = cause_word(why.as_ref().map(|why| why.cause));
if let Some(says) = &line { 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); rounds_of.push(round);
causes.push(Some(cause)); causes.push(Some(cause));
} }
@ -478,7 +523,15 @@ fn metrics(members: &[Member], lines: &[Line], rounds_of: &[usize], causes: &[Op
let (silent, failed) = (turns.iter().filter(|turn| turn["outcome"] == "silent").count(), turns.iter().filter(|turn| turn["outcome"] == "failed").count()); 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 answered = turns.len() - failed;
let work = mind_lines.iter().filter(|line| work_talk(&line.says)).count(); 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!({ json!({
"narration": narration,
"personas": per, "personas": per,
"turns": turns.len(), "turns": turns.len(),
"wakes": count_causes(&every), "wakes": count_causes(&every),
@ -507,7 +560,7 @@ fn policy_words(policy: WakePolicy) -> String {
match policy { match policy {
WakePolicy::Live => "live: the operator or another Mind addressing her (the heartbeat's rule today)".into(), 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::Ruled => "ruled: a line addressing her, from anyone, and any human line in her rooms".into(),
WakePolicy::HumansPace => "humans_pace: human lines only, each waking every Mind in the room once; a Mind's line wakes no one".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::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(), WakePolicy::AllMessages => "all_messages: any line in her rooms, a Mind's too (the old loop, the control)".into(),
} }
@ -533,10 +586,12 @@ fn markdown(plan_path: &Path, plan: &SimFile, members: &[Member], group_state: O
let mut out = String::new(); let mut out = String::new();
let _ = writeln!(out, "# Swarm simulation\n"); 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, "> **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, "> **No explicit addressee.** Whom a line is to is the Interpreter's to say (C3b); until then a spoken line carries no Matrix mention, so one persona addresses another only through names in the text.\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, "- plan: `{}`", plan_path.display());
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, "- 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: {}", plan.rooms.join(", "), plan.rounds, plan.repeats, plan.seed, plan.round_minutes); 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, "- 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, "- 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, "- 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");
@ -564,7 +619,9 @@ fn markdown(plan_path: &Path, plan: &SimFile, members: &[Member], group_state: O
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, "- 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 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, "- 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, "- 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|---|---|---|---|---|---|"); let _ = writeln!(out, "| persona | wakes | messages | failed | silence rate | addressed |\n|---|---|---|---|---|---|");
if let Some(personas) = metrics["personas"].as_object() { if let Some(personas) = metrics["personas"].as_object() {
for (name, row) in personas { for (name, row) in personas {

View file

@ -88,8 +88,9 @@ fn turns(run: &Value) -> Vec<(u64, String, String)> {
#[test] #[test]
fn the_wake_policies_are_the_heartbeats_one_function() { fn the_wake_policies_are_the_heartbeats_one_function() {
let libby = Addressee::new(LIBBY, ["libby", "Libby"]); 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: false, follow_up: false, reply_to: None, new: false }; 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, run); 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"); let (named, unnamed) = ("Libby, tea?", "what a day");
use WakeCause::*; use WakeCause::*;
// Ruled: anyone addressing her, any human line. // Ruled: anyone addressing her, any human line.
@ -102,9 +103,17 @@ fn the_wake_policies_are_the_heartbeats_one_function() {
assert_eq!(ask(WakePolicy::Live, "@meta:x", named, Speaker::Operator, 0), Some(AddressedByHuman)); 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, TOBIAH, named, Speaker::Mind, 0), Some(AddressedByMind));
assert_eq!(ask(WakePolicy::Live, "@meta:x", unnamed, Speaker::Operator, 0), None); assert_eq!(ask(WakePolicy::Live, "@meta:x", unnamed, Speaker::Operator, 0), None);
// Humans pace: a Mind's line never wakes a Mind. // 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
assert_eq!(ask(WakePolicy::HumansPace, TOBIAH, named, Speaker::Mind, 0), None); // addresses her or continues an exchange she is in.
assert_eq!(ask(WakePolicy::HumansPace, "@meta:x", unnamed, Speaker::Operator, 0), Some(Human)); 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. // 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, 1), Some(AddressedByMind));
assert_eq!(ask(WakePolicy::NamesWithCap(2), TOBIAH, named, Speaker::Mind, 2), None); assert_eq!(ask(WakePolicy::NamesWithCap(2), TOBIAH, named, Speaker::Mind, 2), None);
@ -149,20 +158,33 @@ fn naming_runs_away_under_the_ruled_set_and_stops_at_the_cap() {
let capped = turns(&capped); 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:?}"); 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 dir = tempfile::tempdir().unwrap();
let (_, paced) = run_plan(&plan(dir.path(), "\"humans_pace\"", 6, ""), &namers()); let (_, paced) = run_plan(&plan(dir.path(), "{ humans_pace = 4 }", 6, ""), &namers());
assert_eq!(turns(&paced).len(), 2, "under humans_pace only the operator's line wakes anyone"); assert!(turns(&paced).is_empty(), "under humans_pace an unaddressed public line wakes no one, and no Mind's line ever does");
} }
#[test] #[test]
fn a_human_interjection_wakes_everyone_in_her_room_under_humans_pace() { fn under_humans_pace_her_own_room_wakes_her_and_a_public_room_only_by_address_or_her_exchange() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let interjection = "[[message]]\nround = 4\nfrom = \"@deru:gamecult.org\"\nname = \"Deru\"\nroom = \"#minds:gamecult.org\"\nsays = \"kettle news\"\n"; cast(dir.path());
let path = plan(dir.path(), "\"humans_pace\"", 5, ""); let path = dir.path().join("plan.toml");
std::fs::write(&path, format!("{}{interjection}", std::fs::read_to_string(&path).unwrap())).unwrap(); 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 (members, run) = run_plan(&path, &namers());
let rounds = run["metrics"]["wakes_by_round"].as_array().unwrap(); let turns = turns(&run);
assert_eq!((rounds[0]["causes"]["human"].as_u64(), rounds[3]["causes"]["human"].as_u64(), rounds[1]["causes"]["addressed_by_mind"].as_u64()), (Some(2), Some(2), Some(0)), "{rounds:?}"); assert_eq!(
assert_eq!(run["metrics"]["personas"]["Tobiah"]["addressed"]["Libby"].as_u64(), run["metrics"]["personas"]["Tobiah"]["messages"].as_u64()); 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"); assert_eq!(members[0].state, control(), "the seam: no state moved");
} }
@ -217,16 +239,18 @@ fn a_seed_replays_its_order_and_another_seed_changes_it() {
} }
#[test] #[test]
fn a_wake_by_an_id_written_as_text_is_counted_once_and_listed() { fn an_at_handle_in_a_said_line_is_a_mention_and_its_wakes_are_counted_once() {
let dir = tempfile::tempdir().unwrap(); 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() }); 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 (_, run) = run_plan(&plan(dir.path(), "\"ruled\"", 3, ""), &model);
let addressed = &run["metrics"]["mind_addressed_wakes"]; let addressed = &run["metrics"]["mind_addressed_wakes"];
let libby_mind_wakes = turns(&run).iter().filter(|(_, who, why)| who == "Libby" && why == "addressed_by_mind").count(); 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!(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["total"].as_u64().unwrap() as usize, turns(&run).iter().filter(|(_, _, why)| why == "addressed_by_mind").count());
assert_eq!(addressed["id_as_text"].as_u64().unwrap() as usize, libby_mind_wakes, "the strongest evidence of each wake, once per wake: {addressed}"); 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_wakes"].as_array().unwrap().len(), libby_mind_wakes); assert_eq!(addressed["id_as_text"].as_u64(), Some(0));
} }
#[test] #[test]
@ -235,7 +259,7 @@ fn the_report_names_its_gaps_and_carries_representative_lines_and_usage() {
let model = chatty(); let model = chatty();
let harness = Harness { instance: "eureka".into(), persona: None, model: Some(&model), tuning: dir.path().join("persona-tuning.toml") }; 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(), "\"ruled\"", 3, "")).unwrap(); let report = simulate(&harness, &plan(dir.path(), "\"ruled\"", 3, "")).unwrap();
for part in ["# Swarm simulation", "State does not evolve during a run", "No explicit addressee", "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 |"] { 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}"); assert!(report.contains(part), "{part}\n{report}");
} }
} }
@ -253,3 +277,18 @@ fn a_cast_past_eight_or_a_foreign_state_is_refused() {
std::fs::write(&path, format!("rounds = 1\nstart = \"2026-11-20T15:00:00Z\"\nrooms = [\"#a:x\"]\n{many}")).unwrap(); std::fs::write(&path, format!("rounds = 1\nstart = \"2026-11-20T15:00:00Z\"\nrooms = [\"#a:x\"]\n{many}")).unwrap();
assert!(format!("{:#}", simulate(&harness, &path).unwrap_err()).contains("1 to 8")); assert!(format!("{:#}", simulate(&harness, &path).unwrap_err()).contains("1 to 8"));
} }
#[test]
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() { 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); let packet = packet_of(TurnKind::Chat, &state(), &chat_room(), &History::default(), 1);
assert_eq!(packet.present, ["Kiko", "Libby"], "newest first"); 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-kiko] Kiko \u{2014} 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-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("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); 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 room = chat_room();
let (tense, easy) = (packet_of(TurnKind::Chat, &state(), &room, &History::default(), 3), packet_of(TurnKind::Chat, &eased, &room, &History::default(), 3)); 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_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] #[test]
fn mood_is_movement_since_her_last_turn() { fn mood_is_movement_since_her_last_turn() {
let room = chat_room(); let room = chat_room();
let first = packet_of(TurnKind::Chat, &state(), &room, &History::default(), 1); 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(); let mut before = state();
before["activationProfile"]["situationalState"]["valence"]["currentActivation"] = json!(0.5); before["activationProfile"]["situationalState"]["valence"]["currentActivation"] = json!(0.5);
before["activationProfile"]["situationalState"]["arousal"]["currentActivation"] = json!(0.41); before["activationProfile"]["situationalState"]["arousal"]["currentActivation"] = json!(0.41);
let moved = packet_of(TurnKind::Chat, &state(), &room, &History { previous: Some(before), ..History::default() }, 1); 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); 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); 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] #[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; tuning.select.context_bytes = identity + 200;
let packet = packet_tuned(TurnKind::Chat, &fixed_only, &chat_room(), &History::default(), 1, &tuning); 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("- 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); 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; tuning.select.context_bytes = identity + 100;
let packet = packet_tuned(TurnKind::Chat, &fixed_only, &chat_room(), &History::default(), 1, &tuning); 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.context.contains("- mood") && !packet.context.contains("also here"), "{}", packet.context);
assert!(packet.identity.len() + packet.context.len() <= tuning.select.context_bytes); 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))); let no_table = run(&Stale(None, Some(written)));
assert!(no_table["why"].as_str().unwrap().contains("holds no addressing table"), "{no_table}"); 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 //! 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. //! 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 std::path::Path;
use anyhow::{Context, Result, bail}; use anyhow::{Context, Result, bail};
@ -17,12 +18,12 @@ use sha2::{Digest, Sha256};
pub const TUNING_ROOT: &str = "/etc/gamecult/minds"; pub const TUNING_ROOT: &str = "/etc/gamecult/minds";
pub const TUNING_FILE: &str = "persona-tuning.toml"; 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, /// The Persona stage's setting (map section 2): she continues the Projector's paragraph, her interior, with speech only
/// invariant 5). It licenses nothing: Ghostlight's membrane already says a thin moment gets little or nothing. /// 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 = "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."; 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. /// 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. /// The context room the fixed slots need beside the identity: the hour and the mood lines always fit.
const FIXED_ROOM: usize = 256; const FIXED_ROOM: usize = 256;
@ -39,13 +40,43 @@ const WORDS_MAX: usize = 2000;
/// The most room lines the group state reads: a recent window, not the room's history. /// The most room lines the group state reads: a recent window, not the room's history.
const GROUP_LINES_MAX: usize = 40; const GROUP_LINES_MAX: usize = 40;
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)] #[serde(default, deny_unknown_fields)]
pub struct Tuning { pub struct Tuning {
pub projector: ProjectorTuning, pub projector: ProjectorTuning,
pub persona: PersonaTuning, pub persona: PersonaTuning,
pub select: SelectTuning, pub select: SelectTuning,
pub lens: LensWeights, 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. /// The Projector's call: its model, its domain guidance and its word budgets.
@ -164,7 +195,7 @@ impl Default for SelectTuning {
people_full: 2, people_full: 2,
beat_tail_lines: 6, beat_tail_lines: 6,
group_state: true, group_state: true,
group_lines: 6, group_lines: 12,
group_bytes: 360, group_bytes: 360,
caps: PoolCaps::default(), caps: PoolCaps::default(),
} }

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(); 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_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"]["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. // 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(); 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)); assert_eq!(output.status.code(), Some(0), "{}", text(&output.stderr));

View file

@ -262,7 +262,7 @@ mind_body::projection::harness: impl MouthReader for Fixture
mind_body::projection::harness: pub use super :: simulate :: simulate ; 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 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 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: fn connector_key (credentials : & Path) -> Result < String >
mind_body::projection::narrate: impl Failed mind_body::projection::narrate: impl Failed
mind_body::projection::narrate: impl KitModel mind_body::projection::narrate: impl KitModel
@ -291,6 +291,7 @@ mind_body::projection::tuning: impl Default for PersonaTuning
mind_body::projection::tuning: impl Default for PoolCaps mind_body::projection::tuning: impl Default for PoolCaps
mind_body::projection::tuning: impl Default for ProjectorTuning mind_body::projection::tuning: impl Default for ProjectorTuning
mind_body::projection::tuning: impl Default for SelectTuning 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: 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 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 Loaded # [derive (Clone , Debug , PartialEq , Serialize)] pub-fields[tuning: Tuning, source: & 'static str, sha256: String]
@ -298,7 +299,7 @@ mind_body::projection::tuning: struct PersonaTuning # [derive (Clone , Debug , P
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 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 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, group_state: bool, group_lines: usize, group_bytes: usize, caps: PoolCaps] 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 , Default , PartialEq , Serialize , Deserialize)] pub-fields[projector: ProjectorTuning, persona: PersonaTuning, select: SelectTuning, lens: LensWeights] 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: fn on_hold (mind : & dyn MindPort) -> Result < Held >
mind_body::queue: impl Held mind_body::queue: impl Held
mind_body::queue: impl Held: fn contains (& self , item : & PipelineRef) -> bool mind_body::queue: impl Held: fn contains (& self , item : & PipelineRef) -> bool