Skip to main content

agentmux_srv_core/backend/supervisor/
policy.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Supervisor's rules, with no I/O: which turns are judged, the limits,
5//! and what each verdict leads to. Spec §3.2 and §3.4.
6
7use crate::ambient::digest::TurnEnding;
8use crate::backend::blockcontroller::health::TriggerKind;
9
10use super::{Limits, SupervisorDecision, SupervisorMode, SupervisorState, SupervisorStatus, Verdict};
11
12/// What the watcher knows about a turn that just ended.
13#[derive(Clone, Debug, PartialEq, Eq)]
14pub struct TurnFacts {
15    /// What started the turn; `None` when the ledger didn't say, or for the
16    /// judgement a mode change asks for.
17    pub trigger: Option<TriggerKind>,
18    /// Model calls in the turn (`result.num_turns`): 1 means it used no tool.
19    pub steps: u32,
20    /// How the conversation ends, from the digest.
21    pub ending: TurnEnding,
22    /// The agent has background tasks still running.
23    pub background_running: bool,
24    /// A fingerprint of the agent's last final message.
25    pub reply: String,
26    pub now_ms: u64,
27    /// Why the agent can't work (`Unavailable::reason`) when it is `limited`
28    /// or `signed_out`; `None` otherwise.
29    pub unavailable: Option<String>,
30}
31
32/// What happens before any model is asked.
33#[derive(Clone, Debug, PartialEq, Eq)]
34pub enum PreJudge {
35    /// Nothing to do for this turn.
36    Ignore,
37    /// Stop for the user without asking the judge.
38    Pause(String),
39    /// Background work will wake the agent; judge that turn instead.
40    Wait,
41    Judge,
42}
43
44/// Take a turn that ended into `state`, and say whether it is judged. Updates
45/// the run counters: a turn the user started resets the run (spec §3.4); a
46/// turn the Supervisor started counts toward no-progress.
47pub fn on_turn_end(state: &mut SupervisorState, mode: SupervisorMode, facts: &TurnFacts) -> PreJudge {
48    if mode == SupervisorMode::Off || facts.trigger == Some(TriggerKind::System) {
49        return PreJudge::Ignore;
50    }
51    if state.mode != mode {
52        *state = SupervisorState { history: std::mem::take(&mut state.history), ..SupervisorState::new(mode, facts.now_ms) };
53    }
54    // Out of quota or signed out: every turn fails until that ends, and the
55    // judge runs on the same account, so pause without asking it.
56    if let Some(why) = &facts.unavailable {
57        return PreJudge::Pause(format!("{why}."));
58    }
59    match facts.trigger {
60        Some(TriggerKind::User | TriggerKind::Broadcast) => state.reset_run(),
61        Some(TriggerKind::Supervisor) => {
62            if facts.steps <= 1 {
63                state.no_progress += 1;
64            } else {
65                state.no_progress = 0;
66            }
67        }
68        _ => {}
69    }
70    match facts.ending {
71        TurnEnding::AskedUser => PreJudge::Pause("It asked you a question.".to_string()),
72        // The user's message has no answer yet: nothing of the agent's to judge.
73        TurnEnding::UserLast => PreJudge::Ignore,
74        _ if facts.background_running => PreJudge::Wait,
75        _ => PreJudge::Judge,
76    }
77}
78
79/// What the Supervisor does with the judge's answer.
80#[derive(Clone, Debug, PartialEq, Eq)]
81pub enum Action {
82    /// Send continuation number `n` of the mode's limit, for the judge's `reason`.
83    Continue { n: u32, reason: String },
84    /// Stop for the user.
85    Pause(String),
86    Done(String),
87    /// The judge gave no usable verdict: send nothing, notify as usual.
88    NoVerdict,
89}
90
91/// The action for a verdict, after the limits (spec §3.4). `None` is no verdict.
92pub fn decide(state: &SupervisorState, mode: SupervisorMode, verdict: Option<(Verdict, &str)>, facts: &TurnFacts) -> Action {
93    let Some((verdict, reason)) = verdict else {
94        return Action::NoVerdict;
95    };
96    match verdict {
97        Verdict::Done => Action::Done(reason.to_string()),
98        Verdict::NeedsUser => Action::Pause(reason.to_string()),
99        Verdict::Blocked => Action::Pause(format!("Blocked: {reason}")),
100        Verdict::Continue => match limit_reached(state, mode, facts) {
101            Some(why) => Action::Pause(why),
102            None => Action::Continue { n: state.continuations + 1, reason: reason.to_string() },
103        },
104    }
105}
106
107/// Why another continuation would pass a limit, or `None`.
108pub fn limit_reached(state: &SupervisorState, mode: SupervisorMode, facts: &TurnFacts) -> Option<String> {
109    limit_reached_in(&mode.limits(), state, facts)
110}
111
112/// `limit_reached` under explicit `limits` (the settings, read once).
113pub fn limit_reached_in(limits: &Limits, state: &SupervisorState, facts: &TurnFacts) -> Option<String> {
114    if state.continuations >= limits.continuations {
115        return Some(format!("{} continuations in a row; over to you.", state.continuations));
116    }
117    if let Some(run_ms) = limits.run_ms {
118        if state.run_started_at_ms > 0 && facts.now_ms.saturating_sub(state.run_started_at_ms) >= run_ms {
119            return Some(format!("Kept going for {}; over to you.", duration_text(run_ms)));
120        }
121    }
122    if state.no_progress >= limits.no_progress {
123        return Some(format!("No progress: {} continued turns without using a tool.", state.no_progress));
124    }
125    let continued = facts.trigger == Some(TriggerKind::Supervisor);
126    if continued && !facts.reply.is_empty() && facts.reply == state.last_reply {
127        return Some("It gave the same reply twice.".to_string());
128    }
129    None
130}
131
132/// "2 hours", "1 hour", "90 minutes": the time cap as a person would say it.
133fn duration_text(ms: u64) -> String {
134    let minutes = ms / 60_000;
135    let plural = |n: u64, unit: &str| format!("{n} {unit}{}", if n == 1 { "" } else { "s" });
136    if minutes >= 60 && minutes % 60 == 0 {
137        plural(minutes / 60, "hour")
138    } else {
139        plural(minutes, "minute")
140    }
141}
142
143/// Record `action` in `state` (status, counters, history).
144pub fn apply(state: &mut SupervisorState, action: &Action, verdict: Option<Verdict>, facts: &TurnFacts) {
145    use super::SupervisorAction as A;
146    let (status, history_action, reason) = match action {
147        Action::Continue { n, reason } => {
148            state.continuations = *n;
149            if state.run_started_at_ms == 0 {
150                state.run_started_at_ms = facts.now_ms;
151            }
152            (SupervisorStatus::Continued, A::Continued, reason.clone())
153        }
154        Action::Pause(why) => (SupervisorStatus::Paused, A::Paused, why.clone()),
155        Action::Done(why) => (SupervisorStatus::Done, A::Done, why.clone()),
156        Action::NoVerdict => (
157            SupervisorStatus::Watching,
158            A::NoVerdict,
159            "Couldn't judge this turn, so it stopped as usual.".to_string(),
160        ),
161    };
162    state.last_reply = facts.reply.clone();
163    state.status = status;
164    state.reason = reason.clone();
165    state.limit = state.mode.limits().continuations;
166    state.record(SupervisorDecision { at_ms: facts.now_ms, action: history_action, verdict, reason });
167}
168
169/// Record a stop that needed no judge (`PreJudge::Pause`).
170pub fn apply_pause(state: &mut SupervisorState, why: &str, facts: &TurnFacts) {
171    apply(state, &Action::Pause(why.to_string()), None, facts);
172}
173
174/// Record that background work is running.
175pub fn apply_wait(state: &mut SupervisorState, facts: &TurnFacts) {
176    let reason = "Waiting for its background work to finish.".to_string();
177    state.status = SupervisorStatus::Waiting;
178    state.reason = reason.clone();
179    state.last_reply = facts.reply.clone();
180    state.record(SupervisorDecision { at_ms: facts.now_ms, action: super::SupervisorAction::Waited, verdict: None, reason });
181}