Merge hands/persona-wake-humans-pace into the drain: humans-pace rule and open floor over the drain, strikes and set-aside

Simulator keeps the drain's turn::history (last wake read from her records) and adds the floor's lines; domain.rs keeps the drain's stewarded read; the project path reads her rooms by own_rooms_among.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-27 23:59:35 +01:00
commit 25706ea647
10 changed files with 701 additions and 90 deletions

View file

@ -63,7 +63,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, FileTrace, Outcome, Start, carry, trace_lines};
use mind_body::heartbeat::{FileStore, HeartbeatView, own_rooms};
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};
@ -261,13 +262,23 @@ fn run_project(args: &[String]) -> Result<String> {
(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),
};
// 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))));
@ -295,11 +306,18 @@ fn run_project(args: &[String]) -> Result<String> {
last_heard: vec![],
recent: vec![],
own_rooms: own,
woken_for: woken,
last_outcome,
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();
}
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!(

View file

@ -32,7 +32,7 @@ use eureka_pipeline::{OrgRepo, PipelineKind, RunTurn, Slug};
use huginn_mind::PipelineFacts;
use crate::address::{Addressee, Name, is_for, project_names};
use crate::chat_client::{Basis, Chat, ChatDelivery, ChatPending};
use crate::chat_client::{Basis, Chat, ChatDelivery, ChatPending, 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};
@ -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<String> {
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<Option<Addressing>>;
@ -441,20 +447,24 @@ 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,
/// 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 }
}
}
@ -464,18 +474,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<LineFacts> {
let mut run = 0usize;
let mut run_rooms: Vec<&str> = Vec::new();
let mut last_at: Option<u64> = 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 +507,24 @@ 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),
open_floor: !lines[..at].iter().any(|earlier| earlier.room == line.room && earlier.at_ms >= since && minds.iter().any(|mind| *mind == earlier.sender)),
}
})
.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<Item = &'a str>) -> Result<Vec<String>> {
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<Item = &'a str>, aliases: impl IntoIterator<Item = &'a str>) -> Vec<String> {
/// case-blind. A direct message is hers by `address::is_for`, not by name.
pub(crate) fn own_rooms<'r, 'a>(repos: impl IntoIterator<Item = &'r str>, aliases: impl IntoIterator<Item = &'a str>) -> Vec<String> {
let names: Vec<&str> = repos.into_iter().map(|repo| repo.rsplit_once('/').map_or(repo, |(_, name)| name)).collect();
let mut found: Vec<String> = Vec::new();
for alias in aliases {
@ -514,18 +542,65 @@ pub fn own_rooms<'a>(repos: impl IntoIterator<Item = &'a str>, 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<WakeCause> {
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 || 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<usize> {
if !open_line(hearers, speaker) {
return None;
}
let candidates: Vec<usize> = (0..hearers.len()).filter(|at| hearers[*at].open).collect();
let standings: Vec<Standing> = candidates.iter().map(|at| hearers[*at].standing.clone()).collect();
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()
.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 {
@ -550,12 +625,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);
@ -593,6 +668,77 @@ pub(crate) fn read_pending(chat: &dyn Chat) -> Result<ChatPending> {
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<LineFacts> {
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
}
/// 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| {
let mut pending: Vec<&ChatDelivery> = row.pending.iter().collect();
pending.sort_by_key(|delivery| delivery.seq);
pending
})
.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 floor = Floor { won: vec![Vec::new(); rows.len()], spoken_for: vec![false; rows.len()] };
for (index, row) in rows.iter().enumerate() {
for delivery in &sorted[index] {
let event = delivery.event_id.as_str();
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;
}
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)
{
floor.won[at].push(event.to_owned());
}
}
}
floor
}
struct Row<'a> {
seat: &'a Seat<'a>,
released: bool,
@ -693,61 +839,74 @@ pub fn poll(organs: &Organs, config: &Config) -> Result<Outcome> {
let mut launches: Vec<String> = Vec::new();
let mut launched: Vec<Slug> = 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 {
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 minds: Vec<String> = config.personas.iter().map(|mind| mind.matrix_id.clone()).collect();
let facts = pending_facts(&pending, row.addressee.matrix_id(), &minds, &row.own_rooms);
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);
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);
// 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();
// 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;
}
}
}
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.
let due = (now - state.last_beat_at).num_seconds() >= i64::from(beat_s);
let standings: Vec<Standing> = 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<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

@ -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,8 +733,330 @@ 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");
}
/// 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<String> {
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<WakeCause> {
let own: Vec<String> = own.iter().map(|room| (*room).to_owned()).collect();
// 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.
fn four_minds(at: u64, ago: u64) -> Vec<ContextLine> {
(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<ContextLine>) -> 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));
}
fn general(seq: u64, sender: &str, text: &str) -> ChatDelivery {
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());
}
}
#[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: 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: 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: 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");
}
#[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_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.advance(1);
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");
}
#[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 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 [
(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<Hearer<'a>> {
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;
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", &[]);
// 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()]);
assert!(rooms(true).is_err(), "unread is an error the caller reports, not no rooms");
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");
}
}

View file

@ -407,6 +407,7 @@ fn drain<C: Chat>(instance: &Slug, start: &Start<C>) -> Outcome {
last_heard: vec![],
recent: past.recent,
own_rooms: own.clone(),
woken_for: vec![],
last_outcome: past.last_outcome,
last_wake: past.last_wake,
records: past.records,

View file

@ -243,6 +243,9 @@ pub struct Request {
pub recent: Vec<Vec<String>>,
/// 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<String>,
/// 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<String>,
/// 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`. Read from her
/// records (`turn::history`); a harness run takes a fixture's (`--last-outcome`).
@ -321,8 +324,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),
})

View file

@ -364,6 +364,7 @@ pub fn fixture_request(harness: &Harness, fixture: &Fixture, state: Option<Value
last_heard: fixture.last_heard.clone(),
recent: vec![],
own_rooms: vec![],
woken_for: vec![],
last_outcome: None,
last_wake: None,
records: vec![],

View file

@ -43,7 +43,7 @@ use super::turn::{self, Actuator, Edited, Sent, history, last_wake};
use super::{DomainFacts, DomainSource, MouthReader, Organs, ReadFixture, ReadSource, Request, Through, TurnKind};
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.
@ -256,13 +256,17 @@ struct Woken {
by: Vec<Value>,
}
/// 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<usize>, Vec<LineFacts>) {
let visible: Vec<usize> = (0..lines.len()).filter(|at| lines[*at].visible_to(&member.entry.id, &member.rooms)).collect();
let facts: Vec<FactLine> = 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<Woken> {
// The lines she sees, and their facts from the heartbeat's one owner of them.
let visible: Vec<usize> = (0..lines.len()).filter(|at| lines[*at].visible_to(&member.entry.id, &member.rooms)).collect();
let seeing: Vec<FactLine> = 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 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<usize>, facts: Vec<LineFacts>) -> Option<Woken> {
let mut found: Vec<(usize, WakeCause)> = Vec::new();
for (at, facts) in visible.into_iter().zip(facts) {
if !unseen(seen, lines, at) {
@ -386,6 +390,8 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize)
let opening = lines.len();
let mut seen: Vec<Seen> = vec![Seen::new(); 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<usize> = std::collections::BTreeSet::new();
// Every turn record of hers, oldest first: the run's trace, which her last outcome, her recent selections, her exchange
// and her last wake are read from (`turn::history`).
let mut records: Vec<Vec<Value>> = vec![Vec::new(); members.len()];
@ -397,7 +403,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<Woken>)> = 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<usize>, Vec<LineFacts>)> = 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_wake(&records[at]).map(|turn| u64::try_from((round_at - turn).num_seconds()).unwrap_or(0)),
last_turn_ms: last_wake(&records[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<Standing> = members.iter().enumerate().map(|(at, member)| standing(at, member)).collect();
let mut won: Vec<Vec<usize>> = 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<Hearer> = 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<Woken>)> = 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) {
@ -447,6 +496,7 @@ fn run(harness: &Harness, plan: &SimFile, members: &mut [Member], repeat: usize)
last_heard: vec![],
recent: past.recent,
own_rooms: member.entry.own_rooms.clone(),
woken_for: won[at].iter().map(|line| lines[*line].delivery(*line, &id, &lines).event_id).collect(),
last_outcome: past.last_outcome,
last_wake: past.last_wake,
records: past.records,

View file

@ -107,7 +107,7 @@ fn ask(from: &str, says: &str, speaker: Speaker, facts: LineFacts) -> Option<Wak
}
fn facts(own_room: bool, in_exchange: bool) -> LineFacts {
LineFacts { mind_run: 0, own_room, in_exchange }
LineFacts { mind_run: 0, own_room, in_exchange, open_floor: false }
}
#[test]
@ -158,7 +158,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<FactLine> = lines.iter().map(|line| FactLine { sender: &line.from, room: &line.room, at_ms: line.at_ms, is_direct: false }).collect();
let seeing: Vec<FactLine> = 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<usize> = (0..lines.len()).filter(|at| lines[*at].from != LIBBY).collect();
@ -172,13 +172,16 @@ 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<Option<WakeCause>> = heard.iter().map(|at| wakes(&libby, &lines[*at].delivery(*at, LIBBY, &lines), speaker(&lines[*at]), simulated[*at])).collect();
let by_poll: Vec<Option<WakeCause>> = 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<Option<WakeCause>> = heard.iter().map(|at| wakes(&libby, &lines[*at].delivery(*at, LIBBY, &lines), speaker(&lines[*at]), closed(simulated[*at]))).collect();
let by_poll: Vec<Option<WakeCause>> = 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.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, 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<_>>(), 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]
@ -329,7 +332,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::<Vec<_>>();
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.
@ -1145,3 +1148,26 @@ fn t_l1_sim_and_mouth_records_same_shape() {
let told = |taken: &crate::projection::turn::Taken| outcome_of(&taken.record).unwrap().lines(forms(&taken.state));
assert_eq!(told(&simulated), told(&live), "she is told the same of either");
}
/// 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<_>>(), vec![1, 2]);
let first = run["transcript"].as_array().unwrap().iter().find(|line| line["woke"] == "human").unwrap();
assert_eq!(first["from"], TOBIAH, "{first}");
}

View file

@ -942,7 +942,7 @@ impl PersonaSource for Stored {
}
fn request(dir: &std::path::Path, renders: Option<usize>, judge_against: Option<Value>) -> 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<String>| {
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();

View file

@ -149,8 +149,9 @@ 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: 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
@ -258,7 +259,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