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 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-27 22:40:40 +01:00
commit 6088444907
2 changed files with 190 additions and 63 deletions

View file

@ -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<usize> {
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<usize> = (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<Utc>, config: &Config) -> Vec<Standing> {
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<Utc>, config: &Config, minds: &[String]) -> Vec<Vec<String>> {
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<Vec<String>>,
/// 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<bool>,
}
/// 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<Utc>) -> 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<Utc>, 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<Vec<&ChatDelivery>> = rows
.iter()
.map(|row| {
@ -677,32 +700,33 @@ fn floors(rows: &[Row], state: &HeartbeatState, now: DateTime<Utc>, config: &Con
})
.collect();
let raw: Vec<Vec<LineFacts>> = rows.iter().zip(&sorted).map(|(row, pending)| pending_facts(pending, row.addressee.matrix_id(), minds, &row.own_rooms)).collect();
let mut won: Vec<Vec<String>> = 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<Hearer> = 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<Hearer> = 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<Outcome> {
// 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<String> = 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<String> = Vec::new();
let mut tried: Vec<usize> = 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<Outcome> {
// 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<Standing> = 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 => {

View file

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