persona-wake-span W2: the live span, one pure wake_end, one Interpreter at close, the first experiment's stagger

A start is one wake. After her first turn the process polls the mouth every 5 s; a line that wakes her by the heartbeat's own rule (Hearing::waking, now the open's derivation too) is the next turn of the same agent conversation with only the new lines as input. The Projector and the Persona do not rerun. live::wake_end alone decides the end: a failed turn, the day cap, the wake's spend, span_s, idle_s. The Interpreter runs once at close over every completed turn's receipts and held lines, then the wake record, then the final ack. Each in-wake line shown goes through Mouth::shown. A turn's strike sits on its own row; the wake record strikes only when no turn row landed. A wake that began retreating takes one room a turn.

The stagger is ported from the first experiment's live Persona (persona.rs at 0fd1232^, stagger_ms and stagger_hash): a line addressed to several Minds is taken after her rank among them, 8 s a rank, in the span and at the open (the open waits, then reads the mouth afresh). Start gains pause; Outcome::Drained gains turns and ended.

Cut: the one-turn tail of drain, the settle closure, the rooms.len() strike closure and the open's private waking derivation.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-02 16:08:06 +01:00
commit 9187ee0df2
7 changed files with 1011 additions and 146 deletions

View file

@ -2,8 +2,8 @@
//! one start of the Persona organ (`mind_body::persona::carry`) inside
//! `mind-persona@<instance>`. 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: <why>` 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: <why>` 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<Start<
session: state_directory()?.join("agent-session.cc"),
box_socket: PathBuf::from(required("MIND_PERSONA_BOX_SOCKET")?),
clock: Box::new(chrono::Utc::now),
pause: Box::new(std::thread::sleep),
})
}

View file

@ -1414,3 +1414,23 @@ fn t_h4_held_starts_back_off_like_failures_and_never_hold_her_for_a_day() {
assert_eq!(gaps, [20, 40, 80, 160, 320, 640, 900, 900].map(i64::from), "{launches:?}: each held start waits the failure backoff, to the beat");
assert_eq!(launches.len(), 9, "an hour of held starts costs nine unit starts, not 360: {launches:?}");
}
/// W2: lines that reach a Mind whose wake is open are the wake's, read from the mouth by the wake itself. The heartbeat starts no second unit for
/// them, writes no claim for them, and does not wake her for them once her unit has ended with her trace holding them decided.
#[test]
fn lines_that_reach_a_mind_with_a_wake_open_start_no_second_unit_and_claim_nothing() {
let rig = quiet_rig();
rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[]));
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] });
rig.in_a_turn(ANN);
for seq in 2..=4 {
rig.say(ANN, delivery(seq, "@op:chat", "Ann, and again", &[]));
rig.advance(60);
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "her unit is active: line {seq} is her wake's, and starts nothing");
}
assert_eq!(rig.launched(), vec![Slug("ann".into())], "one start, one unit");
assert_eq!(rig.store.state.borrow().clone().unwrap().handled_mentions, ["ann:$e1"], "no claim was written for the lines her wake took");
rig.finish_turn(ANN);
rig.advance(120);
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "her wake decided them all: nothing wakes her again");
}

View file

@ -6,12 +6,19 @@
//! start handed the mouth and heard nothing back of (`settle_handed`: resent under its id inside `OWED_WINDOW_S`, else unknown; no model
//! call); and takes one wake over every room that holds a waking line (`heartbeat::wakes`, the one rule), oldest waking line first (a start
//! the beat woke, with no waking line, wakes in the room of the newest pending line, else her first room). The wake runs in this order, and
//! her trace holds it in this order: `projection::wake` runs the Projector once and the Persona once; her agent takes one turn with her tools
//! (`say`, `read`, `shell`, `request_tool`), each call's receipt a row; once that turn completed, the Interpreter puts her state and writes
//! its receipt (a failed turn runs no Interpreter, so a retry never applies a delta twice); then the wake record lands. The turn is a row of her trace first (`{stem}-t1`, holding the lines it took), and the ack of its lines follows that row: a start killed after it has decided what it answered.
//! her trace holds it in this order: `projection::wake` runs the Projector once and the Persona once (the open); her agent takes a turn with her tools
//! (`say`, `read`, `shell`, `request_tool`), each call's receipt a row, and the turn is a row of her trace first (`{stem}-t{k}`, holding the lines it took),
//! the ack of its lines following that row: a start killed after it has decided what it answered.
//!
//! The wake then stays open (`live`, cut W2 of `docs/persona-wake-span-map.md`). It polls the mouth every `live::POLL_S` seconds, and a line that wakes her, by the
//! same rule the open used, starts the next turn in the same agent conversation with only the new lines as its input: the Projector and the Persona do not run again, and the
//! heartbeat never starts an active unit, so no second copy exists. `live::wake_end` alone says when it is over: a failed turn, the day cap, the wake's spend cap, `agent.span_s`
//! open, or `agent.idle_s` since her last turn ended. The close then runs the Interpreter once, over every completed turn's receipts and every line those turns held (a failed
//! turn runs none for itself, so a retry never applies a delta twice; a wake no turn completed runs none), puts her state, writes its receipt, and lands the wake record.
//! A line addressed to several Minds is taken after her rank among them, at the open and in the span (`live::stagger_ms`).
//!
//! Her trace alone says whether a line is decided (`projection::decided`, the reader the heartbeat's poll uses too): a line is done when a
//! row that did not fail held it (a turn row, or the wake record for the lines no turn held), or it is set aside. The mouth's pending list and its ack cursor are transport and decide nothing; the ack is cleanup,
//! row that did not fail held it (a turn row, or the wake record for the trailing lines of its rooms that no turn held), or it is set aside. The mouth's pending list and its ack cursor are transport and decide nothing; the ack is cleanup,
//! through the highest seq below the first line of a waking room that her trace does not yet hold decided. A turn holds the lines she was
//! shown: every line of the turn's room and, of the other waking rooms, those the Persona's page had room for (`Waked::elsewhere_shown`) and
//! her own, and what is no message (a notice, an edit), which nothing shows. A failed wake acks nothing.
@ -46,13 +53,18 @@ use serde_json::{Value, json};
use crate::address::{Addressee, is_for, localpart, others_addressed};
use crate::chat_client::{Basis, Chat, ChatDelivery, Form, TailLine};
use crate::control::{ControlSource, Effective, HeldReason, derive};
use crate::heartbeat::{HeartbeatView, Speaker, own_rooms, pending_facts, read_pending, wakes};
use crate::heartbeat::{HeartbeatView, Speaker, own_rooms, read_pending};
use crate::projection::agent::read::Read as ReadTool;
use crate::projection::agent::request_tool::RequestTool;
use crate::projection::agent::say::{Say, Sent};
use crate::projection::agent::shell::Shell;
use crate::projection::agent::{Agent, Ended, Receipt, day_ends, day_usd, Executor, FileSession, Steps, TraceLedger, Wake as AgentWake, instructions as agent_instructions, ready_intentions, step};
use crate::projection::{Applied, DAY_CAP_HOLD, DomainSource, Fault, HuginnPersonaSource, Model, Mouth, Organs, PersonaStore, Put, ReadSource, Request, Through, TurnKind, Waked, decided, failed as record_failed, heard_of, history, interpret_and_put, is_wake, load_tuning, settle_handed, wake, own_addressee as heard_as};
use crate::projection::agent::{Agent, Ended, Receipt, day_ends, day_usd, Executor, FileSession, Steps, TraceLedger, Wake as AgentWake, instructions as agent_instructions, ready_intentions, step, wake_usd};
use crate::projection::{Applied, DAY_CAP_HOLD, DomainSource, Failed, Fault, HuginnPersonaSource, Model, Mouth, Organs, PersonaStore, Put, ReadSource, Request, Through, TurnKind, Waked, decided, failed as record_failed, heard_of, history, interpret_and_put, is_wake, load_tuning, settle_handed, wake, own_addressee as heard_as};
mod live;
pub use live::End;
use live::{Hearing, MOUTH_FAILS_MAX, POLL_S, Span, Taking, find, stagger_ms, take, wake_end};
/// The admitting agent's name on what her Persona admitted; `self_run::inbox` still reads her briefs by it.
pub const AGENT: &str = "mind-persona";
@ -245,8 +257,9 @@ fn ordered(rows: impl IntoIterator<Item = (String, Value)>) -> Vec<Value> {
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<u64> },
/// 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<End>, acked_through: Option<u64> },
/// 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<Utc> },
@ -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<C: Chat> {
/// Her box's door (`MIND_PERSONA_BOX_SOCKET`): where her agent's shell commands go.
pub box_socket: PathBuf,
pub clock: Box<dyn Fn() -> DateTime<Utc>>,
/// 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<dyn Fn(std::time::Duration)>,
}
/// 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<C: Chat>(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<C: Chat>(instance: &Slug, start: &Start<C>) -> 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<C: Chat>(start: &Start<C>, pool: &[ChatDelivery], watched: &BTreeSet<String>, acked: &mut Option<u64>) {
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<C: Chat>(instance: &Slug, start: &Start<C>, 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<C: Chat>(instance: &Slug, start: &Start<C>) -> 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<ChatDelivery> = 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<C: Chat>(instance: &Slug, start: &Start<C>) -> 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<Waking> = 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<C: Chat>(instance: &Slug, start: &Start<C>) -> Outcome {
let mut first = true;
let (aside, due): (Vec<Waking>, Vec<Waking>) = 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<String> = 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<Waking> = 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<C: Chat>(instance: &Slug, start: &Start<C>) -> Outcome {
rooms.extend(deliveries.last().map(|delivery| delivery.room_alias.as_str()).or(config.rooms.first().map(String::as_str)));
}
let mut acked: Option<u64> = 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<u64>| {
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<Value> = aside.iter().map(|line| json!({ "room": line.room, "event": line.event, "sender": line.sender, "text": line.text })).collect();
@ -452,10 +490,10 @@ fn drain<C: Chat>(instance: &Slug, start: &Start<C>) -> 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<C: Chat>(instance: &Slug, start: &Start<C>) -> 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<Receipt> = vec![];
// The lines the turns that completed held: what the Interpreter reads of what she heard.
let mut counted: Vec<String> = 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<String> = 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<String> = pool.iter().map(|delivery| delivery.event_id.clone()).collect();
let mut live_rooms: Vec<String> = 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<String> = 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<Addressee> {
let mut minds = view.and_then(|view| view.addressing().ok().flatten()).map(|table| table.minds).unwrap_or_default();
if minds.is_empty() {

View file

@ -65,17 +65,39 @@ struct FakeMouth {
send_fails: Cell<bool>,
/// The mouth refuses every send so.
refuses: Cell<Option<Refusal>>,
/// The mouth refuses a send whose basis is not the newest event of its room (`Refusal::RoomMoved`), as the real one does.
strict: Cell<bool>,
/// The newest event that reached each room.
newest: RefCell<std::collections::BTreeMap<String, String>>,
/// Reads of the pending list fail this many more times, once a wake has begun to wait (the first pause).
pending_fails: Cell<u32>,
waiting: Cell<bool>,
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<FakeMouth> {
fn pending(&self, after: u64) -> Result<ChatPending> {
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<ChatSendReceipt> {
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<Script>,
/// What every organ did, in order.
log: Log,
/// Lines that reach the mouth while a wake waits, as (the tick at or after which one arrives, the line): delivered by the first pause that
/// finds the clock there. A tick is a second of the fake clock, which also moves one second per read of it.
arrivals: Rc<RefCell<Vec<(i64, ChatDelivery)>>>,
/// Every wait a start asked for, in order.
pauses: Rc<RefCell<Vec<std::time::Duration>>>,
}
impl Rig {
@ -302,15 +329,17 @@ impl Rig {
ControlWriter::open(dir.path().join("control.cc")).unwrap().set_brake(true, at(0), "op").unwrap();
SwarmWriter::open(dir.path().join("swarm.cc")).unwrap().set_brake(true, at(0), "op").unwrap();
let log = Log::default();
let mouth = Rc::new(FakeMouth { held: RefCell::new(deliveries), sent: RefCell::default(), acks: RefCell::default(), ack_fails: Cell::new(false), send_fails: Cell::new(false), refuses: Cell::new(None), log: log.clone() });
let newest = deliveries.iter().map(|delivery| (delivery.room_alias.clone(), delivery.event_id.clone())).collect();
let mouth = Rc::new(FakeMouth { held: RefCell::new(deliveries), sent: RefCell::default(), acks: RefCell::default(), ack_fails: Cell::new(false), send_fails: Cell::new(false), refuses: Cell::new(None), strict: Cell::new(false), newest: RefCell::new(newest), pending_fails: Cell::new(0), waiting: Cell::new(false), log: log.clone() });
let trace = Rc::new(MemTrace { rows: RefCell::default(), fail: Cell::new(false), fail_suffix: RefCell::default(), log: log.clone() });
let store = FakeStore { log: log.clone(), ..FakeStore::new(control()) };
let agent = Rc::new(Script { answers: RefCell::default(), seen: RefCell::default(), log: log.clone() });
Self { mouth, trace, store: Rc::new(store), dir, ticks: Rc::default(), review: RefCell::default(), agent, log }
Self { mouth, trace, store: Rc::new(store), dir, ticks: Rc::default(), review: RefCell::default(), agent, log, arrivals: Rc::default(), pauses: Rc::default() }
}
fn run(&self, model: impl Model + 'static) -> Outcome {
let ticks = self.ticks.clone();
let (pause_ticks, arrivals, pauses, mouth) = (self.ticks.clone(), self.arrivals.clone(), self.pauses.clone(), self.mouth.clone());
let start = || {
Ok(Start {
config: Config { rooms: vec!["#minds:gamecult.org".into()], operators: vec![META.into()], minds: vec!["@eureka:gamecult.org".into(), LIBBY.into()], own_sender: "@eureka:gamecult.org".into(), model: "test-model".into(), review_room: self.review.borrow().clone() },
@ -329,6 +358,17 @@ impl Rig {
ticks.set(ticks.get() + 1);
Utc.timestamp_millis_opt(i64::try_from(BASE_MS).unwrap()).unwrap() + Duration::seconds(ticks.get())
}),
pause: Box::new(move |wait| {
pauses.borrow_mut().push(wait);
pause_ticks.set(pause_ticks.get() + i64::try_from(wait.as_secs()).unwrap());
let now = pause_ticks.get();
let (due, later): (Vec<_>, Vec<_>) = arrivals.borrow_mut().drain(..).partition(|(at, _)| *at <= now);
*arrivals.borrow_mut() = later;
mouth.waiting.set(true);
for (_, line) in due {
mouth.arrive(line);
}
}),
})
};
carry(&FileSource::new(self.dir.path().join("control.cc")), &FileSource::new(self.dir.path().join("swarm.cc")), &Slug("eureka".into()), start)
@ -363,7 +403,7 @@ fn three_rooms() -> Rig {
fn t_p1_one_projector_one_persona() {
let rig = three_rooms();
let tally = Tally::default();
assert_eq!(rig.run(tally.clone()), Outcome::Drained { wakes: 1, acked_through: Some(3) });
assert_eq!(rig.run(tally.clone()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(3) });
let prompts = tally.0.borrow();
assert_eq!(prompts.len(), 4, "a wake with waking lines in three rooms makes exactly four model calls: the Projector, the Persona and the Interpreter's two halves");
assert!(prompts[2].starts_with(INTERPRETER));
@ -398,37 +438,38 @@ fn t_p1_no_drafts_in_prompt() {
assert!(tally.0.borrow().iter().all(|prompt| !prompt.contains("typed>")), "no draft markup and no speech form reaches either call");
}
/// A wake over several rooms that fails cannot say which room failed it: no strike, no ack, and the next wake takes the oldest waking room only.
/// A wake over several rooms that fails cannot say which room failed it: no strike, no ack, and the next wake takes the oldest waking room only,
/// and one room a turn after it, so a failure is found in one room alone.
#[test]
fn t_p1_a_failed_blended_wake_strikes_nothing_and_acks_nothing() {
let rig = three_rooms();
assert_eq!(rig.run(failing(REFUSED)), Outcome::Drained { wakes: 1, acked_through: None }, "a failed wake acks nothing");
assert_eq!(rig.run(failing(REFUSED)), Outcome::Drained { wakes: 1, turns: 0, ended: Some(End::Failed), acked_through: None }, "a failed wake acks nothing");
assert!(rig.acks().is_empty());
let records = rig.records();
assert_eq!(records[0]["status"], "failed");
assert!(rig.all_records().iter().all(|record| record.get("strike").is_none()), "{:?}", rig.all_records());
let tally = Tally::default();
assert_eq!(rig.run(tally.clone()), Outcome::Drained { wakes: 1, acked_through: Some(1) }, "the next wake takes room 1 alone, and acks through its lines");
assert_eq!(rig.run(tally.clone()), Outcome::Drained { wakes: 1, turns: 3, ended: Some(End::Idle), acked_through: Some(3) }, "the next wake takes room 1 alone, then each room after it alone");
let prompts = tally.0.borrow();
assert!(prompts[1].contains("morning, are you there") && !prompts[1].contains("evening, a question") && !prompts[1].contains("night, one more"), "{}", prompts[1]);
assert_eq!(rig.records()[1]["rooms"], json!([room(1)]));
assert_eq!(rig.turns()[0]["held"], json!(["$e1"]), "the rooms it did not take are not held");
drop(prompts);
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: Some(3) }, "the rooms after it, when it did not fail, are blended again");
assert_eq!(rig.records()[1]["rooms"], json!([room(1), room(2), room(3)]));
assert_eq!(rig.turns().iter().map(|turn| turn["held"].clone()).collect::<Vec<_>>(), [json!(["$e1"]), json!(["$e2"]), json!(["$e3"])], "one room a turn: a failure is found in one room alone");
}
/// Self's rule: a poison line in room B with an innocent older line in room A. The blend fails and strikes nothing; then A is taken alone and
/// completes; B alone fails twice and is set aside. A is never set aside.
/// completes and B alone is the wake's next turn, which fails: the strike is on that turn's row, on B's line. B alone fails a second time and is
/// set aside. A is never set aside.
#[test]
fn t_p1_a_poison_line_in_one_room_never_sets_an_innocent_room_aside() {
let rig = Rig::new(vec![line(1, &room(1), META, "an ordinary hello"), line(2, &room(2), META, "POISON arrives")]);
let model = || poisoned("POISON", REFUSED);
assert_eq!(rig.run(model()), Outcome::Drained { wakes: 1, acked_through: None }, "the blend fails");
assert_eq!(rig.run(model()), Outcome::Drained { wakes: 1, acked_through: Some(1) }, "room A alone completes, and is acked; room B's line is not");
assert_eq!(rig.run(model()), Outcome::Drained { wakes: 1, acked_through: None }, "room B alone fails: the first strike");
assert_eq!(rig.run(model()), Outcome::Drained { wakes: 1, acked_through: None }, "the second strike");
assert_eq!(rig.run(model()), Outcome::Drained { wakes: 0, acked_through: Some(2) }, "the poison line is set aside and acked past");
let records = rig.records();
let refused = || Err(Failed { reason: REFUSED.into(), outage: false, usage: None });
assert_eq!(rig.run(poisoned("POISON", REFUSED)), Outcome::Drained { wakes: 1, turns: 0, ended: Some(End::Failed), acked_through: None }, "the blend fails");
rig.agent.answers.borrow_mut().extend([Ok(Stepped { items: vec![InputItem::AssistantText { text: "Done.".into() }], text: "Done.".into(), calls: vec![], stop: StopReason::EndTurn, usage: spent() }), refused()]);
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 2, ended: Some(End::Failed), acked_through: Some(1) }, "room A alone completes, and is acked; room B alone fails: the first strike");
rig.agent.answers.borrow_mut().push_back(refused());
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Failed), acked_through: None }, "room B alone fails: the second strike");
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 0, turns: 0, ended: None, acked_through: Some(2) }, "the poison line is set aside and acked past");
let records = rig.all_records();
let strikes: Vec<&Value> = records.iter().filter_map(|record| record.get("strike")).collect();
assert_eq!(strikes, [&json!("$e2"), &json!("$e2")], "{records:?}");
let aside: Vec<&Value> = records.iter().flat_map(|record| record["set_aside"].as_array().into_iter().flatten()).map(|line| &line["event"]).collect();
@ -443,7 +484,7 @@ fn t_p1_strike_then_set_aside() {
rig.run(failing(REFUSED));
assert!(rig.acks().is_empty(), "two failed wakes ack nothing");
assert_eq!(rig.records().iter().map(|record| record["strike"].clone()).collect::<Vec<_>>(), [json!("$e1"), json!("$e1")], "a failure in a wake over one room strikes its oldest line");
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 0, acked_through: Some(1) }, "the third start sets the line aside and acks past it, with no wake");
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 0, turns: 0, ended: None, acked_through: Some(1) }, "the third start sets the line aside and acks past it, with no wake");
assert!(rig.records().iter().any(|record| record["set_aside"][0]["event"] == "$e1"));
}
@ -454,7 +495,7 @@ fn t_p1_a_set_aside_line_is_acked_before_the_wake_reads_the_room() {
rig.run(failing(REFUSED));
rig.run(failing(REFUSED));
let tally = Tally::default();
assert_eq!(rig.run(tally.clone()), Outcome::Drained { wakes: 1, acked_through: Some(2) });
assert_eq!(rig.run(tally.clone()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(2) });
assert_eq!(rig.acks(), [1, 2], "past the set-aside line first, then the wake's");
assert_eq!(rig.records().last().unwrap()["status"], "completed");
assert!(tally.0.borrow()[1].contains("a fine second line"));
@ -467,14 +508,14 @@ fn t_p1_an_outage_charges_no_strike() {
rig.run(failing(OUTAGE));
let records = rig.records();
assert!(records.iter().all(|record| record["outage"] == true && record.get("strike").is_none()), "{records:?}");
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: Some(1) }, "the body's failures never set a line aside");
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(1) }, "the body's failures never set a line aside");
}
/// A failed wake acks nothing, not even the lines of rooms nobody is waiting in that sit below the line it was waking on.
#[test]
fn t_p1_a_failed_wake_acks_no_line_below_the_waking_one() {
let rig = Rig::new(vec![line(1, "#minds:gamecult.org", LIBBY, "status: green"), line(2, &room(1), META, "a line the model refuses")]);
assert_eq!(rig.run(failing(REFUSED)), Outcome::Drained { wakes: 1, acked_through: None });
assert_eq!(rig.run(failing(REFUSED)), Outcome::Drained { wakes: 1, turns: 0, ended: Some(End::Failed), acked_through: None });
assert!(rig.acks().is_empty());
}
@ -483,9 +524,9 @@ fn t_p1_a_failed_wake_acks_no_line_below_the_waking_one() {
fn t_p1_a_decided_line_is_not_woken_for_again() {
let rig = Rig::new(vec![line(1, &room(1), META, "hello"), line(2, &room(2), META, "and hello")]);
rig.mouth.ack_fails.set(true);
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: None }, "the wake completed, its ack did not");
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: None }, "the wake completed, its ack did not");
rig.mouth.ack_fails.set(false);
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 0, acked_through: Some(2) }, "no second wake for lines held by a completed one");
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 0, turns: 0, ended: None, acked_through: Some(2) }, "no second wake for lines held by a completed one");
assert_eq!(rig.records().len(), 1);
}
@ -501,7 +542,7 @@ fn t_p1_each_waking_room_is_named_once() {
#[test]
fn t_p1_a_wake_holds_only_its_own_rooms_lines() {
let rig = Rig::new(vec![line(1, &room(1), META, "hello"), line(2, "#minds:gamecult.org", LIBBY, "status: green")]);
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: Some(2) }, "the other room's line is cleaned up behind her");
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(2) }, "the other room's line is cleaned up behind her");
assert_eq!(rig.turns()[0]["held"], json!(["$e1"]));
}
@ -510,10 +551,10 @@ fn t_p1_a_wake_holds_only_its_own_rooms_lines() {
fn t_p1_a_start_no_line_woke_is_a_beat() {
let rig = Rig::new(vec![line(1, "#minds:gamecult.org", LIBBY, "status: green")]);
rig.trace.fail.set(true);
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: None }, "the record did not land, so nothing is acked");
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Failed), acked_through: None }, "the record did not land, so nothing is acked");
assert!(rig.acks().is_empty());
rig.trace.fail.set(false);
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: Some(1) });
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(1) });
assert_eq!(rig.records()[0]["kind"], "beat");
}
@ -524,11 +565,12 @@ fn t_p1_lines_the_page_had_no_room_for_are_not_held_or_acked() {
let mut lines = vec![line(1, &room(1), META, "the turn's room")];
lines.extend((2..=61).map(|seq| line(seq, &room(2), META, &format!("line {seq} of a long talk elsewhere, said at some length so that the page fills"))));
let rig = Rig::new(lines);
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: Some(1) }, "acked only below the oldest line she was not shown");
let held: Vec<String> = rig.turns()[0]["held"].as_array().unwrap().iter().map(|event| event.as_str().unwrap().to_owned()).collect();
assert!(held.contains(&"$e1".to_owned()) && held.contains(&"$e61".to_owned()), "{held:?}");
assert!(!held.contains(&"$e2".to_owned()) && held.len() < 61, "the oldest of the long room were not shown, so not held: {held:?}");
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: Some(61) }, "the lines left in the mouth wake her again, now in the turn's room");
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 2, ended: Some(End::Idle), acked_through: Some(61) }, "the lines the page had no room for are the wake's second turn, and are acked behind it");
let held = |turn: usize| -> Vec<String> { rig.turns()[turn]["held"].as_array().unwrap().iter().map(|event| event.as_str().unwrap().to_owned()).collect() };
assert!(held(0).contains(&"$e1".to_owned()) && held(0).contains(&"$e61".to_owned()), "{:?}", held(0));
assert!(!held(0).contains(&"$e2".to_owned()) && held(0).len() < 61, "the oldest of the long room were not shown, so the first turn does not hold them: {:?}", held(0));
assert!(held(1).contains(&"$e2".to_owned()) && held(0).len() + held(1).len() == 61, "the second turn holds exactly what the first did not: {:?}", held(1));
assert_eq!(rig.acks().first().copied(), Some(1), "the first turn's ack stops below the oldest line she was not shown");
}
/// The other rooms' lines are read in the order they were said, whatever order the mouth delivered them in.
@ -548,7 +590,7 @@ fn t_p1_a_notice_in_another_room_does_not_hold_the_ack() {
let mut notice = line(3, &room(2), META, "a notice");
notice.form = Form::Notice;
let rig = Rig::new(vec![line(1, &room(1), META, "hello"), line(2, &room(2), META, "and hello"), notice, line(4, &room(1), META, "once more")]);
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: Some(4) });
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(4) });
}
/// Soul s2 turn-room-overflow-held: a turn room too long for the page tells her how many lines said to her it left out, and every line the
@ -600,7 +642,7 @@ const MOVES: &str = r#"{"notes":{"remember":[{"text":"Tobiah thinks the room is
#[test]
fn t_p2_one_call_one_put_one_receipt() {
let rig = three_rooms();
assert_eq!(rig.run(Interprets(MOVES)), Outcome::Drained { wakes: 1, acked_through: Some(3) });
assert_eq!(rig.run(Interprets(MOVES)), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(3) });
let state = {
let puts = rig.store.puts.borrow();
assert_eq!(puts.len(), 1, "one put a wake");
@ -624,7 +666,7 @@ fn t_p2_one_call_one_put_one_receipt() {
#[test]
fn t_p2_a_failed_call_puts_nothing_and_the_wake_still_decides_its_lines() {
let rig = three_rooms();
assert_eq!(rig.run(Interprets("this is not the contract")), Outcome::Drained { wakes: 1, acked_through: Some(3) });
assert_eq!(rig.run(Interprets("this is not the contract")), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(3) });
assert!(rig.store.puts.borrow().is_empty());
let records = rig.all_records();
let receipt = rows(&records, "interpreter")[0];
@ -766,7 +808,7 @@ fn t_p2_schema_refusal_no_put() {
fn t_a2_order() {
let rig = Rig::new(vec![line(1, &room(1), META, "morning, are you there")]);
rig.agent.answers.borrow_mut().push_back(says(&room(1), "Morning. I am here."));
assert_eq!(rig.run(Interprets(MOVES)), Outcome::Drained { wakes: 1, acked_through: Some(1) });
assert_eq!(rig.run(Interprets(MOVES)), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(1) });
let log = rig.log.all();
let first = |what: &str| log.iter().position(|done| done == what).unwrap_or_else(|| panic!("{what} never happened: {log:?}"));
let last = |what: &str| log.iter().rposition(|done| done == what).unwrap();
@ -789,10 +831,10 @@ fn t_a2_order() {
fn t_a2_a_retried_wake_puts_her_state_once() {
let rig = Rig::new(vec![line(1, &room(1), META, "morning, are you there")]);
rig.agent.answers.borrow_mut().push_back(Err(Failed { reason: "the provider failed the call: RateLimited".into(), outage: true, usage: None }));
assert_eq!(rig.run(Interprets(MOVES)), Outcome::Drained { wakes: 1, acked_through: None });
assert_eq!(rig.run(Interprets(MOVES)), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Failed), acked_through: None });
assert!(rig.store.puts.borrow().is_empty(), "no put behind a failed agent turn");
assert!(rows(&rig.all_records(), "interpreter").is_empty(), "and no receipt");
assert_eq!(rig.run(Interprets(MOVES)), Outcome::Drained { wakes: 1, acked_through: Some(1) });
assert_eq!(rig.run(Interprets(MOVES)), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(1) });
let puts = rig.store.puts.borrow();
assert_eq!(puts.len(), 1, "one put across both wakes");
assert_eq!(puts[0]["thoughtMemory"]["shortTerm"].as_array().unwrap().len(), 1, "one note from the one line");
@ -805,7 +847,7 @@ fn t_a2_a_retried_wake_puts_her_state_once() {
fn t_a2_an_interpreter_failure_after_the_agent_acted_fails_nothing() {
let rig = Rig::new(vec![line(1, &room(1), META, "morning, are you there")]);
rig.agent.answers.borrow_mut().push_back(says(&room(1), "Morning. I am here."));
assert_eq!(rig.run(poisoned(INTERPRETER, OUTAGE)), Outcome::Drained { wakes: 1, acked_through: Some(1) });
assert_eq!(rig.run(poisoned(INTERPRETER, OUTAGE)), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(1) });
let records = rig.all_records();
assert_eq!(records.iter().filter(|record| is_wake(record)).map(|record| record["status"].clone()).collect::<Vec<_>>(), vec![json!("completed")]);
let receipt = rows(&records, "interpreter")[0];
@ -844,7 +886,7 @@ fn t_a2_told_once() {
fn t_a2_an_agent_outage_strikes_nothing() {
let rig = Rig::new(vec![line(1, &room(1), META, "morning, are you there")]);
rig.agent.answers.borrow_mut().push_back(Err(Failed { reason: "the provider failed the call: Authentication".into(), outage: true, usage: None }));
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: None });
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Failed), acked_through: None });
let records = rig.records();
assert_eq!((records[0]["status"].as_str(), records[0]["outage"].clone(), rig.turns()[0]["outage"].clone()), (Some("failed"), json!(true), json!(true)), "the wake and its turn say outage: {records:?}");
assert!(rig.all_records().iter().all(|record| record.get("strike").is_none()), "an outage strikes nothing");
@ -902,7 +944,7 @@ fn t_h5_a_start_held_after_a_completed_wake_counts_in_the_run() {
assert!(matches!(rig.run(Tally::default()), Outcome::Held { .. }));
cap(50.0);
rig.agent.answers.borrow_mut().push_back(says(&room(1), "I am here."));
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: Some(1) }, "the raised cap wakes her");
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(1) }, "the raised cap wakes her");
cap(3.0);
rig.mouth.held.borrow_mut().push(line(2, &room(1), META, "and again"));
assert!(matches!(rig.run(Tally::default()), Outcome::Held { .. }));
@ -935,7 +977,7 @@ fn t_h3_rollover_wakes_held_lines() {
assert!(matches!(rig.run(Tally::default()), Outcome::Held { .. }));
rig.ticks.set(43_200 + 60);
rig.agent.answers.borrow_mut().push_back(says(&room(1), "good morning"));
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: Some(1) });
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(1) });
assert_eq!(organ_calls(&rig), ["projector", "persona", "agent", "agent", "interpreter", "interpreter"].map(str::to_owned), "the day's spend counts from nothing");
assert_eq!(rig.mouth.sent.borrow().len(), 1, "she answered it");
assert_eq!(rig.records().len(), 1);
@ -979,7 +1021,7 @@ fn t_h4_a_backlog_over_the_budget_shows_the_newest_lines_and_says_how_many_it_le
let lines: Vec<ChatDelivery> = (1..=300).map(|n| line(n, &room(1), META, &format!("{n:04} {}", "x".repeat(text_len(n) - 5)))).collect();
let rig = Rig::new(lines);
rig.agent.answers.borrow_mut().push_back(says(&room(1), "I am here."));
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: Some(300) }, "every line is acked, shown or not");
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(300) }, "every line is acked, shown or not");
let input = agent_first_input(&rig);
// The count by hand: newest first, each line and its newline, until the next would pass the budget.
let (mut used, mut kept) = (0, 0_u64);
@ -1003,7 +1045,7 @@ fn t_h4_a_backlog_over_the_budget_shows_the_newest_lines_and_says_how_many_it_le
fn t_h5_a_newest_line_over_the_budget_is_kept_and_the_older_one_is_left_out() {
let rig = Rig::new(vec![line(1, &room(1), META, "older and small"), line(2, &room(1), META, &format!("big {}", "y".repeat(HELD_LINES_BUDGET + 100)))]);
rig.agent.answers.borrow_mut().push_back(says(&room(1), "I am here."));
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: Some(2) });
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(2) });
let input = agent_first_input(&rig);
assert!(input.contains("big yyy") && !input.contains("older and small"), "the newest is kept alone");
assert!(input.contains("\n1 older line(s) were not shown, the oldest in room=\"!dm-1:gamecult.org\" at "), "{}", &input[..400.min(input.len())]);
@ -1038,7 +1080,7 @@ fn t_a2_the_interpreter_reads_this_wakes_shell_command() {
fn t_w1_a_one_turn_wake_writes_one_turn_row() {
let rig = Rig::new(vec![line(1, &room(1), META, "morning, are you there")]);
rig.agent.answers.borrow_mut().push_back(says(&room(1), "Morning. I am here."));
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: Some(1) });
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(1) });
let turns = rig.turns();
assert_eq!(turns.len(), 1);
let turn = &turns[0];
@ -1062,7 +1104,7 @@ fn t_w1_a_start_killed_after_its_turn_has_decided_and_acked_its_lines_and_is_tol
rig.agent.answers.borrow_mut().push_back(says(&room(1), "QUIETLINE"));
// The wake record is the last thing a start writes: one that cannot be written is a start that died before it.
*rig.trace.fail_suffix.borrow_mut() = "-w".into();
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: Some(1) }, "the turn row decided the line, and the ack followed it");
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(1) }, "the turn row decided the line, and the ack followed it");
assert!(rig.records().is_empty(), "no wake record exists");
assert_eq!(rig.turns().len(), 1);
*rig.trace.fail_suffix.borrow_mut() = String::new();
@ -1084,19 +1126,24 @@ fn t_w1_the_turn_row_alone_keeps_an_answered_line_from_waking_her_again() {
let rig = Rig::new(vec![line(1, &room(1), META, "morning, are you there")]);
*rig.trace.fail_suffix.borrow_mut() = "-w".into();
rig.mouth.ack_fails.set(true);
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: None }, "neither the wake record nor the ack landed");
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: None }, "neither the wake record nor the ack landed");
*rig.trace.fail_suffix.borrow_mut() = String::new();
rig.mouth.ack_fails.set(false);
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 0, acked_through: Some(1) }, "the turn row decided the line: no second wake, only the ack");
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 0, turns: 0, ended: None, acked_through: Some(1) }, "the turn row decided the line: no second wake, only the ack");
assert_eq!(rig.agent.seen.borrow().len(), 1);
}
/// W1-I2: a turn row that cannot be written decides nothing, so nothing is acked past its lines.
/// W1-I2: a turn row that cannot be written decides nothing, so no ack follows the turn. The wake ends there (nothing of the turn is decided, so no
/// later line is taken on a guess), and the wake record, which holds the lines no turn row did, is what decides them; the ack follows it.
#[test]
fn t_w1_a_turn_row_that_cannot_be_written_acks_nothing() {
fn t_w1_a_turn_row_that_cannot_be_written_is_decided_by_the_wake_record_and_acked_behind_it() {
let rig = Rig::new(vec![line(1, &room(1), META, "morning, are you there")]);
*rig.trace.fail_suffix.borrow_mut() = "-t1".into();
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, acked_through: None });
assert!(rig.acks().is_empty() && rig.turns().is_empty());
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Failed), acked_through: Some(1) });
assert!(rig.turns().is_empty());
assert_eq!(rig.records()[0]["held"], json!(["$e1"]), "the wake record holds the lines no turn row did");
assert_eq!(rig.log.all().iter().filter(|what| *what == "ack").count(), 1, "one ack, and it follows the wake record: {:?}", rig.log.all());
assert!(rig.log.all().iter().position(|what| what == "ack") > rig.log.all().iter().position(|what| what == "row:wake"));
}
mod open_wake;

View file

@ -0,0 +1,309 @@
//! A wake that stays open (cut W2): its second and later turns, the end it comes to, and its close. One start, the fake clock, the scripted agent.
use super::*;
const EUREKA: &str = "@eureka:gamecult.org";
const MINDS: &str = "#minds:gamecult.org";
/// Her agent ends its turn at once.
fn done() -> std::result::Result<Stepped, Failed> {
Ok(Stepped { items: vec![InputItem::AssistantText { text: "Done.".into() }], text: "Done.".into(), calls: vec![], stop: StopReason::EndTurn, usage: spent() })
}
/// Her agent runs `command` in her shell.
fn shells(id: &str, command: &str) -> std::result::Result<Stepped, Failed> {
let call = ToolCall { call_id: id.into(), name: "shell".into(), arguments: json!({ "command": command }).to_string() };
Ok(Stepped { items: vec![InputItem::ToolCall { call_id: call.call_id.clone(), name: call.name.clone(), arguments: call.arguments.clone() }], text: String::new(), calls: vec![call], stop: StopReason::ToolUse, usage: spent() })
}
/// A line that reaches the mouth by the time the fake clock reads `tick`.
fn arrives(rig: &Rig, tick: i64, line: ChatDelivery) {
rig.arrivals.borrow_mut().push((tick, line));
}
/// A line of the operator's, `tick` seconds into the wake.
fn later(seq: u64, room: &str, tick: i64, text: &str) -> ChatDelivery {
line_at(seq, room, META, text, BASE_MS + u64::try_from(tick).unwrap() * 1000)
}
fn answers(rig: &Rig, list: impl IntoIterator<Item = std::result::Result<Stepped, Failed>>) {
rig.agent.answers.borrow_mut().extend(list);
}
fn tune(rig: &Rig, body: &str) {
std::fs::write(rig.dir.path().join("persona-tuning.toml"), body).unwrap();
}
fn calls(rig: &Rig, stage: &str) -> usize {
rig.log.all().iter().filter(|what| *what == stage).count()
}
fn at_of(row: &Value) -> DateTime<Utc> {
row["at"].as_str().unwrap().parse().unwrap()
}
fn user_text(items: &[InputItem]) -> String {
match items.last() {
Some(InputItem::UserText { text }) => text.clone(),
other => panic!("a turn's last item is its lines: {other:?}"),
}
}
/// W2-I6, I7 and the turn itself: a second line a minute after the first is a second turn of the same wake, in the same agent conversation, with only the new
/// line as its input. The Projector and the Persona ran once, the Interpreter once over both turns' receipts, and each turn's lines were acked behind its own row.
#[test]
fn t_w2_a_second_line_is_a_second_turn_of_one_wake() {
let rig = Rig::new(vec![line(1, &room(1), META, "first line, are you there")]);
answers(&rig, [shells("one", "ls /srv/one"), done(), shells("two", "ls /srv/two"), done()]);
arrives(&rig, 60, later(2, &room(1), 60, "and a second line"));
let model = Tally::default();
assert_eq!(rig.run(model.clone()), Outcome::Drained { wakes: 1, turns: 2, ended: Some(End::Idle), acked_through: Some(2) });
assert_eq!((calls(&rig, "projector"), calls(&rig, "persona"), calls(&rig, "interpreter")), (1, 1, 2), "one Projector, one Persona, and the Interpreter's two halves once, over both turns");
// The second turn's request carries the first turn's items as its prefix: one conversation.
let seen = rig.agent.seen.borrow();
assert_eq!(seen.len(), 4);
let (first_end, second) = (&seen[1], &seen[2]);
assert_eq!(second.len(), first_end.len() + 2, "the first turn's items, her closing words, then the new lines");
assert!(first_end.iter().zip(second).all(|(before, now)| format!("{before:?}") == format!("{now:?}")), "{second:?}");
let (opening, input) = (user_text(&seen[0]), user_text(second));
assert!(opening.contains("What she lives now") && opening.contains("first line, are you there"), "{opening}");
assert!(input.contains("and a second line") && !input.contains("first line") && !input.contains("What she lives now") && !input.contains("Her own inner voice"), "the second turn is the new lines alone: {input}");
drop(seen);
// Both turns' acts reach the one Interpreter pass.
for prompt in model.0.borrow().iter().filter(|prompt| prompt.starts_with(INTERPRETER)) {
let acts = prompt.split("\nACTS\n").nth(1).unwrap_or_else(|| panic!("no ACTS section: {prompt}")).split("NARRATION").next().unwrap();
assert!(acts.contains("\"ls /srv/one\"") && acts.contains("\"ls /srv/two\""), "{acts}");
}
let turns = rig.turns();
assert_eq!(turns.iter().map(|turn| (turn["turn"].clone(), turn["held"].clone())).collect::<Vec<_>>(), [(json!(1), json!(["$e1"])), (json!(2), json!(["$e2"]))]);
let records = rig.records();
assert_eq!((records.len(), records[0]["turns"].clone(), records[0]["ended"].clone(), records[0]["status"].clone(), records[0]["held"].clone()), (1, json!(2), json!("idle"), json!("completed"), json!([])));
assert_eq!(rig.acks(), [1, 2], "each turn's lines are acked behind its own row");
let ids: Vec<String> = rig.all_records().iter().filter(|row| row["agent"] == "call").map(|row| row["call"].as_str().unwrap().to_owned()).collect();
assert!(ids.iter().any(|id| id.contains("-t2-m")) && ids.iter().collect::<std::collections::BTreeSet<_>>().len() == ids.len(), "no two model calls of the wake share a request id: {ids:?}");
}
/// W2-I7: the Interpreter runs once at the close, not once per turn: three turns still make its two halves, and its receipt and the put are one each.
#[test]
fn t_w2_the_interpreter_runs_once_at_close_over_all_turns() {
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
arrives(&rig, 100, later(2, &room(1), 100, "second"));
arrives(&rig, 250, later(3, &room(1), 250, "third"));
assert_eq!(rig.run(Interprets(MOVES)), Outcome::Drained { wakes: 1, turns: 3, ended: Some(End::Idle), acked_through: Some(3) });
assert_eq!(calls(&rig, "interpreter"), 2, "two halves, once");
assert_eq!((rig.store.puts.borrow().len(), rows(&rig.all_records(), "interpreter").len()), (1, 1));
let log = rig.log.all();
let last_turn = log.iter().rposition(|what| what == "row:turn").unwrap();
assert!(log.iter().position(|what| what == "interpreter").unwrap() > last_turn, "after the last turn, not between turns: {log:?}");
}
/// W2-I6: no Projector and no Persona call for a line that arrives in an open wake, however many turns follow.
#[test]
fn t_w2_the_projector_and_the_persona_do_not_rerun_for_a_line_in_an_open_wake() {
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
for (n, tick) in [(2, 80), (3, 160), (4, 240)] {
arrives(&rig, tick, later(n, &room(1), tick, &format!("line {n}")));
}
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 4, ended: Some(End::Idle), acked_through: Some(4) });
assert_eq!((calls(&rig, "projector"), calls(&rig, "persona"), calls(&rig, "agent")), (1, 1, 4));
}
/// The idle window: no line after her turn, so the wake waits idle_s, polling every 5 s, and closes `ended: idle`.
#[test]
fn t_w2_a_wake_with_no_new_line_closes_idle_after_idle_s_of_five_second_polls() {
let rig = Rig::new(vec![line(1, &room(1), META, "hello")]);
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(1) });
let (turn, wake) = (at_of(&rig.turns()[0]), at_of(&rig.records()[0]));
let waited = (wake - turn).num_seconds();
assert!((300..330).contains(&waited), "the close came {waited} s after her turn");
let pauses = rig.pauses.borrow();
assert!(pauses.len() > 20 && pauses.iter().all(|wait| wait.as_secs() == 5), "{pauses:?}");
}
/// The span: a line every minute keeps the wake open until span_s, and no longer.
#[test]
fn t_w2_a_wake_open_span_s_closes_though_lines_keep_coming() {
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
tune(&rig, "[agent]\nspan_s = 300\nidle_s = 120\n");
for n in 0..40 {
arrives(&rig, 40 + 40 * n, later(2 + n as u64, &room(1), 40 + 40 * n, &format!("line {n}")));
}
let Outcome::Drained { turns, ended, .. } = rig.run(Tally::default()) else { panic!("drained") };
assert_eq!(ended, Some(End::Span));
assert!((4..=9).contains(&turns), "{turns} turns");
let (first, wake) = (at_of(&rig.turns()[0]), at_of(&rig.records()[0]));
let open = (wake - first).num_seconds();
assert!((250..330).contains(&open), "the wake closed {open} s after its first turn");
assert!(!rig.arrivals.borrow().is_empty(), "lines that came after the span were never read by this wake");
assert_eq!(rig.records()[0]["ended"], "span");
}
/// A line that wakes her nothing: another room's member line starts no turn, and a notice in the wake's room is held by the wake record, which
/// decides it, and acked behind it.
#[test]
fn t_w2_a_line_that_wakes_nothing_starts_no_turn_and_the_wake_record_holds_it_if_it_is_in_the_wakes_rooms() {
let rig = Rig::new(vec![line(1, &room(1), META, "hello")]);
arrives(&rig, 40, line_at(2, MINDS, ANN, "status: green", BASE_MS + 40_000));
let mut notice = later(3, &room(1), 80, "a notice");
notice.form = Form::Notice;
arrives(&rig, 80, notice);
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(3) });
assert_eq!(rig.agent.seen.borrow().len(), 1, "her agent took the one turn");
let records = rig.records();
assert_eq!(records[0]["held"], json!(["$e3"]), "the notice, in the wake's room, and no other room's line");
assert!(decided(&rig.trace.records().unwrap()).contains("$e3"));
}
/// The backstop: Minds tagging her in a row wake her only while fewer than MIND_RUN_BACKSTOP lines of the run came before; the pool of lines the wake
/// has seen is what the run is counted over, whatever was acked, so a chain does not restart at each ack.
#[test]
fn t_w2_minds_tagging_her_in_a_row_stop_waking_her_at_the_backstop() {
let tagged = |seq: u64, tick: i64| ChatDelivery { mentions: vec![EUREKA.into()], ..line_at(seq, MINDS, LIBBY, &format!("libby says {seq}"), BASE_MS + u64::try_from(tick).unwrap() * 1000) };
let rig = Rig::new(vec![tagged(1, 0)]);
for seq in 2..=6 {
arrives(&rig, 100 * (seq as i64 - 1), tagged(seq, 100 * (seq as i64 - 1)));
}
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 4, ended: Some(End::Idle), acked_through: Some(6) }, "four Mind lines wake her, the fifth and sixth do not");
let seen: String = rig.agent.seen.borrow().iter().flatten().map(|item| format!("{item:?}")).collect();
assert!(seen.contains("libby says 4") && !seen.contains("libby says 5") && !seen.contains("libby says 6"), "the lines past the backstop are not shown to her agent");
assert_eq!(rig.records()[0]["held"], json!(["$e5", "$e6"]), "they woke nothing, and are in the wake's room: the wake record holds them");
}
/// (b) of W1: the mouth refuses a say whose basis is not the newest event of the room, so each line a turn shows must be shown to the mouth. A say after an
/// in-wake line is sent against that line.
#[test]
fn t_w2_a_say_after_an_in_wake_line_is_sent_against_that_line() {
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
rig.mouth.strict.set(true);
answers(&rig, [says(&room(1), "first answer"), done(), says(&room(1), "second answer"), done()]);
arrives(&rig, 60, later(2, &room(1), 60, "second"));
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 2, ended: Some(End::Idle), acked_through: Some(2) });
let sent = rig.mouth.sent.borrow();
assert_eq!(sent.iter().map(|request| request.text.as_str()).collect::<Vec<_>>(), ["first answer", "second answer"], "the second say was not refused RoomMoved");
assert_eq!(sent[1].basis.as_ref().and_then(|basis| basis.seen_event_id.as_deref()), Some("$e2"));
}
/// W1 (a) and a turn 2 failure that is no outage: the strike is on turn 2's row, on turn 2's oldest waking line, once; the wake record is completed, the
/// Interpreter ran over turn 1, and the line is woken for again by the next start.
#[test]
fn t_w2_a_failed_second_turn_strikes_its_line_on_its_own_row_and_the_wake_still_closes_completed() {
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
answers(&rig, [shells("one", "ls /srv/one"), done(), Err(Failed { reason: "the agent's turn ended early: Refusal".into(), outage: false, usage: None })]);
arrives(&rig, 60, later(2, &room(1), 60, "the line the model refuses"));
let model = Tally::default();
assert_eq!(rig.run(model.clone()), Outcome::Drained { wakes: 1, turns: 2, ended: Some(End::Failed), acked_through: Some(1) });
let turns = rig.turns();
assert_eq!((turns[1]["status"].as_str(), turns[1]["strike"].clone()), (Some("failed"), json!("$e2")));
assert_eq!(rig.all_records().iter().filter(|row| row.get("strike").is_some()).count(), 1, "struck once, on the turn's row, not again on the wake record");
let wake = &rig.records()[0];
assert_eq!((wake["status"].as_str(), wake["ended"].as_str(), wake.get("failed").is_none(), wake["held"].clone()), (Some("completed"), Some("failed"), true, json!([])));
assert_eq!(calls(&rig, "interpreter"), 2, "the Interpreter ran, over turn 1");
assert!(model.0.borrow().iter().filter(|prompt| prompt.starts_with(INTERPRETER)).all(|prompt| prompt.contains("\"ls /srv/one\"")));
assert!(!decided(&rig.trace.records().unwrap()).contains("$e2"), "a failed turn decides nothing");
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(2) }, "the next start answers the line");
}
/// An outage in turn 2 strikes nothing.
#[test]
fn t_w2_an_outage_in_a_second_turn_strikes_nothing() {
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
answers(&rig, [done(), Err(Failed { reason: OUTAGE.into(), outage: true, usage: None })]);
arrives(&rig, 60, later(2, &room(1), 60, "second"));
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 2, ended: Some(End::Failed), acked_through: Some(1) });
assert!(rig.all_records().iter().all(|row| row.get("strike").is_none()));
assert_eq!(rig.turns()[1]["outage"], true);
}
/// The wake's own spend cap: the turns' spend is summed, and the wake closes `spend` when it reaches wake_usd.
#[test]
fn t_w2_a_wake_closes_when_its_turns_have_spent_the_wake_cap() {
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
// One turn here is about $0.0003 a call.
tune(&rig, "[agent]\nwake_usd = 0.0005\n");
answers(&rig, [shells("one", "ls /srv/one")]);
arrives(&rig, 60, later(2, &room(1), 60, "second"));
let Outcome::Drained { ended, .. } = rig.run(Tally::default()) else { panic!("drained") };
assert_eq!(ended, Some(End::Spend));
assert_eq!(rig.records()[0]["ended"], "spend");
}
/// The day cap, reached in a later turn, ends the wake, and the next start is held.
#[test]
fn t_w2_the_day_cap_reached_mid_wake_ends_it_and_the_next_start_is_held() {
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
tune(&rig, "[agent]\nday_usd = 1.0\nwake_usd = 0.5\n");
// The day has spent $0.9995 of its $1.00, and a call costs $0.0003: turn 1 fits, turn 2's second call does not.
let usage = json!(Spent { input_tokens: 499_750, output_tokens: 0, ..spent() });
let at = Utc.timestamp_millis_opt(i64::try_from(BASE_MS).unwrap()).unwrap().to_rfc3339();
rig.trace.rows.borrow_mut().push(("seed-g0".into(), json!({ "agent": "call", "at": at, "usage": usage, "seq": 0 })));
answers(&rig, [done(), says(&room(1), "second answer")]);
arrives(&rig, 60, later(2, &room(1), 60, "second"));
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 2, ended: Some(End::DayCap), acked_through: Some(2) });
assert_eq!(rig.records()[0]["ended"], "day_cap");
rig.mouth.held.borrow_mut().push(line(3, &room(1), META, "third"));
assert!(matches!(rig.run(Tally::default()), Outcome::Held { .. }), "the day is spent: the next start holds her");
}
/// A failed read of the mouth is a skipped poll; three in a row end the wake as an outage, which strikes nothing.
#[test]
fn t_w2_failed_mouth_reads_skip_polls_and_three_in_a_row_end_the_wake() {
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
rig.mouth.pending_fails.set(2);
arrives(&rig, 60, later(2, &room(1), 60, "second"));
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 2, ended: Some(End::Idle), acked_through: Some(2) }, "two failed reads cost two polls, and nothing else");
let rig = Rig::new(vec![line(1, &room(1), META, "first")]);
rig.mouth.pending_fails.set(3);
arrives(&rig, 60, later(2, &room(1), 60, "second"));
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Failed), acked_through: Some(1) });
assert_eq!(rig.records()[0]["status"], "completed");
assert!(rig.all_records().iter().all(|row| row.get("strike").is_none() && row.get("failed").is_none()));
assert!(calls(&rig, "interpreter") == 2, "the turn that ran still closes with its Interpreter");
}
/// The first event whose hash ranks her `rank`th of the two Minds a line tags.
fn event_ranking_her(rank: u64) -> String {
let table: Vec<Addressee> = [EUREKA, LIBBY].iter().map(|id| Addressee::new(id, [crate::address::localpart(id)])).collect();
(0..2000)
.map(|n| format!("$tag{n}"))
.find(|event| crate::persona::live::stagger_ms(&table[0], &table, &ChatDelivery { event_id: event.clone(), mentions: vec![EUREKA.into(), LIBBY.into()], ..line(1, MINDS, META, "both of you") }) == rank * 8000)
.expect("among 2000 events one ranks her so")
}
/// A line to both of two Minds, in a public room: the operator's, tagging both.
fn to_both(seq: u64, event: &str, tick: i64) -> ChatDelivery {
ChatDelivery { event_id: event.into(), mentions: vec![EUREKA.into(), LIBBY.into()], ..line_at(seq, MINDS, META, "both of you, a question", BASE_MS + u64::try_from(tick).unwrap() * 1000) }
}
/// The first experiment's stagger, in the span: a line that tags two Minds is taken by the one ranked second a step (8 s) after the one ranked first, and
/// a Mind ranked first takes it at once.
#[test]
fn t_w2_a_line_to_several_awake_minds_is_taken_after_her_rank() {
let first_turn_two = |rank: u64| {
let rig = Rig::new(vec![line(1, &room(1), META, "hello")]);
arrives(&rig, 60, to_both(2, &event_ranking_her(rank), 60));
rig.run(Tally::default());
assert_eq!(rig.turns().len(), 2, "rank {rank}");
at_of(&rig.turns()[1])
};
let (at_once, after_a_step) = (first_turn_two(0), first_turn_two(1));
let delay = (after_a_step - at_once).num_seconds();
assert!((8..20).contains(&delay), "the second-ranked Mind took the line {delay} s after the first-ranked one would have");
}
/// The first experiment's stagger, at the open: a start woken by a line tagging two Minds waits her rank, then reads the mouth afresh, so a line that
/// arrived while she waited is in her first turn.
#[test]
fn t_w2_the_open_waits_her_rank_and_reads_the_mouth_afresh() {
let ranked_second = event_ranking_her(1);
let rig = Rig::new(vec![to_both(1, &ranked_second, 0)]);
arrives(&rig, 4, later(2, MINDS, 4, "and one more thing while you wait"));
assert_eq!(rig.run(Tally::default()), Outcome::Drained { wakes: 1, turns: 1, ended: Some(End::Idle), acked_through: Some(2) });
assert_eq!(rig.pauses.borrow().first().copied(), Some(std::time::Duration::from_secs(8)), "one step for rank one");
assert_eq!(rig.turns()[0]["held"], json!([ranked_second, "$e2"]), "the line that came in the wait is in the first turn");
assert_eq!(calls(&rig, "projector"), 1, "the wait reran no organ");
let rig = Rig::new(vec![to_both(1, &event_ranking_her(0), 0)]);
rig.run(Tally::default());
assert_eq!(rig.pauses.borrow().first().copied(), Some(std::time::Duration::from_secs(5)), "ranked first: no wait before the wake, only the span's polls");
}

View file

@ -0,0 +1,205 @@
//! The live span of a wake (`docs/persona-wake-span-map.md`, cut W2): what the drain decides after her first turn, while the wake is open.
//!
//! A wake is one start of `mind-persona@<instance>`. After a turn the process polls the mouth every `POLL_S` seconds. A line that wakes her
//! by the heartbeat's own rule (`Hearing::waking`, which the open uses too) starts the next turn in the same agent conversation, with only the
//! new lines as its input. The wake ends by one pure function, `wake_end`, and by nothing else.
//!
//! What this gives up: a line after the first is answered on the inner voice the wake opened with, and her state moves only when the
//! wake closes.
use std::collections::{BTreeMap, BTreeSet};
use chrono::{DateTime, Duration, Utc};
use serde_json::Value;
use super::{Config, STRIKES, speaker, strikes};
use crate::address::{Addressee, addresses, is_for};
use crate::chat_client::ChatDelivery;
use crate::heartbeat::{pending_facts, wakes};
use crate::projection::AgentTuning;
use crate::projection::agent::{Cap, Ended};
/// How often an open wake reads the mouth, in seconds: the first experiment's `PERSONA_POLL_S`.
pub(crate) const POLL_S: u64 = 5;
/// How many mouth reads in a row may fail before the wake ends. One failed read is a skipped poll.
pub(crate) const MOUTH_FAILS_MAX: u32 = 3;
/// A line is taken this many seconds per rank after the first Mind addressed (`stagger_ms`), the first experiment's `STAGGER_STEP_S`: calibration,
/// about the time a Mind takes to answer (7 to 13 s observed on 2026-11-03).
pub(crate) const STAGGER_STEP_S: u64 = 8;
/// Why a wake ended: the first of these that holds, in this order.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum End {
/// A turn failed, or the wake could not read the mouth or her trace.
Failed,
/// A turn reached the day's cap.
DayCap,
/// This wake's spend reached `agent.wake_usd`.
Spend,
/// The wake has been open `agent.span_s`.
Span,
/// No turn has started for `agent.idle_s` since her last ended.
Idle,
}
impl End {
pub(crate) fn name(self) -> &'static str {
match self {
Self::Failed => "failed",
Self::DayCap => "day_cap",
Self::Spend => "spend",
Self::Span => "span",
Self::Idle => "idle",
}
}
}
impl std::fmt::Display for End {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.name())
}
}
/// Where a wake stands in time: when it opened and when her last turn ended.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Span {
pub opened: DateTime<Utc>,
pub last_ended: DateTime<Utc>,
}
/// Whether the wake ends now, and why. `last` is how her last turn ended, `spent_usd` this wake's spend over all its turns.
pub(crate) fn wake_end(span: &Span, last: &Ended, spent_usd: f64, now: DateTime<Utc>, bounds: &AgentTuning) -> Option<End> {
let seconds = |secs: u64| Duration::seconds(i64::try_from(secs).unwrap_or(i64::MAX));
if matches!(last, Ended::Failed(_)) {
Some(End::Failed)
} else if matches!(last, Ended::Cap(Cap::DaySpend)) {
Some(End::DayCap)
} else if spent_usd >= bounds.wake_usd || matches!(last, Ended::Cap(Cap::WakeSpend)) {
Some(End::Spend)
} else if now - span.opened >= seconds(bounds.span_s) {
Some(End::Span)
} else if now - span.last_ended >= seconds(bounds.idle_s) {
Some(End::Idle)
} else {
None
}
}
/// How long after a poll first sees `delivery` a Mind takes it, in milliseconds. This is the first experiment's stagger, ported from
/// `crates/mind-body/src/persona.rs` at `0fd1232^` (`stagger_ms`, ruling `eureka-body:ruling:unaddressed-tell-stagger-ruled`): none in a direct
/// message, otherwise her rank times `STAGGER_STEP_S`. The Minds the line is for rank by a hash of the Mind and the event, so the first Mind
/// by that order takes it at once and the others one step apart: addressing several does not make a chorus, and the later ones read the
/// earlier ones' answers before they give theirs. A rank is the number of Minds addressed whose hash sorts before hers, from the line and the
/// addressing table alone (the sender is not counted), so every process computes the same order with no word between them and nobody is always
/// last. A line that is not for her (an own-room or exchange line, an open floor) is hers alone to take: no delay.
pub(crate) fn stagger_ms(own: &Addressee, addressing: &[Addressee], delivery: &ChatDelivery) -> u64 {
if delivery.is_direct || !is_for(own, delivery) {
return 0;
}
let mut minds: Vec<&Addressee> = addressing.iter().filter(|mind| mind.matrix_id() != delivery.sender && mind.matrix_id() != own.matrix_id() && addresses(mind, delivery)).collect();
minds.sort_unstable_by_key(|mind| mind.matrix_id());
minds.dedup_by_key(|mind| mind.matrix_id());
let mine = (stagger_hash(own.matrix_id(), &delivery.event_id), own.matrix_id());
let rank = minds.iter().filter(|mind| (stagger_hash(mind.matrix_id(), &delivery.event_id), mind.matrix_id()) < mine).count();
rank as u64 * STAGGER_STEP_S * 1000
}
/// FNV-1a over the Mind, a separator and the event, then murmur3's finalizer so a Mind's order against another changes from event to event
/// (FNV alone leaves it nearly fixed by the Minds' names): fixed by this definition, so every Mind's process computes the same order.
/// Verbatim from the first experiment's `stagger_hash`.
pub(crate) fn stagger_hash(mind: &str, event_id: &str) -> u64 {
let mut hash = mind.bytes().chain(std::iter::once(0xff)).chain(event_id.bytes()).fold(0xcbf2_9ce4_8422_2325, |hash, byte| (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3));
hash ^= hash >> 33;
hash = hash.wrapping_mul(0xff51_afd7_ed55_8ccd);
hash ^= hash >> 33;
hash = hash.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
hash ^ (hash >> 33)
}
/// Who she is to the room, as the heartbeat reads it: the one derivation of "this line wakes her", for the open and for every poll of the span.
pub(crate) struct Hearing<'a> {
pub config: &'a Config,
pub her: &'a Addressee,
pub addressing: &'a [Addressee],
pub own_rooms: &'a [String],
/// The lines the heartbeat woke her for, read once at the open: the open floor is hers only on those. The heartbeat claims no floor line for a
/// Mind whose unit is active, so nothing new can appear in it mid-wake.
pub claimed: &'a [String],
}
impl Hearing<'_> {
/// For each of `deliveries` (oldest first), whether it wakes her: the heartbeat's `wakes`, or a claim the heartbeat made for her.
pub(crate) fn waking(&self, deliveries: &[&ChatDelivery]) -> Vec<bool> {
let mut facts = pending_facts(deliveries, &self.config.own_sender, &self.config.minds, self.own_rooms);
for (delivery, facts) in deliveries.iter().zip(&mut facts) {
facts.open_floor &= self.claimed.contains(&delivery.event_id);
}
deliveries.iter().zip(&facts).map(|(delivery, facts)| self.claimed.contains(&delivery.event_id) || wakes(self.her, delivery, speaker(self.config, delivery), *facts).is_some()).collect()
}
}
/// What a poll finds in the mouth that this wake has not dealt with.
pub(crate) struct Found<'a> {
/// Every line her trace does not hold decided and no turn of this wake has taken, and that has not struck out, oldest first.
pub fresh: Vec<&'a ChatDelivery>,
/// Those of `fresh` that wake her.
pub waking: Vec<&'a ChatDelivery>,
}
/// The lines of `pool` (oldest first) that are new to the wake: not decided by her trace (`done`), not in a turn this wake ran (`taken`), and
/// not a line two wakes failed on, which the next open sets aside.
pub(crate) fn find<'a>(hearing: &Hearing<'_>, pool: &'a [ChatDelivery], done: &BTreeSet<&str>, records: &[Value], taken: &BTreeSet<String>) -> Found<'a> {
let all: Vec<&ChatDelivery> = pool.iter().collect();
let flags = hearing.waking(&all);
let mut found = Found { fresh: vec![], waking: vec![] };
for (delivery, waking) in all.into_iter().zip(flags) {
if done.contains(delivery.event_id.as_str()) || taken.contains(&delivery.event_id) || strikes(records, &delivery.event_id) >= STRIKES {
continue;
}
found.fresh.push(delivery);
if waking {
found.waking.push(delivery);
}
}
found
}
/// The next turn: the lines it holds, the rooms the wake now has, and the line its failure would strike.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Taking {
pub hold: Vec<String>,
pub rooms: Vec<String>,
/// The oldest waking line, when the turn's waking lines are all in one room: a failure that is no outage strikes it and no other. A turn
/// over several rooms cannot say which one failed it, and strikes nothing.
pub strike: Option<String>,
}
/// Whether the wake takes a turn now, and on what. A waking line is taken once it is due (`stagger_ms` from the poll that first saw it); the
/// turn then holds every waking line, due or not (she is never shown a line and kept from the ones before it), and every other new line of the
/// wake's rooms, her own and what is no message included, as the open's `held` does. The room of a waking line joins the wake. A wake that began
/// retreating (the start after one that failed for a reason that is no outage takes one room at a time, so a failure is found in one room alone
/// and strikes that room's oldest line and no innocent room's) takes one room a turn.
pub(crate) fn take(hearing: &Hearing<'_>, found: &Found<'_>, rooms: &[String], retreating: bool, first_seen: &mut BTreeMap<String, DateTime<Utc>>, now: DateTime<Utc>) -> Option<Taking> {
let oldest_room = found.waking.first().map(|delivery| delivery.room_alias.as_str());
let waking: Vec<&ChatDelivery> = found.waking.iter().copied().filter(|delivery| !retreating || Some(delivery.room_alias.as_str()) == oldest_room).collect();
for delivery in &waking {
first_seen.entry(delivery.event_id.clone()).or_insert(now);
}
let due = waking.iter().any(|delivery| now - first_seen[&delivery.event_id] >= Duration::milliseconds(i64::try_from(stagger_ms(hearing.her, hearing.addressing, delivery)).unwrap_or(i64::MAX)));
if !due {
return None;
}
let mut rooms = rooms.to_vec();
for delivery in &waking {
if !rooms.contains(&delivery.room_alias) {
rooms.push(delivery.room_alias.clone());
}
}
let hold = found.fresh.iter().filter(|delivery| rooms.contains(&delivery.room_alias)).map(|delivery| delivery.event_id.clone()).collect();
let waking_rooms: BTreeSet<&str> = waking.iter().map(|delivery| delivery.room_alias.as_str()).collect();
let strike = (waking_rooms.len() == 1).then(|| waking.first().map(|delivery| delivery.event_id.clone())).flatten();
Some(Taking { hold, rooms, strike })
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,132 @@
//! The pure parts of a wake's span: when it ends, and how long a line addressed to several Minds waits for her.
use chrono::TimeZone;
use super::*;
use crate::chat_client::Form;
use crate::projection::Failed;
fn at(secs: i64) -> DateTime<Utc> {
Utc.timestamp_opt(1_800_000_000 + secs, 0).unwrap()
}
/// A wake that opened at 0 and whose last turn ended at `last`, judged at `now`.
fn ends(last: Ended, spent: f64, ended_at: i64, now: i64) -> Option<End> {
wake_end(&Span { opened: at(0), last_ended: at(ended_at) }, &last, spent, at(now), &AgentTuning::default())
}
fn failed() -> Ended {
Ended::Failed(Failed { reason: "refused".into(), outage: false, usage: None })
}
#[test]
fn a_wake_waiting_for_a_line_ends_idle_at_idle_s_after_her_last_turn() {
assert_eq!(ends(Ended::EndTurn, 0.1, 100, 399), None);
assert_eq!(ends(Ended::EndTurn, 0.1, 100, 400), Some(End::Idle), "idle_s is 300");
// The window runs from her last turn's end, not from the wake's opening.
assert_eq!(ends(Ended::EndTurn, 0.1, 1000, 1299), None);
assert_eq!(ends(Ended::EndTurn, 0.1, 1000, 1300), Some(End::Idle));
}
#[test]
fn a_wake_open_span_s_ends_though_lines_keep_coming() {
assert_eq!(ends(Ended::EndTurn, 0.1, 1799, 1799), None);
assert_eq!(ends(Ended::EndTurn, 0.1, 1799, 1800), Some(End::Span), "span_s is 1800");
}
#[test]
fn a_wake_that_has_spent_its_cap_ends() {
assert_eq!(ends(Ended::EndTurn, 0.99, 0, 10), None);
assert_eq!(ends(Ended::EndTurn, 1.0, 0, 10), Some(End::Spend), "wake_usd is 1.00");
assert_eq!(ends(Ended::Cap(Cap::WakeSpend), 0.1, 0, 10), Some(End::Spend), "a turn the wake cap stopped");
}
#[test]
fn a_turn_that_hit_the_day_cap_or_failed_ends_the_wake() {
assert_eq!(ends(Ended::Cap(Cap::DaySpend), 0.1, 0, 10), Some(End::DayCap));
assert_eq!(ends(failed(), 0.1, 0, 10), Some(End::Failed));
// A turn a per-turn bound stopped is no reason to end the wake.
assert_eq!(ends(Ended::Cap(Cap::ToolCalls), 0.1, 0, 10), None);
assert_eq!(ends(Ended::Cap(Cap::ModelCalls), 0.1, 0, 10), None);
}
#[test]
fn the_ends_are_judged_in_order() {
// Everything true at once: failed, then the day cap, then the wake's spend, then the span, then idle.
assert_eq!(ends(failed(), 5.0, 0, 5000), Some(End::Failed));
assert_eq!(ends(Ended::Cap(Cap::DaySpend), 5.0, 0, 5000), Some(End::DayCap));
assert_eq!(ends(Ended::EndTurn, 5.0, 0, 5000), Some(End::Spend));
assert_eq!(ends(Ended::EndTurn, 0.1, 0, 5000), Some(End::Span));
assert_eq!(ends(Ended::EndTurn, 0.1, 0, 1000), Some(End::Idle));
}
const ALL: [&str; 3] = ["@eureka:gamecult.org", "@libby:gamecult.org", "@kiko:gamecult.org"];
fn table() -> Vec<Addressee> {
ALL.iter().map(|id| Addressee::new(id, [crate::address::localpart(id)])).collect()
}
fn said(event: &str, sender: &str, room: &str, direct: bool, mentions: &[&str], text: &str) -> ChatDelivery {
ChatDelivery {
seq: 1,
room_alias: room.into(),
room_id: room.into(),
event_id: event.into(),
sender: sender.into(),
sender_display: String::new(),
text: text.into(),
at_unix_ms: 0,
context: vec![],
mentions: mentions.iter().map(|id| (*id).to_owned()).collect(),
is_direct: direct,
image: None,
basis: None,
form: Form::Message,
reply_to: Default::default(),
}
}
/// Each Mind's delay for one line from the operator tagging all three.
fn delays(event: &str) -> Vec<u64> {
let line = said(event, "@meta:gamecult.org", "#minds:gamecult.org", false, &ALL, "all of you, a question");
let table = table();
table.iter().map(|own| stagger_ms(own, &table, &line)).collect()
}
/// The first experiment's stagger (`persona.rs` at `0fd1232^`): a line addressed to several Minds is taken by them one step apart, each at her rank.
#[test]
fn a_line_to_three_minds_is_taken_one_step_apart() {
for event in ["$a", "$b", "$c", "$d", "$e"] {
let mut ranks = delays(event);
ranks.sort_unstable();
assert_eq!(ranks, [0, 8000, 16000], "{event}: the first Mind takes it at once and the others 8 s per rank");
}
}
#[test]
fn the_order_changes_from_event_to_event_so_nobody_is_always_last() {
let last: BTreeSet<usize> = (0..40).map(|n| delays(&format!("$ev{n}")).iter().position(|delay| *delay == 16000).unwrap()).collect();
assert_eq!(last.len(), 3, "each of the three is last for some event: {last:?}");
}
#[test]
fn the_sender_is_not_counted_and_a_line_not_for_her_or_in_a_direct_message_waits_for_no_one() {
let table = table();
// Libby tags Eureka and Kiko: two Minds, not three.
let line = said("$x", ALL[1], "#minds:gamecult.org", false, &[ALL[0], ALL[2]], "you two");
let mut ranks: Vec<u64> = [&table[0], &table[2]].iter().map(|own| stagger_ms(own, &table, &line)).collect();
ranks.sort_unstable();
assert_eq!(ranks, [0, 8000]);
// A line that is not for Kiko is hers to take at once, whoever else it names.
assert_eq!(stagger_ms(&table[1], &table, &said("$y", "@meta:gamecult.org", "#minds:gamecult.org", false, &[ALL[0]], "just you")), 0);
// A direct message is one Mind's alone.
assert_eq!(stagger_ms(&table[0], &table, &said("$z", "@meta:gamecult.org", "!dm:gamecult.org", true, &[], "hello")), 0);
}
#[test]
fn the_hash_is_fixed_so_every_process_computes_the_same_order() {
assert_eq!(stagger_hash("@eureka:gamecult.org", "$e1"), stagger_hash("@eureka:gamecult.org", "$e1"));
assert_ne!(stagger_hash("@eureka:gamecult.org", "$e1"), stagger_hash("@libby:gamecult.org", "$e1"));
assert_ne!(stagger_hash("@eureka:gamecult.org", "$e1"), stagger_hash("@eureka:gamecult.org", "$e2"));
assert_eq!(STAGGER_STEP_S, 8, "the step is the calibration the ruling names");
}