Skip to main content

agentmux_srv_core/backend/supervisor/
settings.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Supervisor's settings: the master switch and the limits. Read from the
5//! live config when a decision is made, never from a snapshot taken at start,
6//! so a change in the Settings pane or by hand in settings.json applies to the
7//! next decision. docs/specs/SPEC_SWARM_SECTIONS_SUPERVISOR_SETTINGS_AND_KANBAN_2026_10_24.md §5, §6.2.
8
9use std::sync::{Arc, OnceLock};
10
11use crate::backend::wconfig::ConfigState;
12
13use super::{Limits, SupervisorMode};
14
15/// `supervisor:enabled`: the master switch. While off nothing is judged or
16/// continued and a mode can't be set (Off is always accepted).
17pub const KEY_ENABLED: &str = "supervisor:enabled";
18pub const KEY_STEADY_CONTINUATIONS: &str = "supervisor:steady:continuations";
19pub const KEY_STEADY_MINUTES: &str = "supervisor:steady:minutes";
20pub const KEY_DRIVE_CONTINUATIONS: &str = "supervisor:drive:continuations";
21pub const KEY_DRIVE_MINUTES: &str = "supervisor:drive:minutes";
22pub const KEY_NO_PROGRESS: &str = "supervisor:noprogress";
23/// `supervisor:cooldown`: seconds between a turn's end and its continuation.
24pub const KEY_COOLDOWN: &str = "supervisor:cooldown";
25/// `supervisor:hourly`: continuations across all panes in a rolling hour.
26pub const KEY_HOURLY: &str = "supervisor:hourly";
27pub const KEY_NOTIFY_NEEDS_YOU: &str = "supervisor:notify:needsyou";
28pub const KEY_NOTIFY_LIMIT: &str = "supervisor:notify:limit";
29pub const KEY_NOTIFY_FAILED: &str = "supervisor:notify:failed";
30pub const KEY_NOTIFY_DONE: &str = "supervisor:notify:done";
31
32/// Every key the Supervisor reads, for callers that watch for a change.
33pub const KEYS: [&str; 12] = [
34    KEY_ENABLED,
35    KEY_STEADY_CONTINUATIONS,
36    KEY_STEADY_MINUTES,
37    KEY_DRIVE_CONTINUATIONS,
38    KEY_DRIVE_MINUTES,
39    KEY_NO_PROGRESS,
40    KEY_COOLDOWN,
41    KEY_HOURLY,
42    KEY_NOTIFY_NEEDS_YOU,
43    KEY_NOTIFY_LIMIT,
44    KEY_NOTIFY_FAILED,
45    KEY_NOTIFY_DONE,
46];
47
48// The defaults are the schema's (schema/settings.json); the settings-defaults
49// test checks they agree.
50const DEFAULT_ENABLED: bool = false;
51const DEFAULT_STEADY_CONTINUATIONS: u32 = 5;
52const DEFAULT_STEADY_MINUTES: u32 = 0;
53const DEFAULT_DRIVE_CONTINUATIONS: u32 = 15;
54const DEFAULT_DRIVE_MINUTES: u32 = 120;
55const DEFAULT_NO_PROGRESS: u32 = 2;
56const DEFAULT_COOLDOWN: u32 = 30;
57const DEFAULT_HOURLY: u32 = 30;
58const DEFAULT_NOTIFY: bool = true;
59
60/// Bounds a value is clamped to (a hand edit can be anything).
61const CONTINUATIONS_RANGE: (u32, u32) = (1, 100);
62const MINUTES_RANGE: (u32, u32) = (0, 1440);
63const NO_PROGRESS_RANGE: (u32, u32) = (1, 10);
64const COOLDOWN_RANGE: (u32, u32) = (0, 600);
65const HOURLY_RANGE: (u32, u32) = (0, 1000);
66
67static CONFIG: OnceLock<Arc<ConfigState>> = OnceLock::new();
68
69/// Attach the live settings (bootstrap). Until then the defaults apply.
70pub fn install_config(config: Arc<ConfigState>) {
71    let _ = CONFIG.set(config);
72}
73
74/// What the settings say now.
75#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub struct SupervisorSettings {
77    pub enabled: bool,
78    pub steady_continuations: u32,
79    pub steady_minutes: u32,
80    pub drive_continuations: u32,
81    pub drive_minutes: u32,
82    pub no_progress: u32,
83    /// Seconds a continuation waits after its turn ended (0 sends at once).
84    pub cooldown_secs: u32,
85    /// Continuations across every pane in a rolling hour (0 is no cap).
86    pub hourly: u32,
87    pub notify_needs_you: bool,
88    pub notify_limit: bool,
89    pub notify_failed: bool,
90    pub notify_done: bool,
91}
92
93/// The groups of Supervisor notices the notify settings narrow.
94#[derive(Clone, Copy, Debug, PartialEq, Eq)]
95pub enum NoticeGroup {
96    /// It needs you: a question, "needs you", "blocked".
97    NeedsYou,
98    /// It hit a limit: continuations, time, no progress, the same reply twice, the fleet budget.
99    Limit,
100    /// It couldn't continue: delivery failed, the agent can't run.
101    Failed,
102    /// It found the work done.
103    Done,
104}
105
106impl Default for SupervisorSettings {
107    fn default() -> Self {
108        SupervisorSettings {
109            enabled: DEFAULT_ENABLED,
110            steady_continuations: DEFAULT_STEADY_CONTINUATIONS,
111            steady_minutes: DEFAULT_STEADY_MINUTES,
112            drive_continuations: DEFAULT_DRIVE_CONTINUATIONS,
113            drive_minutes: DEFAULT_DRIVE_MINUTES,
114            no_progress: DEFAULT_NO_PROGRESS,
115            cooldown_secs: DEFAULT_COOLDOWN,
116            hourly: DEFAULT_HOURLY,
117            notify_needs_you: DEFAULT_NOTIFY,
118            notify_limit: DEFAULT_NOTIFY,
119            notify_failed: DEFAULT_NOTIFY,
120            notify_done: DEFAULT_NOTIFY,
121        }
122    }
123}
124
125/// Whether this out-of-range `(key, value)` hasn't been logged yet: settings
126/// are read at every decision, and one bad value would repeat its warning.
127fn first_clamp(key: &str, value: u64) -> bool {
128    static LOGGED: std::sync::Mutex<Vec<(String, u64)>> = std::sync::Mutex::new(Vec::new());
129    let mut logged = LOGGED.lock().unwrap_or_else(|e| e.into_inner());
130    if logged.iter().any(|(k, v)| k == key && *v == value) {
131        return false;
132    }
133    if logged.len() >= 64 {
134        logged.clear();
135    }
136    logged.push((key.to_string(), value));
137    true
138}
139
140fn number(config: &ConfigState, key: &str, default: u32, (min, max): (u32, u32)) -> u32 {
141    match config.extra_u64(key) {
142        None => default,
143        Some(v) => {
144            let clamped = v.clamp(u64::from(min), u64::from(max)) as u32;
145            if u64::from(clamped) != v && first_clamp(key, v) {
146                tracing::warn!(key, value = v, used = clamped, "supervisor: setting out of range, clamped");
147            }
148            clamped
149        }
150    }
151}
152
153impl SupervisorSettings {
154    pub fn from_config(config: &ConfigState) -> Self {
155        SupervisorSettings {
156            enabled: config.extra_bool(KEY_ENABLED).unwrap_or(DEFAULT_ENABLED),
157            steady_continuations: number(config, KEY_STEADY_CONTINUATIONS, DEFAULT_STEADY_CONTINUATIONS, CONTINUATIONS_RANGE),
158            steady_minutes: number(config, KEY_STEADY_MINUTES, DEFAULT_STEADY_MINUTES, MINUTES_RANGE),
159            drive_continuations: number(config, KEY_DRIVE_CONTINUATIONS, DEFAULT_DRIVE_CONTINUATIONS, CONTINUATIONS_RANGE),
160            drive_minutes: number(config, KEY_DRIVE_MINUTES, DEFAULT_DRIVE_MINUTES, MINUTES_RANGE),
161            no_progress: number(config, KEY_NO_PROGRESS, DEFAULT_NO_PROGRESS, NO_PROGRESS_RANGE),
162            cooldown_secs: number(config, KEY_COOLDOWN, DEFAULT_COOLDOWN, COOLDOWN_RANGE),
163            hourly: number(config, KEY_HOURLY, DEFAULT_HOURLY, HOURLY_RANGE),
164            notify_needs_you: config.extra_bool(KEY_NOTIFY_NEEDS_YOU).unwrap_or(DEFAULT_NOTIFY),
165            notify_limit: config.extra_bool(KEY_NOTIFY_LIMIT).unwrap_or(DEFAULT_NOTIFY),
166            notify_failed: config.extra_bool(KEY_NOTIFY_FAILED).unwrap_or(DEFAULT_NOTIFY),
167            notify_done: config.extra_bool(KEY_NOTIFY_DONE).unwrap_or(DEFAULT_NOTIFY),
168        }
169    }
170
171    /// The settings now; the defaults before the config is attached.
172    pub fn current() -> Self {
173        #[cfg(any(test, feature = "test-support"))]
174        if let Some(s) = SETTINGS_IN_TEST.with(|c| c.get()) {
175            return s;
176        }
177        CONFIG.get().map(|c| Self::from_config(c)).unwrap_or_default()
178    }
179
180    /// Whether the OS notification for `group` is on. The rows, lines and
181    /// history show every stop regardless; the global `notify:os:*` toggles
182    /// still apply on top.
183    pub fn notifies(&self, group: NoticeGroup) -> bool {
184        match group {
185            NoticeGroup::NeedsYou => self.notify_needs_you,
186            NoticeGroup::Limit => self.notify_limit,
187            NoticeGroup::Failed => self.notify_failed,
188            NoticeGroup::Done => self.notify_done,
189        }
190    }
191
192    /// `mode`'s limits under these settings. Off has none.
193    pub fn limits(&self, mode: SupervisorMode) -> Limits {
194        let minutes = |m: u32| (m > 0).then(|| u64::from(m) * 60 * 1000);
195        match mode {
196            SupervisorMode::Off => Limits { continuations: 0, run_ms: None, no_progress: 0 },
197            SupervisorMode::Steady => Limits {
198                continuations: self.steady_continuations,
199                run_ms: minutes(self.steady_minutes),
200                no_progress: self.no_progress,
201            },
202            SupervisorMode::Drive => Limits {
203                continuations: self.drive_continuations,
204                run_ms: minutes(self.drive_minutes),
205                no_progress: self.no_progress,
206            },
207        }
208    }
209}
210
211#[cfg(any(test, feature = "test-support"))]
212thread_local! {
213    static ENABLED_IN_TEST: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
214    static SETTINGS_IN_TEST: std::cell::Cell<Option<SupervisorSettings>> = const { std::cell::Cell::new(None) };
215}
216
217/// Make [`SupervisorSettings::current`] return `settings` for the calling test thread only.
218#[cfg(test)]
219pub fn set_settings_for_test(settings: SupervisorSettings) {
220    SETTINGS_IN_TEST.with(|c| c.set(Some(settings)));
221}
222
223/// Set the master switch for the calling test thread only.
224#[cfg(test)]
225pub fn set_enabled_for_test(on: bool) {
226    ENABLED_IN_TEST.with(|c| c.set(Some(on)));
227}
228
229/// Whether the master switch is on now.
230pub fn enabled() -> bool {
231    #[cfg(any(test, feature = "test-support"))]
232    if let Some(on) = ENABLED_IN_TEST.with(|c| c.get()) {
233        return on;
234    }
235    CONFIG.get().and_then(|c| c.extra_bool(KEY_ENABLED)).unwrap_or(DEFAULT_ENABLED)
236}
237
238/// The sentence a refused mode change gives.
239pub const SWITCHED_OFF: &str = "The Supervisor is switched off. Turn it on with supervisor:enabled in the settings.";
240
241/// Log a settings write that touches the Supervisor's keys, with who made it
242/// (`agent_id` is empty for the app itself).
243pub fn log_change(new_keys: &serde_json::Map<String, serde_json::Value>, agent_id: &str) {
244    let changed: Vec<String> =
245        KEYS.iter().filter_map(|k| new_keys.get(*k).map(|v| format!("{k}={v}"))).collect();
246    if changed.is_empty() {
247        return;
248    }
249    let caller = if agent_id.is_empty() { "the app" } else { agent_id };
250    tracing::info!(caller, changed = %changed.join(", "), "supervisor: settings changed");
251}
252
253/// Parse a `setconfig` request into its keys, logging who changed a
254/// Supervisor key (anyone who can write settings may; none is anonymous).
255pub fn parse_setconfig(
256    data: serde_json::Value,
257    agent_id: &str,
258) -> Result<serde_json::Map<String, serde_json::Value>, String> {
259    let keys: serde_json::Map<String, serde_json::Value> =
260        serde_json::from_value(data).map_err(|e| format!("setconfig: {e}"))?;
261    log_change(&keys, agent_id);
262    Ok(keys)
263}