Skip to main content

agentmux_srv/server/
agent_lifecycle.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What keeps agents that outlive their pane from piling up
5//! (`docs/specs/SPEC_ALWAYS_AVAILABLE_AGENTS_2026_10_27.md` §7, D5 and D6; P4a). With
6//! `agents:always_available` on, closing a pane no longer stops its agent, so two limits stand in for
7//! the pane:
8//!
9//! - **Idle stop (D5).** An agent with no view (its block is parked) that has been idle for the window
10//!   (`agents:idle_stop_minutes`, default 60, 0 = never; `agent:idle_stop_minutes` on its block
11//!   overrides it) is stopped by a sweep once a minute. It stays addressable: a message starts it and
12//!   resumes its session (`jekt_start`). Never stopped: an agent in a turn, one waiting on the user, one
13//!   that holds a claimed Kanban task or has a held message, or one that holds the build slot.
14//! - **Cap (D6).** A start (`agent_attach::start_agent`: `agent.start`, a message, a Job) is admitted
15//!   while fewer than `agents:max_running` (default 24, 0 = no cap) agent processes run and, on Windows,
16//!   commit use is under `agents:commit_limit_pct` (default 85, 0 = off). Over either, the agent idle
17//!   longest with no view is stopped to make room; when none can be, the start is refused with
18//!   `capacity:` and a message stays held.
19//!
20//! An agent that is shown in a pane is never stopped by either: it has a view. Off, none of this runs.
21
22use std::collections::HashMap;
23use std::time::Duration;
24
25use crate::backend::agent_state::{agent_status_of_block, AgentState};
26use crate::backend::{blockcontroller, obj};
27
28use super::AppState;
29
30pub const SETTING_IDLE_STOP_MINUTES: &str = "agents:idle_stop_minutes";
31pub const SETTING_MAX_RUNNING: &str = "agents:max_running";
32pub const SETTING_COMMIT_LIMIT_PCT: &str = "agents:commit_limit_pct";
33/// Block meta: this agent's own idle window in minutes (0 = never stop it).
34pub const META_IDLE_STOP_MINUTES: &str = "agent:idle_stop_minutes";
35
36const DEFAULT_IDLE_STOP_MINUTES: f64 = 60.0;
37const DEFAULT_MAX_RUNNING: f64 = 24.0;
38const DEFAULT_COMMIT_LIMIT_PCT: f64 = 85.0;
39/// How often the idle sweep runs.
40const SWEEP_EVERY: Duration = Duration::from_secs(60);
41
42/// The limits, from settings. `None`: that limit is off.
43#[derive(Debug, Clone, Copy, PartialEq)]
44pub(crate) struct Policy {
45    pub idle_stop_ms: Option<u64>,
46    pub max_running: Option<usize>,
47    pub commit_limit_pct: Option<f64>,
48}
49
50impl Policy {
51    pub(crate) fn from_extra(extra: &HashMap<String, serde_json::Value>) -> Self {
52        let num = |key: &str, default: f64| extra.get(key).and_then(|v| v.as_f64()).unwrap_or(default);
53        let on = |n: f64| (n > 0.0).then_some(n);
54        Self {
55            idle_stop_ms: on(num(SETTING_IDLE_STOP_MINUTES, DEFAULT_IDLE_STOP_MINUTES)).map(|m| (m * 60_000.0) as u64),
56            max_running: on(num(SETTING_MAX_RUNNING, DEFAULT_MAX_RUNNING)).map(|n| n as usize),
57            commit_limit_pct: on(num(SETTING_COMMIT_LIMIT_PCT, DEFAULT_COMMIT_LIMIT_PCT)),
58        }
59    }
60}
61
62fn policy(state: &AppState) -> Policy {
63    Policy::from_extra(&state.config_watcher.get_full_config().settings.extra)
64}
65
66/// A running agent process and what the policy needs to know about it.
67#[derive(Debug, Clone)]
68pub(crate) struct Live {
69    pub block_id: String,
70    /// The agent's slug (what a Kanban claim and the build slot name), else its id.
71    pub agent_id: String,
72    pub uid: String,
73    /// In no tab: nobody is looking at it.
74    pub parked: bool,
75    pub state: Option<AgentState>,
76    pub since_ms: u64,
77    /// The block's own window: `Some(None)` never stop it, `Some(Some(ms))` its own window.
78    pub idle_override: Option<Option<u64>>,
79}
80
81impl Live {
82    /// Idle with no view, so it may be stopped to make room. An agent set to never stop is not.
83    pub(crate) fn evictable(&self) -> bool {
84        self.parked && self.state == Some(AgentState::Idle) && self.idle_override != Some(None)
85    }
86
87    /// Idle with no view for longer than its window (`default_ms` unless the block sets its own).
88    pub(crate) fn idle_expired(&self, now_ms: u64, default_ms: Option<u64>) -> bool {
89        let window = self.idle_override.unwrap_or(default_ms);
90        self.evictable() && window.is_some_and(|w| now_ms.saturating_sub(self.since_ms) >= w)
91    }
92}
93
94/// When each parked agent block was first seen without a view (ms). The agent-state tracker times how
95/// long a state has lasted, shown in a pane or not; the idle window is for the time with no view.
96fn view_lost_at() -> &'static std::sync::Mutex<HashMap<String, u64>> {
97    static LOST: std::sync::OnceLock<std::sync::Mutex<HashMap<String, u64>>> = std::sync::OnceLock::new();
98    LOST.get_or_init(Default::default)
99}
100
101/// Move each parked agent's `since_ms` up to when it was first seen parked, and forget blocks that are
102/// shown again or gone. A sweep sees a pane's closing within a minute, so the window can only run long.
103fn idle_from_view_lost(lost: &mut HashMap<String, u64>, lives: &mut [Live], now: u64) {
104    lost.retain(|block_id, _| lives.iter().any(|l| l.parked && l.block_id == *block_id));
105    for l in lives.iter_mut().filter(|l| l.parked) {
106        let first_parked = *lost.entry(l.block_id.clone()).or_insert(now);
107        l.since_ms = l.since_ms.max(first_parked);
108    }
109}
110
111/// The block's own idle window: `Some(None)` never stop it, `Some(Some(ms))` its own window.
112pub(crate) fn idle_override_of(block: &obj::Block) -> Option<Option<u64>> {
113    block.meta.get(META_IDLE_STOP_MINUTES).and_then(|v| v.as_f64()).map(|m| (m > 0.0).then(|| (m * 60_000.0) as u64))
114}
115
116/// The idle window that applies to `block`: its own, else the default (`None`: no window).
117pub(crate) fn idle_window_of(state: &AppState, block: &obj::Block) -> Option<u64> {
118    idle_override_of(block).unwrap_or(policy(state).idle_stop_ms)
119}
120
121/// The agent processes running now, one per agent block that has a live controller.
122pub(crate) fn live_agents(state: &AppState) -> Vec<Live> {
123    let mstore = &state.mstore;
124    let now = agentmux_common::time::now_ms_u64();
125    let Ok(blocks) = super::app_api::agent_block::blocks_in_tabs_or_parked(mstore) else {
126        return Vec::new();
127    };
128    let mut lives: Vec<Live> = blocks
129        .into_iter()
130        .filter_map(|(block, tab)| {
131            let controller = blockcontroller::get_controller(&block.oid)?;
132            if controller.get_runtime_status().shellprocstatus != blockcontroller::STATUS_RUNNING {
133                return None;
134            }
135            let agent = crate::sagas::park_agents::agent_of_block(state, &block.oid, &block)?;
136            let slug = mstore.agent_def_get(&agent.id).ok().flatten().map(|d| d.slug).filter(|s| !s.is_empty());
137            let status = agent_status_of_block(mstore, &block.oid);
138            let idle_override = idle_override_of(&block);
139            Some(Live {
140                block_id: block.oid.clone(),
141                agent_id: slug.unwrap_or_else(|| agent.id.clone()),
142                uid: agent.id,
143                parked: tab.is_none(),
144                state: status.map(|s| s.state),
145                since_ms: status.map_or(now, |s| s.since_ms),
146                idle_override,
147            })
148        })
149        .collect();
150    idle_from_view_lost(&mut view_lost_at().lock().unwrap_or_else(|e| e.into_inner()), &mut lives, now);
151    lives
152}
153
154/// The ids of the agents running in this process: the only ones whose memory folders it looks at
155/// (`native_drift::OwnedAgents`). `Live::uid` is the `db_agents` row id, the same id as the agent
156/// definition and the memory roster (`AgentInstance::id == definition_id`, `row.rs`).
157pub(crate) fn running_agent_ids(state: &AppState) -> std::collections::HashSet<String> {
158    live_agents(state).into_iter().map(|l| l.uid).collect()
159}
160
161/// Why this agent is not stopped even when idle: it holds a claimed Kanban task, has a message held
162/// for it, or holds the build slot. `None`: nothing keeps it.
163pub(crate) fn exempt(state: &AppState, live: &Live) -> Option<&'static str> {
164    exempt_agent(state, &live.agent_id, &live.uid)
165}
166
167/// [`exempt`] for the agent `uid`, whose slug (else its id) is `agent_id`: what a Kanban claim and
168/// the build slot name.
169pub(crate) fn exempt_agent(state: &AppState, agent_id: &str, uid: &str) -> Option<&'static str> {
170    // A read that fails keeps the agent: stopping it on a guess could drop work.
171    match state.work_store.work_queue_claimed_by(agent_id, uid) {
172        Ok(claimed) if claimed.is_empty() => {}
173        Ok(_) => return Some("holds a claimed task"),
174        Err(_) => return Some("its claimed tasks could not be read"),
175    }
176    match state.mstore.jekt_held_targets() {
177        Ok(held) if !held.iter().any(|t| t == uid) => {}
178        Ok(_) => return Some("has a held message"),
179        Err(_) => return Some("its held messages could not be read"),
180    }
181    if build_slot_holder().is_some_and(|holder| holder.eq_ignore_ascii_case(agent_id)) {
182        return Some("holds the build slot");
183    }
184    None
185}
186
187/// The agent that holds the host's build slot (`~/.agentmux/shared/locks/build-slot.sh`), if any.
188fn build_slot_holder() -> Option<String> {
189    let owner = dirs::home_dir()?.join(".agentmux").join("shared").join("locks").join("build").join("slot").join("owner");
190    holder_in(&std::fs::read_to_string(owner).ok()?)
191}
192
193/// The `agent=` line of a build-slot owner file.
194fn holder_in(owner_file: &str) -> Option<String> {
195    owner_file.lines().find_map(|l| l.strip_prefix("agent=")).map(|a| a.trim().to_string()).filter(|a| !a.is_empty())
196}
197
198/// Stop `live` the way an explicit stop does (its process; the block, the transcript and the session stay).
199async fn stop(state: &AppState, live: &Live, why: &str) -> bool {
200    match crate::sagas::agent_teardown::stop(state, &live.block_id, true, None).await {
201        Ok(_) => {
202            tracing::info!(agent = %live.agent_id, block_id = %live.block_id, "agent lifecycle: stopped it ({why})");
203            true
204        }
205        Err(e) => {
206            tracing::warn!(agent = %live.agent_id, block_id = %live.block_id, "agent lifecycle: could not stop it ({why}): {e}");
207            false
208        }
209    }
210}
211
212/// The words of a note to the lead of an agent that was stopped to make room for another's start: who, why,
213/// what it was working on (its goal, cut short), and how to get it back.
214fn stop_note(victim: &str, started: &str, why: &str, goal: Option<&str>) -> String {
215    let mut note = format!("Your agent {victim} was stopped to make room for starting {started} ({why}).");
216    if let Some(goal) = goal.map(str::trim).filter(|g| !g.is_empty()) {
217        let short: String = goal.chars().take(160).collect();
218        note.push_str(&format!(" It was working on: {short}{}.", if short.len() < goal.len() { "…" } else { "" }));
219    }
220    note.push_str(" Start it again with Agents start once there is room.");
221    note
222}
223
224/// Tell the stopped agent's lead (see `worker_notes::tell_leader`) that admission stopped it: losing an agent
225/// in silence is what this exists to prevent.
226fn tell_leader_of_stop(state: &AppState, victim: &Live, started: &str, why: &str) {
227    let name_of = |id: &str| state.mstore.agent_def_get(id).ok().flatten().map(|d| d.name).unwrap_or_else(|| id.to_string());
228    let goal = state.mstore.get::<obj::Block>(&victim.block_id).ok().flatten().and_then(|b| crate::backend::work_facts::goal_of(&b.meta));
229    let note = stop_note(&name_of(&victim.uid), &name_of(started), why, goal.as_deref());
230    if !crate::backend::worker_notes::tell_leader(&state.mstore, &victim.uid, &note) {
231        tracing::info!(agent = %victim.agent_id, "agent lifecycle: no leader to tell that it was stopped to make room");
232    }
233}
234
235/// One idle sweep: stop each agent with no view that has been idle past its window and that nothing
236/// keeps running. Returns how many were stopped.
237pub(crate) async fn sweep_once(state: &AppState) -> usize {
238    if !crate::sagas::park_agents::enabled(state) {
239        return 0;
240    }
241    let default_ms = policy(state).idle_stop_ms;
242    let now = agentmux_common::time::now_ms_u64();
243    let mut stopped = 0;
244    for live in live_agents(state) {
245        if live.idle_expired(now, default_ms) && exempt(state, &live).is_none() && stop(state, &live, "idle with no view").await {
246            stopped += 1;
247        }
248    }
249    stopped
250}
251
252/// Run the idle sweep once a minute.
253pub(crate) fn install(state: &AppState) {
254    // An agent that starts a turn is wanted running, whatever stopped it before.
255    super::agent_wanted_running::install(state.broker.clone(), state.mstore.clone(), state.event_bus.clone());
256    let state = state.clone();
257    tokio::spawn(async move {
258        loop {
259            tokio::time::sleep(SWEEP_EVERY).await;
260            sweep_once(&state).await;
261        }
262    });
263}
264
265/// Commit use as a percentage of the commit limit, where the host reports it (Windows:
266/// `GlobalMemoryStatusEx`). `None` elsewhere: Linux overcommits and macOS has no commit limit, so no
267/// figure means no refusal.
268pub(crate) fn commit_used_pct() -> Option<f64> {
269    #[cfg(target_os = "windows")]
270    {
271        use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
272        let mut mem: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
273        mem.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
274        if unsafe { GlobalMemoryStatusEx(&mut mem) } != 0 && mem.ullTotalPageFile > 0 {
275            return Some((mem.ullTotalPageFile - mem.ullAvailPageFile) as f64 / mem.ullTotalPageFile as f64 * 100.0);
276        }
277    }
278    None
279}
280
281/// The commit (GB) the host can hold in all, where it reports one (Windows: `GlobalMemoryStatusEx`).
282pub(crate) fn commit_total_gb() -> Option<f64> {
283    #[cfg(target_os = "windows")]
284    {
285        use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
286        let mut mem: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
287        mem.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
288        if unsafe { GlobalMemoryStatusEx(&mut mem) } != 0 && mem.ullTotalPageFile > 0 {
289            return Some(mem.ullTotalPageFile as f64 / (1024.0 * 1024.0 * 1024.0));
290        }
291    }
292    None
293}
294
295/// What stopping one idle agent frees, in GB of commit: a `claude.exe` holds about 1 GB of private commit
296/// (`agents::runner::DEFAULT_AGENT_COMMIT_RESERVE_GB` has the measurement).
297const COMMIT_FREED_BY_ONE_STOP_GB: f64 = 1.0;
298
299/// Whether stopping one idle agent can bring commit use down to the limit. `Err` says how much has to go
300/// and that nothing was stopped, so a start that stops an agent for nothing is never made. With no total
301/// to size the shortfall against (non-Windows, or a failed read) it cannot tell, and the stop goes ahead.
302fn one_stop_brings_commit_down(used_pct: f64, limit_pct: f64, total_gb: Option<f64>) -> Result<(), String> {
303    let Some(total) = total_gb else { return Ok(()) };
304    let short_gb = (used_pct - limit_pct) / 100.0 * total;
305    if short_gb <= COMMIT_FREED_BY_ONE_STOP_GB {
306        return Ok(());
307    }
308    Err(format!(
309        "capacity: memory commit is at {used_pct:.0}% (the limit is {limit_pct:.0}%): about {short_gb:.1} GB has to be freed and stopping one idle agent frees about {COMMIT_FREED_BY_ONE_STOP_GB:.0} GB, so no agent was stopped. Free memory (close programs or stop agents), then start it again"
310    ))
311}
312
313/// The commit use and limit (percent) when use is over the limit, whichever limit `over_limit` names first
314/// (it names the cap before commit): a stop for the cap is as useless as one for commit when commit use is
315/// past what one stop frees.
316fn commit_over(policy: &Policy, used_pct: Option<f64>) -> Option<(f64, f64)> {
317    match (used_pct, policy.commit_limit_pct) {
318        (Some(used), Some(limit)) if used > limit => Some((used, limit)),
319        _ => None,
320    }
321}
322
323/// Which limit a start is over, and why.
324#[derive(Debug, PartialEq)]
325enum Over {
326    Cap(String),
327    Commit(String),
328}
329
330impl Over {
331    fn why(&self) -> &str {
332        match self {
333            Over::Cap(why) | Over::Commit(why) => why,
334        }
335    }
336}
337
338/// Whether the host is at its cap or over its commit limit, given the agents running.
339fn over_limit(policy: &Policy, running: usize, commit_pct: Option<f64>) -> Option<Over> {
340    if let Some(max) = policy.max_running.filter(|max| running >= *max) {
341        return Some(Over::Cap(format!("{running} agents are running (the limit is {max})")));
342    }
343    match (policy.commit_limit_pct, commit_pct) {
344        (Some(limit), Some(used)) if used > limit => Some(Over::Commit(format!("memory commit is at {used:.0}% (the limit is {limit:.0}%)"))),
345        _ => None,
346    }
347}
348
349/// How long an admitted start counts as running before its process shows as such.
350const PENDING_FOR: Duration = Duration::from_secs(90);
351
352/// Starts admitted but not yet seen running, so a burst of starts counts each other.
353/// Each entry holds a `Weak` to its instance's store: that keeps the store's address from being reused
354/// while the entry exists, and an entry whose store is gone (a test's) is dropped.
355type Reservation = (std::sync::Weak<crate::backend::storage::store::Store>, std::time::Instant);
356
357fn pending() -> &'static std::sync::Mutex<HashMap<String, Reservation>> {
358    static PENDING: std::sync::OnceLock<std::sync::Mutex<HashMap<String, Reservation>>> = std::sync::OnceLock::new();
359    PENDING.get_or_init(Default::default)
360}
361
362/// The reservations a batch made ([`admit_batch`]): only these let their agent's start through without
363/// counting the room again, and only once. An ordinary reservation (a start that was admitted) does not,
364/// or an agent started, stopped and started again within [`PENDING_FOR`] would skip the cap.
365fn batch_held() -> &'static std::sync::Mutex<std::collections::HashSet<String>> {
366    static HELD: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<String>>> = std::sync::OnceLock::new();
367    HELD.get_or_init(Default::default)
368}
369
370/// The key of an admitted start: per store, so two instances in one process (tests) do not count each other.
371fn pending_key(state: &AppState, agent_id: &str) -> String {
372    format!("{:p}:{agent_id}", std::sync::Arc::as_ptr(&state.mstore))
373}
374
375/// The admitted starts of this instance that are not yet running and not yet [`PENDING_FOR`] old. One
376/// seen among `live` is dropped for good: it counts as itself from then on, and if it is stopped to
377/// make room it must not count a second time.
378fn pending_not_running(state: &AppState, live: &[Live]) -> usize {
379    let prefix = pending_key(state, "");
380    let mut pending = pending().lock().unwrap_or_else(|e| e.into_inner());
381    pending.retain(|key, (store, at)| {
382        if at.elapsed() >= PENDING_FOR || store.strong_count() == 0 {
383            return false;
384        }
385        match key.strip_prefix(prefix.as_str()) {
386            Some(id) => !live.iter().any(|l| l.uid == id || l.agent_id == id),
387            None => true,
388        }
389    });
390    pending.keys().filter(|key| key.starts_with(prefix.as_str())).count()
391}
392
393/// Whether `agent_id` holds a reservation that has not run out.
394fn is_reserved(state: &AppState, agent_id: &str) -> bool {
395    pending().lock().unwrap_or_else(|e| e.into_inner()).get(&pending_key(state, agent_id)).is_some_and(|(store, at)| at.elapsed() < PENDING_FOR && store.strong_count() > 0)
396}
397
398/// Whether `agent_id`'s start is the one a batch reserved room for, taking that claim: the next start
399/// of the agent is counted as any other.
400fn take_batch_claim(state: &AppState, agent_id: &str) -> bool {
401    let key = pending_key(state, agent_id);
402    is_reserved(state, agent_id) && batch_held().lock().unwrap_or_else(|e| e.into_inner()).remove(&key)
403}
404
405/// A start that was admitted did not happen (the agent is unknown, its provider has no headless mode, its
406/// CLI is missing): its room is free again.
407pub(crate) fn release_start(state: &AppState, agent_id: &str) {
408    let key = pending_key(state, agent_id);
409    batch_held().lock().unwrap_or_else(|e| e.into_inner()).remove(&key);
410    pending().lock().unwrap_or_else(|e| e.into_inner()).remove(&key);
411}
412
413/// The room [`admit_batch`] claimed under the stand-in key `from` is now the agent `to`'s, in one step:
414/// a batch that makes its agents as it goes (spawn) keeps its room under stand-ins until each exists,
415/// and the agent's own start must find its room reserved, not count it against itself.
416pub(crate) fn rekey_reservation(state: &AppState, from: &str, to: &str) {
417    let mut pending = pending().lock().unwrap_or_else(|e| e.into_inner());
418    let (from_key, to_key) = (pending_key(state, from), pending_key(state, to));
419    if let Some(reservation) = pending.remove(&from_key) {
420        pending.insert(to_key.clone(), reservation);
421        let mut claims = batch_held().lock().unwrap_or_else(|e| e.into_inner());
422        if claims.remove(&from_key) {
423            claims.insert(to_key);
424        }
425    }
426}
427
428/// One admission at a time: the count, the stop that makes room and the claim of the room are one step.
429fn admission() -> &'static tokio::sync::Mutex<()> {
430    static LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
431    &LOCK
432}
433
434/// May `agent_id` be started? Yes when it already runs, when nothing is over a limit, or when an idle
435/// agent with no view can be stopped to make room; otherwise `Err("capacity: ...")`.
436pub(crate) async fn admit_start(state: &AppState, agent_id: &str) -> Result<(), String> {
437    admit(state, agent_id, commit_used_pct, commit_total_gb, true).await
438}
439
440pub(crate) async fn admit_start_with(state: &AppState, agent_id: &str, commit_pct: impl Fn() -> Option<f64>) -> Result<(), String> {
441    admit(state, agent_id, commit_pct, || None, true).await
442}
443
444/// [`admit_start_with`] with the host's commit total given too: with one, a stop that cannot free enough is
445/// not made.
446#[cfg(test)]
447pub(crate) async fn admit_start_with_total(state: &AppState, agent_id: &str, commit_pct: impl Fn() -> Option<f64>, commit_total: impl Fn() -> Option<f64>) -> Result<(), String> {
448    admit(state, agent_id, commit_pct, commit_total, true).await
449}
450
451/// Why `agent_id`'s start would be refused now: [`admit_start`] without its side effects (it stops no one
452/// and claims no room), so a sender is not told "starting" about a start that will not happen. `None`:
453/// it would go ahead, or no limit applies.
454pub(crate) fn start_blocked(state: &AppState, agent_id: &str) -> Option<String> {
455    start_blocked_with(state, agent_id, commit_used_pct, commit_total_gb)
456}
457
458pub(crate) fn start_blocked_with(state: &AppState, agent_id: &str, commit_pct: impl Fn() -> Option<f64>, commit_total: impl Fn() -> Option<f64>) -> Option<String> {
459    let live = live_agents(state);
460    if live.iter().any(|l| l.uid == agent_id || l.agent_id == agent_id) {
461        return None;
462    }
463    // A host agent in a folder a container agent can write waits for the person, whatever the limits say.
464    if let Some(why) = state.mstore.agent_def_get(agent_id).ok().flatten().and_then(|def| crate::backend::folder_overlap::waiting_reason(&state.mstore, &def)) {
465        return Some(why);
466    }
467    if !crate::sagas::park_agents::enabled(state) || is_reserved(state, agent_id) {
468        return None;
469    }
470    let policy = policy(state);
471    let used = commit_pct();
472    let over = over_limit(&policy, live.len() + pending_not_running(state, &live), used)?;
473    if let Some((used, limit)) = commit_over(&policy, used) {
474        if let Err(why) = one_stop_brings_commit_down(used, limit, commit_total()) {
475            return Some(why);
476        }
477    }
478    let can_stop_one = live.iter().any(|l| l.evictable() && exempt(state, l).is_none());
479    (!can_stop_one).then(|| format!("capacity: {}, and no agent with no view is idle enough to stop for it", over.why()))
480}
481
482/// [`admit_start`] for a start that must not cost another agent its process (restart resume): over a limit
483/// it is refused with `Err("capacity: ...")` where `admit_start` would stop an idle agent to make room.
484/// The check and the claim of the room are one step under the admission lock.
485pub(crate) async fn admit_start_without_eviction(state: &AppState, agent_id: &str) -> Result<(), String> {
486    admit(state, agent_id, commit_used_pct, commit_total_gb, false).await
487}
488
489async fn admit(state: &AppState, agent_id: &str, commit_pct: impl Fn() -> Option<f64>, commit_total: impl Fn() -> Option<f64>, evict: bool) -> Result<(), String> {
490    if !crate::sagas::park_agents::enabled(state) {
491        return Ok(());
492    }
493    // A batch already claimed this agent's room (`admit_batch`): its start is the one that room is for.
494    if take_batch_claim(state, agent_id) {
495        return Ok(());
496    }
497    let policy = policy(state);
498    if policy.max_running.is_none() && policy.commit_limit_pct.is_none() {
499        return Ok(());
500    }
501    let _one_at_a_time = admission().lock().await;
502    let mut live = live_agents(state);
503    if live.iter().any(|l| l.uid == agent_id || l.agent_id == agent_id) {
504        return Ok(());
505    }
506    let mut could_not_stop = std::collections::HashSet::new();
507    let mut stopped_for_commit = None;
508    loop {
509        let used = commit_pct();
510        let Some(over) = over_limit(&policy, live.len() + pending_not_running(state, &live), used) else {
511            let reservation = (std::sync::Arc::downgrade(&state.mstore), std::time::Instant::now());
512            pending().lock().unwrap_or_else(|e| e.into_inner()).insert(pending_key(state, agent_id), reservation);
513            return Ok(());
514        };
515        if !evict {
516            return Err(format!("capacity: {}, and this start does not stop other agents", over.why()));
517        }
518        // The commit figure may not fall until a stopped process has fully exited: one stop per start,
519        // not every idle agent for a figure that is slow to move (or held up by something else).
520        let commit_over = commit_over(&policy, used);
521        if let (Some((used, limit)), Some(stopped)) = (commit_over, &stopped_for_commit) {
522            return Err(format!("capacity: memory commit is at {used:.0}% (the limit is {limit:.0}%), and stopping {stopped} did not bring it down"));
523        }
524        if let Some((used, limit)) = commit_over {
525            one_stop_brings_commit_down(used, limit, commit_total())?;
526        }
527        let victim = live
528            .iter()
529            .filter(|l| l.evictable() && !could_not_stop.contains(&l.block_id) && exempt(state, l).is_none())
530            .min_by_key(|l| l.since_ms)
531            .cloned();
532        let Some(victim) = victim else {
533            return Err(format!("capacity: {}, and no agent with no view is idle enough to stop for it", over.why()));
534        };
535        if stop(state, &victim, &format!("to make room: {}", over.why())).await {
536            tell_leader_of_stop(state, &victim, agent_id, over.why());
537            if commit_over.is_some() {
538                stopped_for_commit = Some(victim.agent_id.clone());
539            }
540            live.retain(|l| l.block_id != victim.block_id);
541        } else {
542            could_not_stop.insert(victim.block_id);
543        }
544    }
545}
546
547/// An agent a batch would start: the key its room is held under (its id, or a stand-in while it does
548/// not exist yet) and the name a refusal gives it.
549pub(crate) struct Wanted {
550    pub key: String,
551    pub label: String,
552}
553
554/// "A", "A and B", "A, B and C".
555fn names_in_words(labels: &[&str]) -> String {
556    match labels {
557        [] => String::new(),
558        [only] => (*only).to_string(),
559        [init @ .., last] => format!("{} and {last}", init.join(", ")),
560    }
561}
562
563/// May all of `wanted` start? A batch never stops an agent to make room (a start may stop one idle
564/// agent with no view; five of them stopping five would be a mass stop nobody asked for), and it is
565/// admitted whole or refused whole. Those already running need no room. With `reserve` the room is
566/// claimed under the same lock as the check, so a start that comes between this and the batch's own
567/// cannot take it; [`release_batch`] gives it back when the batch is done or failed.
568pub(crate) async fn admit_batch(state: &AppState, wanted: &[Wanted], reserve: bool) -> Result<(), String> {
569    admit_batch_with(state, wanted, reserve, commit_used_pct).await
570}
571
572pub(crate) async fn admit_batch_with(state: &AppState, wanted: &[Wanted], reserve: bool, commit_pct: impl Fn() -> Option<f64>) -> Result<(), String> {
573    if !crate::sagas::park_agents::enabled(state) {
574        return Ok(());
575    }
576    let policy = policy(state);
577    if policy.max_running.is_none() && policy.commit_limit_pct.is_none() {
578        return Ok(());
579    }
580    let _one_at_a_time = admission().lock().await;
581    let live = live_agents(state);
582    let to_start: Vec<&Wanted> = wanted.iter().filter(|w| !live.iter().any(|l| l.uid == w.key || l.agent_id == w.key) && !is_reserved(state, &w.key)).collect();
583    if to_start.is_empty() {
584        return Ok(());
585    }
586    let running = live.len() + pending_not_running(state, &live);
587    let asked = to_start.len();
588    let room = policy.max_running.map_or(usize::MAX, |max| max.saturating_sub(running));
589    let idle = live.iter().filter(|l| l.evictable() && exempt(state, l).is_none()).count();
590    let stop_some = if idle > 0 { format!("Stop some agents ({idle} {} idle with no view), or ask for fewer.", if idle == 1 { "is" } else { "are" }) } else { "Stop some agents, or ask for fewer.".to_string() };
591    if let (Some(limit), Some(used)) = (policy.commit_limit_pct, commit_pct()) {
592        if used > limit {
593            return Err(format!("capacity: memory commit is at {used:.0}% (the limit is {limit:.0}%), so none of the {asked} asked would start. {stop_some}"));
594        }
595    }
596    if asked > room {
597        let max = policy.max_running.unwrap_or(running);
598        let labels: Vec<&str> = to_start.iter().map(|w| w.label.as_str()).collect();
599        let fit = names_in_words(&labels[..room]);
600        let rest = names_in_words(&labels[room..]);
601        let outcome = if room == 0 { format!("none of the {asked} asked would fit: {rest}") } else { format!("room for {room} of the {asked} asked: {fit} would fit, {rest} would not") };
602        return Err(format!("capacity: {running} agents are running (the limit is {max}); {outcome}. {stop_some}"));
603    }
604    if reserve {
605        let mut held = pending().lock().unwrap_or_else(|e| e.into_inner());
606        let mut claims = batch_held().lock().unwrap_or_else(|e| e.into_inner());
607        for w in to_start {
608            let key = pending_key(state, &w.key);
609            claims.insert(key.clone());
610            held.insert(key, (std::sync::Arc::downgrade(&state.mstore), std::time::Instant::now()));
611        }
612    }
613    Ok(())
614}
615
616/// Give back the room [`admit_batch`] claimed for `wanted`: the batch is done (its agents run, and
617/// count as themselves) or failed.
618pub(crate) fn release_batch(state: &AppState, wanted: &[Wanted]) {
619    for w in wanted {
620        release_start(state, &w.key);
621    }
622}
623
624#[cfg(test)]
625mod tests;