From a52c7dc51fa584f720d0809bc7ee38398f31acbb Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 19:58:52 +0100 Subject: [PATCH] Persona wake: one humans-pace rule, owned by the heartbeat for the poll and the simulator WakePolicy and the plan's wake field are gone. heartbeat::wakes is the humans-pace rule; heartbeat::line_facts owns the Mind run, her own room and her exchange (moved from the simulator); heartbeat::own_rooms derives her rooms from her stewardships. The poll weighs each delivery with the facts of its context lines, and the live drain sets own_rooms from her stewarded repos. A plan that still carries wake fails to parse. Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/bin/mind-persona.rs | 12 +- crates/mind-body/src/heartbeat.rs | 163 +++++++++++++------- crates/mind-body/src/projection.rs | 4 +- crates/mind-body/src/projection/domain.rs | 40 +++-- crates/mind-body/src/projection/simulate.rs | 80 ++-------- crates/mind-body/tests/public_surface.txt | 2 + 6 files changed, 169 insertions(+), 132 deletions(-) diff --git a/crates/mind-body/src/bin/mind-persona.rs b/crates/mind-body/src/bin/mind-persona.rs index 078c2d9..01c7b2e 100644 --- a/crates/mind-body/src/bin/mind-persona.rs +++ b/crates/mind-body/src/bin/mind-persona.rs @@ -56,7 +56,7 @@ use mind_body::chat_rudp::{RudpChat, connection_id}; use mind_body::cli::{instance_and_endpoint, instance_and_maybe_endpoint}; use mind_body::control::{CONTROL_ROOT, FileSource, control_path, swarm_path}; use mind_body::persona::{Config, carry}; -use mind_body::heartbeat::{FileStore, HeartbeatView}; +use mind_body::heartbeat::{FileStore, HeartbeatView, own_rooms}; use mind_body::projection::harness::{Fixture, Harness, batch, fixture_request, simulate, state_file}; use mind_body::projection::{DomainSource, HttpForge, HuginnPersonaSource, KitModel, LiveReads, MindDomain, Model, MouthReader, ReadSource, Organs as ProjectOrgans, PersonaSource, Request as ProjectRequest, TUNING_FILE, TUNING_ROOT, Through, TurnKind, connector_key, project}; @@ -199,6 +199,14 @@ fn run_project(args: &[String]) -> Result { (Some(address), Some(forge)) => Some(MindDomain::new(HuginnClient::new(address, instance.clone(), TIMEOUT), HttpForge::new(&forge))), _ => None, }; + // Her own rooms, as the heartbeat reads them: the rooms the mouth names for a repo she stewards. Unread, she has none. + let own = match (&domain, &chat) { + (Some(domain), Some(chat)) => match (domain.stewarded(), chat.pending()) { + (Ok(repos), Ok(pending)) => own_rooms(repos.iter().map(String::as_str), pending.deliveries.iter().map(|delivery| delivery.room_alias.as_str())), + _ => vec![], + }, + _ => vec![], + }; // Her reads by intent (map 16.22.3): her mind through the same endpoint, the forge when it is named, the web. let reads = address.map(|address| LiveReads::new(HuginnClient::new(address, instance.clone(), TIMEOUT), setting("MIND_PERSONA_FORGE_URL").map(|forge| HttpForge::new(&forge)))); let organs = ProjectOrgans { @@ -224,7 +232,7 @@ fn run_project(args: &[String]) -> Result { through, last_heard: vec![], recent: vec![], - own_rooms: vec![], + own_rooms: own, last_outcome, last_wake: None, records: vec![], diff --git a/crates/mind-body/src/heartbeat.rs b/crates/mind-body/src/heartbeat.rs index 1459d17..c64c126 100644 --- a/crates/mind-body/src/heartbeat.rs +++ b/crates/mind-body/src/heartbeat.rs @@ -421,28 +421,13 @@ impl Speaker { } } -/// Which lines wake a Persona off the beat. `Live` is the heartbeat's rule today and the only one `poll` uses; the rest -/// are what desk question `po-mind-wakes-mind` weighs, run in `mind-persona project --simulate` until it is answered. -/// The beat is not here: every policy has it, and it wakes one Persona by `tempo::pick`. -#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum WakePolicy { - /// The operator or another Mind addressing her (`is_for`). A member's line does not. - Live, - /// Ruling `persona-only-wake-humans-in-rooms`: a line addressing her, from anyone, and any human line in her rooms. - Ruled, - /// Ruling `persona-only-humans-pace`: a human's line wakes her in her own room (a direct message, or a room that is - /// hers); in a public room only when it addresses her or continues an exchange she is in. A Mind's line wakes her - /// only by an explicit mention (a Matrix mention of her or a reply to her, never a name in prose), in any room, and - /// only while fewer than this many Mind lines in a row came before it across her rooms (`LineFacts::mind_run`): the - /// backstop. - HumansPace(usize), - /// `Ruled`, with at most this many lines in her current Mind-only run (`LineFacts::mind_run`) before a human must - /// speak where it runs: a Mind's line past the cap wakes no one. - NamesWithCap(usize), - /// The swarm's old loop, a control: any line in her rooms but her own. - AllMessages, -} +/// The backstop of the wake rule: a Mind's explicit mention wakes her only while fewer than this many Mind lines in a row +/// came before it across her rooms (`LineFacts::mind_run`). +pub(crate) const MIND_RUN_BACKSTOP: usize = 4; + +/// She is in a room's exchange when she has spoken there within this many minutes before the line: others talking on does +/// not keep her in it. A simulation plan may set another window; the live poll uses this one. +pub(crate) const EXCHANGE_MINUTES: i64 = 30; /// Why a line wakes her, strongest first. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)] @@ -451,18 +436,15 @@ pub(crate) enum WakeCause { AddressedByHuman, Human, AddressedByMind, - /// A Mind's line that does not address her: only the control wakes on it. - Mind, } -/// What the room says about a line, beside the line: the facts a policy may weigh. The live poll knows none of them yet -/// and passes the default; `Live` reads none. +/// 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. pub mind_run: usize, - /// The line is in a room of hers: a direct message (the delivery says so) or a room configured as hers. + /// The line is in a room of hers: a direct message, or a room named for a repo she stewards (`own_rooms`). 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, @@ -476,31 +458,72 @@ impl Default for LineFacts { } } -/// Whether a line in her rooms wakes `who` off the beat under `policy`, and why. The one owner of the wake rule: the -/// heartbeat's poll asks it with `Live`, the simulator with the policy under test. -pub(crate) fn wakes(policy: WakePolicy, who: &Addressee, delivery: &ChatDelivery, speaker: Speaker, facts: LineFacts) -> Option { +/// One line of the rooms she sees, as `line_facts` weighs it: who said it, where, and when. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +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. +pub(crate) fn line_facts(lines: &[FactLine], her: &str, minds: &[String], own_rooms: &[String], window_ms: u64) -> Vec { + let mut run = 0usize; + let mut run_rooms: Vec<&str> = Vec::new(); + lines + .iter() + .enumerate() + .map(|(at, line)| { + let mind_run = run; + if minds.iter().any(|mind| mind == line.sender) { + run += 1; + run_rooms.push(line.room); + } else if run_rooms.contains(&line.room) { + run = 0; + run_rooms.clear(); + } + 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), + in_exchange: lines[..at].iter().any(|earlier| earlier.room == line.room && earlier.sender == her && earlier.at_ms >= since), + } + }) + .collect() +} + +/// Which of `aliases` are her own rooms: those named for a repo she stewards (`#huginn:gamecult.org` for `GameCult/Huginn`), +/// case-blind. A direct message is hers by `FactLine::is_direct`, not by name. +pub fn own_rooms<'a>(repos: impl IntoIterator, aliases: impl IntoIterator) -> Vec { + let names: Vec<&str> = repos.into_iter().map(|repo| repo.rsplit_once('/').map_or(repo, |(_, name)| name)).collect(); + let mut found: Vec = Vec::new(); + for alias in aliases { + let local = alias.strip_prefix('#').map(|rest| rest.split_once(':').map_or(rest, |(local, _)| local)); + if local.is_some_and(|local| names.iter().any(|name| name.eq_ignore_ascii_case(local))) && !found.iter().any(|held| held == alias) { + found.push(alias.to_owned()); + } + } + found +} + +/// Whether a line in her rooms wakes `who` off the beat, and why: the one owner of the wake rule, asked by the heartbeat's +/// poll and by the simulator. A human's line wakes her in her own room (a direct message, or a room named for a repo she +/// stewards), and in a public room only when it addresses her or continues an exchange she is in. A Mind's line wakes +/// her only by an explicit mention (a Matrix mention of her or a reply to her, never a name in prose), in any room, and +/// only while fewer than `MIND_RUN_BACKSTOP` Mind lines in a row came before it across her rooms. +pub(crate) fn wakes(who: &Addressee, delivery: &ChatDelivery, speaker: Speaker, facts: LineFacts) -> Option { if speaker == Speaker::Her { return None; } let addressed = is_for(who, delivery); - let human = speaker.human(); - let cause = match (human, addressed) { - (true, true) => WakeCause::AddressedByHuman, - (true, false) => WakeCause::Human, - (false, true) => WakeCause::AddressedByMind, - (false, false) => WakeCause::Mind, - }; - let wakes = match policy { - WakePolicy::Live => addressed && matches!(speaker, Speaker::Operator | Speaker::Mind), - WakePolicy::Ruled => human || addressed, - WakePolicy::HumansPace(cap) => { - let explicit = delivery.mentions.iter().any(|id| id == who.matrix_id()) || matches!(delivery.basis, Some(Basis::Tag | Basis::Reply)); - if human { addressed || delivery.is_direct || facts.own_room || facts.in_exchange } else { explicit && facts.mind_run < cap } - } - WakePolicy::NamesWithCap(cap) => human || (addressed && facts.mind_run < cap), - WakePolicy::AllMessages => true, - }; - wakes.then_some(cause) + if speaker.human() { + let wakes = addressed || delivery.is_direct || facts.own_room || facts.in_exchange; + return wakes.then_some(if addressed { WakeCause::AddressedByHuman } else { WakeCause::Human }); + } + let explicit = delivery.mentions.iter().any(|id| id == who.matrix_id()) || matches!(delivery.basis, Some(Basis::Tag | Basis::Reply)); + (explicit && facts.mind_run < MIND_RUN_BACKSTOP).then_some(WakeCause::AddressedByMind) } impl Config { @@ -518,6 +541,34 @@ impl Config { } } +/// The facts of each of `pending` (in seq order), over the lines she can see: every delivery's context lines before it, +/// then the delivery, merged in time order and each line once. The mouth's context is the room's own earlier lines, hers +/// among them, so the Mind run and her exchange read as the simulator's room gives them. +pub(crate) fn pending_facts(pending: &[&ChatDelivery], her: &str, minds: &[String], own_rooms: &[String]) -> Vec { + let mut lines: Vec<(FactLine, Option)> = Vec::new(); + for (index, delivery) in pending.iter().enumerate() { + 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)); + } + } + 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))), + } + } + lines.sort_by_key(|(line, _)| line.at_ms); + let facts = line_facts(&lines.iter().map(|(line, _)| *line).collect::>(), her, minds, own_rooms, u64::try_from(EXCHANGE_MINUTES * 60_000).unwrap_or_default()); + let mut of = vec![LineFacts::default(); pending.len()]; + for ((_, slot), facts) in lines.iter().zip(facts) { + if let Some(index) = slot { + of[*index] = facts; + } + } + of +} + /// The mouth pages a pending answer, so fewer deliveries may come than wait. /// The heartbeat acks nothing: it asks again after the highest seq it has until /// the answer is empty. A mouth that never empties is cut off at `PENDING_PAGES`. @@ -546,6 +597,8 @@ struct Row<'a> { pending: Vec, /// Whom a delivery may address in her: her roster names and her projects' names as the last poll that read her pending chat left them. addressee: Addressee, + /// Her rooms among the pending deliveries': those named for a repo she stewards, as the last poll read her stewardships. + own_rooms: Vec, note: String, } @@ -608,7 +661,7 @@ pub fn poll(organs: &Organs, config: &Config) -> Result { // Her last-read names when the table holds her, else her roster names alone. let roster = Addressee::new(&seat.who.matrix_id, [seat.who.public_name.as_str(), seat.who.handle.as_str()]); let kept = stored_addressing.minds.iter().find(|stored| stored.matrix_id() == seat.who.matrix_id).cloned().unwrap_or_else(|| roster.clone()); - let mut row = Row { seat, released, busy, pending: vec![], addressee: kept, note: String::new() }; + let mut row = Row { seat, released, busy, pending: vec![], addressee: kept, own_rooms: vec![], note: String::new() }; // Pending chat, read-only, for a released Mind. if row.released { match read_pending(seat.chat) { @@ -621,7 +674,10 @@ pub fn poll(organs: &Organs, config: &Config) -> Result { // Her projects' names address her too; read only when something is pending. A failed read keeps her last-read row. if !row.pending.is_empty() { match stewardships_of(seat.mind) { - Ok((names, repos)) => row.addressee = roster.with_stewardships(names, repos), + Ok((names, repos)) => { + row.own_rooms = own_rooms(repos.iter().map(|repo| repo.0.as_str()), row.pending.iter().map(|delivery| delivery.room_alias.as_str())); + row.addressee = roster.with_stewardships(names, repos); + } Err(error) => row.note = format!("{} stewardship names unread: {error}", row.note).trim().to_string(), } } @@ -643,10 +699,13 @@ 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); pending .into_iter() - .filter(|delivery| wakes(WakePolicy::Live, &row.addressee, delivery, config.speaker(&row.addressee, delivery), LineFacts::default()).is_some()) - .map(|delivery| format!("{}:{}", slug.0, delivery.event_id)) + .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 }; diff --git a/crates/mind-body/src/projection.rs b/crates/mind-body/src/projection.rs index 6171994..b579187 100644 --- a/crates/mind-body/src/projection.rs +++ b/crates/mind-body/src/projection.rs @@ -217,7 +217,7 @@ pub struct Request { /// The ids each earlier projection selected, oldest first, for freshness: a simulation's earlier turns of hers. /// Empty live until trace v2 (C3c) carries them. pub recent: Vec>, - /// The rooms that are hers, by the key the lines carry: a simulation's plan. The live body records none yet. + /// The rooms that are hers, by the key the lines carry: live from `heartbeat::own_rooms` (the rooms named for her stewarded repos), simulated from the plan. pub own_rooms: Vec, /// The record of her last turn, which her packet opens with what came of (`outcome::outcome_of`): the Interpreter's /// decision under `interpreter` and the receipts of the lines that went out under `posted`, or `failed`. A @@ -298,7 +298,7 @@ fn read_room(chat: &dyn MouthReader, request: &Request, own: &Addressee) -> (Roo display: delivery.sender_display.clone(), text: delivery.text.clone(), at_ms: delivery.at_unix_ms, - // The heartbeat's rule, the one that woke her: never a second opinion here. Under humans_pace a human's line in + // 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)), event: delivery.event_id.clone(), diff --git a/crates/mind-body/src/projection/domain.rs b/crates/mind-body/src/projection/domain.rs index f94ea69..36473a9 100644 --- a/crates/mind-body/src/projection/domain.rs +++ b/crates/mind-body/src/projection/domain.rs @@ -190,17 +190,25 @@ impl MindDomain { } } +impl MindDomain { + fn ask(&self, selection: &Selection) -> Result { + let request = HuginnMindRequest::Query { instance: self.client.instance().clone(), selection: selection.clone(), semantic: None }; + match self.client.call(request).map_err(|_| anyhow!("her mind could not be asked"))? { + HuginnMindResponse::Query(page) => Ok(page), + HuginnMindResponse::Refused(_) => bail!("her mind refused the read"), + _ => bail!("her mind answered a read with something else"), + } + } + + /// The repos she stewards in force (`Org/Repo`), through her read door: the drain's input to `heartbeat::own_rooms`. + pub fn stewarded(&self) -> Result> { + stewarded(&|selection| self.ask(selection), &self.client.instance().0) + } +} + impl DomainSource for MindDomain { fn read(&self, since: DateTime, now: DateTime) -> Result { - let ask = |selection: &Selection| -> Result { - let request = HuginnMindRequest::Query { instance: self.client.instance().clone(), selection: selection.clone(), semantic: None }; - match self.client.call(request).map_err(|_| anyhow!("her mind could not be asked"))? { - HuginnMindResponse::Query(page) => Ok(page), - HuginnMindResponse::Refused(_) => bail!("her mind refused the read"), - _ => bail!("her mind answered a read with something else"), - } - }; - read(&ask, &self.client.instance().0, &self.forge, since, now) + read(&|selection| self.ask(selection), &self.client.instance().0, &self.forge, since, now) } } @@ -288,10 +296,8 @@ fn who(provenance: &PipelineProvenance, her: &str) -> Who { } } -/// Her domain from `since`: her in-force stewardships and her campaigns through `ask` (her door), each stewarded repo's -/// pull requests through `forge`. Any failure fails the whole read, except a repo that is archived, missing or moved, -/// which is skipped and named. -pub(crate) fn read(ask: &Ask, her: &str, forge: &dyn ForgeGet, since: DateTime, now: DateTime) -> Result { +/// The repos `her` stewards in force, each once. +pub(crate) fn stewarded(ask: &Ask, her: &str) -> Result> { let mut repos: Vec = Vec::new(); for item in all(ask, &in_force(of_kind(PipelineKind::Stewardship)))? { if let PipelineFacts::Stewardship { instance, repo, .. } = &item.facts @@ -301,6 +307,14 @@ pub(crate) fn read(ask: &Ask, her: &str, forge: &dyn ForgeGet, since: DateTime, now: DateTime) -> Result { + let repos = stewarded(ask, her)?; let slugs: Vec = all(ask, &in_force(of_kind(PipelineKind::Campaign)))?.iter().map(|item| root(item).to_owned()).collect::>().into_iter().collect(); let mut campaigns: Vec = slugs.iter().map(|slug| CampaignFacts { slug: slug.clone(), rulings: Vec::new() }).collect(); if !slugs.is_empty() { diff --git a/crates/mind-body/src/projection/simulate.rs b/crates/mind-body/src/projection/simulate.rs index f82a960..83cbb3d 100644 --- a/crates/mind-body/src/projection/simulate.rs +++ b/crates/mind-body/src/projection/simulate.rs @@ -2,7 +2,7 @@ //! one `project` through the Persona stage, and each one's drafts the Interpreter sends join the room as from her Matrix id, so the //! next one hears them. //! -//! Who wakes is the heartbeat's: `heartbeat::wakes` under the plan's `WakePolicy`, over each persona's addressee as the +//! Who wakes is the heartbeat's: `heartbeat::wakes` over each persona's addressee as the //! heartbeat's addressing table holds it (her stewarded projects' names included) when the plan names the table. The //! beat is the heartbeat's too: when it falls, one Persona wakes, the winner of `tempo::pick`. Who wakes in a round is //! decided from the room as the round opens, as one heartbeat poll decides from the pending it read: a line spoken by a @@ -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, FileStore, HeartbeatView, LineFacts, Speaker, WakeCause, WakePolicy, addressed_by_member, wakes}; +use crate::heartbeat::{Addressing, DEFAULT_BEAT_S, EXCHANGE_MINUTES, FactLine, FileStore, HeartbeatView, Speaker, WakeCause, addressed_by_member, line_facts, wakes}; use crate::tempo::{Standing, pick}; /// The most personas a simulation holds: the swarm. @@ -61,14 +61,12 @@ struct SimFile { repeats: usize, #[serde(default)] seed: u64, - #[serde(default = "ruled")] - wake: WakePolicy, /// The heartbeat's beat, in seconds of simulated time; 0 is no beat. #[serde(default = "beat_s")] beat_s: u32, #[serde(default = "two")] round_minutes: i64, - /// She is in a room's exchange when she has spoken there within this many minutes before the line (`humans_pace`): + /// She is in a room's exchange when she has spoken there within this many minutes before the line: /// others talking on does not keep her in it. #[serde(default = "exchange_minutes")] exchange_minutes: i64, @@ -94,11 +92,7 @@ fn two() -> i64 { } fn exchange_minutes() -> i64 { - 30 -} - -fn ruled() -> WakePolicy { - WakePolicy::Ruled + EXCHANGE_MINUTES } fn beat_s() -> u32 { @@ -115,7 +109,7 @@ struct CastEntry { /// Her rooms; none is every room of the plan. #[serde(default)] rooms: Vec, - /// The rooms that are hers, where any human line wakes her under `humans_pace`. Neither the heartbeat's table nor + /// The rooms that are hers, where any human line wakes her. Neither the heartbeat's table nor /// `persona.env` records which rooms a Mind owns, so the plan says; a direct message is always hers. #[serde(default)] own_rooms: Vec, @@ -196,30 +190,6 @@ fn speaker(line: &Line, member: &Member, operators: &[String], cast: &[String]) } } -/// For each line, how many Mind lines in a row came before it in her current Mind-only run: one run across every room -/// she sees, which a human's line ends only when it is in a room the run has lines in. Meta chatting in #eureka does not -/// end a loop in #minds. -fn mind_runs(lines: &[Line], cast: &[String], member: &Member) -> Vec { - let mut run = 0usize; - let mut run_rooms: Vec<&str> = Vec::new(); - lines - .iter() - .map(|line| { - let before = run; - if line.visible_to(&member.entry.id, &member.rooms) { - if cast.contains(&line.from) { - run += 1; - run_rooms.push(&line.room); - } else if run_rooms.contains(&line.room.as_str()) { - run = 0; - run_rooms.clear(); - } - } - before - }) - .collect() -} - /// How a Mind's line addressed her, by the evidence `is_for` had, strongest first: a Matrix tag or a reply to her, her /// Matrix id written as plain text, or one of her names in the text. fn how_addressed(line: &Line, at: usize, member: &Member, lines: &[Line]) -> &'static str { @@ -233,7 +203,7 @@ fn how_addressed(line: &Line, at: usize, member: &Member, lines: &[Line]) -> &'s } } -/// One wake: why (the strongest cause among her new lines, under the plan's policy) and, when only Minds' lines caused +/// One wake: why (the strongest cause among her new lines) and, when only Minds' lines caused /// it, the strongest evidence that addressed her and the lines that did. struct Woken { cause: WakeCause, @@ -243,25 +213,20 @@ struct Woken { by: Vec, } -/// Whether she is in the exchange a line belongs to: she spoke in its room within `window` before it. -fn in_exchange(lines: &[Line], at: usize, her: &str, window: Duration) -> bool { - let line = &lines[at]; - let since = line.at_ms.saturating_sub(u64::try_from(window.num_milliseconds()).unwrap_or(0)); - lines[..at].iter().any(|earlier| earlier.room == line.room && earlier.from == her && earlier.at_ms >= since) -} - /// 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. -#[allow(clippy::too_many_arguments, reason = "one wake decision's inputs, each a plan or room fact")] -fn woken(lines: &[Line], runs: &[usize], seen: &Seen, member: &Member, operators: &[String], cast: &[String], policy: WakePolicy, gap: Duration) -> Option { +fn woken(lines: &[Line], seen: &Seen, member: &Member, operators: &[String], cast: &[String], gap: Duration) -> Option { + // The lines she sees, and their facts from the heartbeat's one owner of them. + let visible: Vec = (0..lines.len()).filter(|at| lines[*at].visible_to(&member.entry.id, &member.rooms)).collect(); + let seeing: Vec = visible.iter().map(|at| FactLine { sender: &lines[*at].from, room: &lines[*at].room, at_ms: lines[*at].at_ms, is_direct: lines[*at].dm_to.is_some() }).collect(); + let facts = line_facts(&seeing, &member.entry.id, cast, &member.entry.own_rooms, u64::try_from(gap.num_milliseconds()).unwrap_or(0)); let mut found: Vec<(usize, WakeCause)> = Vec::new(); - for (at, line) in lines.iter().enumerate() { - if !unseen(seen, lines, at) || !line.visible_to(&member.entry.id, &member.rooms) { + for (at, facts) in visible.into_iter().zip(facts) { + if !unseen(seen, lines, at) { continue; } - let delivery = line.delivery(at, &member.entry.id, lines); - let facts = LineFacts { mind_run: runs[at], own_room: member.entry.own_rooms.contains(&line.room), in_exchange: in_exchange(lines, at, &member.entry.id, gap) }; - if let Some(cause) = wakes(policy, &member.addressee, &delivery, speaker(line, member, operators, cast), facts) { + let delivery = lines[at].delivery(at, &member.entry.id, lines); + if let Some(cause) = wakes(&member.addressee, &delivery, speaker(&lines[at], member, operators, cast), facts) { found.push((at, cause)); } } @@ -285,7 +250,6 @@ fn cause_word(cause: Option) -> &'static str { Some(WakeCause::AddressedByHuman) => "addressed_by_human", Some(WakeCause::Human) => "human", Some(WakeCause::AddressedByMind) => "addressed_by_mind", - Some(WakeCause::Mind) => "mind", None => "beat", } } @@ -393,7 +357,7 @@ 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, &mind_runs(&lines, &cast, member), &seen[at], member, &plan.operators, &cast, plan.wake, Duration::minutes(plan.exchange_minutes)).map(|why| (at, Some(why)))).collect(); + 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(); // 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) { @@ -725,16 +689,6 @@ fn number(value: &Value) -> String { value.as_f64().map_or_else(|| "n/a".into(), |number| format!("{number:.3}")) } -fn policy_words(policy: WakePolicy) -> String { - match policy { - WakePolicy::Live => "live: the operator or another Mind addressing her (the heartbeat's rule today)".into(), - WakePolicy::Ruled => "ruled: a line addressing her, from anyone, and any human line in her rooms".into(), - WakePolicy::HumansPace(cap) => format!("humans_pace (cap {cap}): a human's line wakes a Mind in her own room always, and in a public room when it addresses her or continues an exchange she is in; a Mind's line wakes another only by an explicit mention or a reply, while her current Mind-only run, across her rooms, is under {cap} lines, never by a name in prose"), - WakePolicy::NamesWithCap(cap) => format!("names_with_cap {cap}: ruled, but a Mind's line wakes no one once her current Mind-only run, across her rooms, has {cap} lines, until a human speaks where it runs"), - WakePolicy::AllMessages => "all_messages: any line in her rooms, a Mind's too (the old loop, the control)".into(), - } -} - /// `count` lines spread evenly over the transcript, the first and the last included. fn representative(transcript: &[Value], count: usize) -> Vec<&Value> { if transcript.len() <= count { @@ -806,7 +760,7 @@ fn markdown(plan_path: &Path, plan: &SimFile, members: &[Member], group_state: O let _ = writeln!(out, "- rooms: {}; rounds: {}; repeats: {}; seed: {}; minutes a round: {}; she is in a room's exchange when she spoke there within {} min", plan.rooms.join(", "), plan.rounds, plan.repeats, plan.seed, plan.round_minutes, plan.exchange_minutes); let owners: Vec = members.iter().filter(|member| !member.entry.own_rooms.is_empty()).map(|member| format!("{}: {}", member.entry.name, member.entry.own_rooms.join(", "))).collect(); let _ = writeln!(out, "- own rooms (from the plan: neither the heartbeat's table nor `persona.env` records room ownership): {}", if owners.is_empty() { "none".to_owned() } else { owners.join("; ") }); - let _ = writeln!(out, "- wake: {}; beat: {}", policy_words(plan.wake), if plan.beat_s == 0 { "off".to_owned() } else { format!("every {} s of simulated time, one Persona by `tempo::pick`", plan.beat_s) }); + let _ = writeln!(out, "- wake: humans pace (`heartbeat::wakes`); beat: {}", if plan.beat_s == 0 { "off".to_owned() } else { format!("every {} s of simulated time, one Persona by `tempo::pick`", plan.beat_s) }); let _ = writeln!(out, "- group state in the Projector's packet: {}", match group_state { Some(true) => "on", Some(false) => "off", None => "unknown (the tuning did not load)" }); let _ = writeln!(out, "- speech: the Interpreter's lines, each posted to its room; none is silence"); let _ = writeln!(out, "- wakes are counted per wake, by its strongest cause: addressed by a human, a human line, addressed by a Mind, a Mind's line (control only), the beat. A Mind-addressed wake's evidence is its strongest: a Matrix mention or reply, her id written as text, a name in the text"); diff --git a/crates/mind-body/tests/public_surface.txt b/crates/mind-body/tests/public_surface.txt index 1cd8d5b..372db1c 100644 --- a/crates/mind-body/tests/public_surface.txt +++ b/crates/mind-body/tests/public_surface.txt @@ -149,6 +149,7 @@ mind_body::control: struct SwarmWriter pub-fields[] mind_body::control: struct UnsafeStore # [derive (Debug)] pub-fields[path: PathBuf, mode: u32, uid: u32] mind_body::heartbeat: # [derive (Clone , Debug , PartialEq , Eq)] pub enum Outcome { Held (HeldReason) , Polled { launched : Vec < Slug > , } , } mind_body::heartbeat: const DEFAULT_BEAT_S : u32 +mind_body::heartbeat: fn own_rooms < 'a > (repos : impl IntoIterator < Item = & 'a str > , aliases : impl IntoIterator < Item = & 'a str >) -> Vec < String > mind_body::heartbeat: fn poll (organs : & Organs , config : & Config) -> Result < Outcome > mind_body::heartbeat: impl Config mind_body::heartbeat: impl Config: fn new (personas : Vec < PersonaId > , operators : Vec < String > , beat_s : u32) -> Result < Self > @@ -260,6 +261,7 @@ mind_body::projection::domain: impl HttpForge mind_body::projection::domain: impl HttpForge: fn new (base_url : & str) -> Self mind_body::projection::domain: impl MindDomain mind_body::projection::domain: impl MindDomain: fn new (client : HuginnClient , forge : HttpForge) -> Self +mind_body::projection::domain: impl MindDomain: fn stewarded (& self) -> Result < Vec < String > > mind_body::projection::domain: impl Names mind_body::projection::domain: pub trait DomainSource { fn read (& self , since : DateTime < Utc > , now : DateTime < Utc >) -> Result < DomainFacts > ; } mind_body::projection::domain: struct DomainFacts # [derive (Clone , Debug , Default , PartialEq , Eq , Serialize , Deserialize)] pub-fields[]