diff --git a/crates/mind-body/src/bin/mind-persona.rs b/crates/mind-body/src/bin/mind-persona.rs index 7ac0b45..52587b4 100644 --- a/crates/mind-body/src/bin/mind-persona.rs +++ b/crates/mind-body/src/bin/mind-persona.rs @@ -2,8 +2,8 @@ //! one start of the Persona organ (`mind_body::persona::carry`) inside //! `mind-persona@`. This reads the process's arguments and //! environment, the things the library never reads, builds the organs once the brakes allow a turn, and prints the -//! outcome: `dead` when a brake is held; else the drain (`drained: N turns, acked through S, K puts refused`), which takes -//! a turn in each room holding a waking line and acks once (`persona-turn-drains-deliveries`); or `failed: ` for a +//! outcome: `dead` when a brake is held; else the drain (`drained: 1 wake, K turns, ended idle, acked through S`), one wake that stays +//! open after its first turn (`persona::live`: it polls the mouth and takes a turn for each line that wakes her, until it is idle or reaches its span or its caps); or `failed: ` for a //! start that read nothing, exit 1. It exits 0 for `dead` and `drained`, and 2 when the arguments or the environment //! are wrong. //! @@ -124,6 +124,7 @@ fn start(config: Config, instance: &Slug, endpoint: SocketAddr) -> Result) -> Vec { pub enum Outcome { /// The brake did not allow it; nothing was touched. Dead(HeldReason), - /// The drain ran: the wakes taken (none, or one), and the seq the start acked through (none when it acked nothing). - Drained { wakes: usize, acked_through: Option }, + /// The drain ran: the wakes taken (none, or one), the turns the wake ran, why it ended (none when no wake ran), and the seq the start acked + /// through (none when it acked nothing). + Drained { wakes: usize, turns: usize, ended: Option, acked_through: Option }, /// Her agent has spent its day's cap: no organ was called, no wake was recorded and the lines that would have woken her stay unacked, to /// wake her once the UTC day ends at `until`. A `Drained` with no wakes says nothing was waking her; this says she was held. Held { until: DateTime }, @@ -258,8 +271,9 @@ impl fmt::Display for Outcome { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Dead(reason) => write!(f, "dead: {reason:?}"), - Self::Drained { wakes, acked_through } => { - write!(f, "drained: {wakes} wakes, acked through {}", acked_through.map_or_else(|| "nothing".to_owned(), |seq| seq.to_string())) + Self::Drained { wakes, turns, ended, acked_through } => { + let ended = ended.map_or_else(String::new, |end| format!(", ended {end}")); + write!(f, "drained: {wakes} wake{}, {turns} turn{}{ended}, acked through {}", if *wakes == 1 { "" } else { "s" }, if *turns == 1 { "" } else { "s" }, acked_through.map_or_else(|| "nothing".to_owned(), |seq| seq.to_string())) } Self::Held { until } => write!(f, "held: the agent's day cap, until {}", until.to_rfc3339()), Self::Failed(why) => write!(f, "failed: {why}"), @@ -293,6 +307,9 @@ pub struct Start { /// Her box's door (`MIND_PERSONA_BOX_SOCKET`): where her agent's shell commands go. pub box_socket: PathBuf, pub clock: Box DateTime>, + /// Waits this long: `thread::sleep` live. An open wake waits between its polls of the mouth, and a start staggers its open by it; a test's is a + /// function that advances its clock. + pub pause: Box, } /// One start. `control` is the instance's control store and `swarm` the swarm's. Brakes first, and nothing after them: @@ -301,7 +318,7 @@ pub fn carry(control: &impl ControlSource, swarm: &impl ControlSource, match read(control, swarm, instance) { Effective::Held { reason } => Outcome::Dead(reason), Effective::Released(_) => match build() { - Ok(start) => drain(instance, &start), + Ok(start) => drain(instance, &start, false), Err(fault) => Outcome::Failed(format!("{fault:#}")), }, } @@ -330,7 +347,38 @@ fn place(trace: &dyn Trace) -> usize { trace.records().map_or(usize::MAX, |records| records.len()) } -fn drain(instance: &Slug, start: &Start) -> Outcome { +/// The ack, cleanup behind her trace: through the highest seq of `pool` below the first line of a watched room that her trace does not yet hold +/// decided. It decides nothing. A start killed before a turn's row landed does not ack past a line it did not answer, and a line whose row did not +/// land is never acked past. +fn settle(start: &Start, pool: &[ChatDelivery], watched: &BTreeSet, acked: &mut Option) { + let records = match start.trace.records() { + Ok(records) => records, + Err(fault) => return eprintln!("mind-persona: her trace was not read, so nothing is acked: {fault:#}"), + }; + let done = decided(&records); + let blocked = pool.iter().filter(|delivery| watched.contains(delivery.room_alias.as_str()) && !done.contains(delivery.event_id.as_str())).map(|delivery| delivery.seq).min(); + let through = pool.iter().map(|delivery| delivery.seq).filter(|seq| blocked.is_none_or(|limit| *seq < limit)).max().filter(|seq| acked.is_none_or(|held| *seq > held)); + if let Some(seq) = through { + match start.chat.ack(seq) { + Ok(()) => *acked = Some(seq), + Err(fault) => eprintln!("mind-persona: the ack through {seq} failed: {fault:#}"), + } + } +} + +/// Her input shows these lines of a turn: a say in their rooms is sent against the newest of them (`Mouth::shown`). +fn show(mouth: &Mouth<'_>, deliveries: &[&ChatDelivery], hold: &[&str]) { + let mut shown: Vec<&&ChatDelivery> = deliveries.iter().filter(|delivery| hold.contains(&delivery.event_id.as_str())).collect(); + shown.sort_by_key(|delivery| (delivery.at_unix_ms, delivery.seq)); + for delivery in shown { + mouth.shown(&delivery.room_alias, &delivery.event_id); + } +} + +/// One start: the open (brakes, state, the lines that wake her, the Projector and the Persona once), her first turn, then her live span (polls of +/// the mouth, a turn for each line that wakes her, in the same agent conversation: `live`), then the close (the Interpreter once, the wake record, +/// the last ack). `staggered` says the open has already waited out its stagger (`live::stagger_ms`) and read the mouth again. +fn drain(instance: &Slug, start: &Start, staggered: bool) -> Outcome { let began = (start.clock)(); let began_ms = u64::try_from(began.timestamp_millis()).unwrap_or_default(); let config = &start.config; @@ -352,6 +400,8 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { let stem = format!("n{}", first_read.len()); let mut deliveries: Vec<&ChatDelivery> = pending.deliveries.iter().collect(); deliveries.sort_by_key(|delivery| delivery.seq); + // The same lines, owned and growing: what the wake has seen of the mouth, the acks' and the turns' one list of lines. + let mut pool: Vec = deliveries.iter().map(|delivery| (*delivery).clone()).collect(); // The newest event of each room her input held: a say is refused by the mouth if another sender reached the room after it. let mut newest: BTreeMap<&str, (u64, &str)> = BTreeMap::new(); let lines = deliveries.iter().map(|delivery| (delivery.room_alias.as_str(), delivery.at_unix_ms, delivery.event_id.as_str())).chain(pending.tail.iter().flatten().map(|line| (line.room.as_str(), line.at_unix_ms, line.event_id.as_str()))); @@ -387,16 +437,15 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { Ok(lines) => lines.unwrap_or_default(), Err(fault) => return failed("the heartbeat state was not read", fault), }; - let mut facts = pending_facts(&deliveries, &config.own_sender, &config.minds, &own); - for (delivery, facts) in deliveries.iter().zip(&mut facts) { - facts.open_floor &= claimed.contains(&delivery.event_id); - } // A line the heartbeat woke her for is waking whatever this start would have derived: the poll's claim is the one derivation, and a - // line it keeps waking her for that this start did not answer would be a loop. + // line it keeps waking her for that this start did not answer would be a loop. The wake's polls ask the same `Hearing`. + let addressing = addressing_of(config, start.addressing.as_deref(), &her); + let hearing = Hearing { config, her: &her, addressing: &addressing, own_rooms: &own, claimed: &claimed }; + let flags = hearing.waking(&deliveries); let waking_all: Vec = deliveries .iter() - .zip(&facts) - .filter(|(delivery, facts)| claimed.contains(&delivery.event_id) || wakes(&her, delivery, speaker(config, delivery), **facts).is_some()) + .zip(&flags) + .filter(|(_, waking)| **waking) .map(|(delivery, _)| Waking { room: delivery.room_alias.as_str(), event: delivery.event_id.as_str(), sender: if delivery.sender_display.is_empty() { delivery.sender.as_str() } else { delivery.sender_display.as_str() }, text: delivery.text.as_str() }) .collect(); let woken = !waking_all.is_empty(); @@ -406,12 +455,19 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { let mut first = true; let (aside, due): (Vec, Vec) = waking_all.into_iter().filter(|line| !done.contains(line.event)).partition(|line| std::mem::take(&mut first) && strikes(&trace, line.event) >= STRIKES); // The rooms of every line this start owes a wake or a set-aside: the ack never passes an undecided line of theirs, shown or not. - let watched: BTreeSet<&str> = aside.iter().chain(&due).map(|line| line.room).collect(); + let mut watched: BTreeSet = aside.iter().chain(&due).map(|line| line.room.to_owned()).collect(); // The wake after one that failed for a reason that is no outage takes only the oldest waking room: a failure the blend of rooms hid is // found in one room alone, where it strikes that room's oldest line and no innocent room's. let retreating = trace.iter().rev().find(|record| is_wake(record)).is_some_and(|record| record_failed(record) && record.get("outage").is_none()); let oldest_room = due.first().map(|line| line.room); let waking: Vec = due.into_iter().filter(|line| !retreating || Some(line.room) == oldest_room).collect(); + // A line addressed to several Minds is taken by each after her rank among them (`live::stagger_ms`, the first experiment's stagger), so the later + // ones read the earlier ones' answers before they give theirs. The open waits out the shortest delay among its waking lines, as that session's + // first poll did, and reads the mouth afresh. + if !staggered && let Some(delay) = waking.iter().filter_map(|line| deliveries.iter().find(|delivery| delivery.event_id == line.event)).map(|delivery| stagger_ms(&her, &addressing, delivery)).min().filter(|delay| *delay > 0) { + (start.pause)(std::time::Duration::from_millis(delay)); + return drain(instance, start, true); + } // The waking rooms, oldest waking line first: the first is the wake's room and every other an arrival in it. A start no line woke is // the beat's, in the room of the newest pending line, else her first room. let mut rooms: Vec<&str> = Vec::new(); @@ -425,24 +481,6 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { rooms.extend(deliveries.last().map(|delivery| delivery.room_alias.as_str()).or(config.rooms.first().map(String::as_str))); } let mut acked: Option = None; - // The ack is cleanup behind her trace and decides nothing: through the highest seq below the first undecided line of a room this start owes - // a wake or a set-aside (taken in this wake or not). A start killed before its wake record landed does not ack past a line it did not - // answer, and a line whose record did not land is never acked past. - let settle = |acked: &mut Option| { - let records = match start.trace.records() { - Ok(records) => records, - Err(fault) => return eprintln!("mind-persona: her trace was not read, so nothing is acked: {fault:#}"), - }; - let done = decided(&records); - let blocked = deliveries.iter().filter(|delivery| watched.contains(delivery.room_alias.as_str()) && !done.contains(delivery.event_id.as_str())).map(|delivery| delivery.seq).min(); - let through = deliveries.iter().map(|delivery| delivery.seq).filter(|seq| blocked.is_none_or(|limit| *seq < limit)).max().filter(|seq| acked.is_none_or(|held| *seq > held)); - if let Some(seq) = through { - match start.chat.ack(seq) { - Ok(()) => *acked = Some(seq), - Err(fault) => eprintln!("mind-persona: the ack through {seq} failed: {fault:#}"), - } - } - }; // A line set aside is recorded, then acked past before the wake, so the wake reads the room without it. if !aside.is_empty() { let lines: Vec = aside.iter().map(|line| json!({ "room": line.room, "event": line.event, "sender": line.sender, "text": line.text })).collect(); @@ -452,10 +490,10 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { } } if rooms.is_empty() || !aside.is_empty() { - settle(&mut acked); + settle(start, &pool, &watched, &mut acked); } if rooms.is_empty() { - return Outcome::Drained { wakes: 0, acked_through: acked }; + return Outcome::Drained { wakes: 0, turns: 0, ended: None, acked_through: acked }; } let now = (start.clock)(); let records = match start.trace.records() { @@ -531,97 +569,211 @@ fn drain(instance: &Slug, start: &Start) -> Outcome { // other. A failed Projector, Persona or agent turn runs no Interpreter, so the retry of a failed wake never applies a delta twice; an // Interpreter that fails after the agent acted fails nothing, because a retry would wake the agent again and risk saying a line twice. let mut fault = waked.failed.clone(); + let mut end = fault.as_ref().map(|_| End::Failed); + let (mut turns_run, mut completed, mut landed) = (0usize, 0usize, 0usize); let mut receipts: Vec = vec![]; + // The lines the turns that completed held: what the Interpreter reads of what she heard. + let mut counted: Vec = vec![]; + // Every line a turn of this wake took, whether or not its row landed or it completed: the wake takes no line twice. + let mut taken: BTreeSet = BTreeSet::new(); + // What the mouth held when the wake opened: lines the open did not hold stay undecided, as they always have, and are not the close's to decide. + let opened: BTreeSet = pool.iter().map(|delivery| delivery.event_id.clone()).collect(); + let mut live_rooms: Vec = rooms.iter().map(|room| (*room).to_owned()).collect(); // Whether the failure is a turn's and is on the turn row that landed: a failure is struck on one row only, or its line would be struck twice. let mut by_turn = false; - // Whether a turn row landed: the row that holds the lines it took. - let mut turned = false; - // A failed row says why, and whether it was an outage. A failure that is no outage, in a wake over one room, is a strike against that - // room's oldest waking line and no other; a wake over several rooms cannot say which one failed it, and strikes nothing: the next wake - // takes one room. - let mark = |row: &mut Value, fault: &Fault, strike: bool| { + // A failed row says why, and whether it was an outage. A failure that is no outage strikes the oldest waking line of a turn whose waking + // lines are all in one room, and no other; a turn over several rooms cannot say which one failed it, and strikes nothing: the next wake takes one room. + let mark = |row: &mut Value, fault: &Fault, strike: Option<&str>| { row["failed"] = json!(fault.reason); if fault.outage { row["outage"] = json!(true); - } else if strike && rooms.len() == 1 && let Some(line) = waking.first() { - row["strike"] = json!(line.event); + } else if let Some(event) = strike { + row["strike"] = json!(event); } }; + let open_strike: Option<&str> = if rooms.len() == 1 { waking.first().map(|line| line.event) } else { None }; if fault.is_none() { let name = if public_name.is_empty() { instance.0.clone() } else { public_name.clone() }; let opening = opening(&waked); + let instructions = agent_instructions(&name); let told: Vec<&str> = waked.report["last_outcome"]["told"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); - let input = lines_input(&deliveries, &held, &config.own_sender, &told); let fresh = ready_intentions(&state, now); let session = FileSession::new(&start.session); let ledger = TraceLedger::new(&*start.trace, stem.clone()); let agent = Agent { model: start.agent.as_ref(), session: &session, executors: &executors, ledger: &ledger, bounds: &bounds.agent, clock: &*start.clock }; - let turn_id = format!("{wake_id}-t1"); - match step(&agent, &AgentWake { id: &turn_id, wake: &wake_id, instructions: &agent_instructions(&name), opening: &opening, input: &input, fresh: &fresh, first: true }) { - Ok(turn) => { - let mut row = json!({ - "wake": wake_id, - "turn": 1, - "held": held, - "status": if matches!(turn.ended, Ended::Failed(_)) { "failed" } else { "completed" }, - "ended": format!("{:?}", turn.ended), - "model_calls": turn.model_calls, - "tool_calls": turn.tool_calls, - "usd": turn.usd, - "at": (start.clock)().to_rfc3339(), - "seq": place(&*start.trace), - }); - receipts = turn.receipts; - if let Ended::Failed(failed) = turn.ended { - let failure = Fault { reason: failed.reason, outage: failed.outage }; - mark(&mut row, &failure, true); - fault = Some(failure); - } - // The turn row lands before any ack of its lines: a row that cannot be written decides nothing, so `settle` acks nothing past - // them, and a start killed after it does not wake for the lines she has answered. - match start.trace.record(&format!("{stem}-t1"), &row) { - Ok(()) => { - turned = true; - by_turn = fault.is_some(); - if fault.is_none() { - settle(&mut acked); - } + let outage = |reason: &str| Ended::Failed(Failed { reason: reason.to_owned(), outage: true, usage: None }); + let mut span = Span { opened: began, last_ended: began }; + let mut first_seen = BTreeMap::new(); + let mut mouth_fails = 0u32; + let mut next = Some(Taking { hold: held.iter().map(|event| (*event).to_owned()).collect(), rooms: live_rooms.clone(), strike: open_strike.map(str::to_owned) }); + // Turn 1 is her first turn, the open's; each turn after it is a line that woke her while the wake was open. Every turn goes through the same + // `step`, the same ledger and the same ack, and a turn's row lands before any ack of its lines. + while let Some(taking) = next.take() { + turns_run += 1; + let k = turns_run; + watched.extend(taking.rooms.iter().cloned()); + taken.extend(taking.hold.iter().cloned()); + live_rooms = taking.rooms; + let refs: Vec<&ChatDelivery> = pool.iter().collect(); + let hold: Vec<&str> = taking.hold.iter().map(String::as_str).collect(); + if k > 1 { + show(&mouth, &refs, &hold); + } + let input = lines_input(&refs, &hold, &config.own_sender, if k == 1 { &told } else { &[] }); + let turn_id = format!("{wake_id}-t{k}"); + let mut last = match step(&agent, &AgentWake { id: &turn_id, wake: &wake_id, instructions: &instructions, opening: &opening, input: &input, fresh: &fresh, first: k == 1 }) { + Ok(turn) => { + let mut row = json!({ + "wake": wake_id, + "turn": k, + "held": hold, + "status": if matches!(turn.ended, Ended::Failed(_)) { "failed" } else { "completed" }, + "ended": format!("{:?}", turn.ended), + "model_calls": turn.model_calls, + "tool_calls": turn.tool_calls, + "usd": turn.usd, + "at": (start.clock)().to_rfc3339(), + "seq": place(&*start.trace), + }); + let failure = if let Ended::Failed(failed) = &turn.ended { Some(Fault { reason: failed.reason.clone(), outage: failed.outage }) } else { None }; + if let Some(failure) = &failure { + mark(&mut row, failure, taking.strike.as_deref()); } - Err(lost) => eprintln!("mind-persona: the record of turn 1 of wake {key} was not appended, so nothing is acked: {lost:#}"), + // The turn row lands before any ack of its lines: a row that cannot be written decides nothing, so `settle` acks nothing past + // them, and a start killed after it does not wake for the lines she has answered. + let row_landed = match start.trace.record(&format!("{stem}-t{k}"), &row) { + Ok(()) => { + landed += 1; + true + } + Err(lost) => { + eprintln!("mind-persona: the record of turn {k} of wake {key} was not appended, so nothing is acked: {lost:#}"); + false + } + }; + let failed_turn = failure.is_some(); + match failure { + None => { + completed += 1; + receipts.extend(turn.receipts); + counted.extend(taking.hold.iter().cloned()); + if row_landed { + settle(start, &pool, &watched, &mut acked); + } + } + // Turn 1's failure is the wake's; a later turn's is its own row's and ends the wake, which the turns before it completed. + Some(failure) if k == 1 => { + by_turn = row_landed; + fault = Some(failure); + } + Some(_) => {} + } + // A completed turn whose row did not land ends the wake: nothing of it is decided, and the next line would be taken on a guess. + if row_landed || failed_turn { turn.ended } else { outage("the turn's row was not appended") } + } + Err(bug) if k == 1 => return failed("her agent could not be set up", bug), + Err(bug) => { + eprintln!("mind-persona: turn {k} of wake {key} could not be set up: {bug:#}"); + outage("a turn could not be set up") + } + }; + span.last_ended = (start.clock)(); + // The wake waits for the next line that wakes her, until `wake_end` says it is over. + loop { + let records = match start.trace.records() { + Ok(records) => records, + Err(lost) => { + eprintln!("mind-persona: her trace was not read: {lost:#}"); + last = outage("her trace was not read"); + Vec::new() + } + }; + if let Some(over) = wake_end(&span, &last, wake_usd(&records, &wake_id, &bounds.agent), (start.clock)(), &bounds.agent) { + end = Some(over); + break; + } + (start.pause)(std::time::Duration::from_secs(POLL_S)); + match read_pending(&start.chat) { + Ok(page) => { + mouth_fails = 0; + for delivery in page.deliveries { + if !pool.iter().any(|held| held.event_id == delivery.event_id) { + pool.push(delivery); + } + } + pool.sort_by_key(|delivery| delivery.seq); + } + Err(lost) => { + // One failed read is a skipped poll. Three in a row end the wake, as an outage, which strikes nothing. + mouth_fails += 1; + eprintln!("mind-persona: the mouth was not read ({mouth_fails} in a row): {lost:#}"); + if mouth_fails >= MOUTH_FAILS_MAX { + last = outage("the mouth was not read"); + } + continue; + } + } + let done = decided(&records); + let found = find(&hearing, &pool, &done, &records, &taken); + // A line that wakes her and is not yet taken holds the ack behind it, in whatever room it is. + watched.extend(found.waking.iter().map(|delivery| delivery.room_alias.clone())); + if let Some(taking) = take(&hearing, &found, &live_rooms, retreating, &mut first_seen, (start.clock)()) { + next = Some(taking); + break; } } - Err(bug) => return failed("her agent could not be set up", bug), } - if fault.is_none() { - interpreted(start, instance, &state, &waked, &receipts, &deliveries, &held, rooms[0], &stem, began_ms, &mouth); + // The close: the Interpreter once, over every completed turn's receipts and every line those turns held. + if completed > 0 { + let refs: Vec<&ChatDelivery> = pool.iter().collect(); + let heard: Vec<&str> = counted.iter().map(String::as_str).collect(); + interpreted(start, instance, &state, &waked, &receipts, &refs, &heard, &live_rooms[0], &stem, began_ms, &mouth); } } + // The lines of the wake's rooms that arrived after its open and woke nothing, and that no turn took: the wake record holds them. A wake no + // turn row landed for holds the lines of its open, as a failed record decides nothing. + let trailing: Vec = if landed == 0 { + held.iter().map(|event| (*event).to_owned()).collect() + } else { + let records = start.trace.records().unwrap_or_default(); + let done = decided(&records); + let found = find(&hearing, &pool, &done, &records, &taken); + found.fresh.iter().filter(|delivery| live_rooms.contains(&delivery.room_alias) && !opened.contains(&delivery.event_id) && !found.waking.iter().any(|waking| waking.event_id == delivery.event_id)).map(|delivery| delivery.event_id.clone()).collect() + }; + let end = end.unwrap_or(End::Failed); let record_key = format!("{stem}-w"); let mut record = json!({ "key": record_key, "seq": place(&*start.trace), "began": began_at, "kind": kind, - "room": rooms[0], - "rooms": rooms, - // The lines no turn held: all of them when no turn ran. - "held": if turned { Vec::<&str>::new() } else { held }, + "room": live_rooms[0], + "rooms": live_rooms, + "held": trailing, "narration": waked.narration, "prose": waked.prose, "usage": waked.usage, "selected": waked.report["renders"][0]["selected"], - "status": if fault.is_none() { "completed" } else { "failed" }, + "turns": turns_run, + "ended": end.name(), + "status": if completed > 0 { "completed" } else { "failed" }, "at": (start.clock)().to_rfc3339(), }); - if let Some(fault) = &fault { - mark(&mut record, fault, !by_turn); + if completed == 0 + && let Some(fault) = &fault + { + mark(&mut record, fault, if by_turn { None } else { open_strike }); } - // The wake record lands after everything the wake did. The turn's ack is behind it already; a wake that failed acked nothing, so its + // The wake record lands after everything the wake did. The turns' acks are behind them already; a wake that failed acked nothing, so its // lines are woken for again (in one room if it was a blend). if let Err(fault) = start.trace.record(&record_key, &record) { eprintln!("mind-persona: the record of wake {key} was not appended: {fault:#}"); } - Outcome::Drained { wakes: 1, acked_through: acked } + // The final ack: what the close decided. A wake that completed no turn acks nothing. + if completed > 0 { + settle(start, &pool, &watched, &mut acked); + } + Outcome::Drained { wakes: 1, turns: turns_run, ended: Some(end), acked_through: acked } } /// The most bytes of held lines her agent's first user text carries: sixteen times the Persona packet's 1500-byte stimulus, since the @@ -888,7 +1040,6 @@ fn addressees(own: &Addressee, addressing: &[Addressee], delivery: &ChatDelivery /// The swarm's addressing as her Persona reads it now: the heartbeat's table, or, before the heartbeat has written one, each configured /// Mind by her id and localpart and herself by her own addressee. Her own row is always present: the table's, else her own addressee. -#[allow(dead_code, reason = "kept for the three-stage turn (map C2 keep list): its first caller removes this allow")] fn addressing_of(config: &Config, view: Option<&dyn HeartbeatView>, own: &Addressee) -> Vec { let mut minds = view.and_then(|view| view.addressing().ok().flatten()).map(|table| table.minds).unwrap_or_default(); if minds.is_empty() { diff --git a/crates/mind-body/src/persona/drain_tests.rs b/crates/mind-body/src/persona/drain_tests.rs index 8b69e8c..92d9b94 100644 --- a/crates/mind-body/src/persona/drain_tests.rs +++ b/crates/mind-body/src/persona/drain_tests.rs @@ -65,17 +65,39 @@ struct FakeMouth { send_fails: Cell, /// The mouth refuses every send so. refuses: Cell>, + /// The mouth refuses a send whose basis is not the newest event of its room (`Refusal::RoomMoved`), as the real one does. + strict: Cell, + /// The newest event that reached each room. + newest: RefCell>, + /// Reads of the pending list fail this many more times, once a wake has begun to wait (the first pause). + pending_fails: Cell, + waiting: Cell, log: Log, } +impl FakeMouth { + /// A line reaches the mouth. + fn arrive(&self, delivery: ChatDelivery) { + self.newest.borrow_mut().insert(delivery.room_alias.clone(), delivery.event_id.clone()); + self.held.borrow_mut().push(delivery); + } +} + impl Chat for Rc { fn pending(&self, after: u64) -> Result { + if self.waiting.get() && self.pending_fails.get() > 0 { + self.pending_fails.set(self.pending_fails.get() - 1); + bail!("the mouth is unreachable"); + } Ok(ChatPending { persona: "eureka".into(), deliveries: self.held.borrow().iter().filter(|delivery| delivery.seq > after).cloned().collect(), tail: Some(vec![]), tail_gaps: vec![] }) } fn send(&self, request: &ChatSendRequest) -> Result { if self.send_fails.get() { bail!("the mouth is unreachable"); } + if self.strict.get() && request.basis.as_ref().and_then(|basis| basis.seen_event_id.as_ref()) != self.newest.borrow().get(&request.room_alias) { + return Ok(ChatSendReceipt { request_id: request.request_id.clone(), event_id: None, refusal: Some(Refusal::RoomMoved), newer: vec![] }); + } self.sent.borrow_mut().push(request.clone()); self.log.push("send"); if let Some(refusal) = self.refuses.get() { @@ -294,6 +316,11 @@ struct Rig { agent: Rc