From c32096631500288f8db015471652131178120b92 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 21:07:19 +0100 Subject: [PATCH 1/9] Persona wake: the Mind run lapses with the exchange window, only a new message wakes, one DM check, the drain reads her rooms as the poll does The Mind run ends after a silence of the exchange window, so a tag in #minds or a Mind-to-Mind DM wakes her again. An edit or a notice wakes no one on any path. A direct message is hers by address::is_for alone. The drain's own rooms come from heartbeat::own_rooms_among (the poll's stewardship reader, no forge URL), and an unread mind or mouth is named in the run's report. Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/bin/mind-persona.rs | 24 ++- crates/mind-body/src/heartbeat.rs | 43 +++-- crates/mind-body/src/heartbeat/tests.rs | 151 ++++++++++++++++++ crates/mind-body/src/projection/domain.rs | 40 ++--- crates/mind-body/src/projection/simulate.rs | 2 +- .../src/projection/simulate/tests.rs | 3 +- crates/mind-body/tests/public_surface.txt | 3 +- 7 files changed, 215 insertions(+), 51 deletions(-) diff --git a/crates/mind-body/src/bin/mind-persona.rs b/crates/mind-body/src/bin/mind-persona.rs index 01c7b2e..4d435fb 100644 --- a/crates/mind-body/src/bin/mind-persona.rs +++ b/crates/mind-body/src/bin/mind-persona.rs @@ -56,7 +56,8 @@ use mind_body::chat_rudp::{RudpChat, connection_id}; use mind_body::cli::{instance_and_endpoint, instance_and_maybe_endpoint}; use mind_body::control::{CONTROL_ROOT, FileSource, control_path, swarm_path}; use mind_body::persona::{Config, carry}; -use mind_body::heartbeat::{FileStore, HeartbeatView, own_rooms}; +use mind_body::heartbeat::{FileStore, HeartbeatView, own_rooms_among}; +use mind_body::queue::HuginnMind; use mind_body::projection::harness::{Fixture, Harness, batch, fixture_request, simulate, state_file}; use mind_body::projection::{DomainSource, HttpForge, HuginnPersonaSource, KitModel, LiveReads, MindDomain, Model, MouthReader, ReadSource, Organs as ProjectOrgans, PersonaSource, Request as ProjectRequest, TUNING_FILE, TUNING_ROOT, Through, TurnKind, connector_key, project}; @@ -199,13 +200,17 @@ fn run_project(args: &[String]) -> Result { (Some(address), Some(forge)) => Some(MindDomain::new(HuginnClient::new(address, instance.clone(), TIMEOUT), HttpForge::new(&forge))), _ => None, }; - // Her own rooms, as the heartbeat reads them: the rooms the mouth names for a repo she stewards. Unread, she has none. - let own = match (&domain, &chat) { - (Some(domain), Some(chat)) => match (domain.stewarded(), chat.pending()) { - (Ok(repos), Ok(pending)) => own_rooms(repos.iter().map(String::as_str), pending.deliveries.iter().map(|delivery| delivery.room_alias.as_str())), - _ => vec![], + // Her own rooms, as the heartbeat reads them: the rooms the mouth names for a repo she stewards. An unread mind or mouth is + // said in the report, not read as no rooms. + let (own, own_unread) = match (address, &chat) { + (Some(address), Some(chat)) => match chat.pending() { + Ok(pending) => match own_rooms_among(&HuginnMind::new(HuginnClient::new(address, instance.clone(), TIMEOUT)), pending.deliveries.iter().map(|delivery| delivery.room_alias.as_str())) { + Ok(rooms) => (rooms, None), + Err(error) => (vec![], Some(format!("her stewardships unread: {error}"))), + }, + Err(error) => (vec![], Some(format!("the mouth's pending unread: {error}"))), }, - _ => vec![], + _ => (vec![], None), }; // Her reads by intent (map 16.22.3): her mind through the same endpoint, the forge when it is named, the web. let reads = address.map(|address| LiveReads::new(HuginnClient::new(address, instance.clone(), TIMEOUT), setting("MIND_PERSONA_FORGE_URL").map(|forge| HttpForge::new(&forge)))); @@ -237,7 +242,10 @@ fn run_project(args: &[String]) -> Result { last_wake: None, records: vec![], }; - let report = project(&organs, &request, chrono::Utc::now())?; + let mut report = project(&organs, &request, chrono::Utc::now())?; + if let Some(unread) = own_unread { + report["own_rooms_unread"] = unread.into(); + } let addressing = &report["addressing"]; // The addressing source is what decides "said to her": said first, where a person running this by hand sees it. eprintln!( diff --git a/crates/mind-body/src/heartbeat.rs b/crates/mind-body/src/heartbeat.rs index c64c126..c1c16f2 100644 --- a/crates/mind-body/src/heartbeat.rs +++ b/crates/mind-body/src/heartbeat.rs @@ -32,7 +32,7 @@ use eureka_pipeline::{OrgRepo, PipelineKind, RunTurn, Slug}; use huginn_mind::PipelineFacts; use crate::address::{Addressee, Name, is_for, project_names}; -use crate::chat_client::{Basis, Chat, ChatDelivery}; +use crate::chat_client::{Basis, Chat, ChatDelivery, Form}; use crate::control::{ControlSource, Effective, FileSource, HeldReason, SwarmEffective, read_effective, read_envelope, set_mode_world_readable}; use crate::launch::{Clock, Launcher}; use crate::queue::{MindPort, headers, in_force, of_kind}; @@ -441,10 +441,11 @@ pub(crate) enum WakeCause { /// What the room says about a line, beside the line: the facts `wakes` weighs, from `line_facts`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct LineFacts { - /// How many lines her current Mind-only run held before this one: one run across every room she sees, so a loop - /// cannot dodge the backstop by changing rooms, and ended only by a human's line in a room the run has lines in. + /// How many lines her current Mind-only run held before this one: one run across every line the caller gives, so a + /// loop cannot dodge the backstop by changing rooms. A human's line in a room the run has lines in ends it, and so + /// does a silence of the exchange window: no line within it, and the next Mind's tag starts afresh. pub mind_run: usize, - /// The line is in a room of hers: a direct message, or a room named for a repo she stewards (`own_rooms`). + /// The line is in a room named for a repo she stewards (`own_rooms`). A direct message is hers by `address::is_for`. 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, @@ -464,18 +465,28 @@ pub(crate) struct FactLine<'a> { pub sender: &'a str, pub room: &'a str, pub at_ms: u64, - pub is_direct: bool, } /// The facts of every line of an ordered list of the lines she sees, hers included: the one owner of the Mind run, her /// rooms and her exchange, for the live poll and the simulator alike. `minds` is every Mind of the roster, her too. +/// Both count over the lines they are given and no others: the simulator gives every line of every room she is in; the poll +/// gives the pending deliveries and the mouth's context of each (at most 20 earlier lines of its room), because the mouth +/// shows her no room that has nothing pending. So live, a run that alternates rooms is counted per room that has +/// something pending, and an exchange 20 lines back is not seen; the simulator overstates the bound by that much. pub(crate) fn line_facts(lines: &[FactLine], her: &str, minds: &[String], own_rooms: &[String], window_ms: u64) -> Vec { let mut run = 0usize; let mut run_rooms: Vec<&str> = Vec::new(); + let mut last_at: Option = None; lines .iter() .enumerate() .map(|(at, line)| { + // The run lapses with time: no line within the window before this one, and no run is left to count. + if last_at.is_some_and(|last| line.at_ms.saturating_sub(last) > window_ms) { + run = 0; + run_rooms.clear(); + } + last_at = Some(line.at_ms); let mind_run = run; if minds.iter().any(|mind| mind == line.sender) { run += 1; @@ -487,16 +498,23 @@ pub(crate) fn line_facts(lines: &[FactLine], her: &str, minds: &[String], own_ro let since = line.at_ms.saturating_sub(window_ms); LineFacts { mind_run, - own_room: line.is_direct || own_rooms.iter().any(|room| room == line.room), + own_room: own_rooms.iter().any(|room| room == line.room), in_exchange: lines[..at].iter().any(|earlier| earlier.room == line.room && earlier.sender == her && earlier.at_ms >= since), } }) .collect() } +/// Her own rooms among `aliases`, read from her mind the way the poll reads her stewardships (`stewardships_of`): the drain's +/// input. An unreadable mind is an error for the caller to report, never an empty answer. +pub fn own_rooms_among<'a>(mind: &dyn MindPort, aliases: impl IntoIterator) -> Result> { + let (_, repos) = stewardships_of(mind)?; + Ok(own_rooms(repos.iter().map(|repo| repo.0.as_str()), aliases)) +} + /// Which of `aliases` are her own rooms: those named for a repo she stewards (`#huginn:gamecult.org` for `GameCult/Huginn`), -/// case-blind. A direct message is hers by `FactLine::is_direct`, not by name. -pub fn own_rooms<'a>(repos: impl IntoIterator, aliases: impl IntoIterator) -> Vec { +/// case-blind. A direct message is hers by `address::is_for`, not by name. +pub(crate) fn own_rooms<'a>(repos: impl IntoIterator, aliases: impl IntoIterator) -> Vec { let names: Vec<&str> = repos.into_iter().map(|repo| repo.rsplit_once('/').map_or(repo, |(_, name)| name)).collect(); let mut found: Vec = Vec::new(); for alias in aliases { @@ -514,12 +532,13 @@ pub fn own_rooms<'a>(repos: impl IntoIterator, aliases: impl Int /// 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 `MIND_RUN_BACKSTOP` Mind lines in a row came before it across her rooms. pub(crate) fn wakes(who: &Addressee, delivery: &ChatDelivery, speaker: Speaker, facts: LineFacts) -> Option { - if speaker == Speaker::Her { + // Only a new message wakes her: an edit of a line, or a notice, never does, whoever sent it. + if speaker == Speaker::Her || delivery.form != Form::Message { return None; } let addressed = is_for(who, delivery); if speaker.human() { - let wakes = addressed || delivery.is_direct || facts.own_room || facts.in_exchange; + let wakes = addressed || facts.own_room || facts.in_exchange; return wakes.then_some(if addressed { WakeCause::AddressedByHuman } else { WakeCause::Human }); } let explicit = delivery.mentions.iter().any(|id| id == who.matrix_id()) || matches!(delivery.basis, Some(Basis::Tag | Basis::Reply)); @@ -550,12 +569,12 @@ pub(crate) fn pending_facts(pending: &[&ChatDelivery], her: &str, minds: &[Strin let room = delivery.room_alias.as_str(); for context in &delivery.context { if !lines.iter().any(|(held, _)| held.room == room && held.sender == context.sender && held.at_ms == context.at_unix_ms) { - lines.push((FactLine { sender: &context.sender, room, at_ms: context.at_unix_ms, is_direct: delivery.is_direct }, None)); + lines.push((FactLine { sender: &context.sender, room, at_ms: context.at_unix_ms }, None)); } } match lines.iter_mut().find(|(held, _)| held.room == room && held.sender == delivery.sender && held.at_ms == delivery.at_unix_ms) { Some((_, slot)) => *slot = Some(index), - None => lines.push((FactLine { sender: &delivery.sender, room, at_ms: delivery.at_unix_ms, is_direct: delivery.is_direct }, Some(index))), + None => lines.push((FactLine { sender: &delivery.sender, room, at_ms: delivery.at_unix_ms }, Some(index))), } } lines.sort_by_key(|(line, _)| line.at_ms); diff --git a/crates/mind-body/src/heartbeat/tests.rs b/crates/mind-body/src/heartbeat/tests.rs index af08819..4636ae6 100644 --- a/crates/mind-body/src/heartbeat/tests.rs +++ b/crates/mind-body/src/heartbeat/tests.rs @@ -733,3 +733,154 @@ fn a_member_line_in_a_room_named_for_her_repo_wakes_her_off_the_beat() { rig.say(BOB, delivery(2, "@member:chat", "what a day", &[])); assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "#swarm is named for her repo"); } + +/// The wake rule over the facts the poll builds: the pending deliveries and their context, as Bob (`@bob:chat`) reads them. +mod wake_rule { + use super::*; + use crate::chat_client::ContextLine; + + const DAY: u64 = 86_400_000; + const MINUTE: u64 = 60_000; + + fn bob() -> Addressee { + Addressee::new("@bob:chat", ["Bob"]) + } + + fn minds() -> Vec { + vec!["@ann:chat".into(), "@bob:chat".into()] + } + + fn said(sender: &str, at: u64) -> ContextLine { + ContextLine { sender: sender.into(), text: "x".into(), at_unix_ms: at } + } + + /// What the poll concludes for one delivery (its context is its own); `own` are her rooms. + fn woken(line: &ChatDelivery, speaker: Speaker, own: &[&str]) -> Option { + let own: Vec = own.iter().map(|room| (*room).to_owned()).collect(); + let facts = pending_facts(&[line], "@bob:chat", &minds(), &own); + wakes(&bob(), line, speaker, facts[0]) + } + + /// Four alternating Mind lines, the last of them `ago` before `at`, a minute apart. + fn four_minds(at: u64, ago: u64) -> Vec { + (0..4).map(|index| said(if index % 2 == 0 { "@ann:chat" } else { "@bob:chat" }, at - ago - (4 - index) * MINUTE)).collect() + } + + fn tag(room: &str, at: u64, context: Vec) -> ChatDelivery { + ChatDelivery { room_alias: room.into(), at_unix_ms: at, context, ..delivery(1, "@ann:chat", "a word", &["@bob:chat"]) } + } + + #[test] + fn a_minds_tag_wakes_her_after_a_silence_in_a_room_no_human_speaks_in() { + let now = 2 * DAY; + let old = four_minds(now, now - 10 * MINUTE); + assert_eq!(woken(&tag("#minds:chat", now, old.clone()), Speaker::Mind, &[]), Some(WakeCause::AddressedByMind), "four Mind lines two days ago are no run now"); + let reply = ChatDelivery { basis: Some(Basis::Reply), is_direct: true, room_alias: "!dm:chat".into(), context: old, at_unix_ms: now, ..delivery(2, "@ann:chat", "a word", &[]) }; + assert_eq!(woken(&reply, Speaker::Mind, &[]), Some(WakeCause::AddressedByMind), "a Mind-to-Mind DM reply the same"); + } + + #[test] + fn the_backstop_is_four_mind_lines_in_a_row_within_the_exchange_window() { + let now = 3 * DAY; + let three = four_minds(now, MINUTE)[1..].to_vec(); + assert_eq!(woken(&tag("#minds:chat", now, three), Speaker::Mind, &[]), Some(WakeCause::AddressedByMind), "three before it still wake"); + assert_eq!(woken(&tag("#minds:chat", now, four_minds(now, MINUTE)), Speaker::Mind, &[]), None, "four in a row wake no one"); + let after = |ago: u64| woken(&tag("#minds:chat", now, four_minds(now, ago)), Speaker::Mind, &[]); + assert_eq!(after(29 * MINUTE), None, "the last of the four came exactly a window before: the run stands"); + assert_eq!(after(29 * MINUTE + 1), Some(WakeCause::AddressedByMind), "a moment longer and it is over"); + } + + #[test] + fn a_minds_reply_or_tag_wakes_her_with_no_matrix_mention() { + for basis in [Basis::Reply, Basis::Tag] { + let line = ChatDelivery { basis: Some(basis), ..delivery(1, "@ann:chat", "a word", &[]) }; + assert_eq!(woken(&line, Speaker::Mind, &[]), Some(WakeCause::AddressedByMind), "{basis:?}"); + } + assert_eq!(woken(&delivery(1, "@ann:chat", "a word", &[]), Speaker::Mind, &[]), None, "no mention, no basis"); + } + + #[test] + fn only_a_new_message_wakes_her_on_every_path() { + let own = ["#swarm:chat"]; + let exchange = ChatDelivery { room_alias: "#general:chat".into(), at_unix_ms: 10 * MINUTE, context: vec![said("@bob:chat", 5 * MINUTE)], ..delivery(3, "@member:chat", "fixed", &[]) }; + assert_eq!(woken(&exchange, Speaker::Member, &[]), Some(WakeCause::Human), "as a message, the line is in her exchange"); + assert_eq!(woken(&delivery(2, "@ci-bot:chat", "build green", &[]), Speaker::Member, &own), Some(WakeCause::Human), "and in her project room"); + for form in [Form::Edit, Form::Notice] { + let formed = |line: ChatDelivery| ChatDelivery { form, ..line }; + assert_eq!(woken(&formed(ChatDelivery { is_direct: true, room_alias: "!dm:chat".into(), ..delivery(1, "@member:chat", "fixed", &[]) }), Speaker::Member, &[]), None, "{form:?} in a DM"); + assert_eq!(woken(&formed(delivery(2, "@ci-bot:chat", "build green", &[])), Speaker::Member, &own), None, "{form:?} in her project room"); + assert_eq!(woken(&formed(exchange.clone()), Speaker::Member, &[]), None, "{form:?} in her exchange"); + assert_eq!(woken(&formed(delivery(4, "@member:chat", "Bob?", &["@bob:chat"])), Speaker::Member, &[]), None, "{form:?} naming her"); + assert_eq!(woken(&formed(delivery(5, "@ann:chat", "a word", &["@bob:chat"])), Speaker::Mind, &[]), None, "{form:?} from a Mind carrying her mention"); + } + let rig = quiet_rig(); + steward(&rig, BOB, "GameCult/Swarm", &[]); + rig.say(BOB, ChatDelivery { form: Form::Notice, ..delivery(1, "@ci-bot:chat", "build green", &[]) }); + rig.say(BOB, ChatDelivery { form: Form::Edit, is_direct: true, room_alias: "!dm:chat".into(), ..delivery(2, "@member:chat", "fixed", &[]) }); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "off the beat, a notice and an edit start no turn"); + } + + #[test] + fn a_direct_message_wakes_her_as_addressed_by_the_one_check_in_is_for() { + let dm = ChatDelivery { is_direct: true, room_alias: "!dm:chat".into(), ..delivery(1, "@member:chat", "psst", &[]) }; + assert_eq!(woken(&dm, Speaker::Member, &[]), Some(WakeCause::AddressedByHuman)); + } + + /// Ruling persona-attention-and-initiative (2) wants an open hello answered by some Mind; the rule has no fact for it. + #[test] + fn a_member_naming_her_untagged_in_a_public_room_wakes_her_and_a_hello_to_everyone_wakes_no_one() { + let general = |text: &str| ChatDelivery { room_alias: "#general:chat".into(), ..delivery(1, "@member:chat", text, &[]) }; + assert_eq!(woken(&general("Bob, can you look at this?"), Speaker::Member, &[]), Some(WakeCause::AddressedByHuman)); + assert_eq!(woken(&general("hello everyone!"), Speaker::Member, &[]), None); + let rig = quiet_rig(); + for who in [ANN, BOB] { + rig.say(who, ChatDelivery { room_alias: "#general:chat".into(), ..delivery(1, "@newcomer:chat", "hello everyone!", &[]) }); + } + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "no Mind is woken by it off the beat"); + } + + #[test] + fn the_exchange_holds_to_the_millisecond_of_the_window() { + let window = 30 * MINUTE; + let line = |sender, at_ms| FactLine { sender, room: "#general:chat", at_ms }; + let in_exchange = |gap: u64| line_facts(&[line("@bob:chat", 0), line("@member:chat", gap)], "@bob:chat", &minds(), &[], window)[1].in_exchange; + assert!(in_exchange(window), "a line exactly one window after hers is in her exchange"); + assert!(!in_exchange(window + 1)); + } + + #[test] + fn the_mind_run_lapses_after_a_silence_longer_than_the_window_and_not_before() { + let window = 30 * MINUTE; + let line = |sender, at_ms| FactLine { sender, room: "#minds:chat", at_ms }; + let run = |gap: u64| { + let lines = [line("@ann:chat", 0), line("@bob:chat", MINUTE), line("@ann:chat", 2 * MINUTE), line("@bob:chat", 3 * MINUTE), line("@ann:chat", 3 * MINUTE + gap)]; + line_facts(&lines, "@bob:chat", &minds(), &[], window)[4].mind_run + }; + assert_eq!(run(window), 4, "a silence of exactly the window keeps the run"); + assert_eq!(run(window + 1), 0, "a longer one ends it, in a room no human speaks in"); + } + + #[test] + fn her_own_rooms_are_read_from_her_mind_as_the_poll_reads_them_and_an_unreadable_mind_is_an_error() { + let rig = quiet_rig(); + steward(&rig, BOB, "GameCult/Swarm", &[]); + // A stewardship of another instance held in her mind: the poll's reader counts it, so the drain's does. + rig.minds[BOB].committed(vec![PipelineDocument::Stewardship(eureka_pipeline::PipelineStewardship { + instance: Slug("ann".into()), + repo: "GameCult/Annwork".into(), + sequence: 1, + assigned_on: eureka_pipeline::Date("2026-11-06".into()), + note: "assigned".into(), + names: vec![], + })]); + let aliases = ["#SWARM:chat", "#annwork:chat", "#general:chat", "!dm:chat"]; + let rooms = |down: bool| { + let (calls, admits, reads, stewardship_down) = (Cell::new(0), Cell::new(0), Cell::new(0), Cell::new(down)); + own_rooms_among(&Counting { inner: &rig.minds[BOB], calls: &calls, admits: &admits, stewardship_reads: &reads, stewardship_down: &stewardship_down }, aliases) + }; + assert_eq!(rooms(false).unwrap(), vec!["#SWARM:chat".to_owned(), "#annwork:chat".to_owned()]); + assert!(rooms(true).is_err(), "unread is an error the caller reports, not no rooms"); + rig.say(BOB, ChatDelivery { room_alias: "#annwork:chat".into(), ..delivery(1, "@member:chat", "what a day", &[]) }); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "the poll reads the same room as hers"); + } +} diff --git a/crates/mind-body/src/projection/domain.rs b/crates/mind-body/src/projection/domain.rs index 36473a9..f94ea69 100644 --- a/crates/mind-body/src/projection/domain.rs +++ b/crates/mind-body/src/projection/domain.rs @@ -190,25 +190,17 @@ impl MindDomain { } } -impl MindDomain { - fn ask(&self, selection: &Selection) -> Result { - let request = HuginnMindRequest::Query { instance: self.client.instance().clone(), selection: selection.clone(), semantic: None }; - match self.client.call(request).map_err(|_| anyhow!("her mind could not be asked"))? { - HuginnMindResponse::Query(page) => Ok(page), - HuginnMindResponse::Refused(_) => bail!("her mind refused the read"), - _ => bail!("her mind answered a read with something else"), - } - } - - /// The repos she stewards in force (`Org/Repo`), through her read door: the drain's input to `heartbeat::own_rooms`. - pub fn stewarded(&self) -> Result> { - stewarded(&|selection| self.ask(selection), &self.client.instance().0) - } -} - impl DomainSource for MindDomain { fn read(&self, since: DateTime, now: DateTime) -> Result { - read(&|selection| self.ask(selection), &self.client.instance().0, &self.forge, since, now) + let ask = |selection: &Selection| -> Result { + let request = HuginnMindRequest::Query { instance: self.client.instance().clone(), selection: selection.clone(), semantic: None }; + match self.client.call(request).map_err(|_| anyhow!("her mind could not be asked"))? { + HuginnMindResponse::Query(page) => Ok(page), + HuginnMindResponse::Refused(_) => bail!("her mind refused the read"), + _ => bail!("her mind answered a read with something else"), + } + }; + read(&ask, &self.client.instance().0, &self.forge, since, now) } } @@ -296,8 +288,10 @@ fn who(provenance: &PipelineProvenance, her: &str) -> Who { } } -/// The repos `her` stewards in force, each once. -pub(crate) fn stewarded(ask: &Ask, her: &str) -> Result> { +/// Her domain from `since`: her in-force stewardships and her campaigns through `ask` (her door), each stewarded repo's +/// pull requests through `forge`. Any failure fails the whole read, except a repo that is archived, missing or moved, +/// which is skipped and named. +pub(crate) fn read(ask: &Ask, her: &str, forge: &dyn ForgeGet, since: DateTime, now: DateTime) -> Result { let mut repos: Vec = Vec::new(); for item in all(ask, &in_force(of_kind(PipelineKind::Stewardship)))? { if let PipelineFacts::Stewardship { instance, repo, .. } = &item.facts @@ -307,14 +301,6 @@ pub(crate) fn stewarded(ask: &Ask, her: &str) -> Result> { repos.push(repo.0.clone()); } } - Ok(repos) -} - -/// Her domain from `since`: her in-force stewardships and her campaigns through `ask` (her door), each stewarded repo's -/// pull requests through `forge`. Any failure fails the whole read, except a repo that is archived, missing or moved, -/// which is skipped and named. -pub(crate) fn read(ask: &Ask, her: &str, forge: &dyn ForgeGet, since: DateTime, now: DateTime) -> Result { - let repos = stewarded(ask, her)?; let slugs: Vec = all(ask, &in_force(of_kind(PipelineKind::Campaign)))?.iter().map(|item| root(item).to_owned()).collect::>().into_iter().collect(); let mut campaigns: Vec = slugs.iter().map(|slug| CampaignFacts { slug: slug.clone(), rulings: Vec::new() }).collect(); if !slugs.is_empty() { diff --git a/crates/mind-body/src/projection/simulate.rs b/crates/mind-body/src/projection/simulate.rs index 83cbb3d..ac72f22 100644 --- a/crates/mind-body/src/projection/simulate.rs +++ b/crates/mind-body/src/projection/simulate.rs @@ -218,7 +218,7 @@ struct Woken { fn woken(lines: &[Line], seen: &Seen, member: &Member, operators: &[String], cast: &[String], gap: Duration) -> Option { // The lines she sees, and their facts from the heartbeat's one owner of them. let visible: Vec = (0..lines.len()).filter(|at| lines[*at].visible_to(&member.entry.id, &member.rooms)).collect(); - let seeing: Vec = visible.iter().map(|at| FactLine { sender: &lines[*at].from, room: &lines[*at].room, at_ms: lines[*at].at_ms, is_direct: lines[*at].dm_to.is_some() }).collect(); + let seeing: Vec = visible.iter().map(|at| FactLine { sender: &lines[*at].from, room: &lines[*at].room, at_ms: lines[*at].at_ms }).collect(); let facts = line_facts(&seeing, &member.entry.id, cast, &member.entry.own_rooms, u64::try_from(gap.num_milliseconds()).unwrap_or(0)); let mut found: Vec<(usize, WakeCause)> = Vec::new(); for (at, facts) in visible.into_iter().zip(facts) { diff --git a/crates/mind-body/src/projection/simulate/tests.rs b/crates/mind-body/src/projection/simulate/tests.rs index 4e8b2ef..c8836f1 100644 --- a/crates/mind-body/src/projection/simulate/tests.rs +++ b/crates/mind-body/src/projection/simulate/tests.rs @@ -178,8 +178,9 @@ fn t_w1_same_facts_both_paths() { assert_eq!(by_sim, by_poll); assert_eq!(by_sim, vec![None, Some(WakeCause::Human), Some(WakeCause::Human), Some(WakeCause::AddressedByMind), None], "a general line before she spoke, one in her exchange, her room, a Mind's tag, a general line after the exchange lapsed"); for (at, facts) in heard.iter().zip(&polled) { - assert_eq!((facts.own_room, facts.in_exchange), (simulated[*at].own_room, simulated[*at].in_exchange), "line {at}"); + assert_eq!((facts.mind_run, facts.own_room, facts.in_exchange), (simulated[*at].mind_run, simulated[*at].own_room, simulated[*at].in_exchange), "line {at}"); } + assert_eq!(polled.iter().map(|facts| facts.mind_run).collect::>(), vec![0, 1, 0, 0, 0], "her line, then a human's line that ends the run, then a Mind's tag after both"); } #[test] diff --git a/crates/mind-body/tests/public_surface.txt b/crates/mind-body/tests/public_surface.txt index 372db1c..09c301c 100644 --- a/crates/mind-body/tests/public_surface.txt +++ b/crates/mind-body/tests/public_surface.txt @@ -149,7 +149,7 @@ mind_body::control: struct SwarmWriter pub-fields[] mind_body::control: struct UnsafeStore # [derive (Debug)] pub-fields[path: PathBuf, mode: u32, uid: u32] mind_body::heartbeat: # [derive (Clone , Debug , PartialEq , Eq)] pub enum Outcome { Held (HeldReason) , Polled { launched : Vec < Slug > , } , } mind_body::heartbeat: const DEFAULT_BEAT_S : u32 -mind_body::heartbeat: fn own_rooms < 'a > (repos : impl IntoIterator < Item = & 'a str > , aliases : impl IntoIterator < Item = & 'a str >) -> Vec < String > +mind_body::heartbeat: fn own_rooms_among < 'a > (mind : & dyn MindPort , aliases : impl IntoIterator < Item = & 'a str >) -> Result < Vec < String > > mind_body::heartbeat: fn poll (organs : & Organs , config : & Config) -> Result < Outcome > mind_body::heartbeat: impl Config mind_body::heartbeat: impl Config: fn new (personas : Vec < PersonaId > , operators : Vec < String > , beat_s : u32) -> Result < Self > @@ -261,7 +261,6 @@ mind_body::projection::domain: impl HttpForge mind_body::projection::domain: impl HttpForge: fn new (base_url : & str) -> Self mind_body::projection::domain: impl MindDomain mind_body::projection::domain: impl MindDomain: fn new (client : HuginnClient , forge : HttpForge) -> Self -mind_body::projection::domain: impl MindDomain: fn stewarded (& self) -> Result < Vec < String > > mind_body::projection::domain: impl Names mind_body::projection::domain: pub trait DomainSource { fn read (& self , since : DateTime < Utc > , now : DateTime < Utc >) -> Result < DomainFacts > ; } mind_body::projection::domain: struct DomainFacts # [derive (Clone , Debug , Default , PartialEq , Eq , Serialize , Deserialize)] pub-fields[] From 760cc8fb81540e9bceb1f110b57166b4382dc282 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 21:07:24 +0100 Subject: [PATCH 2/9] Persona wake: the simulator's tests drop FactLine's retired is_direct, and the parity test pins the Mind run Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/projection/simulate/tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/mind-body/src/projection/simulate/tests.rs b/crates/mind-body/src/projection/simulate/tests.rs index c8836f1..776d817 100644 --- a/crates/mind-body/src/projection/simulate/tests.rs +++ b/crates/mind-body/src/projection/simulate/tests.rs @@ -159,7 +159,7 @@ fn t_w1_same_facts_both_paths() { let libby = Addressee::new(LIBBY, ["libby", "Libby"]); let speaker = |line: &Line| if line.from == TOBIAH { Speaker::Mind } else { Speaker::Member }; // The simulator's path: the lines she sees, in order. - let seeing: Vec = lines.iter().map(|line| FactLine { sender: &line.from, room: &line.room, at_ms: line.at_ms, is_direct: false }).collect(); + let seeing: Vec = lines.iter().map(|line| FactLine { sender: &line.from, room: &line.room, at_ms: line.at_ms }).collect(); let simulated = line_facts(&seeing, LIBBY, &cast, &own, 30 * 60_000); // The poll's path: the deliveries pending (not her own lines), each with the room's earlier lines as its context. let heard: Vec = (0..lines.len()).filter(|at| lines[*at].from != LIBBY).collect(); @@ -331,7 +331,7 @@ fn a_direct_message_in_one_of_the_plans_rooms_is_refused() { #[test] fn the_mind_run_is_counted_across_her_rooms_and_an_uncounted_run_is_at_the_cap() { let cast = vec![TOBIAH.to_owned(), LIBBY.to_owned(), "@kiko:x".to_owned(), "@other:x".to_owned()]; - let line = |from: &'static str, room: &'static str| FactLine { sender: from, room, at_ms: 0, is_direct: false }; + let line = |from: &'static str, room: &'static str| FactLine { sender: from, room, at_ms: 0 }; let run = |lines: &[FactLine]| line_facts(lines, "@kiko:x", &cast, &[], 0).iter().map(|facts| facts.mind_run).collect::>(); assert_eq!(run(&[line("@meta:x", "#a:x"), line(TOBIAH, "#a:x"), line("@other:x", "#b:x"), line(TOBIAH, "#b:x")]), vec![0, 0, 1, 2]); // Soul's case: Meta chatting in #eureka does not end a loop in #minds; a word from Meta in #minds does. From 355b6237a62984e91ee4d2bf0f28843f8afdf0f3 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 21:08:40 +0100 Subject: [PATCH 3/9] Persona wake: own_rooms takes its repos and aliases at their own lifetimes Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/heartbeat.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mind-body/src/heartbeat.rs b/crates/mind-body/src/heartbeat.rs index c1c16f2..499d0f2 100644 --- a/crates/mind-body/src/heartbeat.rs +++ b/crates/mind-body/src/heartbeat.rs @@ -514,7 +514,7 @@ pub fn own_rooms_among<'a>(mind: &dyn MindPort, aliases: impl IntoIterator(repos: impl IntoIterator, aliases: impl IntoIterator) -> Vec { +pub(crate) fn own_rooms<'r, 'a>(repos: impl IntoIterator, aliases: impl IntoIterator) -> Vec { let names: Vec<&str> = repos.into_iter().map(|repo| repo.rsplit_once('/').map_or(repo, |(_, name)| name)).collect(); let mut found: Vec = Vec::new(); for alias in aliases { From 4b134c3d1eaa1de0e68b5a018f7e603e868c580e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 21:11:40 +0100 Subject: [PATCH 4/9] Persona wake: the drain's own-rooms test follows the mind's one-instance rule Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/heartbeat/tests.rs | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/crates/mind-body/src/heartbeat/tests.rs b/crates/mind-body/src/heartbeat/tests.rs index 4636ae6..3f7be7c 100644 --- a/crates/mind-body/src/heartbeat/tests.rs +++ b/crates/mind-body/src/heartbeat/tests.rs @@ -864,23 +864,15 @@ mod wake_rule { fn her_own_rooms_are_read_from_her_mind_as_the_poll_reads_them_and_an_unreadable_mind_is_an_error() { let rig = quiet_rig(); steward(&rig, BOB, "GameCult/Swarm", &[]); - // A stewardship of another instance held in her mind: the poll's reader counts it, so the drain's does. - rig.minds[BOB].committed(vec![PipelineDocument::Stewardship(eureka_pipeline::PipelineStewardship { - instance: Slug("ann".into()), - repo: "GameCult/Annwork".into(), - sequence: 1, - assigned_on: eureka_pipeline::Date("2026-11-06".into()), - note: "assigned".into(), - names: vec![], - })]); - let aliases = ["#SWARM:chat", "#annwork:chat", "#general:chat", "!dm:chat"]; + // Her mind refuses another instance's stewardship (ForeignInstance), so the poll's and the drain's readers cannot disagree on instance. + let aliases = ["#SWARM:chat", "#general:chat", "!dm:chat"]; let rooms = |down: bool| { let (calls, admits, reads, stewardship_down) = (Cell::new(0), Cell::new(0), Cell::new(0), Cell::new(down)); own_rooms_among(&Counting { inner: &rig.minds[BOB], calls: &calls, admits: &admits, stewardship_reads: &reads, stewardship_down: &stewardship_down }, aliases) }; - assert_eq!(rooms(false).unwrap(), vec!["#SWARM:chat".to_owned(), "#annwork:chat".to_owned()]); + assert_eq!(rooms(false).unwrap(), vec!["#SWARM:chat".to_owned()]); assert!(rooms(true).is_err(), "unread is an error the caller reports, not no rooms"); - rig.say(BOB, ChatDelivery { room_alias: "#annwork:chat".into(), ..delivery(1, "@member:chat", "what a day", &[]) }); + rig.say(BOB, ChatDelivery { ..delivery(1, "@member:chat", "what a day", &[]) }); assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "the poll reads the same room as hers"); } } From 64e61dd20e3b7518f7c700bf42014dddc87a3173 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 21:34:27 +0100 Subject: [PATCH 5/9] Persona wake: a member's open hello in a public room wakes one Mind, the beat's pick A member's untagged new message in a public room that names no Mind wakes exactly one Mind when no Mind of the roster has spoken there within the exchange window. She is the winner of tempo::pick among the Minds that hear the line, so the poll and the simulator choose the same one; a handled key (the poll) or the simulator's taken set keeps it once per line. Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/heartbeat.rs | 136 +++++++++++++++--- crates/mind-body/src/heartbeat/tests.rs | 113 ++++++++++++--- crates/mind-body/src/projection/simulate.rs | 63 +++++++- .../src/projection/simulate/tests.rs | 33 ++++- 4 files changed, 294 insertions(+), 51 deletions(-) diff --git a/crates/mind-body/src/heartbeat.rs b/crates/mind-body/src/heartbeat.rs index 499d0f2..f9f4c1d 100644 --- a/crates/mind-body/src/heartbeat.rs +++ b/crates/mind-body/src/heartbeat.rs @@ -449,13 +449,16 @@ pub(crate) struct LineFacts { 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, + /// No Mind of the roster has spoken in the line's room within the exchange window before it. `line_facts` sets it from + /// the lines; the caller leaves it set only for the Mind the floor falls to (`floor_to`), and `wakes` reads it as hers. + pub open_floor: bool, } /// Fail-safe: a caller that has not counted the Mind run is at the cap, so a Mind's line wakes no one; the room facts /// are unknown, so none opens a wake. impl Default for LineFacts { fn default() -> Self { - Self { mind_run: usize::MAX, own_room: false, in_exchange: false } + Self { mind_run: usize::MAX, own_room: false, in_exchange: false, open_floor: false } } } @@ -500,6 +503,7 @@ pub(crate) fn line_facts(lines: &[FactLine], her: &str, minds: &[String], own_ro mind_run, own_room: own_rooms.iter().any(|room| room == line.room), in_exchange: lines[..at].iter().any(|earlier| earlier.room == line.room && earlier.sender == her && earlier.at_ms >= since), + open_floor: !lines[..at].iter().any(|earlier| earlier.room == line.room && earlier.at_ms >= since && minds.iter().any(|mind| *mind == earlier.sender)), } }) .collect() @@ -538,13 +542,57 @@ pub(crate) fn wakes(who: &Addressee, delivery: &ChatDelivery, speaker: Speaker, } let addressed = is_for(who, delivery); if speaker.human() { - let wakes = addressed || facts.own_room || facts.in_exchange; + let wakes = addressed || facts.own_room || facts.in_exchange || (speaker == Speaker::Member && facts.open_floor); return wakes.then_some(if addressed { WakeCause::AddressedByHuman } else { WakeCause::Human }); } let explicit = delivery.mentions.iter().any(|id| id == who.matrix_id()) || matches!(delivery.basis, Some(Basis::Tag | Basis::Reply)); (explicit && facts.mind_run < MIND_RUN_BACKSTOP).then_some(WakeCause::AddressedByMind) } +/// One Mind that has a line pending, as the open floor sees her: the line as her mouth gave it, whether its room's floor is open +/// to her (`LineFacts::open_floor`), and her standing in the beat's pick. +pub(crate) struct Hearer<'a> { + pub addressee: &'a Addressee, + pub delivery: ChatDelivery, + pub open: bool, + pub standing: Standing, +} + +/// The one Mind an open line falls to, as an index into `hearers`: a member's untagged new message in a public room that +/// names no Mind of the roster, when no Mind has spoken there within the exchange window. She is the beat's pick +/// (`tempo::pick`) among the hearers whose floor is open, so the poll and the simulator choose the same one. None when the +/// line is not open or no hearer is eligible. +pub(crate) fn floor_to(hearers: &[Hearer], speaker: Speaker, beat_s: u32) -> Option { + let line = &hearers.first()?.delivery; + let open = speaker == Speaker::Member + && line.form == Form::Message + && !hearers.iter().any(|hearer| hearer.delivery.is_direct || !hearer.delivery.mentions.is_empty() || is_for(hearer.addressee, &hearer.delivery)); + if !open { + return None; + } + let candidates: Vec = (0..hearers.len()).filter(|at| hearers[*at].open).collect(); + let standings: Vec = candidates.iter().map(|at| hearers[*at].standing.clone()).collect(); + tempo::pick(&standings, beat_s).map(|at| candidates[at]) +} + +/// Every Mind's standing in the pick, from the heartbeat's state: eligible when idle and released. +fn standings_of(rows: &[Row], state: &HeartbeatState, now: DateTime, config: &Config) -> Vec { + rows.iter() + .map(|row| { + let last = state.last_turn_at.get(&row.slug().0).copied(); + Standing { + slug: row.slug().0.clone(), + eligible: row.idle(), + waited_s: last.map(|turn| u64::try_from((now - turn).num_seconds()).unwrap_or(0)), + last_turn_ms: last.map(|turn| turn.timestamp_millis()), + // The seam for topic subscriptions (a later cut): a Mind's nearest subscription scores her deliveries here. + topic_permille: 0, + addressed_by_member: row.addressed_by_member(config), + } + }) + .collect() +} + impl Config { /// Who sent a delivery, as `wakes` sees them. fn speaker(&self, who: &Addressee, delivery: &ChatDelivery) -> Speaker { @@ -608,6 +656,56 @@ fn read_pending(chat: &dyn Chat) -> Result> { Ok(all) } +/// The facts of each of a row's pending lines (in seq order, as `pending`), the open floor narrowed to the events in `taken`. +fn row_facts(row: &Row, pending: &[&ChatDelivery], minds: &[String], taken: &[String]) -> Vec { + let mut facts = pending_facts(pending, row.addressee.matrix_id(), minds, &row.own_rooms); + for (delivery, facts) in pending.iter().zip(&mut facts) { + facts.open_floor &= taken.contains(&delivery.event_id); + } + facts +} + +/// Per row, the events whose open floor falls to her: each pending line is judged once, over every row that holds it, and a +/// line some Mind already took (a handled key for its event) is not judged again. +fn floors(rows: &[Row], state: &HeartbeatState, now: DateTime, config: &Config, minds: &[String]) -> Vec> { + let standings = standings_of(rows, state, now, config); + let sorted: Vec> = rows + .iter() + .map(|row| { + let mut pending: Vec<&ChatDelivery> = row.pending.iter().collect(); + pending.sort_by_key(|delivery| delivery.seq); + pending + }) + .collect(); + let raw: Vec> = rows.iter().zip(&sorted).map(|(row, pending)| pending_facts(pending, row.addressee.matrix_id(), minds, &row.own_rooms)).collect(); + let mut won: Vec> = vec![Vec::new(); rows.len()]; + let mut judged: Vec<&str> = Vec::new(); + for (index, row) in rows.iter().enumerate() { + for (delivery, facts) in sorted[index].iter().zip(&raw[index]) { + let event = delivery.event_id.as_str(); + let taken = state.handled_mentions.iter().any(|key| key.split_once(':').is_some_and(|(_, held)| held == event)); + if !facts.open_floor || taken || judged.contains(&event) { + continue; + } + judged.push(event); + let hearers: Vec = rows + .iter() + .enumerate() + .filter_map(|(at, other)| { + let place = sorted[at].iter().position(|held| held.event_id == event)?; + Some(Hearer { addressee: &other.addressee, delivery: sorted[at][place].clone(), open: raw[at][place].open_floor, standing: standings[at].clone() }) + }) + .collect(); + if let Some(winner) = floor_to(&hearers, config.speaker(&row.addressee, delivery), config.beat_s) + && let Some(at) = rows.iter().position(|other| other.slug().0 == hearers[winner].standing.slug) + { + won[at].push(event.to_owned()); + } + } + } + won +} + struct Row<'a> { seat: &'a Seat<'a>, released: bool, @@ -708,9 +806,11 @@ pub fn poll(organs: &Organs, config: &Config) -> Result { let mut launches: Vec = Vec::new(); let mut launched: Vec = Vec::new(); - // Off the beat: the operator or another Mind of the roster naming her, once per message. It does not wait for the beat; - // it needs her idle and released. - for row in &mut rows { + // Off the beat: a line that wakes her by `wakes`, once per message. It does not wait for the beat; it needs her idle and + // released. The open floor is decided first, over every Mind's pending lines, so one Mind of the roster takes each. + let minds: Vec = config.personas.iter().map(|mind| mind.matrix_id.clone()).collect(); + let floor = floors(&rows, &state, now, config, &minds); + for (index, row) in rows.iter_mut().enumerate() { if !row.idle() { continue; } @@ -718,8 +818,7 @@ pub fn poll(organs: &Organs, config: &Config) -> Result { let mentioned = { let mut pending: Vec<&ChatDelivery> = row.pending.iter().collect(); pending.sort_by_key(|delivery| delivery.seq); - let minds: Vec = config.personas.iter().map(|mind| mind.matrix_id.clone()).collect(); - let facts = pending_facts(&pending, row.addressee.matrix_id(), &minds, &row.own_rooms); + let facts = row_facts(row, &pending, &minds, &floor[index]); pending .into_iter() .zip(facts) @@ -731,6 +830,13 @@ pub fn poll(organs: &Organs, config: &Config) -> Result { match wake(organs, row) { Woke::Started => { state.handled_mentions.push(key); + // The floor lines she took are taken: no other Mind is picked for them. + for event in &floor[index] { + let taken = format!("{}:{event}", slug.0); + if !state.handled_mentions.contains(&taken) { + state.handled_mentions.push(taken); + } + } let excess = state.handled_mentions.len().saturating_sub(MENTIONS_KEPT); state.handled_mentions.drain(..excess); state.last_turn_at.insert(slug.0.clone(), now); @@ -745,21 +851,7 @@ pub fn poll(organs: &Organs, config: &Config) -> Result { // On the beat: when the beat has passed, one wake for the winner of the pick. let due = (now - state.last_beat_at).num_seconds() >= i64::from(beat_s); - let standings: Vec = rows - .iter() - .map(|row| { - let last = state.last_turn_at.get(&row.slug().0).copied(); - Standing { - slug: row.slug().0.clone(), - eligible: row.idle(), - waited_s: last.map(|turn| u64::try_from((now - turn).num_seconds()).unwrap_or(0)), - last_turn_ms: last.map(|turn| turn.timestamp_millis()), - // The seam for topic subscriptions (a later cut): a Mind's nearest subscription scores her deliveries here. - topic_permille: 0, - addressed_by_member: row.addressed_by_member(config), - } - }) - .collect(); + let standings = standings_of(&rows, &state, now, config); // A winner whose unit cannot start loses the beat to the next of the pick, so // one failing Mind never starves the others; a wake ends the beat. let mut passed: Vec = standings.clone(); diff --git a/crates/mind-body/src/heartbeat/tests.rs b/crates/mind-body/src/heartbeat/tests.rs index 3f7be7c..2531db0 100644 --- a/crates/mind-body/src/heartbeat/tests.rs +++ b/crates/mind-body/src/heartbeat/tests.rs @@ -169,6 +169,11 @@ fn delivery(seq: u64, sender: &str, text: &str, mentions: &[&str]) -> ChatDelive } } +/// A line in a room where a Mind spoke just before it: the floor is not open to anyone. +fn quiet(line: ChatDelivery) -> ChatDelivery { + ChatDelivery { context: vec![crate::chat_client::ContextLine { sender: "@ann:chat".into(), text: "x".into(), at_unix_ms: 0 }], ..line } +} + const ANN: usize = 0; const BOB: usize = 1; const NAMES: [&str; 2] = ["ann", "bob"]; @@ -426,8 +431,8 @@ fn a_member_message_naming_nobody_of_hers_scores_nobody() { rig.turn(ANN, 1000); rig.turn(BOB, 90); rig.beat_fell(); - rig.say(BOB, delivery(1, "@member:chat", "good morning, swarm", &[])); - rig.say(BOB, delivery(2, "@member:chat", "is BDS green?", &[])); + rig.say(BOB, quiet(delivery(1, "@member:chat", "good morning, swarm", &[]))); + rig.say(BOB, quiet(delivery(2, "@member:chat", "is BDS green?", &[]))); rig.advance(900); assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }, "BDS is nobody's here: no one stewards it"); } @@ -509,7 +514,7 @@ fn the_heartbeat_writes_the_table_it_read_and_only_when_it_changed() { rig.poll(); assert_eq!(rig.store.addressing_saves.get(), 1, "the roster is written at the first poll"); assert!(!addresses(&table_row(&rig, "@bob:chat"), &delivery(9, "@op:chat", "BDS is down", &[])), "nothing pending, nothing read: no project name yet"); - rig.say(BOB, delivery(1, "@member:chat", "hello", &[])); + rig.say(BOB, quiet(delivery(1, "@member:chat", "hello", &[]))); rig.poll(); assert_eq!(rig.store.addressing_saves.get(), 2); assert!(addresses(&table_row(&rig, "@bob:chat"), &delivery(9, "@op:chat", "BDS is down", &[]))); @@ -522,7 +527,7 @@ fn the_heartbeat_writes_the_table_it_read_and_only_when_it_changed() { fn a_failed_stewardship_read_keeps_her_last_read_names_and_roster_names_when_none_are_stored() { let rig = quiet_rig(); steward(&rig, BOB, "GameCult/BadDaySimulator", &["BDS"]); - rig.say(BOB, delivery(1, "@member:chat", "hello", &[])); + rig.say(BOB, quiet(delivery(1, "@member:chat", "hello", &[]))); rig.poll(); rig.stewardship_down.set(true); rig.say(BOB, delivery(2, "@op:chat", "BDS is down", &[])); @@ -728,7 +733,7 @@ fn matrixs_addressing_facts_wake_her_off_the_beat_only_on_a_message_from_the_ros fn a_member_line_in_a_room_named_for_her_repo_wakes_her_off_the_beat() { let rig = quiet_rig(); steward(&rig, BOB, "GameCult/Swarm", &["Zed"]); - rig.say(BOB, ChatDelivery { room_alias: "#elsewhere:chat".into(), ..delivery(1, "@member:chat", "what a day", &[]) }); + rig.say(BOB, quiet(ChatDelivery { room_alias: "#elsewhere:chat".into(), ..delivery(1, "@member:chat", "what a day", &[]) })); assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "a public room that is not hers wakes her only by address"); rig.say(BOB, delivery(2, "@member:chat", "what a day", &[])); assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "#swarm is named for her repo"); @@ -757,8 +762,9 @@ mod wake_rule { /// What the poll concludes for one delivery (its context is its own); `own` are her rooms. fn woken(line: &ChatDelivery, speaker: Speaker, own: &[&str]) -> Option { let own: Vec = own.iter().map(|room| (*room).to_owned()).collect(); - let facts = pending_facts(&[line], "@bob:chat", &minds(), &own); - wakes(&bob(), line, speaker, facts[0]) + // The open floor is the caller's, narrowed to the pick (`floor_to`): these lines are judged without it. + let facts = LineFacts { open_floor: false, ..pending_facts(&[line], "@bob:chat", &minds(), &own)[0] }; + wakes(&bob(), line, speaker, facts) } /// Four alternating Mind lines, the last of them `ago` before `at`, a minute apart. @@ -826,19 +832,90 @@ mod wake_rule { assert_eq!(woken(&dm, Speaker::Member, &[]), Some(WakeCause::AddressedByHuman)); } - /// Ruling persona-attention-and-initiative (2) wants an open hello answered by some Mind; the rule has no fact for it. - #[test] - fn a_member_naming_her_untagged_in_a_public_room_wakes_her_and_a_hello_to_everyone_wakes_no_one() { - let general = |text: &str| ChatDelivery { room_alias: "#general:chat".into(), ..delivery(1, "@member:chat", text, &[]) }; - assert_eq!(woken(&general("Bob, can you look at this?"), Speaker::Member, &[]), Some(WakeCause::AddressedByHuman)); - assert_eq!(woken(&general("hello everyone!"), Speaker::Member, &[]), None); - let rig = quiet_rig(); - for who in [ANN, BOB] { - rig.say(who, ChatDelivery { room_alias: "#general:chat".into(), ..delivery(1, "@newcomer:chat", "hello everyone!", &[]) }); - } - assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "no Mind is woken by it off the beat"); + fn general(seq: u64, sender: &str, text: &str) -> ChatDelivery { + ChatDelivery { room_alias: "#general:chat".into(), at_unix_ms: 1000 * seq, ..delivery(seq, sender, text, &[]) } } + fn said_in_general(rig: &Rig, line: ChatDelivery) { + for who in [ANN, BOB] { + rig.say(who, line.clone()); + } + } + + #[test] + fn a_member_naming_her_untagged_in_a_public_room_wakes_her() { + assert_eq!(woken(&general(1, "@member:chat", "Bob, can you look at this?"), Speaker::Member, &[]), Some(WakeCause::AddressedByHuman)); + } + + #[test] + fn a_newcomers_open_hello_wakes_exactly_one_mind_the_one_the_pick_names() { + let rig = quiet_rig(); + said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!")); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }, "never-tied waits break to the lowest slug, as the beat's pick does"); + let rig = quiet_rig(); + rig.turn(ANN, 5); + said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!")); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "the longer waiter takes it"); + rig.end_unit(BOB); + rig.advance(1); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "once per line: the Mind who took it is not woken again and no other is picked for it"); + } + + #[test] + fn a_second_hello_after_that_mind_answered_wakes_no_extra_mind() { + let rig = quiet_rig(); + said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!")); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }); + rig.end_unit(ANN); + rig.advance(60); + let answered = vec![crate::chat_client::ContextLine { sender: "@ann:chat".into(), text: "welcome".into(), at_unix_ms: 1500 }]; + said_in_general(&rig, ChatDelivery { context: answered, ..general(2, "@other:chat", "me too, hello") }); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }, "she is in the exchange she opened; Bob is not picked for a line a Mind has answered the room on"); + let rig = quiet_rig(); + let answered = vec![crate::chat_client::ContextLine { sender: "@ann:chat".into(), text: "welcome".into(), at_unix_ms: 1500 }]; + rig.say(BOB, ChatDelivery { context: answered, ..general(2, "@other:chat", "me too, hello") }); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "a Mind who was not in the exchange is not woken by it"); + let rig = quiet_rig(); + rig.say(BOB, ChatDelivery { context: vec![crate::chat_client::ContextLine { sender: "@ann:chat".into(), text: "welcome".into(), at_unix_ms: 1500 }], ..general(3, "@other:chat", "Bob, you too?") }); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "unless the line addresses her"); + } + + #[test] + fn a_minds_own_line_a_notice_an_edit_a_tag_or_an_operator_opens_no_floor() { + for (line, why) in [ + (general(1, "@ann:chat", "hello everyone!"), "a Mind's line"), + (ChatDelivery { form: Form::Notice, ..general(2, "@newcomer:chat", "hello everyone!") }, "a notice"), + (ChatDelivery { form: Form::Edit, ..general(3, "@newcomer:chat", "hello everyone!") }, "an edit"), + (general(4, "@op:chat", "hello everyone!"), "the operator's line (a member's alone opens it)"), + ] { + let rig = quiet_rig(); + said_in_general(&rig, line); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "{why}"); + } + let rig = quiet_rig(); + said_in_general(&rig, ChatDelivery { mentions: vec!["@bob:chat".into()], ..general(5, "@newcomer:chat", "hello") }); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "a line that tags one Mind is hers alone, not the floor's"); + let rig = quiet_rig(); + steward(&rig, BOB, "GameCult/Swarm", &["Zed"]); + said_in_general(&rig, general(6, "@newcomer:chat", "is Zed down?")); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "a line that names a project belongs to its steward, not the floor"); + } + + #[test] + fn the_open_floor_is_judged_the_same_from_the_pending_lines_and_from_the_simulators_room() { + // Never-acted Minds of the roster, eligible: the pick breaks to the lowest slug, in both. + let who = |slug: &str, eligible: bool| (Addressee::new(&format!("@{slug}:chat"), [slug]), tempo::Standing { slug: slug.into(), eligible, waited_s: None, last_turn_ms: None, topic_permille: 0, addressed_by_member: false }); + let (zed, ann) = (who("zed", true), who("ann", true)); + let line = general(1, "@newcomer:chat", "hello everyone!"); + fn hear<'a>(minds: &[&'a (Addressee, tempo::Standing)], open: &[bool], line: &ChatDelivery) -> Vec> { + minds.iter().zip(open).map(|(mind, open)| Hearer { addressee: &mind.0, delivery: line.clone(), open: *open, standing: mind.1.clone() }).collect() + } + assert_eq!(floor_to(&hear(&[&zed, &ann], &[true, true], &line), Speaker::Member, BEAT_S), Some(1), "ann sorts before zed"); + assert_eq!(floor_to(&hear(&[&zed, &ann], &[true, false], &line), Speaker::Member, BEAT_S), Some(0), "a Mind for whom a Mind has spoken in the room is not a candidate"); + let busy = who("ann", false); + assert_eq!(floor_to(&hear(&[&zed, &busy], &[true, true], &line), Speaker::Member, BEAT_S), Some(0), "a busy Mind is not picked"); + assert_eq!(floor_to(&hear(&[&zed, &ann], &[true, true], &line), Speaker::Mind, BEAT_S), None); + } #[test] fn the_exchange_holds_to_the_millisecond_of_the_window() { let window = 30 * MINUTE; diff --git a/crates/mind-body/src/projection/simulate.rs b/crates/mind-body/src/projection/simulate.rs index ac72f22..f963a4c 100644 --- a/crates/mind-body/src/projection/simulate.rs +++ b/crates/mind-body/src/projection/simulate.rs @@ -42,7 +42,7 @@ use super::tuning; use super::{DomainFacts, DomainSource, MouthReader, Organs, ReadFixture, ReadSource, Request, Through, TurnKind, project}; use crate::address::{Addressee, is_for, localpart}; use crate::chat_client::ChatPending; -use crate::heartbeat::{Addressing, DEFAULT_BEAT_S, EXCHANGE_MINUTES, FactLine, FileStore, HeartbeatView, Speaker, WakeCause, addressed_by_member, line_facts, wakes}; +use crate::heartbeat::{Addressing, DEFAULT_BEAT_S, EXCHANGE_MINUTES, FactLine, FileStore, Hearer, HeartbeatView, LineFacts, Speaker, WakeCause, addressed_by_member, floor_to, line_facts, wakes}; use crate::tempo::{Standing, pick}; /// The most personas a simulation holds: the swarm. @@ -213,13 +213,17 @@ struct Woken { by: Vec, } +/// The lines she sees, and their facts from the heartbeat's one owner of them. +fn seeing(lines: &[Line], member: &Member, cast: &[String], gap: Duration) -> (Vec, Vec) { + let visible: Vec = (0..lines.len()).filter(|at| lines[*at].visible_to(&member.entry.id, &member.rooms)).collect(); + let facts: Vec = visible.iter().map(|at| FactLine { sender: &lines[*at].from, room: &lines[*at].room, at_ms: lines[*at].at_ms }).collect(); + let facts = line_facts(&facts, &member.entry.id, cast, &member.entry.own_rooms, u64::try_from(gap.num_milliseconds()).unwrap_or(0)); + (visible, facts) +} + /// Her wake, if a line she has not seen wakes her: in the room of the earliest such line, with the strongest cause among /// that room's waking lines. -fn woken(lines: &[Line], seen: &Seen, member: &Member, operators: &[String], cast: &[String], gap: Duration) -> Option { - // The lines she sees, and their facts from the heartbeat's one owner of them. - let visible: Vec = (0..lines.len()).filter(|at| lines[*at].visible_to(&member.entry.id, &member.rooms)).collect(); - let seeing: Vec = visible.iter().map(|at| FactLine { sender: &lines[*at].from, room: &lines[*at].room, at_ms: lines[*at].at_ms }).collect(); - let facts = line_facts(&seeing, &member.entry.id, cast, &member.entry.own_rooms, u64::try_from(gap.num_milliseconds()).unwrap_or(0)); +fn woken(lines: &[Line], seen: &Seen, member: &Member, operators: &[String], cast: &[String], visible: Vec, facts: Vec) -> Option { let mut found: Vec<(usize, WakeCause)> = Vec::new(); for (at, facts) in visible.into_iter().zip(facts) { if !unseen(seen, lines, at) { @@ -344,6 +348,8 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) let mut seen: Vec = vec![Seen::new(); members.len()]; let mut last_turn: Vec>> = vec![None; members.len()]; let mut last_beat = plan.start; + // The lines whose open floor a Mind took, so no other is picked for them. + let mut floor_taken: std::collections::BTreeSet = std::collections::BTreeSet::new(); let mut recent: Vec>> = vec![Vec::new(); members.len()]; // Each persona's last turn's record, as the commit's trace will hold it: what came of it opens her next packet. let mut last: Vec> = vec![None; members.len()]; @@ -357,7 +363,50 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize) scripted(round, &mut lines, &mut rounds_of, &mut causes)?; let round_at = at_round(round); // Decided from the room as the round opens, as a poll decides from the pending it read. - let mut woke: Vec<(usize, Option)> = members.iter().enumerate().filter_map(|(at, member)| woken(&lines, &seen[at], member, &plan.operators, &cast, Duration::minutes(plan.exchange_minutes)).map(|why| (at, Some(why)))).collect(); + let mut seeings: Vec<(Vec, Vec)> = members.iter().map(|member| seeing(&lines, member, &cast, Duration::minutes(plan.exchange_minutes))).collect(); + // The open floor, as the heartbeat judges it: each line some Mind has not seen and no Mind has taken falls to one + // Mind, the beat's pick among those who hear it. + let standing = |at: usize, member: &Member| Standing { + slug: localpart(&member.entry.id).to_owned(), + eligible: true, + waited_s: last_turn[at].map(|turn| u64::try_from((round_at - turn).num_seconds()).unwrap_or(0)), + last_turn_ms: last_turn[at].map(|turn| turn.timestamp_millis()), + topic_permille: 0, + addressed_by_member: addressed_by_member(&plan.operators, &member.addressee, &pending_for(&lines, &member.entry.id, &member.rooms, |index| unseen(&seen[at], &lines, index)).deliveries), + }; + let standings: Vec = members.iter().enumerate().map(|(at, member)| standing(at, member)).collect(); + let mut won: Vec> = vec![Vec::new(); members.len()]; + for line in 0..lines.len() { + if floor_taken.contains(&line) { + continue; + } + let hearers: Vec<(usize, Hearer)> = members + .iter() + .enumerate() + .filter(|(at, _)| unseen(&seen[*at], &lines, line)) + .filter_map(|(at, member)| { + let place = seeings[at].0.iter().position(|visible| *visible == line)?; + Some((at, Hearer { addressee: &member.addressee, delivery: lines[line].delivery(line, &member.entry.id, &lines), open: seeings[at].1[place].open_floor, standing: standings[at].clone() })) + }) + .collect(); + let Some(first) = hearers.first().map(|(at, _)| *at) else { continue }; + let hearing: Vec = hearers.iter().map(|(_, hearer)| Hearer { addressee: hearer.addressee, delivery: hearer.delivery.clone(), open: hearer.open, standing: hearer.standing.clone() }).collect(); + if let Some(winner) = floor_to(&hearing, speaker(&lines[line], &members[first], &plan.operators, &cast), plan.beat_s) { + won[hearers[winner].0].push(line); + floor_taken.insert(line); + } + } + for (at, (visible, facts)) in seeings.iter_mut().enumerate() { + for (line, facts) in visible.iter().zip(facts.iter_mut()) { + facts.open_floor &= won[at].contains(line); + } + } + let mut woke: Vec<(usize, Option)> = members + .iter() + .zip(seeings) + .enumerate() + .filter_map(|(at, (member, (visible, facts)))| woken(&lines, &seen[at], member, &plan.operators, &cast, visible, facts).map(|why| (at, Some(why)))) + .collect(); // The beat, as the heartbeat's: when it has fallen, one more wake for the winner of `tempo::pick` among those // not already woken. if plan.beat_s > 0 && (round_at - last_beat).num_seconds() >= i64::from(plan.beat_s) { diff --git a/crates/mind-body/src/projection/simulate/tests.rs b/crates/mind-body/src/projection/simulate/tests.rs index 776d817..27c06f7 100644 --- a/crates/mind-body/src/projection/simulate/tests.rs +++ b/crates/mind-body/src/projection/simulate/tests.rs @@ -108,7 +108,7 @@ fn ask(from: &str, says: &str, speaker: Speaker, facts: LineFacts) -> Option LineFacts { - LineFacts { mind_run: 0, own_room, in_exchange } + LineFacts { mind_run: 0, own_room, in_exchange, open_floor: false } } #[test] @@ -173,12 +173,14 @@ fn t_w1_same_facts_both_paths() { .collect(); let pending: Vec<&ChatDelivery> = deliveries.iter().collect(); let polled = pending_facts(&pending, LIBBY, &cast, &own); - let by_sim: Vec> = heard.iter().map(|at| wakes(&libby, &lines[*at].delivery(*at, LIBBY, &lines), speaker(&lines[*at]), simulated[*at])).collect(); - let by_poll: Vec> = heard.iter().zip(&polled).map(|(at, facts)| wakes(&libby, &lines[*at].delivery(*at, LIBBY, &lines), speaker(&lines[*at]), *facts)).collect(); + // The open floor is the caller's, narrowed to the pick; this test judges the rest. + let closed = |facts: LineFacts| LineFacts { open_floor: false, ..facts }; + let by_sim: Vec> = heard.iter().map(|at| wakes(&libby, &lines[*at].delivery(*at, LIBBY, &lines), speaker(&lines[*at]), closed(simulated[*at]))).collect(); + let by_poll: Vec> = heard.iter().zip(&polled).map(|(at, facts)| wakes(&libby, &lines[*at].delivery(*at, LIBBY, &lines), speaker(&lines[*at]), closed(*facts))).collect(); assert_eq!(by_sim, by_poll); assert_eq!(by_sim, vec![None, Some(WakeCause::Human), Some(WakeCause::Human), Some(WakeCause::AddressedByMind), None], "a general line before she spoke, one in her exchange, her room, a Mind's tag, a general line after the exchange lapsed"); for (at, facts) in heard.iter().zip(&polled) { - assert_eq!((facts.mind_run, facts.own_room, facts.in_exchange), (simulated[*at].mind_run, simulated[*at].own_room, simulated[*at].in_exchange), "line {at}"); + assert_eq!((facts.mind_run, facts.own_room, facts.in_exchange, facts.open_floor), (simulated[*at].mind_run, simulated[*at].own_room, simulated[*at].in_exchange, simulated[*at].open_floor), "line {at}"); } assert_eq!(polled.iter().map(|facts| facts.mind_run).collect::>(), vec![0, 1, 0, 0, 0], "her line, then a human's line that ends the run, then a Mind's tag after both"); } @@ -1101,3 +1103,26 @@ fn t4_x5_timeline_the_note_carries_and_nothing_gates_the_welcome() { assert!(libby_state["thoughtMemory"]["shortTerm"].as_array().unwrap().iter().any(|entry| entry["id"] == id), "the note stays in her state"); assert_eq!(run["metrics"]["personas"]["Libby"]["memories"]["written"], 1, "{}", run["metrics"]["personas"]); } + +/// A newcomer's untagged hello in a public room, said at `round`, appended to a plan. +fn hello(path: &Path, round: usize) { + let mut text = std::fs::read_to_string(path).unwrap(); + text.push_str(&format!("[[message]]\nfrom = \"@newcomer:gamecult.org\"\nname = \"Newcomer\"\nroom = \"#minds:gamecult.org\"\nround = {round}\nsays = \"hello everyone!\"\n")); + std::fs::write(path, text).unwrap(); +} + +#[test] +fn an_open_hello_wakes_one_persona_and_a_second_after_her_answer_wakes_no_extra_one() { + let dir = tempfile::tempdir().unwrap(); + let path = bare_plan(dir.path(), 3, ""); + hello(&path, 0); + hello(&path, 2); + let (_, run) = run_plan(&path, &chatty()); + let turns = turns(&run); + // The poll's rule, over the same two never-acted Minds: the pick breaks to the lowest slug, `eureka` before `libby`. + assert_eq!(turns.len(), 2, "one Mind per hello, the same one: {turns:?}"); + assert!(turns.iter().all(|(_, persona, why)| *persona == turns[0].1 && why == "human"), "{turns:?}"); + assert_eq!(turns.iter().map(|(round, _, _)| *round).collect::>(), vec![1, 2]); + let first = run["transcript"].as_array().unwrap().iter().find(|line| line["woke"] == "human").unwrap(); + assert_eq!(first["from"], TOBIAH, "{first}"); +} From de720eacefa33aeaa583cf5a6723d8733d6691d1 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 21:54:35 +0100 Subject: [PATCH 6/9] Persona wake: the open floor has one form gate and one speaker gate, and its once-per-line and tagged-line cases are pinned Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/heartbeat.rs | 5 ++--- crates/mind-body/src/heartbeat/tests.rs | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/crates/mind-body/src/heartbeat.rs b/crates/mind-body/src/heartbeat.rs index f9f4c1d..f0ed00c 100644 --- a/crates/mind-body/src/heartbeat.rs +++ b/crates/mind-body/src/heartbeat.rs @@ -542,7 +542,7 @@ pub(crate) fn wakes(who: &Addressee, delivery: &ChatDelivery, speaker: Speaker, } let addressed = is_for(who, delivery); if speaker.human() { - let wakes = addressed || facts.own_room || facts.in_exchange || (speaker == Speaker::Member && facts.open_floor); + let wakes = addressed || facts.own_room || facts.in_exchange || facts.open_floor; return wakes.then_some(if addressed { WakeCause::AddressedByHuman } else { WakeCause::Human }); } let explicit = delivery.mentions.iter().any(|id| id == who.matrix_id()) || matches!(delivery.basis, Some(Basis::Tag | Basis::Reply)); @@ -563,9 +563,8 @@ pub(crate) struct Hearer<'a> { /// (`tempo::pick`) among the hearers whose floor is open, so the poll and the simulator choose the same one. None when the /// line is not open or no hearer is eligible. pub(crate) fn floor_to(hearers: &[Hearer], speaker: Speaker, beat_s: u32) -> Option { - let line = &hearers.first()?.delivery; + hearers.first()?; let open = speaker == Speaker::Member - && line.form == Form::Message && !hearers.iter().any(|hearer| hearer.delivery.is_direct || !hearer.delivery.mentions.is_empty() || is_for(hearer.addressee, &hearer.delivery)); if !open { return None; diff --git a/crates/mind-body/src/heartbeat/tests.rs b/crates/mind-body/src/heartbeat/tests.rs index 2531db0..fa57bd2 100644 --- a/crates/mind-body/src/heartbeat/tests.rs +++ b/crates/mind-body/src/heartbeat/tests.rs @@ -880,6 +880,20 @@ mod wake_rule { assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "unless the line addresses her"); } + #[test] + fn every_open_line_a_mind_took_in_one_wake_is_taken_and_a_line_tagging_anyone_is_not_open() { + let rig = quiet_rig(); + said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!")); + said_in_general(&rig, general(2, "@other:chat", "hello, I am new too")); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }); + rig.end_unit(ANN); + rig.advance(1); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "her one turn took both lines: Bob is not picked for the second"); + let rig = quiet_rig(); + said_in_general(&rig, ChatDelivery { mentions: vec!["@alice:chat".into()], ..general(3, "@newcomer:chat", "hello alice") }); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "a line that tags a person is not the floor's"); + } + #[test] fn a_minds_own_line_a_notice_an_edit_a_tag_or_an_operator_opens_no_floor() { for (line, why) in [ From 6088444907274f394f3f8875ecb3f909f7b53ec4 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 22:40:40 +0100 Subject: [PATCH 7/9] Persona wake: a failed start passes the open hello to the next of the pick, and a taken hello is spoken for within the exchange window The floor is judged with the Minds whose start failed this poll ineligible, as the beat passes over a refused Mind, so one broken unit no longer holds every hello. A hello another Mind took is no one else's to take or for the beat to hand over while it is within EXCHANGE_MINUTES, whatever the forgotten handled keys remember. Each event is judged once by the first Mind that holds it. Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/heartbeat.rs | 161 +++++++++++++++--------- crates/mind-body/src/heartbeat/tests.rs | 92 +++++++++++++- 2 files changed, 190 insertions(+), 63 deletions(-) diff --git a/crates/mind-body/src/heartbeat.rs b/crates/mind-body/src/heartbeat.rs index f0ed00c..7cf6ea3 100644 --- a/crates/mind-body/src/heartbeat.rs +++ b/crates/mind-body/src/heartbeat.rs @@ -563,10 +563,7 @@ pub(crate) struct Hearer<'a> { /// (`tempo::pick`) among the hearers whose floor is open, so the poll and the simulator choose the same one. None when the /// line is not open or no hearer is eligible. pub(crate) fn floor_to(hearers: &[Hearer], speaker: Speaker, beat_s: u32) -> Option { - hearers.first()?; - let open = speaker == Speaker::Member - && !hearers.iter().any(|hearer| hearer.delivery.is_direct || !hearer.delivery.mentions.is_empty() || is_for(hearer.addressee, &hearer.delivery)); - if !open { + if !open_line(hearers, speaker) { return None; } let candidates: Vec = (0..hearers.len()).filter(|at| hearers[*at].open).collect(); @@ -574,6 +571,12 @@ pub(crate) fn floor_to(hearers: &[Hearer], speaker: Speaker, beat_s: u32) -> Opt tempo::pick(&standings, beat_s).map(|at| candidates[at]) } +/// Whether a line is the floor's at all: a member's untagged message, not direct, naming no Mind of the roster to any hearer of +/// it. Whether anyone is eligible to take it is `floor_to`'s. +pub(crate) fn open_line(hearers: &[Hearer], speaker: Speaker) -> bool { + !hearers.is_empty() && speaker == Speaker::Member && !hearers.iter().any(|hearer| hearer.delivery.is_direct || !hearer.delivery.mentions.is_empty() || is_for(hearer.addressee, &hearer.delivery)) +} + /// Every Mind's standing in the pick, from the heartbeat's state: eligible when idle and released. fn standings_of(rows: &[Row], state: &HeartbeatState, now: DateTime, config: &Config) -> Vec { rows.iter() @@ -664,10 +667,30 @@ fn row_facts(row: &Row, pending: &[&ChatDelivery], minds: &[String], taken: &[St facts } -/// Per row, the events whose open floor falls to her: each pending line is judged once, over every row that holds it, and a -/// line some Mind already took (a handled key for its event) is not judged again. -fn floors(rows: &[Row], state: &HeartbeatState, now: DateTime, config: &Config, minds: &[String]) -> Vec> { - let standings = standings_of(rows, state, now, config); +/// What the open floor decides over the pending lines: per row, the events that fall to her, and whether she holds a hello +/// another Mind has taken. +struct Floor { + won: Vec>, + /// She holds an open hello that another Mind took and that is still within the exchange window: it is spoken for, and the + /// beat does not hand it to her too. + spoken_for: Vec, +} + +/// Whether a line is still the floor's to give: said within the exchange window before `now`. A taken line's handled key is +/// forgotten at `MENTIONS_KEPT`; an old line is no one's to take whatever the keys remember. +fn fresh(delivery: &ChatDelivery, now: DateTime) -> bool { + let window_ms = u64::try_from(EXCHANGE_MINUTES * 60_000).unwrap_or_default(); + u64::try_from(now.timestamp_millis()).unwrap_or_default().saturating_sub(delivery.at_unix_ms) <= window_ms +} + +/// Each pending open line is judged once, over every row that holds it. A line some Mind already took (a handled key for its +/// event) is not judged again, and is spoken for to every other Mind that holds it. A Mind in `passed_over` (her start failed +/// this poll) is not eligible: the line falls to the next of the pick, as the beat's does. +fn floors(rows: &[Row], state: &HeartbeatState, now: DateTime, config: &Config, minds: &[String], passed_over: &[String]) -> Floor { + let mut standings = standings_of(rows, state, now, config); + for standing in &mut standings { + standing.eligible &= !passed_over.contains(&standing.slug); + } let sorted: Vec> = rows .iter() .map(|row| { @@ -677,32 +700,33 @@ fn floors(rows: &[Row], state: &HeartbeatState, now: DateTime, config: &Con }) .collect(); let raw: Vec> = rows.iter().zip(&sorted).map(|(row, pending)| pending_facts(pending, row.addressee.matrix_id(), minds, &row.own_rooms)).collect(); - let mut won: Vec> = vec![Vec::new(); rows.len()]; - let mut judged: Vec<&str> = Vec::new(); + let mut floor = Floor { won: vec![Vec::new(); rows.len()], spoken_for: vec![false; rows.len()] }; for (index, row) in rows.iter().enumerate() { - for (delivery, facts) in sorted[index].iter().zip(&raw[index]) { + for delivery in &sorted[index] { let event = delivery.event_id.as_str(); - let taken = state.handled_mentions.iter().any(|key| key.split_once(':').is_some_and(|(_, held)| held == event)); - if !facts.open_floor || taken || judged.contains(&event) { + let held: Vec<(usize, usize)> = (0..rows.len()).filter_map(|at| Some((at, sorted[at].iter().position(|held| held.event_id == event)?))).collect(); + // Judged once, by the first row that holds it. + if held.first().map(|(at, _)| *at) != Some(index) || !fresh(delivery, now) { continue; } - judged.push(event); - let hearers: Vec = rows - .iter() - .enumerate() - .filter_map(|(at, other)| { - let place = sorted[at].iter().position(|held| held.event_id == event)?; - Some(Hearer { addressee: &other.addressee, delivery: sorted[at][place].clone(), open: raw[at][place].open_floor, standing: standings[at].clone() }) - }) - .collect(); - if let Some(winner) = floor_to(&hearers, config.speaker(&row.addressee, delivery), config.beat_s) + let hearers: Vec = held.iter().map(|(at, place)| Hearer { addressee: &rows[*at].addressee, delivery: sorted[*at][*place].clone(), open: raw[*at][*place].open_floor, standing: standings[*at].clone() }).collect(); + let speaker = config.speaker(&row.addressee, delivery); + if !open_line(&hearers, speaker) { + continue; + } + let takers: Vec<&str> = state.handled_mentions.iter().filter_map(|key| key.split_once(':').filter(|(_, held)| *held == event).map(|(who, _)| who)).collect(); + if !takers.is_empty() { + for (at, place) in &held { + floor.spoken_for[*at] |= raw[*at][*place].open_floor && takers.iter().any(|who| *who != rows[*at].slug().0); + } + } else if let Some(winner) = floor_to(&hearers, speaker, config.beat_s) && let Some(at) = rows.iter().position(|other| other.slug().0 == hearers[winner].standing.slug) { - won[at].push(event.to_owned()); + floor.won[at].push(event.to_owned()); } } } - won + floor } struct Row<'a> { @@ -808,44 +832,59 @@ pub fn poll(organs: &Organs, config: &Config) -> Result { // Off the beat: a line that wakes her by `wakes`, once per message. It does not wait for the beat; it needs her idle and // released. The open floor is decided first, over every Mind's pending lines, so one Mind of the roster takes each. let minds: Vec = config.personas.iter().map(|mind| mind.matrix_id.clone()).collect(); - let floor = floors(&rows, &state, now, config, &minds); - for (index, row) in rows.iter_mut().enumerate() { - if !row.idle() { - continue; - } - let slug = row.slug().clone(); - let mentioned = { - let mut pending: Vec<&ChatDelivery> = row.pending.iter().collect(); - pending.sort_by_key(|delivery| delivery.seq); - let facts = row_facts(row, &pending, &minds, &floor[index]); - pending - .into_iter() - .zip(facts) - .filter(|(delivery, facts)| wakes(&row.addressee, delivery, config.speaker(&row.addressee, delivery), *facts).is_some()) - .map(|(delivery, _)| format!("{}:{}", slug.0, delivery.event_id)) - .find(|key| !state.handled_mentions.contains(key)) - }; - let Some(key) = mentioned else { continue }; - match wake(organs, row) { - Woke::Started => { - state.handled_mentions.push(key); - // The floor lines she took are taken: no other Mind is picked for them. - for event in &floor[index] { - let taken = format!("{}:{event}", slug.0); - if !state.handled_mentions.contains(&taken) { - state.handled_mentions.push(taken); + // A Mind whose start failed on a line the floor gave her passes it on: the next of the pick takes it in the same poll. + let mut passed_over: Vec = Vec::new(); + let mut tried: Vec = Vec::new(); + 'floor: loop { + let floor = floors(&rows, &state, now, config, &minds, &passed_over).won; + for (index, row) in rows.iter_mut().enumerate() { + if !row.idle() || tried.contains(&index) { + continue; + } + let slug = row.slug().clone(); + let mentioned = { + let mut pending: Vec<&ChatDelivery> = row.pending.iter().collect(); + pending.sort_by_key(|delivery| delivery.seq); + let facts = row_facts(row, &pending, &minds, &floor[index]); + pending + .into_iter() + .zip(facts) + .filter(|(delivery, facts)| wakes(&row.addressee, delivery, config.speaker(&row.addressee, delivery), *facts).is_some()) + .map(|(delivery, _)| format!("{}:{}", slug.0, delivery.event_id)) + .find(|key| !state.handled_mentions.contains(key)) + }; + let Some(key) = mentioned else { continue }; + tried.push(index); + match wake(organs, row) { + Woke::Started => { + state.handled_mentions.push(key); + // The floor lines she took are taken: no other Mind is picked for them. + for event in &floor[index] { + let taken = format!("{}:{event}", slug.0); + if !state.handled_mentions.contains(&taken) { + state.handled_mentions.push(taken); + } + } + let excess = state.handled_mentions.len().saturating_sub(MENTIONS_KEPT); + state.handled_mentions.drain(..excess); + state.last_turn_at.insert(slug.0.clone(), now); + row.busy = true; + launches.push(slug.0.clone()); + launched.push(slug); + } + refused => { + match refused { + Woke::Refused(why) => row.note = why, + _ => row.busy = true, + } + if !floor[index].is_empty() { + passed_over.push(slug.0); + continue 'floor; } } - let excess = state.handled_mentions.len().saturating_sub(MENTIONS_KEPT); - state.handled_mentions.drain(..excess); - state.last_turn_at.insert(slug.0.clone(), now); - row.busy = true; - launches.push(slug.0.clone()); - launched.push(slug); } - Woke::Busy => row.busy = true, - Woke::Refused(why) => row.note = why, } + break; } // On the beat: when the beat has passed, one wake for the winner of the pick. @@ -854,6 +893,10 @@ pub fn poll(organs: &Organs, config: &Config) -> Result { // A winner whose unit cannot start loses the beat to the next of the pick, so // one failing Mind never starves the others; a wake ends the beat. let mut passed: Vec = standings.clone(); + // A hello another Mind took is spoken for: the beat does not give it to a second Mind. + for (at, spoken) in floors(&rows, &state, now, config, &minds, &[]).spoken_for.into_iter().enumerate() { + passed[at].eligible &= !spoken; + } while due && let Some(winner) = tempo::pick(&passed, beat_s) { match wake(organs, &rows[winner]) { Woke::Started => { diff --git a/crates/mind-body/src/heartbeat/tests.rs b/crates/mind-body/src/heartbeat/tests.rs index fa57bd2..d2ecaba 100644 --- a/crates/mind-body/src/heartbeat/tests.rs +++ b/crates/mind-body/src/heartbeat/tests.rs @@ -833,9 +833,15 @@ mod wake_rule { } fn general(seq: u64, sender: &str, text: &str) -> ChatDelivery { - ChatDelivery { room_alias: "#general:chat".into(), at_unix_ms: 1000 * seq, ..delivery(seq, sender, text, &[]) } + ChatDelivery { room_alias: "#general:chat".into(), at_unix_ms: now_ms() + 1000 * seq, ..delivery(seq, sender, text, &[]) } } + /// The rig's clock, in the unit the lines carry: a line said just now is within the exchange window of it. + fn now_ms() -> u64 { + u64::try_from(at(1_000_000).timestamp_millis()).unwrap() + } + + fn said_in_general(rig: &Rig, line: ChatDelivery) { for who in [ANN, BOB] { rig.say(who, line.clone()); @@ -868,15 +874,15 @@ mod wake_rule { assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }); rig.end_unit(ANN); rig.advance(60); - let answered = vec![crate::chat_client::ContextLine { sender: "@ann:chat".into(), text: "welcome".into(), at_unix_ms: 1500 }]; + let answered = vec![crate::chat_client::ContextLine { sender: "@ann:chat".into(), text: "welcome".into(), at_unix_ms: now_ms() + 1500 }]; said_in_general(&rig, ChatDelivery { context: answered, ..general(2, "@other:chat", "me too, hello") }); assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }, "she is in the exchange she opened; Bob is not picked for a line a Mind has answered the room on"); let rig = quiet_rig(); - let answered = vec![crate::chat_client::ContextLine { sender: "@ann:chat".into(), text: "welcome".into(), at_unix_ms: 1500 }]; + let answered = vec![crate::chat_client::ContextLine { sender: "@ann:chat".into(), text: "welcome".into(), at_unix_ms: now_ms() + 1500 }]; rig.say(BOB, ChatDelivery { context: answered, ..general(2, "@other:chat", "me too, hello") }); assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "a Mind who was not in the exchange is not woken by it"); let rig = quiet_rig(); - rig.say(BOB, ChatDelivery { context: vec![crate::chat_client::ContextLine { sender: "@ann:chat".into(), text: "welcome".into(), at_unix_ms: 1500 }], ..general(3, "@other:chat", "Bob, you too?") }); + rig.say(BOB, ChatDelivery { context: vec![crate::chat_client::ContextLine { sender: "@ann:chat".into(), text: "welcome".into(), at_unix_ms: now_ms() + 1500 }], ..general(3, "@other:chat", "Bob, you too?") }); assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "unless the line addresses her"); } @@ -894,6 +900,84 @@ mod wake_rule { assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "a line that tags a person is not the floor's"); } + #[test] + fn a_start_that_fails_passes_the_hello_to_the_next_of_the_pick_in_the_same_poll() { + let rig = quiet_rig(); + *rig.launcher.fail_for.borrow_mut() = Some(Slug("ann".into())); + said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!")); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "Ann wins the pick, her unit will not start, and Bob takes the line in the same poll"); + assert!(rig.notes().iter().any(|note| note.contains("start failed")), "the refusal is still said"); + rig.end_unit(BOB); + for poll in 0..10 { + rig.advance(1); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "poll {poll}: Bob took it; Ann's broken unit is not tried for it again"); + } + } + + #[test] + fn when_every_start_fails_the_line_is_tried_once_per_mind_and_then_waits() { + let rig = quiet_rig(); + rig.launcher.fail.set(true); + said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!")); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }); + rig.launcher.fail.set(false); + rig.advance(1); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }, "nothing was taken, so the next poll picks again from the top"); + } + + #[test] + fn the_beat_does_not_give_a_hello_one_mind_took_to_a_second_mind() { + let rig = Rig::new(); + rig.turn(ANN, 5000); + rig.turn(BOB, 4000); + said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!")); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }, "the beat is due: Ann takes the floor and the beat does not wake Bob on the same line"); + rig.end_unit(ANN); + rig.advance(1); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "nor a poll later while the line is within the exchange window"); + rig.advance(31 * 60); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "a Mind that holds only an old taken line is woken by the beat like any other"); + } + + #[test] + fn an_old_hello_whose_taken_key_was_forgotten_wakes_no_one_and_the_keys_are_bounded() { + let rig = quiet_rig(); + rig.with_state(|state| state.handled_mentions = (0..70).map(|at| format!("ann:$old{at}")).collect()); + said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!")); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }); + assert_eq!(rig.store.state.borrow().as_ref().unwrap().handled_mentions.len(), MENTIONS_KEPT, "the handled keys keep their bound"); + rig.end_unit(ANN); + rig.with_state(|state| state.handled_mentions.clear()); + rig.advance(31 * 60); + rig.beat_fell(); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "the line is older than the window: no key to remember it, and it is no one's to take"); + } + + #[test] + fn a_minds_line_in_another_room_does_not_close_this_rooms_floor() { + let rig = quiet_rig(); + let elsewhere = ChatDelivery { room_alias: "#random:chat".into(), at_unix_ms: now_ms() - 1000, ..delivery(9, "@ann:chat", "something", &[]) }; + rig.say(ANN, elsewhere); + said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!")); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }, "Ann spoke in #random, not in #general: she is still a candidate for the hello"); + } + + #[test] + fn a_busy_or_braked_mind_is_never_picked_for_the_floor_and_a_line_to_a_busy_mind_is_not_the_floor() { + let rig = quiet_rig(); + rig.in_a_turn(ANN); + said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!")); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "Ann is in a turn: Bob takes it"); + let rig = quiet_rig(); + rig.control.braked.borrow_mut().push("ann".into()); + said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!")); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "Ann is braked: Bob takes it"); + let rig = quiet_rig(); + rig.in_a_turn(BOB); + said_in_general(&rig, general(1, "@newcomer:chat", "Bob, hello?")); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "a line that names Bob is Bob's, even while he is busy: Ann is not picked for it"); + } + #[test] fn a_minds_own_line_a_notice_an_edit_a_tag_or_an_operator_opens_no_floor() { for (line, why) in [ From 90e2ce935a05a9451404b49032a6d3aed44a5cb8 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 22:44:11 +0100 Subject: [PATCH 8/9] Persona packet: a line the heartbeat woke her for is said to her The wake and the packet's hers were two owners: an open hello that picked her was met among the others. The heartbeat's handled keys name what woke her (heartbeat::woken_for), the Persona unit reads them into Request::woken_for, and a simulation passes the lines its floor gave her; to_her is is_for, her own room, or woken for. Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/bin/mind-persona.rs | 12 +++++++++- crates/mind-body/src/heartbeat.rs | 6 +++++ crates/mind-body/src/heartbeat/tests.rs | 13 +++++++++-- crates/mind-body/src/projection.rs | 9 ++++++-- crates/mind-body/src/projection/harness.rs | 1 + crates/mind-body/src/projection/simulate.rs | 1 + crates/mind-body/src/projection/tests.rs | 25 ++++++++++++++++++++- 7 files changed, 61 insertions(+), 6 deletions(-) diff --git a/crates/mind-body/src/bin/mind-persona.rs b/crates/mind-body/src/bin/mind-persona.rs index 4d435fb..c66462f 100644 --- a/crates/mind-body/src/bin/mind-persona.rs +++ b/crates/mind-body/src/bin/mind-persona.rs @@ -56,7 +56,7 @@ use mind_body::chat_rudp::{RudpChat, connection_id}; use mind_body::cli::{instance_and_endpoint, instance_and_maybe_endpoint}; use mind_body::control::{CONTROL_ROOT, FileSource, control_path, swarm_path}; use mind_body::persona::{Config, carry}; -use mind_body::heartbeat::{FileStore, HeartbeatView, own_rooms_among}; +use mind_body::heartbeat::{FileStore, HeartbeatView, Store, own_rooms_among, woken_for}; use mind_body::queue::HuginnMind; use mind_body::projection::harness::{Fixture, Harness, batch, fixture_request, simulate, state_file}; use mind_body::projection::{DomainSource, HttpForge, HuginnPersonaSource, KitModel, LiveReads, MindDomain, Model, MouthReader, ReadSource, Organs as ProjectOrgans, PersonaSource, Request as ProjectRequest, TUNING_FILE, TUNING_ROOT, Through, TurnKind, connector_key, project}; @@ -212,6 +212,12 @@ fn run_project(args: &[String]) -> Result { }, _ => (vec![], None), }; + // The lines the heartbeat woke her for, from its handled keys; an unread state is said in the report, not read as none. + let (woken, woken_unread) = match heartbeat.as_ref().map(Store::load) { + Some(Ok(state)) => (state.map(|state| woken_for(&state, &instance.0)).unwrap_or_default(), None), + Some(Err(error)) => (vec![], Some(format!("the heartbeat state unread: {error}"))), + None => (vec![], None), + }; // Her reads by intent (map 16.22.3): her mind through the same endpoint, the forge when it is named, the web. let reads = address.map(|address| LiveReads::new(HuginnClient::new(address, instance.clone(), TIMEOUT), setting("MIND_PERSONA_FORGE_URL").map(|forge| HttpForge::new(&forge)))); let organs = ProjectOrgans { @@ -238,6 +244,7 @@ fn run_project(args: &[String]) -> Result { last_heard: vec![], recent: vec![], own_rooms: own, + woken_for: woken, last_outcome, last_wake: None, records: vec![], @@ -246,6 +253,9 @@ fn run_project(args: &[String]) -> Result { if let Some(unread) = own_unread { report["own_rooms_unread"] = unread.into(); } + if let Some(unread) = woken_unread { + report["woken_for_unread"] = unread.into(); + } let addressing = &report["addressing"]; // The addressing source is what decides "said to her": said first, where a person running this by hand sees it. eprintln!( diff --git a/crates/mind-body/src/heartbeat.rs b/crates/mind-body/src/heartbeat.rs index 7cf6ea3..18c9954 100644 --- a/crates/mind-body/src/heartbeat.rs +++ b/crates/mind-body/src/heartbeat.rs @@ -221,6 +221,12 @@ pub trait Store { fn save_addressing(&self, addressing: &Addressing) -> Result<()>; } +/// The lines the heartbeat woke `slug` for, as her handled keys name them (`slug:event`): what her packet reads as said to +/// her, so the wake and the packet cannot disagree about whose line it was. +pub fn woken_for(state: &HeartbeatState, slug: &str) -> Vec { + state.handled_mentions.iter().filter_map(|key| key.split_once(':').filter(|(who, _)| *who == slug).map(|(_, event)| event.to_owned())).collect() +} + /// What a Persona unit may read of `heartbeat.cc`: the swarm's addressing. Read-only. pub trait HeartbeatView { fn addressing(&self) -> Result>; diff --git a/crates/mind-body/src/heartbeat/tests.rs b/crates/mind-body/src/heartbeat/tests.rs index d2ecaba..1be3834 100644 --- a/crates/mind-body/src/heartbeat/tests.rs +++ b/crates/mind-body/src/heartbeat/tests.rs @@ -932,9 +932,8 @@ mod wake_rule { rig.turn(BOB, 4000); said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!")); assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }, "the beat is due: Ann takes the floor and the beat does not wake Bob on the same line"); - rig.end_unit(ANN); rig.advance(1); - assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "nor a poll later while the line is within the exchange window"); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "nor a poll later, Ann still in her turn, while the line is within the exchange window"); rig.advance(31 * 60); assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] }, "a Mind that holds only an old taken line is woken by the beat like any other"); } @@ -978,6 +977,16 @@ mod wake_rule { assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "a line that names Bob is Bob's, even while he is busy: Ann is not picked for it"); } + #[test] + fn the_lines_the_heartbeat_woke_her_for_are_read_from_her_own_handled_keys() { + let rig = quiet_rig(); + said_in_general(&rig, general(1, "@newcomer:chat", "hello everyone!")); + assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] }); + let state = rig.store.state.borrow().clone().unwrap(); + assert_eq!(woken_for(&state, "ann"), vec!["$e1".to_owned()], "the hello that woke her"); + assert!(woken_for(&state, "bob").is_empty(), "not the Mind who was not woken for it"); + } + #[test] fn a_minds_own_line_a_notice_an_edit_a_tag_or_an_operator_opens_no_floor() { for (line, why) in [ diff --git a/crates/mind-body/src/projection.rs b/crates/mind-body/src/projection.rs index b579187..678724b 100644 --- a/crates/mind-body/src/projection.rs +++ b/crates/mind-body/src/projection.rs @@ -219,6 +219,9 @@ pub struct Request { pub recent: Vec>, /// The rooms that are hers, by the key the lines carry: live from `heartbeat::own_rooms` (the rooms named for her stewarded repos), simulated from the plan. pub own_rooms: Vec, + /// The events the heartbeat woke her for (`heartbeat::woken_for`; a simulation's, the lines its floor gave her): said to her, + /// as the wake that named her decided, whoever they were and in whatever room. + pub woken_for: Vec, /// The record of her last turn, which her packet opens with what came of (`outcome::outcome_of`): the Interpreter's /// decision under `interpreter` and the receipts of the lines that went out under `posted`, or `failed`. A /// simulation carries each turn's to her next; a harness run takes a fixture's (`--last-outcome`). None live until @@ -299,8 +302,10 @@ fn read_room(chat: &dyn MouthReader, request: &Request, own: &Addressee) -> (Roo text: delivery.text.clone(), at_ms: delivery.at_unix_ms, // The heartbeat's rule, the one that woke her: never a second opinion here. A human's line in - // her own room always wakes her, so it is to her, as a direct message is (the plan's or unit's `own_rooms`). - to_her: is_for(own, delivery) || (request.own_rooms.contains(&delivery.room_alias) && delivery.sender != request.own_sender && !request.minds.contains(&delivery.sender)), + // her own room always wakes her, so it is to her, as a direct message is (the plan's or unit's `own_rooms`), and so + // is a line the heartbeat woke her for (an open hello she was picked to answer: `woken_for`). + to_her: is_for(own, delivery) + || (delivery.sender != request.own_sender && !request.minds.contains(&delivery.sender) && (request.own_rooms.contains(&delivery.room_alias) || request.woken_for.contains(&delivery.event_id))), event: delivery.event_id.clone(), reply: replied(&delivery.reply_to), }) diff --git a/crates/mind-body/src/projection/harness.rs b/crates/mind-body/src/projection/harness.rs index 8c7a461..eec80d1 100644 --- a/crates/mind-body/src/projection/harness.rs +++ b/crates/mind-body/src/projection/harness.rs @@ -364,6 +364,7 @@ pub fn fixture_request(harness: &Harness, fixture: &Fixture, state: Option, judge_against: Option) -> Request { - Request { instance: INSTANCE.into(), kind: TurnKind::Chat, state: None, room: Some("#swarm:gamecult.org".into()), seed: 5, renders, judge_against, operators: operators(), minds: minds(), own_sender: OWN.into(), tuning: dir.join(TUNING_FILE), through: Through::Projector, last_heard: vec![], recent: vec![], own_rooms: vec![], last_outcome: None, last_wake: None, records: vec![] } + Request { instance: INSTANCE.into(), kind: TurnKind::Chat, state: None, room: Some("#swarm:gamecult.org".into()), seed: 5, renders, judge_against, operators: operators(), minds: minds(), own_sender: OWN.into(), tuning: dir.join(TUNING_FILE), through: Through::Projector, last_heard: vec![], recent: vec![], own_rooms: vec![], woken_for: vec![], last_outcome: None, last_wake: None, records: vec![] } } /// A human's line in her own room is to her (the humans_pace ruling: it always wakes her), with no name and no tag: the arrival @@ -968,6 +968,29 @@ fn a_humans_line_in_her_own_room_is_to_her() { } } +/// A member's open hello in a public room wakes one Mind, the pick; the line is said to her, as a line in her own room is, so she +/// knows she was picked to answer. A Mind who was not woken for it meets it among the others, and a Mind's line is never to her +/// by this route. +#[test] +fn a_line_the_heartbeat_woke_her_for_is_to_her_and_one_it_did_not_is_not() { + let dir = tempfile::tempdir().unwrap(); + let stored = Stored(state()); + let general = "#general:gamecult.org"; + let mouth = |sender: &str| ReadOnlyMouth { pending: ChatPending { persona: "eureka".into(), deliveries: vec![delivery(1, general, sender, "Newcomer", "hello everyone!", &[])], tail: Some(vec![]), tail_gaps: vec![] }, reads: Cell::new(0) }; + let packet = |chat: &ReadOnlyMouth, woken_for: Vec| { + let organs = Organs { persona: Some(&stored), chat: Some(chat), addressing: None, model: None, domain: None, reads: None }; + project(&organs, &Request { room: Some(general.into()), woken_for, ..request(dir.path(), None, None) }, now()).unwrap()["packet"].clone() + }; + let hello = mouth("@newcomer:gamecult.org"); + let picked = packet(&hello, vec!["$e1".into()]); + assert!(picked["context"].as_str().unwrap().contains("turned to her"), "{picked}"); + assert!(picked["speaking"].as_str().unwrap().contains("is waiting on her"), "{picked}"); + let not_picked = packet(&hello, vec![]); + assert!(!not_picked["context"].as_str().unwrap().contains("turned to her") && !not_picked["speaking"].as_str().unwrap_or_default().contains("waiting on her"), "{not_picked}"); + let mind = packet(&mouth("@libby:gamecult.org"), vec!["$e1".into()]); + assert!(!mind["context"].as_str().unwrap().contains("turned to her"), "a Mind's line is to her only by is_for: {mind}"); +} + #[test] fn project_in_every_mode_writes_nothing() { let dir = tempfile::tempdir().unwrap(); From 0ab26384f1db891ad9f000d49eb166974bf0ba6f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 22:46:13 +0100 Subject: [PATCH 9/9] Public surface: heartbeat::woken_for and Request::woken_for Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/tests/public_surface.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/mind-body/tests/public_surface.txt b/crates/mind-body/tests/public_surface.txt index 09c301c..ce81eb8 100644 --- a/crates/mind-body/tests/public_surface.txt +++ b/crates/mind-body/tests/public_surface.txt @@ -151,6 +151,7 @@ mind_body::heartbeat: # [derive (Clone , Debug , PartialEq , Eq)] pub enum Outco mind_body::heartbeat: const DEFAULT_BEAT_S : u32 mind_body::heartbeat: fn own_rooms_among < 'a > (mind : & dyn MindPort , aliases : impl IntoIterator < Item = & 'a str >) -> Result < Vec < String > > mind_body::heartbeat: fn poll (organs : & Organs , config : & Config) -> Result < Outcome > +mind_body::heartbeat: fn woken_for (state : & HeartbeatState , slug : & str) -> Vec < String > mind_body::heartbeat: impl Config mind_body::heartbeat: impl Config: fn new (personas : Vec < PersonaId > , operators : Vec < String > , beat_s : u32) -> Result < Self > mind_body::heartbeat: impl Control for FileControl @@ -253,7 +254,7 @@ mind_body::projection: pub use select :: TurnKind ; mind_body::projection: pub use tuning :: { TUNING_FILE , TUNING_ROOT } ; mind_body::projection: struct HuginnPersonaSource pub-fields[] mind_body::projection: struct Organs< 'a > pub-fields[persona: Option < & 'a dyn PersonaSource >, chat: Option < & 'a dyn MouthReader >, addressing: Option < & 'a dyn HeartbeatView >, model: Option < & 'a dyn Model >, domain: Option < & 'a dyn DomainSource >, reads: Option < & 'a dyn ReadSource >] -mind_body::projection: struct Request pub-fields[instance: String, kind: TurnKind, state: Option < Value >, room: Option < String >, seed: u64, renders: Option < usize >, judge_against: Option < Value >, operators: Vec < String >, minds: Vec < String >, own_sender: String, tuning: PathBuf, through: Through, last_heard: Vec < (String , u64) >, recent: Vec < Vec < String > >, own_rooms: Vec < String >, last_outcome: Option < Value >, last_wake: Option < DateTime < Utc > >, records: Vec < Value >] +mind_body::projection: struct Request pub-fields[instance: String, kind: TurnKind, state: Option < Value >, room: Option < String >, seed: u64, renders: Option < usize >, judge_against: Option < Value >, operators: Vec < String >, minds: Vec < String >, own_sender: String, tuning: PathBuf, through: Through, last_heard: Vec < (String , u64) >, recent: Vec < Vec < String > >, own_rooms: Vec < String >, woken_for: Vec < String >, last_outcome: Option < Value >, last_wake: Option < DateTime < Utc > >, records: Vec < Value >] mind_body::projection::domain: impl DomainSource for DomainFacts mind_body::projection::domain: impl DomainSource for MindDomain mind_body::projection::domain: impl ForgeGet for HttpForge