Heartbeat: no night wake until C4; stale docs and empty tests (Soul F4, F6, F7)
F4: the night wake started a plain mind-persona@ unit and traced it as Sleep and "asleep". Deleted the night branch, Night, Config.night, the HEARTBEAT_SLEEP_UTC and HEARTBEAT_SLEEP_MINDS settings and HeartbeatState.last_night_at (added by this PR, never deployed, so nothing must decode it). A wake's trace entry is her slug. Reflection and consolidation return in C4. F6: deleted a_flag_overrides_the_environment (asserted exit 0 with the config discarded) and the heartbeat test that compared two identical rigs. F7: Cargo.toml no longer says the Persona drains her chat or that launch opens runs; heartbeat.rs no longer says Persona units read its addressing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
6df3255330
commit
8fe9fc351b
5 changed files with 33 additions and 262 deletions
|
|
@ -9,13 +9,13 @@ publish.workspace = true
|
|||
# operator's brakes: a root-owned per-instance CultCache
|
||||
# store (`control`), the operator's CLI over it (`cli`, the `mind-control`
|
||||
# binary) and the one fail-closed reader every acting organ calls
|
||||
# (`control::read_effective`). It also holds the launch primitive (`launch`,
|
||||
# `queue`): the one way her organs open a run and start its unit. The heartbeat
|
||||
# (`heartbeat`, the `mind-heartbeat` binary) runs the shared heartbeat over them. The actuator
|
||||
# (`control::read_effective`). It also holds her units under systemd (`launch`)
|
||||
# and her port to her mind (`queue`). The heartbeat (`heartbeat`, the
|
||||
# `mind-heartbeat` binary) wakes her by starting her unit. The actuator
|
||||
# (`self_run`, the `mind-self-run` binary) carries her one open Self run.
|
||||
#
|
||||
# The Persona organ (`persona`, the `mind-persona` binary) drains her pending chat
|
||||
# through ports. The connector transport is ModelConnector's kit client, pinned to
|
||||
# The Persona organ (`persona`, the `mind-persona` binary) reads the brakes and
|
||||
# carries no turn until the three-stage turn lands (map C3). The connector transport is ModelConnector's kit client, pinned to
|
||||
# the kit's revision (`connector`); the chat transport is cultnet-rs's RUDP client
|
||||
# to Bifrost's mouth (`chat_rudp`). `rmp-serde` is the chat documents' positional
|
||||
# MessagePack codec (`chat_client`); `sha2` derives the mouth's connection id from
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ use std::time::Duration;
|
|||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use eureka_state::HuginnClient;
|
||||
use mind_body::chat_rudp::{RudpChat, connection_id};
|
||||
use mind_body::heartbeat::{Config, DEFAULT_BEAT_S, FileControl, FileStore, Night, Organs, PersonaId, Seat, poll};
|
||||
use mind_body::heartbeat::{Config, DEFAULT_BEAT_S, FileControl, FileStore, Organs, PersonaId, Seat, poll};
|
||||
use mind_body::launch::{SystemClock, SystemdLauncher};
|
||||
use mind_body::queue::HuginnMind;
|
||||
|
||||
|
|
@ -58,9 +58,8 @@ fn config() -> Result<Config> {
|
|||
.map(PersonaId::parse)
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let operators = required("MIND_PERSONA_OPERATOR")?.split(',').map(|id| id.trim().to_string()).filter(|id| !id.is_empty()).collect();
|
||||
let night = Night::from_settings(setting("HEARTBEAT_SLEEP_UTC").as_deref(), setting("HEARTBEAT_SLEEP_MINDS").as_deref())?;
|
||||
let beat_s = u32::try_from(whole("HEARTBEAT_BEAT_S", i64::from(DEFAULT_BEAT_S))?).map_err(|_| anyhow!("HEARTBEAT_BEAT_S is out of range"))?;
|
||||
Config::new(personas, operators, night, beat_s)
|
||||
Config::new(personas, operators, beat_s)
|
||||
}
|
||||
|
||||
fn store() -> Result<FileStore> {
|
||||
|
|
|
|||
|
|
@ -7,17 +7,16 @@
|
|||
//! idle, released Minds, by how long each has waited since the heartbeat last
|
||||
//! woke her, bent by a member addressing her and (a later cut) topics she
|
||||
//! subscribed to. The operator or another Mind tagging or naming her wakes her
|
||||
//! off the beat, once per message. Inside the night window a listed Mind wakes
|
||||
//! once for her night. Nothing is metered here: no meter and no model call.
|
||||
//! off the beat, once per message. There is no night wake until reflection and
|
||||
//! consolidation return (map C4). Nothing is metered here: no meter and no model call.
|
||||
//!
|
||||
//! A wake starts her unit and nothing else: the heartbeat writes no mind (ruling
|
||||
//! `persona-only-heartbeat`: her Mind is written only by Self sessions). It reads
|
||||
//! her mind only for the names her projects go by. Busy is systemd's own: a
|
||||
//! Persona whose unit is active is busy, and a start of an active unit is a no-op.
|
||||
//!
|
||||
//! The heartbeat owns `heartbeat.cc` and is its only writer; Persona units read
|
||||
//! its addressing. The brakes stay the operator's and are read on every poll. The
|
||||
//! heartbeat never acks a delivery.
|
||||
//! The heartbeat owns `heartbeat.cc` and is its only writer. The brakes stay the
|
||||
//! operator's and are read on every poll. The heartbeat never acks a delivery.
|
||||
//!
|
||||
//! A held swarm brake ends the poll before the mind or the mouth is touched.
|
||||
|
||||
|
|
@ -27,7 +26,7 @@ use std::net::SocketAddr;
|
|||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use chrono::{DateTime, SecondsFormat, Timelike, Utc};
|
||||
use chrono::{DateTime, SecondsFormat, Utc};
|
||||
use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore};
|
||||
use eureka_pipeline::{OrgRepo, PipelineKind, RunTurn, Slug};
|
||||
use huginn_mind::PipelineFacts;
|
||||
|
|
@ -94,70 +93,13 @@ pub struct Config {
|
|||
pub personas: Vec<PersonaId>,
|
||||
/// Sender ids that are the operator.
|
||||
pub operators: Vec<String>,
|
||||
/// The nightly window and the Minds that sleep in it; none, no one sleeps.
|
||||
pub night: Option<Night>,
|
||||
/// Seconds between beats: `HEARTBEAT_BEAT_S`, else `DEFAULT_BEAT_S`.
|
||||
pub beat_s: u32,
|
||||
}
|
||||
|
||||
/// The heartbeat's night: a daily window in UTC minutes (it may wrap midnight) and the Minds that sleep in it.
|
||||
/// The heartbeat alone decides who sleeps and when: one Sleep run per Mind per window, never made up if the window
|
||||
/// passes without one.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Night {
|
||||
pub from_min: u32,
|
||||
pub to_min: u32,
|
||||
pub minds: Vec<Slug>,
|
||||
}
|
||||
|
||||
impl Night {
|
||||
/// The nightly sleep from the two settings that name it: both or neither, so a half-set deploy fails at start
|
||||
/// instead of quietly never sleeping, or sleeping no one.
|
||||
pub fn from_settings(window: Option<&str>, minds: Option<&str>) -> Result<Option<Self>> {
|
||||
match (window, minds) {
|
||||
(Some(window), Some(minds)) => Self::parse(window, minds).map(Some),
|
||||
(None, None) => Ok(None),
|
||||
_ => bail!("HEARTBEAT_SLEEP_UTC and HEARTBEAT_SLEEP_MINDS are set together or not at all"),
|
||||
}
|
||||
}
|
||||
|
||||
/// `window` is `HH:MM-HH:MM` in UTC, `minds` the slugs comma-separated.
|
||||
pub fn parse(window: &str, minds: &str) -> Result<Self> {
|
||||
let minute = |text: &str| -> Result<u32> {
|
||||
let (hour, minute) = text.trim().split_once(':').ok_or_else(|| anyhow!("the night window is HH:MM-HH:MM"))?;
|
||||
let (hour, minute) = (hour.parse::<u32>()?, minute.parse::<u32>()?);
|
||||
if hour > 23 || minute > 59 {
|
||||
bail!("the night window is HH:MM-HH:MM");
|
||||
}
|
||||
Ok(hour * 60 + minute)
|
||||
};
|
||||
let (from, to) = window.split_once('-').ok_or_else(|| anyhow!("the night window is HH:MM-HH:MM"))?;
|
||||
let (from_min, to_min) = (minute(from)?, minute(to)?);
|
||||
if from_min == to_min {
|
||||
bail!("the night window is empty");
|
||||
}
|
||||
let minds: Vec<Slug> = minds.split(',').map(|slug| Slug(slug.trim().to_string())).filter(|slug| !slug.0.is_empty()).collect();
|
||||
if minds.is_empty() {
|
||||
bail!("no Mind is listed to sleep");
|
||||
}
|
||||
Ok(Self { from_min, to_min, minds })
|
||||
}
|
||||
|
||||
/// When the window `now` is inside opened, or none outside it.
|
||||
fn opened(&self, now: DateTime<Utc>) -> Option<DateTime<Utc>> {
|
||||
let minute = now.hour() * 60 + now.minute();
|
||||
let inside = if self.from_min < self.to_min { (self.from_min..self.to_min).contains(&minute) } else { minute >= self.from_min || minute < self.to_min };
|
||||
if !inside {
|
||||
return None;
|
||||
}
|
||||
let day = if minute >= self.from_min { now.date_naive() } else { now.date_naive().pred_opt()? };
|
||||
Some(day.and_hms_opt(self.from_min / 60, self.from_min % 60, 0)?.and_utc())
|
||||
}
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// Refuses no Persona, a Persona twice, or a beat of zero seconds.
|
||||
pub fn new(personas: Vec<PersonaId>, operators: Vec<String>, night: Option<Night>, beat_s: u32) -> Result<Self> {
|
||||
pub fn new(personas: Vec<PersonaId>, operators: Vec<String>, beat_s: u32) -> Result<Self> {
|
||||
if personas.is_empty() {
|
||||
bail!("no persona is configured");
|
||||
}
|
||||
|
|
@ -176,7 +118,6 @@ impl Config {
|
|||
Ok(Self {
|
||||
personas,
|
||||
operators,
|
||||
night,
|
||||
beat_s,
|
||||
})
|
||||
}
|
||||
|
|
@ -184,7 +125,7 @@ impl Config {
|
|||
|
||||
/// `heartbeat.cc`'s state: when the last beat fell, the operator messages
|
||||
/// already answered with a wake (once per message, bounded), and when the
|
||||
/// heartbeat last woke each Persona and last started each night.
|
||||
/// heartbeat last woke each Persona.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
|
||||
#[cultcache(type = "eureka.heartbeat.state.v1", schema = "HeartbeatState")]
|
||||
pub struct HeartbeatState {
|
||||
|
|
@ -196,9 +137,6 @@ pub struct HeartbeatState {
|
|||
/// When the heartbeat last started each Persona's turn, by instance slug.
|
||||
#[cultcache(key = 2, default)]
|
||||
pub last_turn_at: BTreeMap<String, DateTime<Utc>>,
|
||||
/// When the heartbeat last started each Persona's night, by instance slug.
|
||||
#[cultcache(key = 3, default)]
|
||||
pub last_night_at: BTreeMap<String, DateTime<Utc>>,
|
||||
}
|
||||
|
||||
const STATE_KEY: &str = "state";
|
||||
|
|
@ -507,10 +445,10 @@ enum Woke {
|
|||
Refused(String),
|
||||
}
|
||||
|
||||
/// The one way the heartbeat wakes a Persona, for a turn or her night: her brake
|
||||
/// read again, then her unit started unless it is active. No run is opened and
|
||||
/// nothing is admitted.
|
||||
fn wake(organs: &Organs, row: &Row, turn: RunTurn) -> Woke {
|
||||
/// The one way the heartbeat wakes a Persona: her brake read again, then her
|
||||
/// unit started unless it is active. No run is opened and nothing is admitted.
|
||||
fn wake(organs: &Organs, row: &Row) -> Woke {
|
||||
let turn = RunTurn::PersonaTurn;
|
||||
if !matches!(organs.control.effective(row.slug()), Effective::Released(_)) {
|
||||
return Woke::Refused("the brake is held".into());
|
||||
}
|
||||
|
|
@ -523,11 +461,6 @@ fn wake(organs: &Organs, row: &Row, turn: RunTurn) -> Woke {
|
|||
}
|
||||
}
|
||||
|
||||
/// What a wake is called in the trace: her slug and the turn.
|
||||
fn wake_label(slug: &Slug, turn: RunTurn) -> String {
|
||||
format!("{}:{turn:?}", slug.0)
|
||||
}
|
||||
|
||||
/// One poll.
|
||||
pub fn poll(organs: &Organs, config: &Config) -> Result<Outcome> {
|
||||
if let SwarmEffective::Held(reason) = organs.control.envelope() {
|
||||
|
|
@ -535,7 +468,7 @@ pub fn poll(organs: &Organs, config: &Config) -> Result<Outcome> {
|
|||
}
|
||||
let now = organs.clock.now();
|
||||
let stored = organs.store.load()?;
|
||||
let mut state = stored.clone().unwrap_or(HeartbeatState { last_beat_at: DateTime::<Utc>::UNIX_EPOCH, handled_mentions: vec![], last_turn_at: BTreeMap::new(), last_night_at: BTreeMap::new() });
|
||||
let mut state = stored.clone().unwrap_or(HeartbeatState { last_beat_at: DateTime::<Utc>::UNIX_EPOCH, handled_mentions: vec![], last_turn_at: BTreeMap::new() });
|
||||
let mut eventful = false;
|
||||
// The table as the last poll left it; unreadable counts as none, is noted in the trace, and is not overwritten.
|
||||
let (stored_addressing, addressing_unread) = match organs.store.load_addressing() {
|
||||
|
|
@ -592,14 +525,14 @@ pub fn poll(organs: &Organs, config: &Config) -> Result<Outcome> {
|
|||
.find(|key| !state.handled_mentions.contains(key))
|
||||
};
|
||||
let Some(key) = mentioned else { continue };
|
||||
match wake(organs, row, RunTurn::PersonaTurn) {
|
||||
match wake(organs, row) {
|
||||
Woke::Started => {
|
||||
state.handled_mentions.push(key);
|
||||
let excess = state.handled_mentions.len().saturating_sub(MENTIONS_KEPT);
|
||||
state.handled_mentions.drain(..excess);
|
||||
state.last_turn_at.insert(slug.0.clone(), now);
|
||||
row.busy = true;
|
||||
launches.push(wake_label(&slug, RunTurn::PersonaTurn));
|
||||
launches.push(slug.0.clone());
|
||||
launched.push(slug);
|
||||
}
|
||||
Woke::Busy => row.busy = true,
|
||||
|
|
@ -607,33 +540,6 @@ pub fn poll(organs: &Organs, config: &Config) -> Result<Outcome> {
|
|||
}
|
||||
}
|
||||
|
||||
// The night: inside the window, one night for a listed Mind who is idle and released and has not been started for one
|
||||
// since the window opened. The operator's mention went first above: she is busy then. A window that passes without a
|
||||
// night is not made up.
|
||||
if let Some(night) = &config.night
|
||||
&& let Some(opened) = night.opened(now)
|
||||
{
|
||||
for row in &mut rows {
|
||||
let slept = state.last_night_at.get(&row.slug().0).is_some_and(|slept| *slept >= opened);
|
||||
if !row.idle() || !night.minds.contains(row.slug()) || slept {
|
||||
continue;
|
||||
}
|
||||
match wake(organs, row, RunTurn::Sleep) {
|
||||
Woke::Started => {
|
||||
let slug = row.slug().clone();
|
||||
state.last_night_at.insert(slug.0.clone(), now);
|
||||
row.note = "asleep".into();
|
||||
row.busy = true;
|
||||
launches.push(wake_label(&slug, RunTurn::Sleep));
|
||||
launched.push(slug);
|
||||
break;
|
||||
}
|
||||
Woke::Busy => row.busy = true,
|
||||
Woke::Refused(why) => row.note = why,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// On the beat: when the beat has passed, one wake for the winner of the pick.
|
||||
let due = (now - state.last_beat_at).num_seconds() >= i64::from(beat_s);
|
||||
let standings: Vec<Standing> = rows
|
||||
|
|
@ -655,13 +561,13 @@ pub fn poll(organs: &Organs, config: &Config) -> Result<Outcome> {
|
|||
// one failing Mind never starves the others; a wake ends the beat.
|
||||
let mut passed: Vec<Standing> = standings.clone();
|
||||
while due && let Some(winner) = tempo::pick(&passed, beat_s) {
|
||||
match wake(organs, &rows[winner], RunTurn::PersonaTurn) {
|
||||
match wake(organs, &rows[winner]) {
|
||||
Woke::Started => {
|
||||
let slug = rows[winner].slug().clone();
|
||||
state.last_beat_at = now;
|
||||
state.last_turn_at.insert(slug.0.clone(), now);
|
||||
rows[winner].busy = true;
|
||||
launches.push(wake_label(&slug, RunTurn::PersonaTurn));
|
||||
launches.push(slug.0.clone());
|
||||
launched.push(slug);
|
||||
break;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@
|
|||
|
||||
use std::cell::{Cell, RefCell};
|
||||
|
||||
use chrono::{Duration, TimeZone};
|
||||
use chrono::Duration;
|
||||
use cultnet_rs::Selection;
|
||||
use eureka_pipeline::{PipelineDocument, PipelineKind as K};
|
||||
use huginn_mind::PipelineSelectionPage;
|
||||
|
|
@ -200,7 +200,7 @@ impl Rig {
|
|||
launcher: Recording::default(),
|
||||
clock: Fixed(Cell::new(at(1_000_000))),
|
||||
store: MemStore::default(),
|
||||
config: Config::new(vec![persona("ann", "Ann"), persona("bob", "Bob")], vec!["@op:chat".into()], None, BEAT_S).unwrap(),
|
||||
config: Config::new(vec![persona("ann", "Ann"), persona("bob", "Bob")], vec!["@op:chat".into()], BEAT_S).unwrap(),
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -230,7 +230,7 @@ impl Rig {
|
|||
|
||||
/// The stored state, made if there is none, changed by `change`.
|
||||
fn with_state(&self, change: impl FnOnce(&mut HeartbeatState)) {
|
||||
let mut state = self.store.state.borrow().clone().unwrap_or(HeartbeatState { last_beat_at: DateTime::<Utc>::UNIX_EPOCH, handled_mentions: vec![], last_turn_at: BTreeMap::new(), last_night_at: BTreeMap::new() });
|
||||
let mut state = self.store.state.borrow().clone().unwrap_or(HeartbeatState { last_beat_at: DateTime::<Utc>::UNIX_EPOCH, handled_mentions: vec![], last_turn_at: BTreeMap::new() });
|
||||
change(&mut state);
|
||||
*self.store.state.borrow_mut() = Some(state);
|
||||
}
|
||||
|
|
@ -293,7 +293,7 @@ fn each_persona_carries_her_own_huginn_and_a_missing_or_malformed_one_refuses_th
|
|||
for bad in ["ann,ann,Ann,@ann:chat", "ann,ann,Ann,@ann:chat,", "ann,ann,Ann,@ann:chat,127.0.0.1:4101", "ann,ann,Ann,@ann:chat,rudp://localhost:4101"] {
|
||||
assert!(PersonaId::parse(bad).is_err(), "{bad}");
|
||||
}
|
||||
assert!(Config::new(personas, vec![], None, 0).is_err(), "a beat of zero seconds is refused");
|
||||
assert!(Config::new(personas, vec![], 0).is_err(), "a beat of zero seconds is refused");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -316,7 +316,7 @@ fn a_beat_wakes_exactly_one_persona_the_one_who_has_waited_longest() {
|
|||
let state = rig.store.state.borrow().clone().unwrap();
|
||||
assert_eq!(state.last_turn_at.get("ann"), Some(&rig.now()), "the wake is her last turn");
|
||||
let trace = rig.store.traces.borrow().last().cloned().unwrap();
|
||||
assert_eq!((trace.tempo_s, trace.launches.clone()), (BEAT_S, vec!["ann:PersonaTurn".to_string()]));
|
||||
assert_eq!((trace.tempo_s, trace.launches.clone()), (BEAT_S, vec!["ann".to_string()]));
|
||||
assert!(trace.instances[ANN].busy);
|
||||
}
|
||||
|
||||
|
|
@ -573,19 +573,6 @@ fn a_persona_that_has_never_acted_goes_first() {
|
|||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into())] });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_heartbeat_holds_no_usage_port_so_usage_cannot_change_a_wake() {
|
||||
// `Organs` has no connector and no readout: the only inputs are the brakes, the minds, the mouths, the units and its own state.
|
||||
let rig = Rig::new();
|
||||
rig.turn(ANN, 3000);
|
||||
rig.turn(BOB, 1000);
|
||||
let first = rig.poll();
|
||||
let again = Rig::new();
|
||||
again.turn(ANN, 3000);
|
||||
again.turn(BOB, 1000);
|
||||
assert_eq!(first, again.poll());
|
||||
}
|
||||
|
||||
// ---- C2 of the Persona-only map: the heartbeat writes no mind and starts no Self run ----
|
||||
|
||||
#[test]
|
||||
|
|
@ -607,11 +594,10 @@ fn a_mind_whose_self_holds_briefs_gets_a_persona_wake_and_no_self_run() {
|
|||
|
||||
#[test]
|
||||
fn no_poll_admits_anything_to_any_mind_whatever_it_wakes() {
|
||||
let mut rig = Rig::new();
|
||||
rig.config.night = Some(Night::parse("13:00-14:00", "ann").unwrap());
|
||||
let rig = Rig::new();
|
||||
let runs_before: Vec<usize> = rig.minds.iter().map(|mind| mind.ids(K::Run).len()).collect();
|
||||
rig.say(BOB, delivery(1, "@op:chat", "Bob, a word", &[]));
|
||||
// One poll wakes bob off the beat and starts ann's night; the next beat wakes nobody else, both busy.
|
||||
// One poll wakes bob off the beat and ann on it; the next beat wakes one of them again.
|
||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("bob".into()), Slug("ann".into())] });
|
||||
rig.end_unit(ANN);
|
||||
rig.end_unit(BOB);
|
||||
|
|
@ -637,7 +623,7 @@ fn trace_at(seconds: i64, tempo_s: u32) -> PollTrace {
|
|||
}
|
||||
|
||||
fn state_at(milliseconds: i64) -> HeartbeatState {
|
||||
HeartbeatState { last_beat_at: crate::testkit::at(milliseconds), handled_mentions: vec!["ann:e1".into()], last_turn_at: BTreeMap::from([("ann".to_string(), crate::testkit::at(3))]), last_night_at: BTreeMap::new() }
|
||||
HeartbeatState { last_beat_at: crate::testkit::at(milliseconds), handled_mentions: vec!["ann:e1".into()], last_turn_at: BTreeMap::from([("ann".to_string(), crate::testkit::at(3))]) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -671,7 +657,7 @@ struct StateBeforeTheCut {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn a_state_written_before_the_cut_reads_with_no_turns_and_no_nights() {
|
||||
fn a_state_written_before_the_cut_reads_with_no_turns() {
|
||||
let dir = TempDir::new().unwrap();
|
||||
let path = dir.path().join("heartbeat.cc");
|
||||
let mut cache = CultCache::new();
|
||||
|
|
@ -680,7 +666,7 @@ fn a_state_written_before_the_cut_reads_with_no_turns_and_no_nights() {
|
|||
cache.pull_all_backing_stores().unwrap();
|
||||
cache.put(STATE_KEY, &StateBeforeTheCut { last_beat_at: crate::testkit::at(7), handled_mentions: vec!["ann:e1".into()] }).unwrap();
|
||||
let state = FileStore::new(&path).load().unwrap().expect("the old state reads");
|
||||
assert_eq!(state, HeartbeatState { last_beat_at: crate::testkit::at(7), handled_mentions: vec!["ann:e1".into()], last_turn_at: BTreeMap::new(), last_night_at: BTreeMap::new() });
|
||||
assert_eq!(state, HeartbeatState { last_beat_at: crate::testkit::at(7), handled_mentions: vec!["ann:e1".into()], last_turn_at: BTreeMap::new() });
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -710,118 +696,6 @@ fn the_file_store_reads_back_the_addressing_it_wrote_to_the_view() {
|
|||
assert_eq!(store.load_addressing().unwrap(), Some(table));
|
||||
}
|
||||
|
||||
// ---- The night ----
|
||||
|
||||
/// A night over the rig's clock, 13:31 UTC: the window holds it, `ann` sleeps.
|
||||
fn nights(window: &str, minds: &str) -> Box<Rig> {
|
||||
let mut rig = Rig::new();
|
||||
rig.config.night = Some(Night::parse(window, minds).unwrap());
|
||||
rig.turn(ANN, 10);
|
||||
rig.turn(BOB, 10);
|
||||
rig.beat_fell();
|
||||
rig
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_window_wraps_midnight_and_names_when_it_opened() {
|
||||
let night = Night::parse("22:00-04:00", "ann").unwrap();
|
||||
let on = |hour, minute| Utc.with_ymd_and_hms(2026, 10, 9, hour, minute, 0).unwrap();
|
||||
assert_eq!(night.opened(on(23, 0)), Some(on(22, 0)));
|
||||
assert_eq!(night.opened(on(2, 0)), Some(on(22, 0) - Duration::days(1)), "after midnight it opened yesterday");
|
||||
assert_eq!(night.opened(on(4, 0)), None, "the end is outside");
|
||||
assert_eq!(night.opened(on(13, 0)), None);
|
||||
assert_eq!(Night::parse("13:00-14:00", "ann").unwrap().opened(on(13, 0)), Some(on(13, 0)), "the start is inside");
|
||||
assert!(Night::parse("13:00-13:00", "ann").is_err() && Night::parse("25:00-03:00", "ann").is_err() && Night::parse("13:00-14:00", " , ").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_keeps_its_minutes_and_its_bounds_are_the_clock() {
|
||||
let on = |hour, minute| Utc.with_ymd_and_hms(2026, 10, 9, hour, minute, 0).unwrap();
|
||||
let night = Night::parse("22:30-04:15", "ann").unwrap();
|
||||
assert_eq!((night.from_min, night.to_min), (22 * 60 + 30, 4 * 60 + 15));
|
||||
assert_eq!(night.opened(on(22, 29)), None);
|
||||
assert_eq!(night.opened(on(22, 30)), Some(on(22, 30)));
|
||||
assert_eq!(night.opened(on(4, 14)), Some(on(22, 30) - Duration::days(1)));
|
||||
assert_eq!(night.opened(on(4, 15)), None);
|
||||
// The last minute of the day is a time, and the first one past it is not.
|
||||
let late = Night::parse("23:59-00:00", "ann").unwrap();
|
||||
assert_eq!((late.from_min, late.to_min), (23 * 60 + 59, 0));
|
||||
assert_eq!(Night::parse("00:00-23:00", "ann").unwrap().to_min, 23 * 60);
|
||||
assert_eq!(Night::parse("12:00-12:59", "ann").unwrap().to_min, 12 * 60 + 59);
|
||||
for bad in ["24:00-03:00", "22:00-24:00", "22:60-03:00", "22:00-03:60", "22:00", "22-03", "aa:bb-03:00"] {
|
||||
assert!(Night::parse(bad, "ann").is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_nightly_sleep_is_both_settings_or_neither() {
|
||||
assert_eq!(Night::from_settings(None, None).unwrap(), None);
|
||||
let night = Night::from_settings(Some("22:30-04:00"), Some("ann, bob")).unwrap().unwrap();
|
||||
assert_eq!((night.from_min, night.to_min, night.minds), (22 * 60 + 30, 4 * 60, vec![Slug("ann".into()), Slug("bob".into())]));
|
||||
for only in [Night::from_settings(Some("22:30-04:00"), None), Night::from_settings(None, Some("ann"))] {
|
||||
let fault = only.expect_err("a half-set night is refused at start").to_string();
|
||||
assert!(fault.contains("HEARTBEAT_SLEEP_UTC") && fault.contains("HEARTBEAT_SLEEP_MINDS"), "{fault}");
|
||||
}
|
||||
assert!(Night::from_settings(Some("nonsense"), Some("ann")).is_err(), "both set, but not a window");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_listed_idle_mind_sleeps_once_per_window_and_a_missed_night_is_not_made_up() {
|
||||
let rig = nights("13:00-14:00", "ann");
|
||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] });
|
||||
assert_eq!(rig.started_turns(), vec![("ann".to_string(), RunTurn::Sleep)], "bob is not listed, and the beat has just fallen");
|
||||
assert_eq!(rig.store.state.borrow().as_ref().unwrap().last_night_at.get("ann"), Some(&rig.now()));
|
||||
// Busy while the night lasts: nothing more. Then her unit ends and the window is spent for her.
|
||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] });
|
||||
rig.launcher.kill_as(&Slug("ann".into()), RunTurn::Sleep);
|
||||
rig.advance(60);
|
||||
rig.beat_fell();
|
||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] }, "one night per window, whatever became of it");
|
||||
assert_eq!(rig.started_turns().len(), 1);
|
||||
// The next window opens a day later and she sleeps again.
|
||||
rig.advance(24 * 3600);
|
||||
rig.beat_fell();
|
||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_night_outside_the_window_for_an_unlisted_mind_or_after_the_window_passed_busy() {
|
||||
let outside = nights("22:00-04:00", "ann,bob");
|
||||
assert_eq!(outside.poll(), Outcome::Polled { launched: vec![] });
|
||||
assert!(outside.started_turns().is_empty());
|
||||
// She is awake (her unit active) when the window opens and until it closes: the night is not made up after.
|
||||
let rig = nights("13:00-14:00", "ann");
|
||||
rig.in_a_turn(ANN);
|
||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] });
|
||||
rig.advance(3600);
|
||||
rig.end_unit(ANN);
|
||||
rig.beat_fell();
|
||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![] });
|
||||
assert!(rig.started_turns().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_operator_goes_first_and_the_night_waits_for_her_to_be_idle() {
|
||||
let rig = nights("13:00-14:00", "ann");
|
||||
rig.say(ANN, delivery(1, "@op:chat", "Ann, a word", &[]));
|
||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] });
|
||||
assert_eq!(rig.started_turns(), vec![("ann".to_string(), RunTurn::PersonaTurn)], "the mention is answered awake, no night that poll");
|
||||
rig.end_unit(ANN);
|
||||
rig.chats[ANN].deliveries.borrow_mut().clear();
|
||||
rig.advance(60);
|
||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into())] });
|
||||
assert_eq!(rig.started_turns().last(), Some(&("ann".to_string(), RunTurn::Sleep)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sleeping_mind_is_not_eligible_for_the_beat() {
|
||||
let rig = nights("13:00-14:00", "ann");
|
||||
rig.with_state(|state| state.last_beat_at = DateTime::<Utc>::UNIX_EPOCH);
|
||||
rig.turn(ANN, 100_000);
|
||||
assert_eq!(rig.poll(), Outcome::Polled { launched: vec![Slug("ann".into()), Slug("bob".into())] });
|
||||
assert_eq!(rig.started_turns(), vec![("ann".to_string(), RunTurn::Sleep), ("bob".to_string(), RunTurn::PersonaTurn)], "the beat went to the Mind who was awake, though ann had waited longer");
|
||||
}
|
||||
|
||||
/// Matrix's word that a message is her DM, a tag or a reply wakes her off the beat from the operator; a notice or an edit never does,
|
||||
/// whatever its basis, and a stranger's direct message is delivered but wakes no one.
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -36,14 +36,6 @@ fn a_unit_configured_from_its_environment_alone_reaches_the_gate_and_ends_dead()
|
|||
assert!(text(&output.stdout).starts_with("dead:"), "{}", text(&output.stdout));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flag_overrides_the_environment() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
// The rooms flag replaces the rooms the environment names.
|
||||
let flagged = run(dir.path(), &[], &[], &["--instance", "eureka", "--rooms", "#swarm:chat"]);
|
||||
assert_eq!(flagged.status.code(), Some(0), "{}", text(&flagged.stderr));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_setting_that_is_missing_or_wrong_ends_two_naming_the_setting_and_no_value() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
|
|
|||
Loading…
Reference in a new issue