persona: a Persona whose agent has spent its day cap does not wake; her lines stay unacked, one hold row a UTC day, and the poll starts no unit for her until it ends (ruling persona-day-cap-behaviour, hold-agent-only)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-01 14:34:35 +01:00
commit c31afce562
7 changed files with 118 additions and 12 deletions

View file

@ -36,7 +36,7 @@ use crate::chat_client::{Basis, Chat, ChatDelivery, ChatPending, Form};
use crate::control::{ControlSource, Effective, FileSource, HeldReason, SwarmEffective, read_effective, read_envelope, set_mode_world_readable};
use crate::launch::{Clock, Launcher};
use crate::persona::TraceView;
use crate::projection::{decided, failed_run};
use crate::projection::{day_held_until, decided, failed_run};
use crate::queue::{MindPort, headers, in_force, of_kind};
use crate::tempo::{self, Standing};
@ -797,6 +797,8 @@ struct Row<'a> {
done: Option<BTreeSet<String>>,
/// How many of her last records are failures in a row, and when the last was made.
failures: (u32, Option<DateTime<Utc>>),
/// Until when her trace says her agent's day cap holds her (`projection::day_held_until`).
held_until: Option<DateTime<Utc>>,
note: String,
}
@ -809,10 +811,11 @@ impl Row<'_> {
self.released && !self.busy
}
/// A failed wake is waited out before the next: `BACKOFF_BASE_S`, doubled by each failure in a row her trace holds, to the beat.
/// No start is made for her: a failed wake is waited out before the next (`BACKOFF_BASE_S`, doubled by each failure in a row her
/// trace holds, to the beat), and a day cap's hold lasts until the UTC midnight her trace's hold row names.
fn cooling(&self, now: DateTime<Utc>, beat_s: u32) -> bool {
let (run, at) = self.failures;
run > 0 && at.is_some_and(|at| (now - at).num_seconds() < backoff(run, beat_s))
self.held_until.is_some_and(|until| now < until) || run > 0 && at.is_some_and(|at| (now - at).num_seconds() < backoff(run, beat_s))
}
/// A member (not the operator) has a pending message that names or tags her.
@ -865,13 +868,14 @@ pub fn poll(organs: &Organs, config: &Config) -> Result<Outcome> {
// Her last-read names when the table holds her, else her roster names alone.
let roster = Addressee::new(&seat.who.matrix_id, [seat.who.public_name.as_str(), seat.who.handle.as_str()]);
let kept = stored_addressing.minds.iter().find(|stored| stored.matrix_id() == seat.who.matrix_id).cloned().unwrap_or_else(|| roster.clone());
let mut row = Row { seat, released, busy, pending: vec![], addressee: kept, own_rooms: vec![], done: None, failures: (0, None), note: String::new() };
let mut row = Row { seat, released, busy, pending: vec![], addressee: kept, own_rooms: vec![], done: None, failures: (0, None), held_until: None, note: String::new() };
// Pending chat, read-only, for a released Mind.
if row.released {
match seat.trace.records() {
Ok(records) => {
row.done = Some(decided(&records).into_iter().map(str::to_owned).collect());
row.failures = failed_run(&records);
row.held_until = day_held_until(&records);
}
Err(error) => {
eventful = true;

View file

@ -1386,3 +1386,25 @@ fn t_l3_a_new_waking_line_is_woken_for_by_the_wake_rule_with_an_owed_list_in_her
assert_eq!(launched, vec![Slug("ann".into())]);
assert!(rig.store.state.borrow().clone().unwrap().handled_mentions.contains(&"ann:$e2".to_owned()), "the new line's claim is written: the wake rule started her");
}
/// The day cap's hold is read from her trace, and it is what bounds the start storm: a held start writes no wake record and decides no
/// line, so without it the poll would start her unit for the same undecided line every poll. Every poll before the hold's `until` starts
/// her never; the first after it starts her for the line.
#[test]
fn t_h3_a_day_cap_hold_in_her_trace_starts_no_one_until_it_ends() {
let rig = quiet_rig();
rig.say(ANN, delivery(1, "@op:chat", "Ann, please", &[]));
rig.poll();
rig.end_unit(ANN);
let until = rig.now() + Duration::seconds(600);
rig.traces[ANN].rows.borrow_mut().push(serde_json::json!({ "held_by": "day_cap", "spent": 3.2, "cap": 3.0, "until": until.to_rfc3339(), "at": rig.now().to_rfc3339() }));
while rig.now() + Duration::seconds(20) < until {
rig.advance(20);
let Outcome::Polled { launched } = rig.poll() else { panic!("held") };
assert!(!launched.iter().any(|slug| slug.0 == "ann"), "{launched:?}");
rig.end_unit(ANN);
}
rig.advance(30);
let Outcome::Polled { launched } = rig.poll() else { panic!("held") };
assert!(launched.iter().any(|slug| slug.0 == "ann"), "the line she was held from wakes her after the hold ends: {launched:?}");
}

View file

@ -52,8 +52,8 @@ 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, Executor, FileSession, Steps, TraceLedger, Wake as AgentWake, instructions as agent_instructions, ready_intentions, step};
use crate::projection::{Applied, DomainSource, Fault, Heard, HuginnPersonaSource, Model, Mouth, Organs, PersonaStore, Put, ReadSource, Request, Taken, Through, TurnKind, Waked, apply_commit, decided, failed as record_failed, history, interpret, is_wake, load_tuning, people_named, settle_handed, wake, own_addressee as heard_as};
use crate::projection::agent::{Agent, Ended, 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, Heard, HuginnPersonaSource, Model, Mouth, Organs, PersonaStore, Put, ReadSource, Request, Taken, Through, TurnKind, Waked, apply_commit, day_held_until, decided, failed as record_failed, history, interpret, is_wake, load_tuning, people_named, settle_handed, wake, own_addressee as heard_as};
/// 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";
@ -248,6 +248,9 @@ pub enum Outcome {
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> },
/// 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> },
/// The start read nothing (the organs could not be built, the daemon or the mouth was down): nothing acked, nothing put.
Failed(String),
}
@ -259,6 +262,7 @@ impl fmt::Display for Outcome {
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::Held { until } => write!(f, "held: the agent's day cap, until {}", until.to_rfc3339()),
Self::Failed(why) => write!(f, "failed: {why}"),
}
}
@ -456,6 +460,24 @@ fn drain<C: Chat>(instance: &Slug, start: &Start<C>) -> Outcome {
Ok(records) => records,
Err(fault) => return failed("her trace was not read", fault),
};
let bounds = match load_tuning(&start.tuning) {
Ok(loaded) => loaded.tuning,
Err(fault) => return failed("her tuning was not read", fault),
};
// Her agent has spent the day's cap: she does not wake. No organ is called, no wake is recorded and nothing is acked that this start
// owes a wake (the watched rooms' undecided lines stay below the ack), so the lines wake her after the UTC day rolls over. One row a
// UTC day says so; the poll reads it (`day_held_until`) and starts no unit for her before `until`.
let spent = day_usd(&records, now, &bounds.agent);
if spent >= bounds.agent.day_usd {
let until = day_ends(now);
if day_held_until(&records) != Some(until) {
let row = json!({ "held_by": DAY_CAP_HOLD, "spent": spent, "cap": bounds.agent.day_usd, "until": until.to_rfc3339(), "at": now.to_rfc3339(), "seq": place(&*start.trace) });
if let Err(fault) = start.trace.record(&format!("{stem}-h"), &row) {
eprintln!("mind-persona: the record that the day cap holds her was not appended: {fault:#}");
}
}
return Outcome::Held { until };
}
// Where this wake begins in her trace: what she is told at it is every row from her last completed wake's start up to here,
// and what her next wake is told starts here.
let began_at = records.len();
@ -496,10 +518,6 @@ fn drain<C: Chat>(instance: &Slug, start: &Start<C>) -> Outcome {
Ok(waked) => waked,
Err(fault) => return failed("the wake could not be set up", fault),
};
let bounds = match load_tuning(&start.tuning) {
Ok(loaded) => loaded.tuning,
Err(fault) => return failed("her tuning was not read", fault),
};
// What the wake held, for the starts after it to read: every delivery of the waking rooms, which she has lived through once the wake
// completed, and the ids her projection selected.
let key = waking.first().map_or_else(|| format!("b{began_ms}"), |line| format!("l{}", line.event));

View file

@ -846,3 +846,50 @@ fn t_a2_an_agent_outage_strikes_nothing() {
assert_eq!(records[1]["strike"], "$e1", "{records:?}");
assert!(rig.acks().is_empty());
}
/// A ledger row for a call that cost more than the day's cap, dated at the clock's day.
fn spend_the_day(rig: &Rig) {
let usage = json!(Spent { input_tokens: 5_000_000, ..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 })));
}
/// The organs a start called, from the log.
fn organ_calls(rig: &Rig) -> Vec<String> {
rig.log.all().into_iter().filter(|what| matches!(what.as_str(), "projector" | "persona" | "agent" | "interpreter")).collect()
}
/// Ruling persona-day-cap-behaviour (hold-agent-only): a Persona whose agent has spent its day's cap does not wake. No organ is called, no
/// wake is recorded, the lines that would have woken her stay unacked, and one row a UTC day says she is held.
#[test]
fn t_h3_cap_holds_lines() {
let rig = Rig::new(vec![line(1, &room(1), META, "morning, are you there")]);
spend_the_day(&rig);
let Outcome::Held { until } = rig.run(Tally::default()) else { panic!("held") };
assert_eq!(until, Utc.timestamp_opt(1_795_910_400, 0).unwrap(), "the next UTC midnight");
assert_eq!(organ_calls(&rig), Vec::<String>::new(), "no Projector, Persona, agent or Interpreter call");
assert!(rig.acks().is_empty(), "the line she owes a wake is not acked: {:?}", rig.acks());
let held = |rig: &Rig| rig.all_records().into_iter().filter(|row| row["held_by"] == "day_cap").collect::<Vec<_>>();
let rows = held(&rig);
assert_eq!((rows.len(), rows[0]["until"].as_str(), rows[0]["cap"].as_f64()), (1, Some(until.to_rfc3339().as_str()), Some(3.0)), "{rows:?}");
assert!(rows[0]["spent"].as_f64().unwrap() >= 3.0);
assert!(matches!(rig.run(Tally::default()), Outcome::Held { .. }), "a second start the same day holds as well");
assert_eq!(held(&rig).len(), 1, "and writes no second row");
assert!(rig.records().is_empty(), "no wake record");
assert!(rig.all_records().iter().all(|row| row["agent"] != "receipt" && row["kind"] != "cap"), "no cap receipt from a start that never woke: {:?}", rig.all_records());
assert!(rig.mouth.sent.borrow().is_empty());
}
/// The same trace once the UTC day has rolled over: the held line wakes her, is answered and is acked, with no new message.
#[test]
fn t_h3_rollover_wakes_held_lines() {
let rig = Rig::new(vec![line(1, &room(1), META, "morning, are you there")]);
spend_the_day(&rig);
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!(organ_calls(&rig), ["projector", "persona", "agent", "agent", "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);
}

View file

@ -53,7 +53,7 @@ pub use read::{LiveReads, ReadFailure, ReadFixture, ReadRequest, ReadSource};
pub use select::TurnKind;
pub(crate) use commit::{Applied, Heard, apply as apply_commit};
pub(crate) use interpret::{deltas as interpret, people as people_named};
pub(crate) use turn::{Taken, decided, failed, failed_run, history, is_wake};
pub(crate) use turn::{DAY_CAP_HOLD, Taken, day_held_until, decided, failed, failed_run, history, is_wake};
pub(crate) use agent::say::{Mouth, settle_handed};
pub(crate) use wake::{Fault, Waked, wake};
pub use tuning::{TUNING_FILE, TUNING_ROOT};

View file

@ -550,7 +550,7 @@ fn charge(bounds: &AgentTuning, usage: &Spent) -> f64 {
/// the `settle` row that names it: the settle's `reserved` is the call row's `seq`, its place in her trace, which no other row
/// holds, where a call id repeats when a wake is retried under its id. A call with neither, or with a usage that does not
/// read or counts no token, is `unmetered_usd`. A row whose time does not read counts as today's.
fn day_usd(rows: &[Value], now: DateTime<Utc>, bounds: &AgentTuning) -> f64 {
pub(crate) fn day_usd(rows: &[Value], now: DateTime<Utc>, bounds: &AgentTuning) -> f64 {
let settled: BTreeMap<u64, &Value> = rows.iter().filter(|row| row["agent"] == "settle").filter_map(|row| Some((row["reserved"].as_u64()?, row))).collect();
rows.iter()
.filter(|row| row["agent"] == "call")
@ -562,6 +562,11 @@ fn day_usd(rows: &[Value], now: DateTime<Utc>, bounds: &AgentTuning) -> f64 {
.sum()
}
/// When `now`'s UTC day ends: the next UTC midnight, the moment `day_usd` counts from nothing again.
pub(crate) fn day_ends(now: DateTime<Utc>) -> DateTime<Utc> {
(now.date_naive() + chrono::Days::new(1)).and_time(chrono::NaiveTime::MIN).and_utc()
}
fn digest_of(model: &str, instructions: &str, tools: &[ToolDefinition]) -> String {
let mut hash = Sha256::new();
for part in [model, instructions] {

View file

@ -63,6 +63,16 @@ pub(crate) fn failed_run(records: &[Value]) -> (u32, Option<DateTime<Utc>>) {
(u32::try_from(run).unwrap_or(u32::MAX), at)
}
/// The `held_by` of the row a start writes when her agent has spent its day's cap and she is not woken (`persona::drain`).
pub(crate) const DAY_CAP_HOLD: &str = "day_cap";
/// When her trace says the day cap holds her until: the `until` of her newest `DAY_CAP_HOLD` row. The one reader, for the drain (one row
/// a day) and the poll (she is not started while it lies ahead).
pub(crate) fn day_held_until(records: &[Value]) -> Option<DateTime<Utc>> {
let row = records.iter().rev().find(|record| record["held_by"] == DAY_CAP_HOLD)?;
DateTime::parse_from_rfc3339(row["until"].as_str()?).ok().map(|until| until.with_timezone(&Utc))
}
/// What her records say of her: what she is to be told (`outcome::told`), the ids her last projections selected, her last rows
/// and when she last woke. The one reader, over a run's list or her trace.
#[derive(Debug, Default, PartialEq)]