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}"); +}