Map: docs/persona-only-heartbeat-map.md (imagination/persona-only-heartbeat,
d861574), cut C2. Rulings: eureka-body:ruling:persona-only-heartbeat (she
reads the Mind and never writes it; no Self runs from the Persona).
Persona organ (persona.rs 3983 -> ~420 lines): deleted the live session
organ whole: TURN_INSTRUCTION, TURN_REMINDER, MESSAGES_HEADER, WORK_QUESTION,
ANSWER_MESSAGES, WAKE_ASK, WORK_TAIL; PersonaReply with intent, remember,
rule, settle, start_self_run, tempo vote and urgency, and reply_schema; the
doctrine and persona-JSON system prompt (read_doctrine, render_instructions,
campaigns); start_session, persona_args, PersonaInbox; act, decode_reply and
every admission (memories, rulings, settles, pulses, follow-ups, run closure);
start_self_run; the responsibilities, recent-runs and wear renderers;
render_input and render_tempo. carry reads the brakes and answers Dead or
NoOrgan; a start writes nothing and records no run. Kept per the map's keep
list for C3: Config (doctrine, image store and fetch fields cut with their
consumers), the brake read, the chat-addressing helpers, the tail renderer
and FileTrace; uncalled ones carry allow(dead_code) naming C3.
Night: sleep.rs is deleted. It was a Mind-writing session built on the
deleted prelude; C4 retargets its contract from history.
attachment.rs is deleted with the reply's save_attachment, its one caller.
chat_image's loader and recall.rs stay for C3 under allow(dead_code).
Heartbeat: no Mind writes. A wake is a plain unit start through the
Launcher (brake, then alive, then start); busy is the unit's own state.
Deleted the Self-run branch (claimable briefs), the self-ended wake, tempo
votes and declared urgency (standing_vote, pending_urgency, last_self_end)
and the run-based last_turn and last_sleep reads; HeartbeatState gains
last_turn_at and last_night_at (default slots, so a state written before
this cut still decodes). The beat is HEARTBEAT_BEAT_S, default 1800 s.
InstanceTrace.vote_beat_s stays as an always-none slot so heartbeat.cc's
older trace records still decode. HeartbeatView loses latest; the
timeline reads FileStore::latest.
tempo.rs: tally, fallback_beat and the PID controller and its sim are
deleted; pick and score stay, without self_permille.
Tests that pinned deleted behaviour are deleted with it; surviving ones are
kept, and two heartbeat tests pin the cut: a Mind with claimable briefs gets
a Persona wake and no Self run, and no poll admits anything to any mind.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
715 lines
28 KiB
Rust
715 lines
28 KiB
Rust
//! The heartbeat: the one process that decides which Persona wakes and when
|
|
//! (rulings `eureka-body:ruling:persona-only-heartbeat`,
|
|
//! `operator-mention-fills-initiative`).
|
|
//!
|
|
//! The beat is the configured `Config::beat_s`. When a beat falls (the beat has
|
|
//! passed since the last one) exactly one Persona wakes: `tempo::pick` over the
|
|
//! 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.
|
|
//!
|
|
//! 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.
|
|
//!
|
|
//! A held swarm brake ends the poll before the mind or the mouth is touched.
|
|
|
|
use std::collections::BTreeMap;
|
|
use std::fmt;
|
|
use std::net::SocketAddr;
|
|
use std::path::PathBuf;
|
|
|
|
use anyhow::{Context, Result, anyhow, bail};
|
|
use chrono::{DateTime, SecondsFormat, Timelike, Utc};
|
|
use cultcache_rs::{CultCache, DatabaseEntry, SingleFileMessagePackBackingStore};
|
|
use eureka_pipeline::{OrgRepo, PipelineKind, RunTurn, Slug};
|
|
use huginn_mind::PipelineFacts;
|
|
|
|
use crate::address::{Addressee, Name, is_for, project_names};
|
|
use crate::chat_client::{Chat, ChatDelivery};
|
|
use crate::control::{ControlSource, Effective, FileSource, HeldReason, SwarmEffective, read_effective, read_envelope, set_mode_world_readable};
|
|
use crate::launch::{Clock, Launcher};
|
|
use crate::queue::{MindPort, headers, in_force, of_kind};
|
|
use crate::tempo::{self, Standing};
|
|
|
|
/// How many handled operator mentions the state remembers.
|
|
const MENTIONS_KEPT: usize = 64;
|
|
/// The most pages of pending chat one poll reads for one Persona.
|
|
const PENDING_PAGES: usize = 16;
|
|
/// The beat, in seconds, when `HEARTBEAT_BEAT_S` is not set.
|
|
pub const DEFAULT_BEAT_S: u32 = 1800;
|
|
|
|
/// Who a Persona is, for the two things the heartbeat matches on: the Matrix
|
|
/// user id its tags carry, and the names a message may call it by. Each Mind is
|
|
/// its own Huginn daemon, so the entry also carries the daemon the Persona's
|
|
/// control, runs and launches are read from.
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub struct PersonaId {
|
|
pub slug: Slug,
|
|
pub public_name: String,
|
|
pub handle: String,
|
|
pub matrix_id: String,
|
|
pub huginn: SocketAddr,
|
|
}
|
|
|
|
impl PersonaId {
|
|
/// `slug,handle,Public Name,@user:server,rudp://<ip>:<port>`.
|
|
pub fn parse(spec: &str) -> Result<Self> {
|
|
const SHAPE: &str =
|
|
"a persona is slug,handle,public name,matrix id,rudp://<ip>:<port> of her Huginn";
|
|
let parts: Vec<&str> = spec.split(',').map(str::trim).collect();
|
|
let [slug, handle, public_name, matrix_id, huginn] = parts.as_slice() else {
|
|
bail!(SHAPE)
|
|
};
|
|
if parts.iter().any(|part| part.is_empty()) {
|
|
bail!(SHAPE);
|
|
}
|
|
let huginn = huginn
|
|
.strip_prefix("rudp://")
|
|
.and_then(|address| address.parse::<SocketAddr>().ok())
|
|
.ok_or_else(|| anyhow!(SHAPE))?;
|
|
let slug = Slug((*slug).to_string());
|
|
slug.validate_slug()
|
|
.map_err(|_| anyhow!("a persona's slug is not a slug"))?;
|
|
Ok(Self {
|
|
slug,
|
|
public_name: (*public_name).to_string(),
|
|
handle: (*handle).to_string(),
|
|
matrix_id: (*matrix_id).to_string(),
|
|
huginn,
|
|
})
|
|
}
|
|
}
|
|
|
|
/// What the heartbeat is told that is not in the mind or the swarm store.
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
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> {
|
|
if personas.is_empty() {
|
|
bail!("no persona is configured");
|
|
}
|
|
if beat_s == 0 {
|
|
bail!("the beat is zero seconds");
|
|
}
|
|
for (index, persona) in personas.iter().enumerate() {
|
|
if personas
|
|
.iter()
|
|
.skip(index + 1)
|
|
.any(|other| other.slug == persona.slug)
|
|
{
|
|
bail!("a persona is configured twice");
|
|
}
|
|
}
|
|
Ok(Self {
|
|
personas,
|
|
operators,
|
|
night,
|
|
beat_s,
|
|
})
|
|
}
|
|
}
|
|
|
|
/// `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.
|
|
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
|
|
#[cultcache(type = "eureka.heartbeat.state.v1", schema = "HeartbeatState")]
|
|
pub struct HeartbeatState {
|
|
#[cultcache(key = 0)]
|
|
pub last_beat_at: DateTime<Utc>,
|
|
/// `<instance>:<event id>` of each operator message that woke a Persona.
|
|
#[cultcache(key = 1)]
|
|
pub handled_mentions: Vec<String>,
|
|
/// 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";
|
|
|
|
/// The swarm's addressing as the heartbeat last read it: each Mind's Matrix id and the names a delivery may call her (her own and her
|
|
/// projects'), in roster order. A cache of the stewardship records, written only by the heartbeat's poll; the Personas read it to rank
|
|
/// and show whom a delivery is for.
|
|
#[derive(Clone, Debug, Default, PartialEq, Eq, DatabaseEntry)]
|
|
#[cultcache(type = "eureka.heartbeat.addressing.v1", schema = "HeartbeatAddressing")]
|
|
pub struct Addressing {
|
|
#[cultcache(key = 0)]
|
|
pub minds: Vec<Addressee>,
|
|
}
|
|
|
|
const ADDRESSING_KEY: &str = "addressing";
|
|
|
|
/// One instance's line in a poll's trace.
|
|
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
|
pub struct InstanceTrace {
|
|
pub instance: String,
|
|
/// Retired: always none. Kept so the records `heartbeat.cc` holds from before the cut still decode (nothing migrates the file).
|
|
pub vote_beat_s: Option<u32>,
|
|
/// The urgency in force for her: 1000 when a member addresses her, else 0.
|
|
pub urgency_permille: u16,
|
|
/// A member's pending message addresses her.
|
|
pub addressed: bool,
|
|
pub busy: bool,
|
|
pub released: bool,
|
|
/// Seconds since her newest Persona turn; -1 when she has had none.
|
|
pub idle_s: i64,
|
|
/// `tempo::score` as text; empty when she was not eligible for the beat.
|
|
pub score: String,
|
|
pub note: String,
|
|
}
|
|
|
|
/// One poll that changed anything.
|
|
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
|
|
#[cultcache(type = "eureka.heartbeat.poll_trace.v1", schema = "HeartbeatPollTrace")]
|
|
pub struct PollTrace {
|
|
#[cultcache(key = 0)]
|
|
pub at: DateTime<Utc>,
|
|
/// The beat in force: `Config::beat_s`.
|
|
#[cultcache(key = 1)]
|
|
pub tempo_s: u32,
|
|
#[cultcache(key = 2)]
|
|
pub instances: Vec<InstanceTrace>,
|
|
#[cultcache(key = 3)]
|
|
pub launches: Vec<String>,
|
|
}
|
|
|
|
impl fmt::Display for PollTrace {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
writeln!(f, "poll at {} tempo {}s", self.at.to_rfc3339_opts(SecondsFormat::Secs, true), self.tempo_s)?;
|
|
for row in &self.instances {
|
|
write!(
|
|
f,
|
|
" {}: urgency {} addressed {} busy {} released {} idle {}s score {:?}",
|
|
row.instance, row.urgency_permille, row.addressed, row.busy, row.released, row.idle_s, row.score
|
|
)?;
|
|
if !row.note.is_empty() {
|
|
write!(f, " note {}", row.note)?;
|
|
}
|
|
writeln!(f)?;
|
|
}
|
|
for launch in &self.launches {
|
|
writeln!(f, " launched {launch}")?;
|
|
}
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
/// `heartbeat.cc`: the state and the trace, one writer.
|
|
pub trait Store {
|
|
fn load(&self) -> Result<Option<HeartbeatState>>;
|
|
fn save(&self, state: &HeartbeatState) -> Result<()>;
|
|
fn record(&self, trace: &PollTrace) -> Result<()>;
|
|
fn load_addressing(&self) -> Result<Option<Addressing>>;
|
|
fn save_addressing(&self, addressing: &Addressing) -> Result<()>;
|
|
}
|
|
|
|
/// What a Persona unit may read of `heartbeat.cc`: the swarm's addressing. Read-only.
|
|
pub trait HeartbeatView {
|
|
fn addressing(&self) -> Result<Option<Addressing>>;
|
|
}
|
|
|
|
/// The store as a CultCache single-file store under the unit's state directory.
|
|
/// It registers the state, the trace and the addressing and nothing else: a file still holding
|
|
/// any older document does not decode, and every use of it fails
|
|
/// naming the file. It is never migrated.
|
|
pub struct FileStore {
|
|
path: PathBuf,
|
|
}
|
|
|
|
impl FileStore {
|
|
pub fn new(path: impl Into<PathBuf>) -> Self {
|
|
Self { path: path.into() }
|
|
}
|
|
|
|
fn registered() -> Result<CultCache> {
|
|
let mut cache = CultCache::new();
|
|
cache.register_entry_type::<HeartbeatState>()?;
|
|
cache.register_entry_type::<PollTrace>()?;
|
|
cache.register_entry_type::<Addressing>()?;
|
|
Ok(cache)
|
|
}
|
|
|
|
fn open(&self) -> Result<CultCache> {
|
|
let mut cache = Self::registered()?;
|
|
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&self.path))?;
|
|
cache.pull_all_backing_stores().with_context(|| self.refusal())?;
|
|
// A pull now carries a record no registered type claims instead of refusing it; the writer still must not write beside one.
|
|
if !cache.foreign_records().is_empty() {
|
|
return Err(anyhow!(self.refusal()));
|
|
}
|
|
Ok(cache)
|
|
}
|
|
|
|
fn refusal(&self) -> String {
|
|
format!("{} holds a document this heartbeat does not read (an old initiative store?): archive it, nothing migrates it", self.path.display())
|
|
}
|
|
|
|
/// The startup check: the file decodes, or does not exist.
|
|
pub fn check(&self) -> Result<()> {
|
|
self.load().map(|_| ())
|
|
}
|
|
|
|
fn settle(&self) -> Result<()> {
|
|
set_mode_world_readable(&self.path)
|
|
}
|
|
}
|
|
|
|
impl Store for FileStore {
|
|
fn load(&self) -> Result<Option<HeartbeatState>> {
|
|
self.snapshot()?.get::<HeartbeatState>(STATE_KEY)
|
|
}
|
|
|
|
fn save(&self, state: &HeartbeatState) -> Result<()> {
|
|
self.open()?.put(STATE_KEY, state)?;
|
|
self.settle()
|
|
}
|
|
|
|
fn record(&self, trace: &PollTrace) -> Result<()> {
|
|
self.open()?.put(format!("{:020}", trace.at.timestamp_millis()), trace)?;
|
|
self.settle()
|
|
}
|
|
|
|
fn load_addressing(&self) -> Result<Option<Addressing>> {
|
|
self.snapshot()?.get::<Addressing>(ADDRESSING_KEY)
|
|
}
|
|
|
|
fn save_addressing(&self, addressing: &Addressing) -> Result<()> {
|
|
self.open()?.put(ADDRESSING_KEY, addressing)?;
|
|
self.settle()
|
|
}
|
|
}
|
|
|
|
impl FileStore {
|
|
/// The newest poll trace: what `mind-heartbeat timeline` prints.
|
|
pub fn latest(&self) -> Result<Option<PollTrace>> {
|
|
let mut all = self.snapshot()?.get_all_with_keys::<PollTrace>()?;
|
|
all.sort_by(|a, b| a.0.cmp(&b.0));
|
|
Ok(all.pop().map(|(_, trace)| trace))
|
|
}
|
|
|
|
/// The file read without a lock and without a write, as the control stores are.
|
|
fn snapshot(&self) -> Result<CultCache> {
|
|
let mut cache = Self::registered()?;
|
|
for envelope in FileSource::new(&self.path).snapshot().with_context(|| self.refusal())? {
|
|
cache.put_raw_envelope(envelope).with_context(|| self.refusal())?;
|
|
}
|
|
Ok(cache)
|
|
}
|
|
}
|
|
|
|
impl HeartbeatView for FileStore {
|
|
fn addressing(&self) -> Result<Option<Addressing>> {
|
|
self.load_addressing()
|
|
}
|
|
}
|
|
|
|
/// What the operator stores allow: the swarm brake, and each instance's own
|
|
/// reading (its brake and the swarm brake).
|
|
pub trait Control {
|
|
fn envelope(&self) -> SwarmEffective;
|
|
fn effective(&self, instance: &Slug) -> Effective;
|
|
}
|
|
|
|
/// The root-owned stores, through the one fail-closed readers.
|
|
pub struct FileControl;
|
|
|
|
impl Control for FileControl {
|
|
fn envelope(&self) -> SwarmEffective {
|
|
read_envelope()
|
|
}
|
|
|
|
fn effective(&self, instance: &Slug) -> Effective {
|
|
read_effective(instance)
|
|
}
|
|
}
|
|
|
|
/// One configured Persona organs: her mind and her mouth.
|
|
pub struct Seat<'a> {
|
|
pub who: PersonaId,
|
|
pub mind: &'a dyn MindPort,
|
|
pub chat: &'a dyn Chat,
|
|
}
|
|
|
|
pub struct Organs<'a> {
|
|
pub seats: &'a [Seat<'a>],
|
|
pub control: &'a dyn Control,
|
|
pub launcher: &'a dyn Launcher,
|
|
pub clock: &'a dyn Clock,
|
|
pub store: &'a dyn Store,
|
|
}
|
|
|
|
/// What one poll did. Every outcome is an answer; only a store that cannot be
|
|
/// reached is an error.
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub enum Outcome {
|
|
/// The swarm brake is held; nothing else was touched.
|
|
Held(HeldReason),
|
|
Polled {
|
|
launched: Vec<Slug>,
|
|
},
|
|
}
|
|
|
|
impl fmt::Display for Outcome {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
match self {
|
|
Self::Held(reason) => write!(f, "held: {reason:?}"),
|
|
Self::Polled { launched } if launched.is_empty() => f.write_str("polled: no launch"),
|
|
Self::Polled { launched } => write!(f, "polled: launched {}", launched.iter().map(|slug| slug.0.as_str()).collect::<Vec<_>>().join(", ")),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Every repo she stewards in force and the chat names of those repos: one query on her mind.
|
|
pub(crate) fn stewardships_of(mind: &dyn MindPort) -> Result<(Vec<Name>, Vec<OrgRepo>)> {
|
|
let (mut names, mut repos) = (Vec::new(), Vec::new());
|
|
for header in headers(mind, &in_force(of_kind(PipelineKind::Stewardship)))? {
|
|
if let PipelineFacts::Stewardship { repo, names: listed, .. } = &header.facts {
|
|
names.extend(project_names(repo, listed));
|
|
repos.push(repo.clone());
|
|
}
|
|
}
|
|
Ok((names, repos))
|
|
}
|
|
|
|
/// Whether a delivery wakes `who` off the beat: the operator or another Mind of
|
|
/// the roster addresses her. A Mind naming herself does not; a member does not.
|
|
fn wakes(config: &Config, who: &Addressee, delivery: &ChatDelivery) -> bool {
|
|
let from_operator = config.operators.contains(&delivery.sender);
|
|
let from_other_mind = delivery.sender != who.matrix_id() && config.personas.iter().any(|mind| mind.matrix_id == delivery.sender);
|
|
(from_operator || from_other_mind) && is_for(who, delivery)
|
|
}
|
|
|
|
/// The mouth pages a pending answer, so fewer deliveries may come than wait.
|
|
/// The heartbeat acks nothing: it asks again after the highest seq it has until
|
|
/// the answer is empty. A mouth that never empties is cut off at `PENDING_PAGES`.
|
|
fn read_pending(chat: &dyn Chat) -> Result<Vec<ChatDelivery>> {
|
|
let mut all: Vec<ChatDelivery> = Vec::new();
|
|
let mut after = 0;
|
|
for _ in 0..PENDING_PAGES {
|
|
let page = chat.pending(after)?.deliveries;
|
|
let Some(top) = page.iter().map(|delivery| delivery.seq).max() else {
|
|
break;
|
|
};
|
|
if top <= after {
|
|
break;
|
|
}
|
|
after = top;
|
|
all.extend(page);
|
|
}
|
|
Ok(all)
|
|
}
|
|
|
|
struct Row<'a> {
|
|
seat: &'a Seat<'a>,
|
|
released: bool,
|
|
/// Her unit is active.
|
|
busy: bool,
|
|
pending: Vec<ChatDelivery>,
|
|
/// Whom a delivery may address in her: her roster names and her projects' names as the last poll that read her pending chat left them.
|
|
addressee: Addressee,
|
|
note: String,
|
|
}
|
|
|
|
impl Row<'_> {
|
|
fn slug(&self) -> &Slug {
|
|
&self.seat.who.slug
|
|
}
|
|
|
|
fn idle(&self) -> bool {
|
|
self.released && !self.busy
|
|
}
|
|
|
|
/// A member (not the operator) has a pending message that names or tags her.
|
|
fn addressed_by_member(&self, config: &Config) -> bool {
|
|
self.pending.iter().any(|delivery| !config.operators.contains(&delivery.sender) && is_for(&self.addressee, delivery))
|
|
}
|
|
}
|
|
|
|
enum Woke {
|
|
Started,
|
|
Busy,
|
|
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 {
|
|
if !matches!(organs.control.effective(row.slug()), Effective::Released(_)) {
|
|
return Woke::Refused("the brake is held".into());
|
|
}
|
|
if organs.launcher.alive(row.slug(), turn) {
|
|
return Woke::Busy;
|
|
}
|
|
match organs.launcher.start(row.slug(), turn) {
|
|
Ok(()) => Woke::Started,
|
|
Err(error) => Woke::Refused(format!("start failed: {error}")),
|
|
}
|
|
}
|
|
|
|
/// 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() {
|
|
return Ok(Outcome::Held(reason));
|
|
}
|
|
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 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() {
|
|
Ok(found) => (found.unwrap_or_default(), None),
|
|
Err(error) => (Addressing::default(), Some(format!("addressing unread: {error}"))),
|
|
};
|
|
|
|
let mut rows: Vec<Row> = Vec::new();
|
|
for seat in organs.seats {
|
|
let released = matches!(organs.control.effective(&seat.who.slug), Effective::Released(_));
|
|
let busy = organs.launcher.alive(&seat.who.slug, RunTurn::PersonaTurn);
|
|
// Her last-read names when the table holds her, else her roster names alone.
|
|
let roster = Addressee::new(&seat.who.matrix_id, [seat.who.public_name.as_str(), seat.who.handle.as_str()]);
|
|
let kept = stored_addressing.minds.iter().find(|stored| stored.matrix_id() == seat.who.matrix_id).cloned().unwrap_or_else(|| roster.clone());
|
|
let mut row = Row { seat, released, busy, pending: vec![], addressee: kept, note: String::new() };
|
|
// Pending chat, read-only, for a released Mind.
|
|
if row.released {
|
|
match read_pending(seat.chat) {
|
|
Ok(deliveries) => row.pending = deliveries,
|
|
Err(_) => {
|
|
eventful = true;
|
|
row.note = "chat: pending failed".into();
|
|
}
|
|
}
|
|
// Her projects' names address her too; read only when something is pending. A failed read keeps her last-read row.
|
|
if !row.pending.is_empty() {
|
|
match stewardships_of(seat.mind) {
|
|
Ok((names, repos)) => row.addressee = roster.with_stewardships(names, repos),
|
|
Err(error) => row.note = format!("{} stewardship names unread: {error}", row.note).trim().to_string(),
|
|
}
|
|
}
|
|
}
|
|
rows.push(row);
|
|
}
|
|
|
|
let beat_s = config.beat_s;
|
|
let mut launches: Vec<String> = Vec::new();
|
|
let mut launched: Vec<Slug> = Vec::new();
|
|
|
|
// Off the beat: the operator or another Mind of the roster naming her, once per message. It does not wait for the beat;
|
|
// it needs her idle and released.
|
|
for row in &mut rows {
|
|
if !row.idle() {
|
|
continue;
|
|
}
|
|
let slug = row.slug().clone();
|
|
let mentioned = {
|
|
let mut pending: Vec<&ChatDelivery> = row.pending.iter().collect();
|
|
pending.sort_by_key(|delivery| delivery.seq);
|
|
pending
|
|
.into_iter()
|
|
.filter(|delivery| wakes(config, &row.addressee, delivery))
|
|
.map(|delivery| format!("{}:{}", slug.0, delivery.event_id))
|
|
.find(|key| !state.handled_mentions.contains(key))
|
|
};
|
|
let Some(key) = mentioned else { continue };
|
|
match wake(organs, row, RunTurn::PersonaTurn) {
|
|
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));
|
|
launched.push(slug);
|
|
}
|
|
Woke::Busy => row.busy = true,
|
|
Woke::Refused(why) => row.note = why,
|
|
}
|
|
}
|
|
|
|
// 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
|
|
.iter()
|
|
.map(|row| {
|
|
let last = state.last_turn_at.get(&row.slug().0).copied();
|
|
Standing {
|
|
slug: row.slug().0.clone(),
|
|
eligible: row.idle(),
|
|
waited_s: last.map(|turn| u64::try_from((now - turn).num_seconds()).unwrap_or(0)),
|
|
last_turn_ms: last.map(|turn| turn.timestamp_millis()),
|
|
// The seam for topic subscriptions (a later cut): a Mind's nearest subscription scores her deliveries here.
|
|
topic_permille: 0,
|
|
addressed_by_member: row.addressed_by_member(config),
|
|
}
|
|
})
|
|
.collect();
|
|
// A winner whose unit cannot start loses the beat to the next of the pick, so
|
|
// 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) {
|
|
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));
|
|
launched.push(slug);
|
|
break;
|
|
}
|
|
Woke::Busy => rows[winner].busy = true,
|
|
Woke::Refused(why) => rows[winner].note = why,
|
|
}
|
|
passed[winner].eligible = false;
|
|
}
|
|
|
|
if stored.as_ref() != Some(&state) {
|
|
organs.store.save(&state)?;
|
|
}
|
|
let addressing = Addressing { minds: rows.iter().map(|row| row.addressee.clone()).collect() };
|
|
match addressing_unread {
|
|
None if addressing != stored_addressing => organs.store.save_addressing(&addressing)?,
|
|
None => {}
|
|
Some(note) => {
|
|
eventful = true;
|
|
if let Some(first) = rows.first_mut() {
|
|
first.note = format!("{} {note}", first.note).trim().to_string();
|
|
}
|
|
}
|
|
}
|
|
if eventful || !launches.is_empty() || rows.iter().any(|row| !row.note.is_empty()) {
|
|
let trace = PollTrace {
|
|
at: now,
|
|
tempo_s: beat_s,
|
|
instances: rows
|
|
.iter()
|
|
.zip(&standings)
|
|
.map(|(row, standing)| InstanceTrace {
|
|
instance: row.slug().0.clone(),
|
|
vote_beat_s: None,
|
|
urgency_permille: tempo::urgency_permille(standing),
|
|
addressed: standing.addressed_by_member,
|
|
busy: row.busy,
|
|
released: row.released,
|
|
idle_s: standing.waited_s.map_or(-1, |waited| i64::try_from(waited).unwrap_or(i64::MAX)),
|
|
score: if standing.eligible { format!("{:.3}", tempo::score(standing, beat_s)) } else { String::new() },
|
|
note: row.note.clone(),
|
|
})
|
|
.collect(),
|
|
launches,
|
|
};
|
|
organs.store.record(&trace).context("the heartbeat trace could not be written")?;
|
|
}
|
|
Ok(Outcome::Polled { launched })
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests;
|