Skip to main content

agentmux_srv/sagas/
agent_teardown.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Agent teardown — the ONE path that stops what an agent owns
5// (docs/specs/SPEC_AGENT_TEARDOWN_SINGLE_PATH_2026_10_01.md).
6//
7// Every way of ending an agent calls this with a `Policy`; nothing else in
8// srv stops an agent's processes (the structural test below pins it):
9//
10// | Consumer                                              | Policy            |
11// |-------------------------------------------------------|-------------------|
12// | pane × / tab × / window-tab × / window ×, ClosePane    | `Policy::close()` |
13// |   (`close_pane`, `delete_block`, `delete_tab`,        |                   |
14// |   `delete_workspace`; the orphan reaper via close_pane)|                   |
15// | `/quit`, `QuitSelf`, no-arg `ClosePane` (`self_quit`)  | `Policy::quit()`  |
16// | Stop, `agent.stop`, `FleetBulkStop` Stop               | `Policy::stop(..)`|
17// | The pane's `AgentStop`, the watchdog (no `AppState`)   | `Policy::stop_cli_only(..)` |
18// |   (`stop_now`; the watchdog then releases the claims   |                   |
19// |   itself, `watchdog::after_stop`, since this keeps them)|                  |
20// | Controller replace (`resync_controller`)              | `Policy::replace()` |
21// | App exit (`main.rs`)                                  | `Policy::app_exit()` |
22// | A drawer closed, a `/btw` throwaway, a spawn rollback, | `discard`         |
23// |   the backstop after a close                          |                   |
24//
25// `Shell()` and `!cmd` processes join the agent's tracker when they spawn
26// (`track_adopted`), and a graceful teardown closes the agent's PtyShell
27// drawers first, so all of them end with it.
28//
29// Phase 1 moved today's behaviour here unchanged, encoded as policies: the
30// close and quit paths are the former `close_pane::shutdown_one` and
31// `self_quit`'s claim/shell steps, verbatim; Stop is `ctrl.stop()`. Phase 2 adds controller
32// replace (`stop_for_replace`, unchanged) and app exit, which now closes every
33// agent gracefully instead of leaving them to the launcher's backstop. Later
34// phases change what a policy covers (spec §10) without touching the consumers.
35
36use serde::Serialize;
37
38use crate::backend::blockcontroller;
39pub(crate) use crate::backend::work_claims::release_claims;
40use crate::server::agent_resources::{self, AgentIdentity, AgentResources};
41use crate::server::AppState;
42
43use super::close_pane::{exit_line, process_extra, process_line, publish_shutdown, save_final_state, short_command, ShutdownExtra};
44
45/// How the agent's own process is stopped.
46#[derive(Clone, Copy, Debug, PartialEq, Eq)]
47pub enum CliStop {
48    /// Stop routing input to it, end the turn, ask it to exit, force-kill at
49    /// the deadline, then drop the block's process tracker (which takes what
50    /// the agent started) and save its final state (spec §6.2 steps 1, 4–9).
51    Graceful,
52    /// `controller.stop()` and nothing else: the controller stays registered
53    /// and the tracker is kept, so what the agent started keeps running
54    /// (today's Stop; spec §5).
55    StopOnly { graceful: bool },
56    /// The controller is being replaced by a new one for the same block
57    /// (session restart): only its own CLI process dies; the tracker and
58    /// every declared-background task survive and are adopted by the new
59    /// controller (`SPEC_BACKGROUND_TASK_TEARDOWN_SURVIVAL_2026_08_20.md`).
60    Replace,
61}
62
63/// What one teardown covers (spec §5). A consumer picks a constructor; it
64/// never adds its own kill code.
65#[derive(Clone, Copy, Debug, PartialEq, Eq)]
66pub struct Policy {
67    pub cli: CliStop,
68    /// Release the agent's work-queue claims (R7) and report the crons that
69    /// target it (R8, kept).
70    pub release_claims: bool,
71    /// Stop the srv-spawned `Shell()` sessions it started (R3).
72    pub stop_shell_sessions: bool,
73    /// Stop its declared `run_in_background` tasks (R2) explicitly. A
74    /// graceful close takes them anyway with the tracker; this is for Stop,
75    /// which keeps the tracker (spec §5, §7.4).
76    pub stop_background: bool,
77    /// Stop a container agent's container (R6), which also drops its
78    /// dev-proxy routes. Stopped, not removed: the next launch restarts it
79    /// (`ContainerManager::ensure_running`), and its volume keeps its state.
80    pub stop_container: bool,
81    /// Dock the floating panes the agent opened into its own tab (choice 4 of
82    /// `SPEC_AGENT_PANE_PLACEMENT_FLOATING_2026_11_22.md`). Only for a Stop: the agent's pane and tab stay, so the
83    /// panes have a tab to go back to; a closing pane or tab would take them with it.
84    pub dock_floaters: bool,
85}
86
87impl Policy {
88    /// A pane, tab, window-tab or window closing: the agent and everything
89    /// it runs, `Shell()` sessions included; claims stay until their lease
90    /// expires, as before (spec §5).
91    pub const fn close() -> Self {
92        Self { cli: CliStop::Graceful, release_claims: false, stop_shell_sessions: true, stop_background: false, stop_container: true, dock_floaters: false }
93    }
94    /// `/quit`, `QuitSelf`, no-argument `ClosePane`: everything (spec §0).
95    pub const fn quit() -> Self {
96        Self { cli: CliStop::Graceful, release_claims: true, stop_shell_sessions: true, stop_background: false, stop_container: true, dock_floaters: false }
97    }
98    /// Stop (`agent.stop`, `FleetBulkStop`): the CLI, and its background
99    /// tasks only if asked; its claims go back to the pool (spec §5). The
100    /// block, its `Shell()` sessions and drawers stay.
101    pub const fn stop(graceful: bool, stop_background: bool) -> Self {
102        Self { cli: CliStop::StopOnly { graceful }, release_claims: true, stop_shell_sessions: false, stop_background, stop_container: false, dock_floaters: true }
103    }
104    /// The watchdog's max-runtime / idle stop: the CLI only, as it always
105    /// has been. Its claims stay, since it may be restarted on the next
106    /// message.
107    pub const fn stop_cli_only(graceful: bool) -> Self {
108        Self { cli: CliStop::StopOnly { graceful }, release_claims: false, stop_shell_sessions: false, stop_background: false, stop_container: false, dock_floaters: false }
109    }
110    /// Restart / controller replace: the CLI only; background tasks survive.
111    pub const fn replace() -> Self {
112        Self { cli: CliStop::Replace, release_claims: false, stop_shell_sessions: false, stop_background: false, stop_container: false, dock_floaters: false }
113    }
114    /// App exit: every agent closes gracefully and its `Shell()` sessions
115    /// stop. Claims stay: the agent comes back with the app and its lease
116    /// covers the gap (spec §5).
117    pub const fn app_exit() -> Self {
118        Self { cli: CliStop::Graceful, release_claims: false, stop_shell_sessions: true, stop_background: false, stop_container: true, dock_floaters: false }
119    }
120}
121
122/// Setting: does Stop keep the agent's `run_in_background` tasks (dev
123/// servers) running when the caller doesn't say? Per user, default `true`,
124/// today's behaviour (spec §11 O2).
125pub const SETTING_STOP_KEEPS_BACKGROUND: &str = "agent:stopkeepsbackground";
126
127/// App exit's overall cap (spec §11 O3), the leftover-shell sweep included:
128/// every agent closes concurrently under it. The launcher waits longer than
129/// this for srv to exit on every quit (`SRV_EXIT_WAIT`, `quiesce_srv`), so
130/// it force-kills srv only if the teardown overran.
131pub const APP_EXIT_CAP: std::time::Duration = agentmux_common::process::SRV_APP_EXIT_CAP;
132
133/// The grace the leftover-shell sweep gives its kill tasks. [reagent #1422 P2]
134const SHELL_SWEEP_GRACE: std::time::Duration = std::time::Duration::from_millis(800);
135
136/// What a teardown did, for the consumer's summary and the audit.
137#[derive(Clone, Debug, Default, Serialize)]
138pub struct TeardownReport {
139    pub block_id: String,
140    /// The agent's id, else its block id.
141    pub agent: String,
142    pub released_claims: usize,
143    pub stopped_shells: usize,
144    /// Cron jobs still targeting the agent (kept).
145    pub crons_targeting: Vec<String>,
146    /// Background tasks stopped explicitly (Stop with `stop_background`).
147    pub stopped_background: usize,
148    /// Stop only: the CLI stop failed. Nothing else was touched (claims and
149    /// background tasks stay), and [`stop`] returns this as its error.
150    #[serde(skip_serializing_if = "Option::is_none")]
151    pub stop_error: Option<String>,
152    /// The container agent's container that was stopped, if any.
153    pub stopped_container: Option<String>,
154    /// Running Docker Compose containers from the agent's working directory,
155    /// left running and reported (`compose_containers_left`).
156    #[serde(skip_serializing_if = "Vec::is_empty")]
157    pub containers_left: Vec<String>,
158    /// Processes from `before` still running after the teardown and one more
159    /// forced kill each (spec §6.2 step 8). Empty is the goal.
160    pub survivors: Vec<agent_resources::ProcessEntry>,
161    /// What it owned when the teardown began.
162    pub before: AgentResources,
163}
164
165/// Every teardown and window close in flight. Each runs as its own task, so
166/// a caller that stops waiting can't cut it short: an HTTP handler whose
167/// client hung up (the host gives `CloseWindow` 2 s) or srv's servers
168/// stopping on quit. [`app_exit`] waits for all of them.
169static CLOSES: std::sync::LazyLock<tokio_util::task::TaskTracker> =
170    std::sync::LazyLock::new(tokio_util::task::TaskTracker::new);
171
172/// Run `fut` to completion as a tracked task, even if the caller is dropped
173/// first; [`app_exit`] waits for it. `None` if it panicked.
174pub(crate) async fn detached<T: Send + 'static>(fut: impl std::future::Future<Output = T> + Send + 'static) -> Option<T> {
175    CLOSES.spawn(fut).await.ok()
176}
177
178/// Tear down every block in `block_ids` concurrently, under ONE deadline:
179/// ten agents take one grace period, not ten. Each runs [`detached`].
180pub async fn run_many(state: &AppState, block_ids: &[String], policy: Policy) -> Vec<TeardownReport> {
181    let deadline = std::time::Instant::now() + blockcontroller::SHUTDOWN_GRACE;
182    let teardowns = block_ids.iter().map(|id| {
183        let (st, id) = (state.clone(), id.clone());
184        async move {
185            let report = detached({
186                let id = id.clone();
187                async move { run_one(&st, &id, policy, deadline).await }
188            })
189            .await;
190            report.unwrap_or_else(|| {
191                tracing::error!(block_id = %id, "agent_teardown: teardown panicked");
192                TeardownReport { agent: id.clone(), block_id: id, ..Default::default() }
193            })
194        }
195    });
196    futures_util::future::join_all(teardowns).await
197}
198
199/// [`run_many`] for one block.
200pub async fn run(state: &AppState, block_id: &str, policy: Policy) -> TeardownReport {
201    run_many(state, std::slice::from_ref(&block_id.to_string()), policy)
202        .await
203        .pop()
204        .unwrap_or_default()
205}
206
207/// [`Policy::stop_cli_only`]'s entry, for callers with no `AppState` (the
208/// watchdog, the pane's `AgentStop` command): `controller.stop()` only.
209/// Errors with `NOT_RUNNING` when the block has no controller.
210pub fn stop_now(block_id: &str, graceful: bool) -> Result<(), String> {
211    debug_assert!(matches!(Policy::stop_cli_only(graceful).cli, CliStop::StopOnly { .. }));
212    let ctrl = blockcontroller::get_controller(block_id)
213        .ok_or_else(|| format!("NOT_RUNNING: no controller for block {block_id}"))?;
214    ctrl.stop(graceful, blockcontroller::STATUS_DONE)?;
215    // Its background browser sessions close with it, as for a full stop.
216    crate::server::browser_session_close::close_for_stop(block_id);
217    Ok(())
218}
219
220/// Stop (`agent.stop`, `FleetBulkStop`, a deferred `Stop` action):
221/// [`Policy::stop`]. `stop_background` is the caller's answer to "also stop
222/// its background tasks?"; `None` takes the user's setting
223/// ([`SETTING_STOP_KEEPS_BACKGROUND`]). Errors with `NOT_RUNNING` when the
224/// block has no controller, as `agent.stop` always has.
225pub async fn stop(state: &AppState, block_id: &str, graceful: bool, stop_background: Option<bool>) -> Result<TeardownReport, String> {
226    if blockcontroller::get_controller(block_id).is_none() {
227        return Err(format!("NOT_RUNNING: no controller for block {block_id}"));
228    }
229    let stop_background = stop_background.unwrap_or_else(|| !stop_keeps_background(state));
230    let report = run(state, block_id, Policy::stop(graceful, stop_background)).await;
231    match report.stop_error {
232        Some(e) => Err(e),
233        None => {
234            // An explicit stop: the agent is wanted stopped, so a restart does not resume it.
235            use crate::server::app_api::agent_attach::{set_desired, DESIRED_STOPPED};
236            set_desired(&state.mstore, block_id, DESIRED_STOPPED);
237            Ok(report)
238        }
239    }
240}
241
242fn stop_keeps_background(state: &AppState) -> bool {
243    state
244        .config_watcher
245        .get_settings()
246        .extra
247        .get(SETTING_STOP_KEEPS_BACKGROUND)
248        .and_then(|v| v.as_bool())
249        .unwrap_or(true)
250}
251
252/// Drop a block's controller and process tracker at once, with no graceful
253/// phase: for a controller that isn't an agent to wind down (a PtyShell
254/// drawer the user closed, a `/btw` throwaway, a spawn being rolled back) and
255/// as the backstop after a close that already ran the teardown (idempotent;
256/// finds nothing left).
257pub fn discard(block_id: &str) {
258    blockcontroller::delete_controller(block_id);
259}
260
261/// The replace policy's entry, for `resync_controller` (synchronous, below
262/// the saga layer, and already holding the old controller): stop its own CLI
263/// process only (`Policy::replace`).
264pub fn replace_now(ctrl: &dyn blockcontroller::Controller) -> Result<(), String> {
265    debug_assert!(matches!(Policy::replace().cli, CliStop::Replace));
266    ctrl.stop_for_replace(blockcontroller::STATUS_DONE)
267}
268
269/// App exit (`main.rs`, after the servers stop): tear down every live agent
270/// with `Policy::app_exit()`, concurrently, and wait for every close already
271/// in flight, all under [`APP_EXIT_CAP`]. Then stop any `Shell()` session left
272/// over (one whose agent is already gone, or whose teardown hit the cap).
273/// Returns how many controllers it closed.
274pub async fn app_exit(state: &AppState) -> usize {
275    // Durable SSH panes detach rather than end their sessions: they live on
276    // on their hosts for the next start to reattach (durable_ssh.rs).
277    crate::backend::blockcontroller::durable_ssh::note_app_exiting();
278    let all: Vec<String> = blockcontroller::get_all_controllers().into_keys().collect();
279    // A drawer is closed by its parent's teardown (`close_sub_blocks`); listing
280    // it here too would run two teardowns of one block at once.
281    let ids = {
282        let (st, ids) = (state.clone(), all.clone());
283        tokio::task::spawn_blocking(move || without_sub_blocks(&st, ids)).await.unwrap_or(all)
284    };
285    let cap = APP_EXIT_CAP.saturating_sub(SHELL_SWEEP_GRACE);
286    // Before the close interrupts them: the next start tells these agents to
287    // carry on (`upgrade_notice`).
288    record_turns_in_flight(state, &ids).await;
289    // And which parked agents are running, for the restart resume to bring back whatever their last turn.
290    crate::server::restart_resume::record_running_at_exit(state, &ids).await;
291    let all_closed = async {
292        run_many(state, &ids, Policy::app_exit()).await;
293        // And every close already in flight: its controller has left the
294        // registry, so the list above doesn't have it (a window closed just
295        // before the quit, whose host stopped waiting for the reply).
296        CLOSES.close();
297        CLOSES.wait().await;
298    };
299    if tokio::time::timeout(cap, all_closed).await.is_err() {
300        tracing::warn!(agents = ids.len(), "app exit: teardown hit the cap; the launcher's backstop takes the rest");
301    }
302    // The kill tasks run taskkill/killpg asynchronously; give them a brief
303    // grace to complete before srv exits. [reagent #1422 P2]
304    let live = state.shell_sessions.stop_all();
305    if live > 0 {
306        tracing::info!(count = live, "app exit: stopping leftover persistent shells");
307        tokio::time::sleep(SHELL_SWEEP_GRACE).await;
308    }
309    ids.len()
310}
311
312/// Add the agents with a turn running among the panes in `ids` to the list the
313/// next start tells to carry on (`upgrade_notice::record_interrupted`). A GUI
314/// quit has closed most of them already (`note_turn_cut_off_by_quit`), so this
315/// catches what is left when srv exits on its own. It only adds: none running
316/// leaves the list as it is. Nothing here can fail the exit.
317async fn record_turns_in_flight(state: &AppState, ids: &[String]) {
318    let controllers = blockcontroller::get_all_controllers();
319    let busy: Vec<String> = ids
320        .iter()
321        .filter(|id| controllers.get(*id).is_some_and(|c| c.get_runtime_status().turn_active))
322        .cloned()
323        .collect();
324    let st = state.clone();
325    let agents = tokio::task::spawn_blocking(move || {
326        distinct_agents(busy.iter().filter_map(|id| {
327            let block = st.mstore.get::<crate::backend::obj::Block>(id).ok().flatten()?;
328            Some(crate::backend::obj::meta_get_string(&block.meta, "agentId", ""))
329        }))
330    })
331    .await
332    .unwrap_or_default();
333    if let Some(paths) = agentmux_common::DataPaths::from_env() {
334        crate::backend::upgrade_notice::record_interrupted(&paths.instance_dir, &agents, agentmux_common::time::now_ms());
335    }
336    if !agents.is_empty() {
337        tracing::info!(count = agents.len(), "app exit: agents with a turn in flight recorded");
338    }
339}
340
341/// A quit is closing the windows (the GUI saved its session record a moment
342/// ago) and the agent in `block_id` has a turn running that the close is about
343/// to interrupt: keep it for the next start to tell it to carry on. The windows
344/// close before srv exits, so by `app_exit` these agents are already gone.
345async fn note_turn_cut_off_by_quit(state: &AppState, block_id: &str) {
346    let st = state.clone();
347    let id = block_id.to_string();
348    let agent = tokio::task::spawn_blocking(move || {
349        if !crate::server::service::session_closed::quit_under_way(&st.mstore) {
350            return None;
351        }
352        let block = st.mstore.get::<crate::backend::obj::Block>(&id).ok().flatten()?;
353        distinct_agents([crate::backend::obj::meta_get_string(&block.meta, "agentId", "")]).pop()
354    })
355    .await
356    .ok()
357    .flatten();
358    if let (Some(agent), Some(paths)) = (agent, agentmux_common::DataPaths::from_env()) {
359        crate::backend::upgrade_notice::record_interrupted(&paths.instance_dir, &[agent], agentmux_common::time::now_ms());
360    }
361}
362
363/// The agent ids in `ids`, each once, none empty (a pane that is no agent's
364/// has none).
365fn distinct_agents(ids: impl IntoIterator<Item = String>) -> Vec<String> {
366    let mut agents: Vec<String> = ids.into_iter().map(|a| a.trim().to_string()).filter(|a| !a.is_empty()).collect();
367    agents.sort();
368    agents.dedup();
369    agents
370}
371
372/// `ids` minus any that is a sub-block (PtyShell drawer) of another block in
373/// it. Store reads: call off the async workers.
374pub(crate) fn without_sub_blocks(state: &AppState, ids: Vec<String>) -> Vec<String> {
375    let subs: std::collections::HashSet<String> = ids
376        .iter()
377        .filter_map(|id| state.mstore.get::<crate::backend::obj::Block>(id).ok().flatten())
378        .flat_map(|b| b.subblockids.unwrap_or_default())
379        .collect();
380    ids.into_iter().filter(|id| !subs.contains(id)).collect()
381}
382
383async fn run_one(state: &AppState, block_id: &str, policy: Policy, deadline: std::time::Instant) -> TeardownReport {
384    let started = std::time::Instant::now();
385    // Identity and inventory while the block is still registered (step 2).
386    let who = AgentIdentity::of(state, block_id);
387    // Store reads (SQLite) off the async workers: a bulk close runs this
388    // for every block at once.
389    let before = {
390        let (st, id) = (state.clone(), block_id.to_string());
391        tokio::task::spawn_blocking(move || agent_resources::snapshot(&st, &id))
392            .await
393            .unwrap_or_default()
394    };
395    let mut report = TeardownReport {
396        block_id: block_id.to_string(),
397        agent: who.label(block_id),
398        before: before.clone(),
399        ..Default::default()
400    };
401
402    // Stop: the CLI first. If it fails the agent is still running, so its
403    // claims and background tasks must stay too (ReAgent P1 on #4174).
404    if let CliStop::StopOnly { graceful } = policy.cli {
405        if let Err(e) = stop_now(block_id, graceful) {
406            tracing::warn!(block_id = %block_id, error = %e, "agent_teardown: stop failed; nothing else touched");
407            report.stop_error = Some(e);
408            return report;
409        }
410    }
411
412    // Step 3: non-process resources, so nothing new reaches a dying agent.
413    if policy.release_claims {
414        let reason = if matches!(policy.cli, CliStop::StopOnly { .. }) { "agent stopped" } else { "agent quit" };
415        let (released, crons) = release_claims_and_list_crons(state, &who, reason).await;
416        report.released_claims = released;
417        report.crons_targeting = crons;
418    }
419    if let (true, Some(uid)) = (policy.dock_floaters, who.uid.as_deref()) {
420        // Its background sessions close with it: the dock below takes only the floaters the person sees.
421        crate::server::browser_session_close::close_for_stop(block_id);
422        crate::server::pane_dock::dock_all(state, uid, block_id).await;
423    }
424    if policy.stop_shell_sessions {
425        report.stopped_shells = before
426            .shell_sessions
427            .iter()
428            .filter(|s| state.shell_sessions.stop(&s.shell_id))
429            .count();
430    }
431
432    if policy.stop_background && !before.background_tasks.is_empty() {
433        report.stopped_background = stop_background_tasks(&before).await;
434    }
435
436    match policy.cli {
437        CliStop::StopOnly { .. } => {} // done first, above
438        CliStop::Replace => {
439            if let Some(ctrl) = blockcontroller::get_controller(block_id) {
440                if let Err(e) = replace_now(ctrl.as_ref()) {
441                    tracing::debug!(block_id = %block_id, error = %e, "agent_teardown: replace");
442                }
443            }
444        }
445        CliStop::Graceful => {
446            // PtyShell drawers first (spec §6.6), so teardown doesn't depend on
447            // the pane being mounted to send `deletesubblock`.
448            close_sub_blocks(state, &before.sub_blocks, deadline).await;
449            report.survivors = close_cli(state, block_id, &who, &before, deadline, started).await;
450            if policy.stop_container {
451                report.stopped_container = stop_container(state, block_id, &before, deadline).await;
452            }
453            report.containers_left = compose_containers_left(state, block_id, &before, deadline).await;
454        }
455    }
456    report
457}
458
459/// Stop a container agent's container (spec §6.7), unless another live pane
460/// runs the same agent in it. Docker's own SIGTERM → SIGKILL grace is bounded
461/// by what's left of the teardown's deadline.
462async fn stop_container(
463    state: &AppState,
464    block_id: &str,
465    before: &AgentResources,
466    deadline: std::time::Instant,
467) -> Option<String> {
468    let name = before.container.clone()?;
469    let shared = {
470        let (st, id, n) = (state.clone(), block_id.to_string(), name.clone());
471        tokio::task::spawn_blocking(move || agent_resources::container_shared(&st, &id, &n)).await.unwrap_or(true)
472    };
473    if shared {
474        tracing::info!(block_id = %block_id, container = %name, "agent_teardown: container still in use; kept");
475        return None;
476    }
477    let cm = state.container_manager.get().await?;
478    let grace = deadline.saturating_duration_since(std::time::Instant::now()).as_secs().max(1) as i64;
479    match cm.stop(&name, grace).await {
480        Ok(()) => {
481            publish_shutdown(state, block_id, "container", format!("stopped container {name}"), ShutdownExtra::default());
482            Some(name)
483        }
484        Err(e) => {
485            tracing::warn!(block_id = %block_id, container = %name, error = %e, "agent_teardown: container stop failed");
486            None
487        }
488    }
489}
490
491/// Running Docker Compose containers started from the agent's working
492/// directory (`docker compose up -d`): they belong to the Docker daemon, not
493/// the agent's process tree, so no tracker ends them. Reported, not stopped:
494/// a person may be using them too. Skipped when the agent works in `/` or
495/// the home directory, where every project would match.
496async fn compose_containers_left(
497    state: &AppState,
498    block_id: &str,
499    before: &AgentResources,
500    deadline: std::time::Instant,
501) -> Vec<String> {
502    let dir = std::path::PathBuf::from(&before.cwd);
503    let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(std::path::PathBuf::from);
504    if before.cwd.is_empty() || dir.parent().is_none() || home.as_deref() == Some(dir.as_path()) {
505        return Vec::new();
506    }
507    let Some(cm) = state.container_manager.get().await else { return Vec::new() };
508    // A daemon that accepts but never answers must not hold up the close.
509    let wait = deadline.saturating_duration_since(std::time::Instant::now()).max(std::time::Duration::from_secs(1));
510    let names = match tokio::time::timeout(wait, cm.running_compose_containers_under(&dir)).await {
511        Ok(Ok(names)) => names,
512        Ok(Err(e)) => {
513            tracing::warn!(block_id = %block_id, error = %e, "agent_teardown: listing Compose containers failed");
514            return Vec::new();
515        }
516        Err(_) => {
517            tracing::warn!(block_id = %block_id, "agent_teardown: Docker didn't list Compose containers in time");
518            return Vec::new();
519        }
520    };
521    for name in &names {
522        publish_shutdown(
523            state,
524            block_id,
525            "container",
526            format!("container {name} (Docker Compose, in this agent's folder) is still running"),
527            ShutdownExtra { container: Some(name.clone()), outcome: Some("left".into()), ..Default::default() },
528        );
529    }
530    names
531}
532
533/// Stop the agent's running `run_in_background` tasks, each with its process
534/// tree, after re-checking each PID is still that task. Returns how many.
535async fn stop_background_tasks(before: &AgentResources) -> usize {
536    let tasks = before.background_tasks.clone();
537    tokio::task::spawn_blocking(move || {
538        let pids = agent_resources::live_background_pids(&tasks);
539        for pid in &pids {
540            tracing::info!(pid, "agent_teardown: stopping a background task");
541            agentmux_common::process::kill_process_group(*pid);
542        }
543        pids.len()
544    })
545    .await
546    .unwrap_or(0)
547}
548
549/// Close a parent's sub-blocks (PtyShell drawers) the way a pane closes,
550/// concurrently and under the parent's deadline.
551async fn close_sub_blocks(state: &AppState, sub_blocks: &[String], deadline: std::time::Instant) {
552    if sub_blocks.is_empty() {
553        return;
554    }
555    let subs = sub_blocks.iter().map(|id| Box::pin(run_one(state, id, Policy::close(), deadline)));
556    futures_util::future::join_all(subs).await;
557    // Their processes are gone. Nothing deletes a drawer's record through a
558    // close saga's `finish_close`, so lift the respawn guard here: if the
559    // parent's close then fails, its drawer can be reopened.
560    for id in sub_blocks {
561        blockcontroller::unmark_closing(id);
562    }
563}
564
565/// The per-agent close (`SPEC_AGENT_PANE_CLOSE_GRACEFUL_SHUTDOWN_2026_09_18.md`
566/// §4.2), then the verify step (agent teardown spec §6.2 step 8). Returns the
567/// survivors.
568async fn close_cli(
569    state: &AppState,
570    block_id: &str,
571    who: &AgentIdentity,
572    before: &AgentResources,
573    deadline: std::time::Instant,
574    started: std::time::Instant,
575) -> Vec<agent_resources::ProcessEntry> {
576    let label = if who.agent_id.is_empty() { "agent".to_string() } else { who.agent_id.clone() };
577    // 1. Stop routing input: no respawn (resync_controller refuses), no
578    //    jekt/muxbus delivery, and — once out of CONTROLLER_REGISTRY — no
579    //    AgentInput either.
580    blockcontroller::mark_closing(block_id);
581    state.reactive_handler.unregister_block(block_id);
582    // A container's pre-start has no controller: end it before the container is stopped below.
583    crate::server::agent_handlers::container_turn::cancel_prestart(block_id);
584    let ctrl = blockcontroller::take_controller(block_id);
585    // 2–4. End the turn, ask the process to exit, force-kill at the deadline;
586    //      resolves once it has actually exited.
587    let (controller_type, outcome) = match ctrl {
588        Some(ctrl) => {
589            if ctrl.get_runtime_status().turn_active {
590                publish_shutdown(state, block_id, "interrupt", "turn interrupted".into(), ShutdownExtra::default());
591                note_turn_cut_off_by_quit(state, block_id).await;
592            }
593            let outcome = ctrl.shutdown(deadline).await;
594            (ctrl.controller_type().to_string(), outcome)
595        }
596        None => (String::new(), blockcontroller::StopOutcome::NotRunning),
597    };
598    let (step, text, extra) = exit_line(&label, &outcome, started.elapsed());
599    publish_shutdown(state, block_id, step, text, extra);
600    // 4b. What it started gets the same chance: SIGTERM to its whole tree,
601    //     then a short wait, before the release below kills what's left.
602    terminate_members(state, block_id, deadline).await;
603    // 5. Only now drop the process tracker — anything the agent itself
604    //    started dies with it, but the agent got to exit first. Whatever is
605    //    still alive at this point is what the release kills.
606    let alive: std::collections::HashSet<u32> =
607        state.process_tracker.list_block(block_id).into_iter().map(|p| p.pid).collect();
608    blockcontroller::release_block_processes(block_id);
609    for p in &before.processes {
610        let killed = alive.contains(&p.pid);
611        publish_shutdown(
612            state,
613            block_id,
614            "process",
615            process_line(&p.command, p.pid, killed),
616            process_extra(p.pid, &p.command, if killed { "killed" } else { "stopped" }),
617        );
618    }
619    // 5b. Verify: everything in the snapshot is gone, else force it once
620    //     more and report what's left.
621    let mut survivors = verify_gone(&before.processes).await;
622    for p in &survivors {
623        publish_shutdown(
624            state,
625            block_id,
626            "survivor",
627            format!("still running: {} (pid {})", short_command(&p.command), p.pid),
628            process_extra(p.pid, &p.command, "survived"),
629        );
630    }
631    // 5c. What still carries the agent's env tag got out of its tracker
632    //     (started through systemd or launchd, or a best-effort miss).
633    //     Reported, not killed: it may be an app the agent opened for the user.
634    for p in escaped(block_id, &survivors).await {
635        publish_shutdown(
636            state,
637            block_id,
638            "survivor",
639            format!("still running, outside the agent's tracking: {} (pid {})", short_command(&p.command), p.pid),
640            process_extra(p.pid, &p.command, "escaped"),
641        );
642        survivors.push(p);
643    }
644    blockcontroller::mark_closing_stopped(block_id);
645    crate::backend::container::credential::revoke_block(block_id);
646    // Any AWS sessions srv minted for this agent leave memory with its container. They are keyed by the agent token's
647    // uid (the bound instance), which a block launched from a template does not carry in `agentId`: drop both.
648    let sessions = crate::identity::aws_broker::sessions::global();
649    if let Some(uid) = crate::backend::agent_resolve::uid_for_block(&state.mstore, block_id) {
650        sessions.revoke_agent(&uid);
651    }
652    if let Some(block) = state.mstore.get::<crate::backend::obj::Block>(block_id).ok().flatten() {
653        let agent = crate::backend::obj::meta_get_string(&block.meta, "agentId", "");
654        if !agent.is_empty() {
655            sessions.revoke_agent(&agent);
656        }
657    }
658    // 6. Save final state.
659    save_final_state(state, block_id);
660    publish_shutdown(state, block_id, "saved", "conversation saved".into(), ShutdownExtra::default());
661    publish_shutdown(state, block_id, "done", "closing".into(), ShutdownExtra::default());
662    tracing::info!(
663        block_id = %block_id,
664        controller_type = %controller_type,
665        outcome = outcome.as_str(),
666        elapsed_ms = started.elapsed().as_millis() as u64,
667        survivors = survivors.len(),
668        "agent_shutdown"
669    );
670    survivors
671}
672
673/// The longest wait after SIGTERM to what an agent started; never past the
674/// teardown's deadline.
675const MEMBERS_GRACE_MAX: std::time::Duration = std::time::Duration::from_secs(2);
676
677/// Ask everything in the block's tree to exit and wait until it has, or the
678/// grace passes. Returns at once where the tracker has no graceful signal
679/// (Windows), nothing is left, or the deadline has passed (the release's
680/// kill follows straight away).
681async fn terminate_members(state: &AppState, block_id: &str, deadline: std::time::Instant) {
682    let grace = deadline.saturating_duration_since(std::time::Instant::now()).min(MEMBERS_GRACE_MAX);
683    if grace.is_zero() {
684        return;
685    }
686    let registry = state.process_tracker.clone();
687    let id = block_id.to_string();
688    let count = move || {
689        let (r, id) = (registry.clone(), id.clone());
690        tokio::task::spawn_blocking(move || r.member_count(&id))
691    };
692    if count().await.unwrap_or(0) == 0 {
693        return;
694    }
695    let (r, id) = (state.process_tracker.clone(), block_id.to_string());
696    if !tokio::task::spawn_blocking(move || r.terminate(&id)).await.unwrap_or(false) {
697        return;
698    }
699    let until = std::time::Instant::now() + grace;
700    while std::time::Instant::now() < until {
701        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
702        if count().await.unwrap_or(0) == 0 {
703            return;
704        }
705    }
706}
707
708/// Live processes tagged with `block_id` (`process_tracker::scan`) that
709/// aren't already in `known`. Two scans [`ESCAPE_SETTLE`] apart: one the
710/// tracker's kill is still ending shows in the first only.
711async fn escaped(block_id: &str, known: &[agent_resources::ProcessEntry]) -> Vec<agent_resources::ProcessEntry> {
712    let scan = |id: String| async move {
713        tokio::task::spawn_blocking(move || crate::backend::process_tracker::scan::tagged(&id))
714            .await
715            .unwrap_or_default()
716    };
717    let first = scan(block_id.to_string()).await;
718    if first.is_empty() {
719        return Vec::new();
720    }
721    tokio::time::sleep(ESCAPE_SETTLE).await;
722    scan(block_id.to_string())
723        .await
724        .into_iter()
725        .filter(|p| first.iter().any(|f| f.pid == p.pid && f.started_at_ms == p.started_at_ms))
726        .filter(|p| !known.iter().any(|k| k.pid == p.pid))
727        .map(|p| agent_resources::ProcessEntry { pid: p.pid, command: p.command, started_at_ms: p.started_at_ms })
728        .collect()
729}
730
731const ESCAPE_SETTLE: std::time::Duration = std::time::Duration::from_millis(300);
732
733/// How long the verify step waits for the tracker's release to take effect,
734/// before and after its one forced kill per survivor.
735const VERIFY_WAIT: std::time::Duration = std::time::Duration::from_millis(1500);
736
737/// Spec §6.2 step 8: wait for every process in the snapshot to be gone. Any
738/// still running (same PID and start time) gets one forced kill of its tree;
739/// whatever is left after that is returned. Never kills a PID the OS has
740/// reused: `survivors` re-checks the start time right before the kill.
741async fn verify_gone(before: &[agent_resources::ProcessEntry]) -> Vec<agent_resources::ProcessEntry> {
742    if before.is_empty() {
743        return Vec::new();
744    }
745    let mut left = wait_gone(before.to_vec()).await;
746    if left.is_empty() {
747        return left;
748    }
749    for p in &left {
750        tracing::warn!(pid = p.pid, command = %p.command, "agent_teardown: forcing a survivor");
751        let (pid, started) = (p.pid, p.started_at_ms);
752        let _ = tokio::task::spawn_blocking(move || agent_resources::force_kill_tree(pid, started)).await;
753    }
754    left = wait_gone(left).await;
755    left
756}
757
758/// Poll until none of `procs` is running or [`VERIFY_WAIT`] passes; returns
759/// the ones still running.
760async fn wait_gone(mut procs: Vec<agent_resources::ProcessEntry>) -> Vec<agent_resources::ProcessEntry> {
761    let until = std::time::Instant::now() + VERIFY_WAIT;
762    loop {
763        procs = tokio::task::spawn_blocking(move || agent_resources::survivors(&procs)).await.unwrap_or_default();
764        if procs.is_empty() || std::time::Instant::now() >= until {
765            return procs;
766        }
767        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
768    }
769}
770
771/// Release the agent's work claims, so the items go back to the pool now
772/// rather than when the 120 s lease expires, and list the crons that target
773/// it (kept: a cron is a deliberate schedule that resumes when the agent is
774/// reopened). SQLite reads and writes, off the async workers.
775async fn release_claims_and_list_crons(state: &AppState, who: &AgentIdentity, reason: &'static str) -> (usize, Vec<String>) {
776    let (identity_store, jobs_store) = (state.work_store.clone(), crate::server::cron::jobs_store(state));
777    let (a, u) = (who.agent_id.clone(), who.uid.clone());
778    let result = tokio::task::spawn_blocking(move || {
779        let released = release_claims(&identity_store, &a, u.as_deref(), reason, agentmux_common::time::now_ms());
780        let crons = jobs_store
781            .and_then(|s| s.cron_list().ok())
782            .map(|jobs| agent_resources::crons_targeting(&jobs, &a, u.as_deref()))
783            .unwrap_or_default();
784        (released, crons)
785    })
786    .await
787    .unwrap_or_default();
788    if result.0 > 0 {
789        crate::server::work_queue::publish_changed(state);
790    }
791    result
792}
793
794#[cfg(test)]
795mod tests {
796    use super::*;
797
798    /// The watchdog's release: the agent's claims go back to the pool with the
799    /// reason, the attempt counted; another agent's claim is left alone.
800    #[test]
801    fn release_claims_returns_one_agents_tasks_with_the_reason_and_counts_the_attempt() {
802        use crate::backend::storage::work_queue::{work_state, ClaimFilter, WorkItem};
803        let dir = tempfile::tempdir().unwrap();
804        let store = crate::backend::storage::store::Store::open_identity_store(&dir.path().join("identity-store.db")).unwrap();
805        for id in ["w1", "w2"] {
806            let item = WorkItem {
807                id: id.into(),
808                title: "t".into(),
809                payload: "p".into(),
810                kind: String::new(),
811                target_agent: String::new(),
812                target_group: String::new(),
813                priority: 0,
814                state: work_state::OPEN.into(),
815                claimed_by: String::new(),
816                target_agent_uid: String::new(),
817                claimed_by_uid: String::new(),
818                claim_expires: None,
819                attempts: 0,
820                max_attempts: 3,
821                created_by: "tester".into(),
822                created_by_uid: String::new(),
823                created_at: 1000,
824                updated_at: 1000,
825                not_before: None,
826                result: String::new(),
827            };
828            store.work_queue_enqueue(&item).unwrap();
829        }
830        let claim_as = |agent: &str, uid: &str| {
831            let f = ClaimFilter { kind: None, agent_id: agent.into(), agent_uid: uid.into(), groups: vec![] };
832            store.work_queue_claim(&f, 2000, 120_000).unwrap().expect("an open item")
833        };
834        let lark = claim_as("Lark", "uid-lark");
835        let korp = claim_as("Korp", "uid-korp");
836
837        let reason = "stopped by the watchdog after 4 h";
838        assert_eq!(release_claims(&store, "Lark", Some("uid-lark"), reason, 3000), 1);
839        let back = store.work_queue_get(&lark.id).unwrap().unwrap();
840        assert_eq!((back.state.as_str(), back.attempts, back.result.as_str()), (work_state::OPEN, 1, reason));
841        assert_eq!(store.work_queue_get(&korp.id).unwrap().unwrap().state, work_state::CLAIMED, "another agent's claim stays");
842        assert_eq!(release_claims(&store, "Lark", Some("uid-lark"), reason, 3000), 0, "nothing left to release");
843    }
844
845    #[test]
846    fn policies_encode_todays_scopes() {
847        assert_eq!(Policy::close(), Policy { cli: CliStop::Graceful, release_claims: false, stop_shell_sessions: true, stop_background: false, stop_container: true, dock_floaters: false });
848        assert_eq!(Policy::quit(), Policy { cli: CliStop::Graceful, release_claims: true, stop_shell_sessions: true, stop_background: false, stop_container: true, dock_floaters: false });
849        assert_eq!(Policy::stop(false, false).cli, CliStop::StopOnly { graceful: false });
850        // Stop releases claims and keeps shells; background tasks as asked.
851        assert!(Policy::stop(true, false).release_claims && !Policy::stop(true, false).stop_shell_sessions);
852        assert!(Policy::stop(true, true).stop_background && !Policy::stop(true, false).stop_background);
853        // Containers stop with a closing agent, never on Stop or a restart.
854        assert!(Policy::close().stop_container && Policy::quit().stop_container && Policy::app_exit().stop_container);
855        assert!(!Policy::stop(true, true).stop_container && !Policy::replace().stop_container);
856        // The watchdog's stop is the CLI only.
857        let w = Policy::stop_cli_only(true);
858        assert!(!w.release_claims && !w.stop_shell_sessions && !w.stop_background);
859        assert_eq!(Policy::replace(), Policy { cli: CliStop::Replace, release_claims: false, stop_shell_sessions: false, stop_background: false, stop_container: false, dock_floaters: false });
860        assert_eq!(Policy::app_exit(), Policy { cli: CliStop::Graceful, release_claims: false, stop_shell_sessions: true, stop_background: false, stop_container: true, dock_floaters: false });
861        // Only a Stop docks the floating panes its agent opened: its pane and tab stay for them to go back to.
862        assert!(Policy::stop(true, false).dock_floaters && !Policy::stop_cli_only(true).dock_floaters && !Policy::close().dock_floaters && !Policy::quit().dock_floaters);
863        // App exit covers the CLI's own grace and the shell sweep.
864        assert!(APP_EXIT_CAP.saturating_sub(SHELL_SWEEP_GRACE) > blockcontroller::SHUTDOWN_GRACE);
865    }
866
867    /// The single path (spec §3 G1, §9.1): outside this module and the
868    /// process machinery itself, nothing in srv stops an agent's processes.
869    #[test]
870    fn nothing_else_stops_an_agent() {
871        // (file suffix, why it may) — every entry is a definition, the
872        // machinery's own internals, or a phase-2 consumer named in the spec.
873        const ALLOWED: &[(&str, &str)] = &[
874            ("sagas/agent_teardown.rs", "the one path"),
875            ("backend/blockcontroller/mod.rs", "defines release_block_processes and delete_controller"),
876            ("backend/blockcontroller/persistent/", "the controller's own shutdown internals"),
877            ("backend/blockcontroller/shell/", "the controller's own stop internals"),
878            ("backend/process_tracker/", "the tracker itself"),
879            ("backend/shell_node.rs", "ShellSessionRegistry's own stop/stop_all"),
880            ("server/http_shell.rs", "the ShellStop tool: the agent stopping one shell on purpose"),
881            ("server/vault_rotate.rs", "a Vault rotation stopping its own set or verify command that ran past its time"),
882        ];
883        const PATTERNS: &[&str] = &[
884            "release_block_processes(",
885            "shell_sessions.stop(",
886            ".stop_all()",
887            ".shutdown(deadline",
888            "ctrl.stop(",
889            ".stop_for_replace(",
890            "delete_controller(",
891        ];
892        let mut offenders = Vec::new();
893        for root in crate::test_support::server_src_roots() {
894            let mut stack = vec![root.clone()];
895            while let Some(dir) = stack.pop() {
896                for entry in std::fs::read_dir(&dir).unwrap() {
897                    let path = entry.unwrap().path();
898                    if path.is_dir() {
899                        stack.push(path);
900                        continue;
901                    }
902                    if path.extension().and_then(|e| e.to_str()) != Some("rs") {
903                        continue;
904                    }
905                    let rel = path.strip_prefix(&root).unwrap().to_string_lossy().replace('\\', "/");
906                    // Test modules in their own files (`tests.rs`, `tests/`).
907                    let is_test_file = rel.ends_with("tests.rs") || rel.contains("/tests/");
908                    if is_test_file || ALLOWED.iter().any(|(a, _)| rel.starts_with(a) || rel == *a) {
909                        continue;
910                    }
911                    let text = std::fs::read_to_string(&path).unwrap();
912                    // Code only: skip comment lines and everything from a test module on.
913                    // (A test-only item the core also builds for the server's tests carries the feature form.)
914                    let cut = ["#[cfg(test)]", "#[cfg(any(test, feature = \"test-support\"))]"].iter().filter_map(|m| text.find(m)).min();
915                    let code = &text[..cut.unwrap_or(text.len())];
916                    for (i, line) in code.lines().enumerate() {
917                        let t = line.trim_start();
918                        if t.starts_with("//") {
919                            continue;
920                        }
921                        if let Some(p) = PATTERNS.iter().find(|p| line.contains(*p)) {
922                            offenders.push(format!("{rel}:{}: `{p}`", i + 1));
923                        }
924                    }
925                }
926            }
927        }
928        assert!(
929            offenders.is_empty(),
930            "an agent's processes are stopped only by sagas::agent_teardown (spec SPEC_AGENT_TEARDOWN_SINGLE_PATH §3 G1); \
931             route these through it:\n{}",
932            offenders.join("\n")
933        );
934    }
935
936    #[test]
937    fn the_agents_with_a_turn_in_flight_are_listed_once_and_a_pane_with_no_agent_is_left_out() {
938        let ids = ["b", " a ", "", "b", "  "].map(String::from);
939        assert_eq!(distinct_agents(ids), vec!["a".to_string(), "b".to_string()]);
940        assert!(distinct_agents(Vec::new()).is_empty());
941    }
942}