Skip to main content

agentmux_srv_core/backend/
quiet_watch.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A leader is told when an agent that owes it work has gone quiet
5//! (docs/specs/SPEC_LEADER_TOLD_WHEN_AN_AGENT_GOES_QUIET_2026_11_21.md, phase 1).
6//!
7//! An agent is **watched** while it owes work: it holds a claimed Kanban task (not on hold, not waiting on an
8//! answer), or it is a spawned worker that has not reported to its leader since the leader last messaged it. It
9//! is **quiet** when it has done nothing for the quiet time: no output, no message sent, no update of a task it
10//! holds. A sweep every 30 seconds reads that from memory (no model call, no poll of the agent): an agent between
11//! turns gets one nudge (a system turn) and, five minutes after it, its watchers are told; a turn that is still
12//! running and has written nothing for the longer running time gets its watchers told, with no nudge.
13//!
14//! The decision (`Watch::step`) is pure, so the timeline is tested with a fake clock; `sweep` reads the stores
15//! and the controllers and delivers.
16
17use std::collections::{HashMap, HashSet};
18use std::sync::{Arc, LazyLock};
19
20use crate::backend::agent_state::AgentState;
21use crate::backend::obj::MetaMapType;
22use crate::backend::work_facts::live_phrase;
23use crate::backend::storage::agents::AgentDefinition;
24use crate::backend::storage::filestore::FileStore;
25use crate::backend::storage::store::Store;
26use crate::backend::storage::work_queue::work_state;
27use crate::backend::wconfig::ConfigState;
28use super::urgent_asks::{self, Ask};
29use super::worker_notes as notes;
30
31/// The quiet time of an agent between turns, in minutes; 0 turns the whole feature off.
32pub const SETTING_QUIET_MINUTES: &str = "agents:quietminutes";
33/// The quiet time of a turn that is running, in minutes.
34pub const SETTING_QUIET_RUNNING_MINUTES: &str = "agents:quietrunningminutes";
35/// How long after the nudge (or, for a running turn, after its quiet time) the watchers are told, in minutes.
36pub const SETTING_QUIET_ESCALATE_MINUTES: &str = "agents:quietescalateminutes";
37
38const DEFAULT_QUIET_MINUTES: i64 = 15;
39const DEFAULT_QUIET_RUNNING_MINUTES: i64 = 30;
40const DEFAULT_ESCALATE_MINUTES: i64 = 5;
41/// An agent is nudged at most this often.
42const NUDGE_SPACING_MS: u64 = 60 * 60_000;
43/// An agent whose turn ended with a command of its own still running in the background is waiting on that command, not
44/// stuck: its quiet time is this many times the usual one, and it is not nudged (a nudge would only cost it a turn).
45const BACKGROUND_FACTOR: u64 = 4;
46/// How often the sweep looks.
47const SWEEP_EVERY: std::time::Duration = std::time::Duration::from_secs(30);
48
49/// The three times, from settings.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub struct Limits {
52    pub quiet_ms: u64,
53    pub running_ms: u64,
54    pub escalate_ms: u64,
55}
56
57/// The limits in `extra`, or `None` when the feature is off (`agents:quietminutes` of 0 or below).
58pub fn limits_from(extra: &HashMap<String, serde_json::Value>) -> Option<Limits> {
59    let minutes = |key: &str, default: i64| extra.get(key).and_then(|v| v.as_i64()).filter(|m| *m >= 0).unwrap_or(default);
60    let quiet = minutes(SETTING_QUIET_MINUTES, DEFAULT_QUIET_MINUTES);
61    if quiet == 0 {
62        return None;
63    }
64    let ms = |m: i64| (m as u64).saturating_mul(60_000);
65    Some(Limits {
66        quiet_ms: ms(quiet),
67        running_ms: ms(minutes(SETTING_QUIET_RUNNING_MINUTES, DEFAULT_QUIET_RUNNING_MINUTES)),
68        escalate_ms: ms(minutes(SETTING_QUIET_ESCALATE_MINUTES, DEFAULT_ESCALATE_MINUTES)),
69    })
70}
71
72/// What the sweep read about one agent that owes work.
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub struct Reading {
75    /// The newest of its own activity (unix ms, 0 when none is known): output, a message it sent, an update of a
76    /// task it holds. A message *to* it is not activity.
77    pub activity_ms: u64,
78    /// A turn is running.
79    pub turn_active: bool,
80    /// Between turns, with a command or job the agent started still running in the background (`background_set`).
81    pub background: bool,
82}
83
84/// The quiet time of an agent between turns: longer while a command of its own runs in the background.
85fn idle_limit(background: bool, lim: &Limits) -> u64 {
86    if background {
87        lim.quiet_ms.saturating_mul(BACKGROUND_FACTOR)
88    } else {
89        lim.quiet_ms
90    }
91}
92
93/// What a quiet agent is owed.
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub enum Action {
96    /// Between turns, the quiet time is up: nudge the agent once.
97    Nudge,
98    /// Tell its watchers; `running` when a turn is still running and has written nothing; `idle_ms` is how long
99    /// it has been quiet.
100    Tell { running: bool, idle_ms: u64 },
101}
102
103#[derive(Debug, Default)]
104struct Episode {
105    /// The clock: the newest of its activity and when it was first seen owing work (so an agent just given work,
106    /// or one found after a restart of srv, gets a whole quiet time).
107    activity_at: u64,
108    nudged_at: Option<u64>,
109    /// The nudge was skipped (one was sent within the hour): the watchers are told at the quiet time.
110    nudge_skipped: bool,
111    told_at: Option<u64>,
112}
113
114/// The quiet episodes of the agents that owe work, by agent.
115#[derive(Debug, Default)]
116pub struct Watch {
117    episodes: HashMap<String, Episode>,
118    last_nudge: HashMap<String, u64>,
119}
120
121impl Watch {
122    /// The next step for the agent `key` at `now_ms`, or `None`. Call it once a sweep for each agent that owes
123    /// work and can be called quiet (see [`callable`]).
124    pub fn step(&mut self, key: &str, reading: Reading, lim: &Limits, now_ms: u64) -> Option<Action> {
125        let ep = self.episodes.entry(key.to_string()).or_insert_with(|| Episode { activity_at: now_ms.max(reading.activity_ms), ..Episode::default() });
126        if reading.activity_ms > ep.activity_at {
127            // It moved: a new episode, and a nudge may be sent again once the hour since the last one is over.
128            *ep = Episode { activity_at: reading.activity_ms, ..Episode::default() };
129        }
130        let idle = now_ms.saturating_sub(ep.activity_at);
131        // Told once for a quiet: the same agent is not told again until it moves (a new episode).
132        let may_tell = |ep: &Episode| ep.told_at.is_none();
133        if reading.turn_active {
134            if idle >= lim.running_ms.saturating_add(lim.escalate_ms) && may_tell(ep) {
135                return Some(Action::Tell { running: true, idle_ms: idle });
136            }
137            return None;
138        }
139        if idle < idle_limit(reading.background, lim) {
140            return None;
141        }
142        if reading.background {
143            // It is waiting on its own command: no nudge, its watchers are told (naming the command).
144            ep.nudge_skipped = true;
145        }
146        if ep.nudged_at.is_none() && !ep.nudge_skipped {
147            let nudged_lately = self.last_nudge.get(key).is_some_and(|at| now_ms.saturating_sub(*at) < NUDGE_SPACING_MS);
148            if nudged_lately {
149                ep.nudge_skipped = true;
150            } else {
151                ep.nudged_at = Some(now_ms);
152                self.last_nudge.insert(key.to_string(), now_ms);
153                return Some(Action::Nudge);
154            }
155        }
156        let due = ep.nudge_skipped || ep.nudged_at.is_some_and(|at| now_ms.saturating_sub(at) >= lim.escalate_ms);
157        if due && may_tell(ep) {
158            return Some(Action::Tell { running: false, idle_ms: idle });
159        }
160        None
161    }
162
163    /// When the quiet that `step` is looking at began (unix ms), if the agent `key` is quiet at `now_ms`: it is between
164    /// turns and idle for the quiet time, or in a turn that has written nothing for the longer running time. Whether
165    /// it was nudged or its watchers told does not matter: this is what the Swarm and the Kanban show.
166    pub fn quiet_since(&self, key: &str, turn_active: bool, background: bool, lim: &Limits, now_ms: u64) -> Option<u64> {
167        let at = self.episodes.get(key)?.activity_at;
168        let limit = if turn_active { lim.running_ms } else { idle_limit(background, lim) };
169        (now_ms.saturating_sub(at) >= limit).then_some(at)
170    }
171
172    /// The watchers of `key` were told at `now_ms`: it is not told again until it moves. Called only once a note went
173    /// out, so a note nobody could receive (no watcher open) or that the one-a-minute gap held is tried again at the
174    /// next sweep.
175    pub fn mark_told(&mut self, key: &str, now_ms: u64) {
176        if let Some(ep) = self.episodes.get_mut(key) {
177            ep.told_at = Some(now_ms);
178        }
179    }
180
181    /// Forget every agent not in `keep` (it owes nothing now, or cannot be called quiet): its next episode starts
182    /// with a whole quiet time.
183    pub fn retain(&mut self, keep: &HashSet<String>) {
184        self.episodes.retain(|k, _| keep.contains(k));
185        if self.last_nudge.len() > 512 {
186            let cutoff = agentmux_common::time::now_ms_u64().saturating_sub(NUDGE_SPACING_MS);
187            self.last_nudge.retain(|_, at| *at >= cutoff);
188        }
189    }
190}
191
192/// An agent that is quiet now, as the Swarm and the Kanban show it (the `quiet` group of the live facts).
193#[derive(Debug, Clone, PartialEq, Eq)]
194pub struct QuietView {
195    /// When the quiet began (unix ms): the agent's last activity.
196    pub since_ms: u64,
197    /// The tasks it holds (numbers); empty for a spawned worker that owes its leader a report.
198    pub tasks: Vec<i64>,
199    /// The agents told when it has been quiet long enough (their names).
200    pub watchers: Vec<String>,
201}
202
203/// The agents quiet at the last sweep, by definition id. A sweep replaces it whole.
204static QUIET: std::sync::LazyLock<parking_lot::Mutex<HashMap<String, QuietView>>> = std::sync::LazyLock::new(Default::default);
205
206/// `def_id` as the last sweep found it, when it was quiet.
207pub fn quiet_view(def_id: &str) -> Option<QuietView> {
208    QUIET.lock().get(def_id).cloned()
209}
210
211/// The most minutes a leader may mute one agent for.
212pub const MAX_MUTE_MINUTES: u64 = 240;
213/// The longest reason kept, in characters.
214const MUTE_REASON_CHARS: usize = 120;
215
216/// A leader's mute of one agent: its quiet clock is stopped until `until_ms`, then runs again from there.
217#[derive(Debug, Clone, PartialEq, Eq)]
218pub struct Mute {
219    pub until_ms: u64,
220    /// Why, in the leader's words (cut, one line).
221    pub reason: String,
222    /// The agent that muted it (its slug): recorded as that agent, never as the operator.
223    pub by: String,
224}
225
226/// The mutes in force, by the muted agent's definition id. Kept in memory: a mute is for at most four hours, and a
227/// restart of srv gives the agent a whole quiet time anyway.
228static MUTES: LazyLock<parking_lot::Mutex<HashMap<String, Mute>>> = LazyLock::new(Default::default);
229
230/// Mute `def_id` for `minutes` (1 to [`MAX_MUTE_MINUTES`]) from `now_ms`, replacing an earlier mute of it.
231pub fn mute(def_id: &str, minutes: u64, reason: &str, by: &str, now_ms: u64) -> Result<Mute, String> {
232    if minutes == 0 || minutes > MAX_MUTE_MINUTES {
233        return Err(format!("minutes must be 1 to {MAX_MUTE_MINUTES} (0 lifts a mute); got {minutes}"));
234    }
235    let reason: String = reason.split_whitespace().collect::<Vec<_>>().join(" ").chars().filter(|c| !c.is_control()).take(MUTE_REASON_CHARS).collect();
236    let muted = Mute { until_ms: now_ms.saturating_add(minutes.saturating_mul(60_000)), reason, by: by.to_string() };
237    MUTES.lock().insert(def_id.to_string(), muted.clone());
238    Ok(muted)
239}
240
241/// Lift the mute of `def_id`; whether there was one in force.
242pub fn unmute(def_id: &str, now_ms: u64) -> bool {
243    MUTES.lock().remove(def_id).is_some_and(|m| m.until_ms > now_ms)
244}
245
246/// The mute of `def_id` in force at `now_ms`, if any.
247pub fn mute_of(def_id: &str, now_ms: u64) -> Option<Mute> {
248    MUTES.lock().get(def_id).filter(|m| m.until_ms > now_ms).cloned()
249}
250
251/// How long an ended mute is kept for the quiet clock: the clock runs again from the mute's end, which a sweep that comes
252/// late (the machine slept) must still know.
253const ENDED_MUTE_KEPT_MS: u64 = 24 * 60 * 60_000;
254
255/// The mute of `def_id` as the quiet clock reads it: one in force, or one that ended at most a day ago (so a sweep that
256/// runs late still starts the clock at the mute's end, not at the last sweep). Older ones are dropped.
257fn mute_for_clock(def_id: &str, now_ms: u64) -> Option<Mute> {
258    let mut mutes = MUTES.lock();
259    mutes.retain(|_, m| now_ms.saturating_sub(m.until_ms) < ENDED_MUTE_KEPT_MS);
260    mutes.get(def_id).cloned()
261}
262
263/// Whether `caller` leads `target` (both agent uids): it is the lead of the target's seat, which for a spawned worker is
264/// the agent that spawned it. Only a lead may mute.
265pub fn leads(mstore: &Store, caller: &str, target: &str) -> bool {
266    let seat_lead = crate::backend::agent_seat::effective_seat_by_id(mstore, target).and_then(|seat| seat.lead);
267    seat_lead.as_deref() == Some(caller) || crate::backend::agent_seat::worker_of(mstore, target).as_deref() == Some(caller)
268}
269
270/// When the newest of the tasks the agent holds moved (unix ms; 0 for none). An urgent message sent to it is not
271/// the agent's own activity, so the tasks it only asked about do not count.
272fn held_moved_ms(tasks: &[OwedTask]) -> u64 {
273    tasks.iter().filter(|t| !t.asked).map(|t| t.updated_ms).max().unwrap_or(0)
274}
275
276/// Whether the agent holds on purpose while quota mode is tight: it set its own `waiting` status line (the leader's
277/// note would only cost the leader a turn to read "idle by design"). The clock is stopped for as long as that line
278/// is its current one and the mode stays tight.
279pub fn holding_for_quota(status: &MetaMapType, quota_tight: bool) -> bool {
280    quota_tight && live_phrase::declared_of(status).is_some_and(|line| line.state.as_deref() == Some("waiting") && line.src == live_phrase::SRC_AGENT)
281}
282
283/// What the agent's status line and a mute add to its clock (unix ms; 0 for nothing). A new status line is something
284/// the agent did, so it counts at the time it was set. A `waiting` line with its time, and a mute, stop the clock:
285/// while one is in force the agent counts as active now, and when it ends the clock runs again from its end.
286pub fn paused_activity(status: &MetaMapType, mute: Option<&Mute>, now_ms: u64) -> u64 {
287    let mut at = live_phrase::declared_of(status).map_or(0, |line| line.at_ms);
288    if let Some(until) = live_phrase::waiting_until(status) {
289        at = at.max(until.min(now_ms));
290    }
291    if let Some(m) = mute {
292        at = at.max(m.until_ms.min(now_ms));
293    }
294    at
295}
296
297/// Whether an agent in this state can be called quiet: it is working or idle. A question waiting for the user,
298/// an agent that cannot run (stopped, failed, limited, signed out) and one with no state are told another way.
299pub fn callable(state: Option<AgentState>) -> bool {
300    matches!(state, Some(AgentState::Working | AgentState::Idle))
301}
302
303/// A task an agent holds.
304#[derive(Debug, Clone, PartialEq, Eq)]
305pub struct OwedTask {
306    pub num: i64,
307    /// Who filed it (an agent's uid), empty when a person did or it is not known.
308    pub filer_uid: String,
309    /// When the task last moved (unix ms).
310    pub updated_ms: u64,
311    /// Not held: an urgent message from a proven sender named it and the agent has not answered (`urgent_asks`).
312    pub asked: bool,
313}
314
315/// The claimed tasks of every holder, keyed by the holder's uid, or `name:<lowercased claimed_by>` when the
316/// holder's uid is not known: the key the Swarm's facts use. A task on hold, waiting on a question, in review,
317/// done or open is not claimed and is not here.
318pub fn claimed_by_holder(items: &[crate::backend::storage::work_board::BoardTask]) -> HashMap<String, Vec<OwedTask>> {
319    let mut out: HashMap<String, Vec<OwedTask>> = HashMap::new();
320    for t in items.iter().filter(|t| t.item.state == work_state::CLAIMED) {
321        let key = if t.item.claimed_by_uid.is_empty() { format!("name:{}", t.item.claimed_by.to_lowercase()) } else { t.item.claimed_by_uid.clone() };
322        let moved = t.item.updated_at.max(t.card.updated_at).max(0) as u64;
323        out.entry(key).or_default().push(OwedTask { num: t.card.num, filer_uid: t.item.created_by_uid.clone(), updated_ms: moved, asked: false });
324    }
325    out.values_mut().for_each(|v| v.sort_by_key(|t| t.num));
326    out
327}
328
329/// The tasks the agent `def` holds.
330pub fn owed_by(claimed: &HashMap<String, Vec<OwedTask>>, def: &AgentDefinition) -> Vec<OwedTask> {
331    let mut tasks: Vec<OwedTask> = claimed.get(&def.id).cloned().unwrap_or_default();
332    for name in [def.slug.to_lowercase(), def.name.to_lowercase()] {
333        if let Some(more) = claimed.get(&format!("name:{name}")) {
334            tasks.extend(more.iter().filter(|t| !tasks.iter().any(|have| have.num == t.num)).cloned().collect::<Vec<_>>());
335        }
336    }
337    tasks.sort_by_key(|t| t.num);
338    tasks
339}
340
341/// Every claimed task, on every board and with no row limit, read once for a sweep or a note: a limit on the
342/// board's rows would cut off the oldest, which are the tasks of the agents that have been quiet longest. Empty
343/// when the read fails.
344pub fn read_claimed(work: &Store, now_ms: i64) -> Vec<crate::backend::storage::work_board::BoardTask> {
345    work.work_claimed_list(now_ms).unwrap_or_default()
346}
347
348/// The first open pane of each agent definition.
349fn first_pane_by_def(mstore: &Store) -> HashMap<String, String> {
350    use crate::backend::obj::{self, Block, Tab};
351    let mut out = HashMap::new();
352    for tab in mstore.get_all::<Tab>().unwrap_or_default() {
353        for id in &tab.blockids {
354            let Some(block) = mstore.get::<Block>(id).ok().flatten() else { continue };
355            let def_id = obj::meta_get_string(&block.meta, "agentId", "");
356            if !def_id.is_empty() {
357                out.entry(def_id).or_insert_with(|| id.clone());
358            }
359        }
360    }
361    out
362}
363
364/// The panes that watch the agent `def_id`: its seat's lead and its spawned-worker leader (when open on this
365/// machine), and the open pane of each agent that filed a task in `filers`. Never its own pane, each once.
366pub fn watcher_panes(mstore: &Store, def_id: &str, filers: &[String]) -> Vec<String> {
367    let own = notes::live_panes_of(mstore, def_id);
368    let mut panes: Vec<String> = Vec::new();
369    let mut add = |pane: Option<String>| {
370        if let Some(p) = pane.filter(|p| !own.contains(p) && !panes.contains(p)) {
371            panes.push(p);
372        }
373    };
374    add(crate::backend::agent_seat::worker_of(mstore, def_id).and_then(|leader| notes::live_panes_of(mstore, &leader).into_iter().next()));
375    add(notes::leader_pane_of(mstore, def_id));
376    for filer in filers.iter().filter(|f| !f.is_empty() && f.as_str() != def_id) {
377        add(notes::live_panes_of(mstore, filer).into_iter().next());
378    }
379    panes
380}
381
382/// Whether an urgent ask is answered: the recipient messaged the sender since (`replied_ms`), updated or completed a
383/// task it named (a held task that moved since), or none of the tasks named is waiting on it any more (done, handed
384/// elsewhere or cancelled). Pure.
385pub fn ask_answered(ask: &Ask, replied_ms: Option<u64>, held: &[OwedTask], still_waiting: bool) -> bool {
386    replied_ms.is_some_and(|at| at >= ask.at_ms) || held.iter().any(|t| ask.tasks.contains(&t.num) && t.updated_ms > ask.at_ms) || !still_waiting
387}
388
389/// The tasks each agent was asked about by an urgent message and has not answered, by the agent's definition id, as
390/// `asked` entries whose filer is the sender (so the sender is told, as a filer is). The answered asks are forgotten.
391fn open_asks_by_def(mstore: &Store, work: &Store, defs: &[AgentDefinition], claimed: &HashMap<String, Vec<OwedTask>>, now_ms: u64) -> HashMap<String, Vec<OwedTask>> {
392    use crate::backend::obj::{self, Block};
393    let mut open: HashMap<String, Vec<OwedTask>> = HashMap::new();
394    let mut done: Vec<Ask> = Vec::new();
395    for ask in urgent_asks::open_asks(now_ms) {
396        let def_id = mstore.get::<Block>(&ask.block_id).ok().flatten().map(|b| obj::meta_get_string(&b.meta, "agentId", "")).unwrap_or_default();
397        let Some(def) = defs.iter().find(|d| d.id == def_id) else {
398            done.push(ask);
399            continue;
400        };
401        let Some(sender) = defs.iter().find(|d| d.slug.eq_ignore_ascii_case(&ask.sender) || d.name.eq_ignore_ascii_case(&ask.sender) || d.id == ask.sender) else { continue };
402        let held = owed_by(claimed, def);
403        let replied = notes::last_report(&def.slug, &notes::live_panes_of(mstore, &sender.id));
404        let waiting = work.work_numbers_waiting_on(&ask.tasks, &def.id, &def.slug).unwrap_or(true);
405        if ask_answered(&ask, replied, &held, waiting) {
406            done.push(ask);
407            continue;
408        }
409        let entry = open.entry(def.id.clone()).or_default();
410        for num in &ask.tasks {
411            if !entry.iter().any(|t| t.num == *num && t.filer_uid == sender.id) {
412                entry.push(OwedTask { num: *num, filer_uid: sender.id.clone(), updated_ms: ask.at_ms, asked: true });
413            }
414        }
415    }
416    if !done.is_empty() {
417        urgent_asks::settle(|a| done.contains(a));
418    }
419    open
420}
421
422/// Whether the spawned worker `def` owes its leader a report: its leader has messaged it since it last messaged
423/// the leader (or it never has).
424fn owes_report(mstore: &Store, defs: &[AgentDefinition], def: &AgentDefinition, worker_pane: &str) -> bool {
425    let Some(leader_id) = crate::backend::agent_seat::worker_of(mstore, &def.id) else { return false };
426    let Some(leader) = defs.iter().find(|d| d.id == leader_id) else { return false };
427    let given = notes::last_report(&leader.slug, &[worker_pane.to_string()]);
428    let reported = notes::last_report(&def.slug, &notes::live_panes_of(mstore, &leader_id));
429    match (given, reported) {
430        (None, _) => false,
431        (Some(_), None) => true,
432        (Some(g), Some(r)) => r < g,
433    }
434}
435
436/// The nudge's text.
437fn nudge_text(tasks: &[OwedTask], quiet_minutes: u64) -> String {
438    let (held, asked) = split_asked(tasks);
439    let mut owes: Vec<String> = Vec::new();
440    if !held.is_empty() {
441        owes.push(format!("You hold {}", task_list(&held)));
442    }
443    if !asked.is_empty() {
444        let lead = if held.is_empty() { "You have" } else { "have" };
445        owes.push(format!("{lead} an unanswered urgent message about {}", task_list(&asked)));
446    }
447    let owes = if owes.is_empty() { "You have not reported to your leader".to_string() } else { owes.join(", ") };
448    format!("{owes} and nothing has run for {quiet_minutes} minutes. Carry on, or say what you are waiting on.")
449}
450
451/// The tasks an agent holds, and the ones an urgent message asked it about.
452fn split_asked(tasks: &[OwedTask]) -> (Vec<OwedTask>, Vec<OwedTask>) {
453    tasks.iter().cloned().partition(|t| !t.asked)
454}
455
456fn task_list(tasks: &[OwedTask]) -> String {
457    let mut nums: Vec<i64> = tasks.iter().map(|t| t.num).collect();
458    nums.sort_unstable();
459    nums.dedup();
460    nums.iter().map(|n| format!("#{n}")).collect::<Vec<_>>().join(", ")
461}
462
463/// The note to a watcher about the quiet agent `name`.
464pub fn quiet_body(name: &str, is_worker: bool, tasks: &[OwedTask], idle_minutes: u64, running: bool, last_words: &str, background: &str) -> String {
465    let who = if is_worker { "worker" } else { "agent" };
466    let (held, asked) = split_asked(tasks);
467    let on = match (held.is_empty(), asked.is_empty()) {
468        (true, true) => " without reporting to you".to_string(),
469        (false, true) => format!(" on {}", task_list(&held)),
470        (true, false) => format!(" without answering your urgent message about {}", task_list(&asked)),
471        (false, false) => format!(" on {}, and has not answered your urgent message about {}", task_list(&held), task_list(&asked)),
472    };
473    let state = if running {
474        "Its turn is still running but has written nothing.".to_string()
475    } else if !background.is_empty() {
476        format!("Its turn ended, and a background command is still running: {background}")
477    } else if last_words.is_empty() {
478        "It is idle.".to_string()
479    } else {
480        format!("It is idle after a turn that ended: \"{last_words}\"")
481    };
482    format!("Your {who} {name} has been quiet for {idle_minutes} min{on}. {state}")
483}
484
485/// Start the sweep. Called once from `main`, beside `worker_notes::install`.
486pub fn install(mstore: Arc<Store>, work: Arc<Store>, filestore: Arc<FileStore>, config: Arc<ConfigState>) {
487    tokio::spawn(async move {
488        let watch = Arc::new(parking_lot::Mutex::new(Watch::default()));
489        let mut tick = tokio::time::interval(SWEEP_EVERY);
490        tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
491        loop {
492            tick.tick().await;
493            let (mstore, work, filestore, config, watch) = (mstore.clone(), work.clone(), filestore.clone(), config.clone(), watch.clone());
494            // The store reads and the delivery are blocking.
495            let _ = tokio::task::spawn_blocking(move || {
496                sweep(&mut watch.lock(), &mstore, &work, &filestore, &config, agentmux_common::time::now_ms_u64());
497            })
498            .await;
499        }
500    });
501}
502
503/// The tasks an agent owes: the ones it holds, and the ones an urgent message asked it about, each ask kept once. A
504/// task that is both held and asked stays in both lists, so the sender of the message is a watcher (its filer) and
505/// the words name the message as well as the task.
506fn with_asked(mut held: Vec<OwedTask>, asked: Vec<OwedTask>) -> Vec<OwedTask> {
507    for more in asked {
508        if !held.iter().any(|t| t.asked && t.num == more.num && t.filer_uid == more.filer_uid) {
509            held.push(more);
510        }
511    }
512    held.sort_by_key(|t| (t.num, t.asked));
513    held
514}
515
516/// One look at every agent that owes work.
517pub fn sweep(watch: &mut Watch, mstore: &Store, work: &Store, filestore: &FileStore, config: &ConfigState, now_ms: u64) {
518    let Some(lim) = limits_from(&config.get_settings().extra) else {
519        watch.retain(&HashSet::new());
520        QUIET.lock().clear();
521        return;
522    };
523    let defs = mstore.agent_def_list().unwrap_or_default();
524    let panes = first_pane_by_def(mstore);
525    notes::absorb(&crate::backend::reactive::get_global_handler().get_audit_log(usize::MAX));
526    let claimed = claimed_by_holder(&read_claimed(work, now_ms as i64));
527    let mut asked = open_asks_by_def(mstore, work, &defs, &claimed, now_ms);
528    let quota_tight = crate::backend::quota_mode::is_tight(&config.get_settings().extra);
529    let mut keep = HashSet::new();
530    let mut quiet_now = HashMap::new();
531    for def in &defs {
532        let Some(block_id) = panes.get(&def.id) else { continue };
533        let tasks = with_asked(owed_by(&claimed, def), asked.remove(&def.id).unwrap_or_default());
534        if tasks.is_empty() && !owes_report(mstore, &defs, def, block_id) {
535            continue;
536        }
537        let state = crate::backend::agent_state::current_state(mstore, block_id);
538        let Some(reading) = read(mstore, block_id, def, &tasks, state, now_ms, quota_tight) else { continue };
539        keep.insert(def.id.clone());
540        let action = watch.step(&def.id, reading, &lim, now_ms);
541        if let Some(since_ms) = watch.quiet_since(&def.id, reading.turn_active, reading.background, &lim, now_ms) {
542            let filers: Vec<String> = tasks.iter().map(|t| t.filer_uid.clone()).collect();
543            let watchers = watcher_panes(mstore, &def.id, &filers).iter().filter_map(|p| agent_name_of_pane(mstore, &defs, p)).collect();
544            let mut nums: Vec<i64> = tasks.iter().map(|t| t.num).collect();
545            nums.dedup();
546            quiet_now.insert(def.id.clone(), QuietView { since_ms, tasks: nums, watchers });
547        }
548        match action {
549            None => {}
550            Some(Action::Nudge) => nudge(&def.id, block_id, &tasks, lim.quiet_ms / 60_000),
551            Some(Action::Tell { running, idle_ms }) => {
552                if tell(mstore, filestore, config, def, block_id, &tasks, running, idle_ms / 60_000, now_ms) {
553                    watch.mark_told(&def.id, now_ms);
554                }
555            }
556        }
557    }
558    watch.retain(&keep);
559    *QUIET.lock() = quiet_now;
560}
561
562/// The name of the agent whose pane is `block_id`.
563fn agent_name_of_pane(mstore: &Store, defs: &[AgentDefinition], block_id: &str) -> Option<String> {
564    use crate::backend::obj::{self, Block};
565    let block = mstore.get::<Block>(block_id).ok().flatten()?;
566    let def_id = obj::meta_get_string(&block.meta, "agentId", "");
567    defs.iter().find(|d| d.id == def_id).map(|d| d.name.clone())
568}
569
570/// What the controller and the stores say about `def`'s pane, or `None` when it cannot be called quiet: it cannot
571/// run, waits for the user, or its controller cannot say when it last wrote (a controller with no turn tracker).
572fn read(mstore: &Store, block_id: &str, def: &AgentDefinition, tasks: &[OwedTask], state: Option<AgentState>, now_ms: u64, quota_tight: bool) -> Option<Reading> {
573    if !callable(state) {
574        return None;
575    }
576    let ctrl = crate::backend::blockcontroller::get_controller(block_id)?;
577    let tracker = ctrl.turn_tracker()?;
578    let output = ctrl.last_output_ms().and_then(|v| u64::try_from(v).ok()).unwrap_or(0);
579    let sent = notes::last_message_by(&def.slug).unwrap_or(0);
580    let moved = held_moved_ms(tasks);
581    let status = mstore.get::<crate::backend::obj::Block>(block_id).ok().flatten().map(|b| b.meta).unwrap_or_default();
582    let paused = if holding_for_quota(&status, quota_tight) { now_ms } else { paused_activity(&status, mute_for_clock(&def.id, now_ms).as_ref(), now_ms) };
583    let turn_active = tracker.pass_started_ms().is_some();
584    let background = !turn_active && !super::background_set::for_block(block_id, now_ms).is_empty();
585    Some(Reading { activity_ms: output.max(sent).max(moved).max(paused), turn_active, background })
586}
587
588fn nudge(def_id: &str, block_id: &str, tasks: &[OwedTask], quiet_minutes: u64) {
589    let Some(target) = notes::note_target(block_id) else { return };
590    let text = format!("[AgentMux] {}", crate::backend::reactive::sanitize::quote_in_system_note(&nudge_text(tasks, quiet_minutes)));
591    match crate::backend::reactive::get_global_handler().deliver_system_note(&target, &text) {
592        Ok(()) => tracing::info!(def_id, "quiet agent nudged"),
593        Err(e) => tracing::warn!(def_id, error = %e, "quiet agent not nudged"),
594    }
595}
596
597#[allow(clippy::too_many_arguments)]
598/// What the agent in `block_id` has running in the background, in a few words (one line, cut): the first command, and how
599/// many more there are.
600fn background_label(block_id: &str, now_ms: u64) -> String {
601    let items = super::background_set::for_block(block_id, now_ms);
602    let Some(first) = items.first() else { return String::new() };
603    let one_line: String = first.label.split_whitespace().collect::<Vec<_>>().join(" ").chars().take(90).collect();
604    match items.len() {
605        1 => one_line,
606        n => format!("{one_line} (and {} more)", n - 1),
607    }
608}
609
610fn tell(mstore: &Store, filestore: &FileStore, config: &ConfigState, def: &AgentDefinition, block_id: &str, tasks: &[OwedTask], running: bool, idle_minutes: u64, now_ms: u64) -> bool {
611    let filers: Vec<String> = tasks.iter().map(|t| t.filer_uid.clone()).collect();
612    let watchers = watcher_panes(mstore, &def.id, &filers);
613    let remote_lead = crate::backend::agent_seat::effective_seat_by_id(mstore, &def.id).and_then(|seat| seat.lead).filter(|lead| crate::backend::agent_seat::is_remote_lead(lead));
614    if watchers.is_empty() && remote_lead.is_none() {
615        return false;
616    }
617    let words = if running { String::new() } else { notes::last_words_of(mstore, filestore, block_id) };
618    let local = || {
619        let is_worker = crate::backend::agent_seat::worker_of(mstore, &def.id).is_some();
620        let background = if running { String::new() } else { background_label(block_id, now_ms) };
621        let body = quiet_body(&def.name, is_worker, tasks, idle_minutes, running, &words, &background);
622        let Some(body) = notes::admit(&def.id, body, now_ms) else { return false };
623        // Information that asks nothing: a cold leader hears it at its next turn, and with the other notes about its
624        // agents when they fall in the same window (`note_outbox`).
625        let line = super::note_outbox::Line {
626            agent: def.id.clone(),
627            text: crate::backend::reactive::sanitize::quote_in_system_note(&body),
628            held_key: Some(format!("quiet:{}", def.id)),
629        };
630        super::note_outbox::queue(mstore, config, &watchers, &line, now_ms);
631        true
632    };
633    // A lead on another machine is sent the same facts by that machine's AgentMux (section 19): queued here, sent by srv.
634    let remote = || {
635        if let Some(lead) = &remote_lead {
636            let nums: Vec<i64> = tasks.iter().map(|t| t.num).collect();
637            super::quiet_remote::queue(lead, super::quiet_remote::Note::new(&def.name, running, idle_minutes, &nums, &words));
638        }
639    };
640    told_both(!watchers.is_empty(), local, remote)
641}
642
643/// The note for the watchers here, then, once that is taken (or when nobody here watches), the one for a lead on another
644/// machine. `false`, with nothing queued for the lead, when the local note is not taken yet: the watch asks again at its
645/// next sweep, and the lead hears once, at the sweep that tells.
646fn told_both(has_local: bool, local: impl FnOnce() -> bool, remote: impl FnOnce()) -> bool {
647    if has_local && !local() {
648        return false;
649    }
650    remote();
651    true
652}
653
654#[cfg(test)]
655#[path = "quiet_watch_tests.rs"]
656mod tests;