Skip to main content

agentmux_srv_core/backend/supervisor/
watcher.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Carries the Supervisor's decisions out: listens for completed turns on the
5//! broker, judges supervised panes' turns, sends continuations, writes the
6//! state Swarm shows and sends the notifications (spec §3.2 to §3.7).
7
8use std::collections::{HashMap, HashSet};
9use std::hash::{Hash, Hasher};
10use std::sync::{Arc, Mutex, OnceLock};
11
12use serde::Deserialize;
13
14use crate::ambient::digest;
15use crate::backend::blockcontroller::core::broadcast_block_update;
16use crate::backend::blockcontroller::health::{TriggerKind, TurnEnd, TurnInput, TurnTrigger};
17use crate::backend::eventbus::EventBus;
18use crate::backend::mps::{Broker, MuxEvent, EVENT_AGENT_TURN};
19use crate::backend::notify::policy::NotifyKind;
20use crate::backend::obj::Block;
21use crate::backend::storage::background_tasks::BackgroundTaskStatus;
22use crate::backend::storage::filestore::FileStore;
23use crate::backend::storage::store::Store;
24
25use super::judge::{self, Judgement};
26use super::pacing::{self, WaitOver};
27use super::settings::{self, NoticeGroup};
28use super::policy::{self, Action, PreJudge, TurnFacts};
29use super::{
30    message, supports, SupervisorAction, SupervisorDecision, SupervisorMode, SupervisorState, SupervisorStatus,
31    Verdict, META_MODE, META_STATE,
32};
33
34/// The fields of a published `agentturn` the Supervisor reads.
35#[derive(Deserialize)]
36struct PublishedTurn {
37    block_id: String,
38    turn_id: u64,
39    #[serde(default)]
40    ended_at_ms: Option<u64>,
41    #[serde(default)]
42    end: Option<TurnEnd>,
43    #[serde(default)]
44    trigger: Option<TurnTrigger>,
45    /// The labelled inputs that joined the turn after it started.
46    #[serde(default)]
47    absorbed: Vec<TurnTrigger>,
48    #[serde(default)]
49    steps: u32,
50}
51
52impl PublishedTurn {
53    /// What the Supervisor treats as having started the turn. A turn AgentMux started on its own
54    /// (a pane's start-up document) that took a real input before it ended is that input's: its
55    /// answer is the agent's work and is judged.
56    fn effective_trigger(&self) -> Option<TriggerKind> {
57        let first = self.trigger.as_ref().map(|t| t.kind);
58        if first != Some(TriggerKind::System) {
59            return first;
60        }
61        self.absorbed.iter().map(|t| t.kind).find(|k| *k != TriggerKind::System).or(first)
62    }
63}
64
65/// A completed turn, as the Supervisor takes it.
66#[derive(Clone, Debug, PartialEq, Eq)]
67struct TurnEnded {
68    block_id: String,
69    turn_id: u64,
70    ended_at_ms: u64,
71    trigger: Option<TriggerKind>,
72    steps: u32,
73}
74
75/// A completed turn from an `agentturn` payload; `None` for a turn still
76/// running or settling, or one that ended by its process exiting.
77fn parse_turn_ended(data: &serde_json::Value) -> Option<TurnEnded> {
78    let t = PublishedTurn::deserialize(data).ok()?;
79    if t.end != Some(TurnEnd::Completed) {
80        return None;
81    }
82    let trigger = t.effective_trigger();
83    Some(TurnEnded {
84        block_id: t.block_id,
85        turn_id: t.turn_id,
86        ended_at_ms: t.ended_at_ms.unwrap_or(0),
87        trigger,
88        steps: t.steps,
89    })
90}
91
92/// Bound on the turn ends remembered to handle each once.
93const SEEN_MAX: usize = 1024;
94
95pub struct Supervisor {
96    mstore: Arc<Store>,
97    filestore: Arc<FileStore>,
98    event_bus: Arc<EventBus>,
99    broker: Arc<Broker>,
100    /// Each supervised pane's run state while srv runs; mirrored to meta.
101    runs: Mutex<HashMap<String, SupervisorState>>,
102    /// Each pane's latest judgement request; a newer one supersedes an older.
103    generations: Mutex<HashMap<String, u64>>,
104    /// One evaluation per pane at a time.
105    locks: Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
106    /// Turn ends already handled: one end can be published twice.
107    seen: Mutex<HashSet<(String, u64, u64)>>,
108    /// Continuations sent in the last hour, across every pane (`supervisor:hourly`).
109    budget: Mutex<pacing::Budget>,
110    /// The fleet-budget notice went out and the budget hasn't had room since: say it once.
111    budget_noticed: std::sync::atomic::AtomicBool,
112}
113
114static INSTANCE: OnceLock<Arc<Supervisor>> = OnceLock::new();
115
116/// The running Supervisor, once `start` has run.
117pub fn instance() -> Option<Arc<Supervisor>> {
118    INSTANCE.get().cloned()
119}
120
121/// Start the Supervisor: watch the broker for completed turns. Idempotent.
122pub fn start(mstore: Arc<Store>, filestore: Arc<FileStore>, event_bus: Arc<EventBus>, broker: Arc<Broker>) {
123    let sup = Arc::new(Supervisor {
124        mstore,
125        filestore,
126        event_bus,
127        broker: broker.clone(),
128        runs: Mutex::default(),
129        generations: Mutex::default(),
130        locks: Mutex::default(),
131        seen: Mutex::default(),
132        budget: Mutex::default(),
133        budget_noticed: Default::default(),
134    });
135    if INSTANCE.set(sup.clone()).is_err() {
136        return;
137    }
138    // Before the observer below is registered, so no live wait exists yet to be mistaken for a stale one.
139    sup.drop_restarted_waits();
140    let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<TurnEnded>();
141    // On the broker's publish path: parse and enqueue only.
142    broker.add_observer(Arc::new(move |ev: &MuxEvent| {
143        if ev.event != EVENT_AGENT_TURN {
144            return;
145        }
146        if let Some(end) = ev.data.as_ref().and_then(parse_turn_ended) {
147            let _ = tx.send(end);
148        }
149    }));
150    tokio::spawn(async move {
151        while let Some(end) = rx.recv().await {
152            if !sup.first_sighting(&end) {
153                continue;
154            }
155            let sup = sup.clone();
156            tokio::spawn(async move {
157                sup.evaluate(&end.block_id, end.trigger, end.steps, true).await;
158            });
159        }
160    });
161}
162
163impl Supervisor {
164    /// A continuation's wait is not persisted: a pane that still says "Continuing after a ..." from
165    /// before this start will never send it, so its row says so instead. Runs once, at start,
166    /// before the first turn end can save a live wait.
167    fn drop_restarted_waits(&self) {
168        let blocks = match self.mstore.get_all::<Block>() {
169            Ok(b) => b,
170            Err(e) => {
171                tracing::warn!(error = %e, "supervisor: could not read panes to clear interrupted waits");
172                return;
173            }
174        };
175        for block in blocks {
176            let Some(mut state) = SupervisorState::from_meta(&block.meta) else { continue };
177            if !pacing::drop_restarted_wait(&mut state) {
178                continue;
179            }
180            let Ok(value) = serde_json::to_value(&state) else { continue };
181            let id = block.oid.clone();
182            let written = self.mstore.with_tx(|tx| {
183                let mut b = tx.must_get::<Block>(&id)?;
184                b.meta.insert(META_STATE.to_string(), value);
185                tx.update(&mut b)?;
186                Ok(())
187            });
188            match written {
189                Ok(()) => broadcast_block_update(&self.mstore, &self.event_bus, &id),
190                Err(e) => tracing::warn!(block_id = %id, error = %e, "supervisor: could not clear an interrupted wait"),
191            }
192        }
193    }
194
195    fn first_sighting(&self, end: &TurnEnded) -> bool {
196        let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner());
197        if seen.len() > SEEN_MAX {
198            seen.clear();
199        }
200        seen.insert((end.block_id.clone(), end.turn_id, end.ended_at_ms))
201    }
202
203    fn next_generation(&self, block_id: &str) -> u64 {
204        let mut g = self.generations.lock().unwrap_or_else(|e| e.into_inner());
205        let n = g.entry(block_id.to_string()).or_insert(0);
206        *n += 1;
207        *n
208    }
209
210    fn is_current(&self, block_id: &str, generation: u64) -> bool {
211        self.generations.lock().unwrap_or_else(|e| e.into_inner()).get(block_id) == Some(&generation)
212    }
213
214    fn lock_for(&self, block_id: &str) -> Arc<tokio::sync::Mutex<()>> {
215        let mut locks = self.locks.lock().unwrap_or_else(|e| e.into_inner());
216        locks.entry(block_id.to_string()).or_default().clone()
217    }
218
219    fn block(&self, block_id: &str) -> Option<Block> {
220        self.mstore.get::<Block>(block_id).ok().flatten()
221    }
222
223    fn state_for(&self, block_id: &str, block: &Block, mode: SupervisorMode, now_ms: u64) -> SupervisorState {
224        let runs = self.runs.lock().unwrap_or_else(|e| e.into_inner());
225        runs.get(block_id)
226            .cloned()
227            .or_else(|| SupervisorState::from_meta(&block.meta))
228            .unwrap_or_else(|| SupervisorState::new(mode, now_ms))
229    }
230
231    /// Keep `state` and write it to the pane's meta, for Swarm, unless a newer
232    /// request (a later turn, a mode change) has taken the pane over since
233    /// `generation`.
234    fn save(&self, block_id: &str, generation: u64, state: &SupervisorState) {
235        if !self.is_current(block_id, generation) {
236            return;
237        }
238        self.runs.lock().unwrap_or_else(|e| e.into_inner()).insert(block_id.to_string(), state.clone());
239        let Ok(value) = serde_json::to_value(state) else { return };
240        let written = self.mstore.with_tx(|tx| {
241            let mut block = tx.must_get::<Block>(block_id)?;
242            block.meta.insert(META_STATE.to_string(), value);
243            tx.update(&mut block)?;
244            Ok(())
245        });
246        match written {
247            Ok(()) => broadcast_block_update(&self.mstore, &self.event_bus, block_id),
248            Err(e) => tracing::warn!(block_id = %block_id, error = %e, "supervisor: could not store its state"),
249        }
250    }
251
252    /// An OS notice for a stop of `group`, unless the user turned that group off
253    /// (`supervisor:notify:*`). The row, the line and the history show every stop regardless.
254    fn notify_group(&self, block_id: &str, group: NoticeGroup, text: String) {
255        if settings::SupervisorSettings::current().notifies(group) {
256            self.notify(block_id, NotifyKind::InputWaiting, Some(text));
257        }
258    }
259
260    fn notify(&self, block_id: &str, kind: NotifyKind, text: Option<String>) {
261        let Some(router) = crate::backend::notify::router::get(&self.broker) else { return };
262        let block_id = block_id.to_string();
263        // The router's emit reads the store: off the async workers.
264        tokio::task::spawn_blocking(move || router.emit(kind, &block_id, text.as_deref(), 0));
265    }
266
267    /// The "finished" notice the router leaves to the Supervisor for a
268    /// supervised pane (spec §3.7), under the router's own rule: a turn
269    /// something other than the user started is announced only when the user
270    /// asked for those (`notify:os:turncompleted:external`).
271    fn notify_finished(&self, block_id: &str, trigger: Option<TriggerKind>) {
272        if !settings::SupervisorSettings::current().notifies(NoticeGroup::Done) {
273            return;
274        }
275        if is_external_start(trigger)
276            && !crate::backend::notify::router::get(&self.broker).is_some_and(|r| r.external_turns_notified())
277        {
278            return;
279        }
280        self.notify(block_id, NotifyKind::TurnCompleted, None);
281    }
282
283    /// Judge `block_id`'s last turn and act on it. `notify` is false for the
284    /// judgement a mode change asks for: the user is looking at the pane.
285    pub async fn evaluate(self: &Arc<Self>, block_id: &str, trigger: Option<TriggerKind>, steps: u32, notify: bool) {
286        let mut generation = self.next_generation(block_id);
287        let lock = self.lock_for(block_id);
288        let _held = lock.lock().await;
289        if !self.is_current(block_id, generation) {
290            return;
291        }
292        let Some(block) = self.block(block_id) else { return };
293        let mode = SupervisorMode::from_meta(&block.meta);
294        if !settings::enabled() || mode == SupervisorMode::Off || !supports(&block.meta) {
295            return;
296        }
297        let now_ms = agentmux_common::time::now_ms_u64();
298        // The user's Stop ended this turn: their override wins, and their own
299        // action needs no notice (the router doesn't send one either).
300        if super::stopped_by_user(block_id) {
301            self.stand_down_for_stop(block_id, generation, &block, mode, now_ms);
302            return;
303        }
304        // No readable conversation (none yet, or a hidden memory reinjection):
305        // nothing to judge, so the notice the router left to us goes out as usual.
306        let Some(activity) = digest::read_recent_activity(&self.filestore, &self.mstore, block_id) else {
307            if notify && trigger != Some(TriggerKind::System) {
308                self.notify_finished(block_id, trigger);
309            }
310            return;
311        };
312        let facts = TurnFacts {
313            trigger,
314            steps,
315            ending: activity.ending,
316            background_running: self.background_running(block_id),
317            reply: fingerprint(&activity.text),
318            now_ms,
319            unavailable: crate::backend::agent_state::unavailable_of_block(&self.mstore, None, block_id, now_ms).map(|u| u.reason()),
320        };
321        let mut state = self.state_for(block_id, &block, mode, now_ms);
322        match policy::on_turn_end(&mut state, mode, &facts) {
323            PreJudge::Ignore => {
324                self.save(block_id, generation, &state);
325                // Nothing judged: the notice the router left to us goes out as
326                // usual (never for AgentMux's own hidden turn).
327                if notify && trigger != Some(TriggerKind::System) {
328                    self.notify_finished(block_id, trigger);
329                }
330                return;
331            }
332            PreJudge::Wait => {
333                policy::apply_wait(&mut state, &facts);
334                self.save(block_id, generation, &state);
335                return;
336            }
337            PreJudge::Pause(why) => {
338                policy::apply_pause(&mut state, &why, &facts);
339                self.save(block_id, generation, &state);
340                if notify {
341                    // An agent that can't run failed; a question needs the user.
342                    let group = if facts.unavailable.is_some() { NoticeGroup::Failed } else { NoticeGroup::NeedsYou };
343                    self.notify_group(block_id, group, format!("Supervisor paused: {why}"));
344                }
345                return;
346            }
347            PreJudge::Judge => {}
348        }
349
350        state.status = SupervisorStatus::Judging;
351        state.reason.clear();
352        self.save(block_id, generation, &state);
353
354        let mut outcome = judge::judge(&self.mstore, block_id, generation, mode, &activity.text, state.continuations).await;
355        // One more try for a call that failed or timed out (a busy shared
356        // login), while the turn is still the latest and the agent still idle.
357        if matches!(outcome, judge::Outcome::Failed)
358            && settings::enabled()
359            && self.is_current(block_id, generation)
360            && !turn_active(block_id)
361        {
362            let retry = self.next_generation(block_id);
363            outcome = judge::judge(&self.mstore, block_id, retry, mode, &activity.text, state.continuations).await;
364            generation = retry;
365        }
366        let judged: Option<Judgement> = match outcome {
367            judge::Outcome::Superseded => return,
368            judge::Outcome::Failed | judge::Outcome::NoVerdict => None,
369            judge::Outcome::Judged(j) => Some(j),
370        };
371        // While the judge ran: a newer turn ended, the mode changed, or the
372        // user (or anything else) started the agent again. Any of these takes over.
373        if !self.is_current(block_id, generation) {
374            return;
375        }
376        if self.block(block_id).map(|b| SupervisorMode::from_meta(&b.meta)) != Some(mode) {
377            return;
378        }
379        // Switched off while the judge ran: its verdict is dropped, the pane
380        // stops showing "judging", and the notice the router left to us goes out.
381        if !settings::enabled() {
382            state.status = SupervisorStatus::Watching;
383            self.save(block_id, generation, &state);
384            if notify && trigger != Some(TriggerKind::System) {
385                self.notify_finished(block_id, trigger);
386            }
387            return;
388        }
389        if turn_active(block_id) {
390            state.status = SupervisorStatus::Watching;
391            self.save(block_id, generation, &state);
392            return;
393        }
394
395        // A Stop that reached srv after the turn ended still wins.
396        if super::stopped_by_user(block_id) {
397            self.stand_down_for_stop(block_id, generation, &block, mode, now_ms);
398            return;
399        }
400
401        let verdict = judged.as_ref().map(|j| (j.verdict, j.reason.as_str()));
402        let action = policy::decide(&state, mode, verdict, &facts);
403        let judged_verdict = judged.as_ref().map(|j| j.verdict);
404        let next = judged.as_ref().map(|j| j.next.clone()).unwrap_or_default();
405        // A continuation waits `supervisor:cooldown` seconds after its turn ended. Anything that
406        // starts a turn in that time takes it over, so it never lands after a different turn
407        // than the one the judge saw.
408        let wait = settings::SupervisorSettings::current().cooldown_secs;
409        if let (Action::Continue { reason, .. }, true) = (&action, wait > 0) {
410            state.status = SupervisorStatus::Waiting;
411            state.reason = format!("{}{wait} s wait: {reason}", pacing::WAIT_PREFIX);
412            self.save(block_id, generation, &state);
413            let sup = self.clone();
414            let block_id = block_id.to_string();
415            tokio::spawn(async move {
416                tokio::time::sleep(std::time::Duration::from_secs(u64::from(wait))).await;
417                sup.continue_after_wait(&block_id, generation, mode, action, judged_verdict, next, facts, notify, trigger)
418                    .await;
419            });
420            return;
421        }
422        self.conclude(block_id, generation, &mut state, action, judged_verdict, &next, &facts, mode, notify, trigger);
423    }
424
425    /// The end of a continuation's wait: send it unless something has taken the pane over.
426    #[allow(clippy::too_many_arguments)]
427    async fn continue_after_wait(
428        &self,
429        block_id: &str,
430        generation: u64,
431        mode: SupervisorMode,
432        action: Action,
433        verdict: Option<Verdict>,
434        next: String,
435        mut facts: TurnFacts,
436        notify: bool,
437        trigger: Option<TriggerKind>,
438    ) {
439        let lock = self.lock_for(block_id);
440        let _held = lock.lock().await;
441        let block = self.block(block_id);
442        let over = WaitOver {
443            superseded: !self.is_current(block_id, generation),
444            switched_off: !settings::enabled(),
445            mode_changed: block.as_ref().map(|b| SupervisorMode::from_meta(&b.meta)) != Some(mode),
446            turn_running: turn_active(block_id),
447            // The turn ended at `facts.now_ms`: a Stop since then counts, however early in the wait.
448            stopped: super::stopped_by_user(block_id) || super::stopped_since(block_id, facts.now_ms),
449        };
450        let now_ms = agentmux_common::time::now_ms_u64();
451        if let Some(why) = over.drop_reason() {
452            // A newer request owns the pane and its state. Otherwise this one's "continuing in ..."
453            // line is cleared here: a Stop is recorded as one, the rest say why it was not sent.
454            if over.superseded || over.mode_changed {
455                return;
456            }
457            let Some(block) = block else { return };
458            if over.stopped {
459                self.stand_down_for_stop(block_id, generation, &block, mode, now_ms);
460                return;
461            }
462            let mut state = self.state_for(block_id, &block, mode, now_ms);
463            state.status = SupervisorStatus::Watching;
464            state.reason = format!("Not continued: {why}.");
465            self.save(block_id, generation, &state);
466            return;
467        }
468        let Some(block) = block else { return };
469        facts.now_ms = now_ms;
470        let mut state = self.state_for(block_id, &block, mode, now_ms);
471        // The wait counts toward the time cap: it may have run out while this waited.
472        let action = match action {
473            Action::Continue { .. } => match policy::limit_reached(&state, mode, &facts) {
474                Some(why) => Action::Pause(why),
475                None => action,
476            },
477            other => other,
478        };
479        self.conclude(block_id, generation, &mut state, action, verdict, &next, &facts, mode, notify, trigger);
480    }
481
482    /// Carry out `action`: send a continuation (inside the fleet budget), record the outcome
483    /// in `state` and the pane's meta, and send the notice its group allows.
484    #[allow(clippy::too_many_arguments)]
485    fn conclude(
486        &self,
487        block_id: &str,
488        generation: u64,
489        state: &mut SupervisorState,
490        mut action: Action,
491        verdict: Option<Verdict>,
492        next: &str,
493        facts: &TurnFacts,
494        mode: SupervisorMode,
495        notify: bool,
496        trigger: Option<TriggerKind>,
497    ) {
498        let mut undeliverable = false;
499        let mut repeat_budget_notice = false;
500        if let Action::Continue { n, reason } = &action {
501            let hourly = settings::SupervisorSettings::current().hourly;
502            let spent = self.budget.lock().unwrap_or_else(|e| e.into_inner()).spend(facts.now_ms, hourly);
503            match spent {
504                Err(wait_ms) => {
505                    repeat_budget_notice = self.budget_noticed.swap(true, std::sync::atomic::Ordering::Relaxed);
506                    let sent = self.budget.lock().unwrap_or_else(|e| e.into_inner()).sent_in_hour(facts.now_ms);
507                    action = Action::Pause(pacing::budget_reached(sent, hourly, wait_ms));
508                }
509                Ok(ticket) => {
510                    self.budget_noticed.store(false, std::sync::atomic::Ordering::Relaxed);
511                    let text = message::continuation(mode, *n, mode.limits().continuations, reason, next);
512                    if let Err(e) = deliver(block_id, &text) {
513                        self.budget.lock().unwrap_or_else(|e| e.into_inner()).refund(ticket);
514                        undeliverable = true;
515                        action = Action::Pause(format!("Couldn't continue it: {e}"));
516                    }
517                }
518            }
519        }
520        policy::apply(state, &action, verdict, facts);
521        self.save(block_id, generation, state);
522        if !notify {
523            return;
524        }
525        match &action {
526            Action::Continue { .. } => {}
527            Action::Pause(why) => {
528                if !repeat_budget_notice {
529                    let group = pacing::pause_group(&action, verdict, undeliverable);
530                    self.notify_group(block_id, group, format!("Supervisor paused: {why}"));
531                }
532            }
533            Action::Done(_) | Action::NoVerdict => self.notify_finished(block_id, trigger),
534        }
535    }
536
537    /// Record that the user's Stop ended the turn: nothing is judged, sent or
538    /// announced, and the run waits for the user's next message.
539    fn stand_down_for_stop(&self, block_id: &str, generation: u64, block: &Block, mode: SupervisorMode, now_ms: u64) {
540        let mut state = self.state_for(block_id, block, mode, now_ms);
541        state.status = SupervisorStatus::Watching;
542        state.reason = STOPPED_BY_USER.to_string();
543        state.record(SupervisorDecision {
544            at_ms: now_ms,
545            action: SupervisorAction::Stopped,
546            verdict: None,
547            reason: STOPPED_BY_USER.to_string(),
548        });
549        self.save(block_id, generation, &state);
550    }
551
552    fn background_running(&self, block_id: &str) -> bool {
553        self.mstore
554            .background_task_list_for_block(block_id)
555            .map(|tasks| tasks.iter().any(|t| t.status == BackgroundTaskStatus::Running))
556            .unwrap_or(false)
557    }
558
559    /// Set a pane's mode: a new run, recorded in its history. An idle agent's
560    /// last turn is judged at once (spec §3.1).
561    pub async fn set_mode(self: &Arc<Self>, block_id: &str, mode: SupervisorMode) -> Result<(), String> {
562        let block = self.block(block_id).ok_or_else(|| "no such pane".to_string())?;
563        if mode != SupervisorMode::Off && !settings::enabled() {
564            return Err(settings::SWITCHED_OFF.to_string());
565        }
566        if mode != SupervisorMode::Off && !supports(&block.meta) {
567            return Err("the Supervisor works with Claude agents only for now".to_string());
568        }
569        let now_ms = agentmux_common::time::now_ms_u64();
570        // A newer request: an evaluation in flight for the pane gives way
571        // without saving, so this never waits behind a judgement.
572        self.next_generation(block_id);
573
574        let history = self.state_for(block_id, &block, mode, now_ms).history;
575        let mut state = SupervisorState { history, ..SupervisorState::new(mode, now_ms) };
576        let label = match mode {
577            SupervisorMode::Off => "Turned off.",
578            SupervisorMode::Steady => "Set to Steady.",
579            SupervisorMode::Drive => "Set to Drive.",
580        };
581        state.record(SupervisorDecision {
582            at_ms: now_ms,
583            action: SupervisorAction::ModeSet,
584            verdict: None,
585            reason: label.to_string(),
586        });
587        let value = serde_json::to_value(&state).map_err(|e| e.to_string())?;
588        self.mstore
589            .with_tx(|tx| {
590                let mut block = tx.must_get::<Block>(block_id)?;
591                if mode == SupervisorMode::Off {
592                    block.meta.remove(META_MODE);
593                } else {
594                    block.meta.insert(META_MODE.to_string(), serde_json::Value::String(mode.as_str().to_string()));
595                }
596                block.meta.insert(META_STATE.to_string(), value);
597                tx.update(&mut block)?;
598                Ok(())
599            })
600            .map_err(|e| e.to_string())?;
601        self.runs.lock().unwrap_or_else(|e| e.into_inner()).insert(block_id.to_string(), state);
602        broadcast_block_update(&self.mstore, &self.event_bus, block_id);
603
604        if mode != SupervisorMode::Off && !turn_active(block_id) {
605            let sup = self.clone();
606            let block_id = block_id.to_string();
607            tokio::spawn(async move { sup.evaluate(&block_id, None, 0, false).await });
608        }
609        Ok(())
610    }
611}
612
613const STOPPED_BY_USER: &str = "You stopped it; it waits for your next message.";
614
615/// Started by something other than the user or the Supervisor: another agent,
616/// a service, a schedule, a background task. The router's notice rule
617/// (`notify_turn_end`) applies to these; a Supervisor turn continues the
618/// user's own work.
619fn is_external_start(trigger: Option<TriggerKind>) -> bool {
620    matches!(trigger, Some(TriggerKind::Agent | TriggerKind::Service | TriggerKind::Schedule | TriggerKind::Task))
621}
622
623fn turn_active(block_id: &str) -> bool {
624    crate::backend::blockcontroller::get_block_controller_status(block_id).is_some_and(|s| s.turn_active)
625}
626
627/// Send the continuation the way a broadcast reaches an agent, as automated
628/// input. An agent whose process isn't running is not started (spec §3.5).
629fn deliver(block_id: &str, text: &str) -> Result<(), String> {
630    use crate::backend::reactive::SenderDelivery;
631    use crate::backend::agent_route::AgentRoute;
632    let input = TurnInput { from: crate::backend::message_origin::MessageOrigin::supervisor(), text: text.to_string(), joins_turn: None };
633    match crate::backend::agent_route::route_agent_message_from(block_id, text, Some(input), crate::backend::message_origin::MessageOrigin::supervisor(), &[], None) {
634        Ok(AgentRoute::Sent(SenderDelivery::Delivered | SenderDelivery::Deferred)) => Ok(()),
635        Ok(AgentRoute::Sent(SenderDelivery::Pty)) => Err("the pane is not an agent session".to_string()),
636        Ok(AgentRoute::StartTurn { .. }) => Err("the agent isn't running".to_string()),
637        Err(e) => Err(e),
638    }
639}
640
641/// A fingerprint of the agent's last message in a digest, to see it repeat.
642pub(super) fn fingerprint(digest_text: &str) -> String {
643    let Some(at) = digest_text.rfind("[assistant] ") else { return String::new() };
644    let mut h = std::collections::hash_map::DefaultHasher::new();
645    digest_text[at..].trim().hash(&mut h);
646    format!("{:016x}", h.finish())
647}
648
649#[cfg(test)]
650pub(super) fn parse_turn_ended_for_test(data: &serde_json::Value) -> Option<(String, Option<TriggerKind>, u32)> {
651    parse_turn_ended(data).map(|t| (t.block_id, t.trigger, t.steps))
652}
653
654#[cfg(test)]
655pub(super) fn is_external_start_for_test(trigger: Option<TriggerKind>) -> bool {
656    is_external_start(trigger)
657}
658
659#[cfg(test)]
660pub(super) fn for_test(mstore: Arc<Store>) -> Arc<Supervisor> {
661    Arc::new(Supervisor {
662        mstore,
663        filestore: Arc::new(FileStore::open_in_memory().unwrap()),
664        event_bus: Arc::new(EventBus::new()),
665        broker: Arc::new(Broker::new()),
666        runs: Mutex::default(),
667        generations: Mutex::default(),
668        locks: Mutex::default(),
669        seen: Mutex::default(),
670        budget: Mutex::default(),
671        budget_noticed: Default::default(),
672    })
673}