Skip to main content

agentmux_common/
agent_roots.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The agent CLIs srv is running, kept on disk for the launcher.
5//!
6//! On Unix each agent CLI leads its own process group (srv spawns it with
7//! `process_group(0)`), so a signal sent to one CLI's group can't reach srv,
8//! and srv's teardown of an agent takes the CLI's MCP servers with it. The
9//! cost: when srv itself dies without closing its agents (SIGKILL, a crash,
10//! a force-kill after its exit deadline), killing srv's group no longer
11//! takes the CLIs. This file is how the launcher finds them then.
12//!
13//! srv writes `<data_dir>/agent-roots.json` (temp file + rename, so a reader
14//! never sees half of it) whenever an agent CLI starts or exits, and deletes
15//! it on a clean exit. It names srv's pid, its Linux cgroup scope when it
16//! has one, and each CLI by pid **and start time**. Once srv has stopped,
17//! [`kill_orphans`] ends what is left:
18//!
19//! - Linux with srv's delegated scope: `cgroup.kill` on each agent cgroup
20//!   (`agent-*`) in it, which holds everything that agent started however it
21//!   detached.
22//! - Everywhere on Unix, and as the fallback: `kill(-pid, SIGKILL)` for each
23//!   recorded CLI that is still the same process (its start time matches)
24//!   and still leads its own group. A pid alone is never signalled: it may
25//!   have been reused since srv wrote it.
26
27use std::io;
28use std::path::{Path, PathBuf};
29
30use serde::{Deserialize, Serialize};
31
32/// File name, in srv's data dir next to `srv.lock`.
33pub const FILE_NAME: &str = "agent-roots.json";
34
35/// What srv writes.
36#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
37pub struct AgentRoots {
38    /// The srv that wrote it; [`kill_orphans`] acts only for this srv.
39    pub srv_pid: u32,
40    /// srv's delegated cgroup scope (Linux), holding one `agent-*` cgroup
41    /// per agent.
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    pub cgroup: Option<PathBuf>,
44    /// Each running agent CLI.
45    #[serde(default)]
46    pub roots: Vec<Root>,
47}
48
49/// One agent CLI: a pid, and when that process started
50/// (`process::process_start_time`), so a reused pid is never mistaken for it.
51#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
52pub struct Root {
53    pub pid: u32,
54    pub start: u64,
55}
56
57pub fn path(data_dir: &Path) -> PathBuf {
58    data_dir.join(FILE_NAME)
59}
60
61/// Replace the file atomically: write a temp file beside it, then rename.
62pub fn write(data_dir: &Path, roots: &AgentRoots) -> io::Result<()> {
63    let target = path(data_dir);
64    let tmp = data_dir.join(format!("{FILE_NAME}.{}.tmp", std::process::id()));
65    let body = serde_json::to_vec(roots).map_err(io::Error::other)?;
66    std::fs::write(&tmp, body)?;
67    std::fs::rename(&tmp, &target).inspect_err(|_| {
68        let _ = std::fs::remove_file(&tmp);
69    })
70}
71
72pub fn read(data_dir: &Path) -> Option<AgentRoots> {
73    serde_json::from_slice(&std::fs::read(path(data_dir)).ok()?).ok()
74}
75
76/// Delete the file (srv's clean exit). Already gone is fine.
77pub fn remove(data_dir: &Path) {
78    let _ = std::fs::remove_file(path(data_dir));
79}
80
81/// What [`kill_orphans`] did, for the caller's log.
82#[derive(Debug, Default, PartialEq, Eq)]
83pub struct Cleanup {
84    /// Agent cgroups `cgroup.kill` was written to.
85    pub cgroups: usize,
86    /// Recorded CLIs that were still running and had their group killed.
87    pub groups: usize,
88    /// Recorded CLIs that had already exited (or whose pid is now someone
89    /// else's): left alone.
90    pub gone: usize,
91}
92
93/// End the agent CLIs a stopped srv (`srv_pid`) left running, then delete
94/// the file. Call only once that srv has exited. `None` when there is no
95/// file, or it was written by another srv (left in place).
96#[cfg(unix)]
97pub fn kill_orphans(data_dir: &Path, srv_pid: u32) -> Option<Cleanup> {
98    let roots = read(data_dir)?;
99    if roots.srv_pid != srv_pid {
100        return None;
101    }
102    let mut done = Cleanup::default();
103    #[cfg(target_os = "linux")]
104    if let Some(scope) = roots.cgroup.as_deref().filter(|s| is_srv_scope(s, srv_pid)) {
105        done.cgroups = kill_agent_cgroups(scope);
106    }
107    for root in &roots.roots {
108        let leader_alive = crate::process::process_start_time(root.pid) == Some(root.start);
109        if (leader_alive && crate::process::leads_own_group(root.pid)) || crate::process::orphaned_group_alive(root.pid) {
110            if crate::process::signal_process_group(root.pid, libc::SIGKILL).is_ok() {
111                done.groups += 1;
112            }
113        } else {
114            done.gone += 1;
115        }
116    }
117    remove(data_dir);
118    Some(done)
119}
120
121/// Whether a recorded CLI's group is still there to end: its leader is still
122/// the process that was recorded (same start time), or the leader is gone but
123/// its helpers still hold the group (`process::orphaned_group_alive`). A pid
124/// that now belongs to some other process is not ours.
125#[cfg(unix)]
126pub fn is_alive(root: &Root) -> bool {
127    match crate::process::process_start_time(root.pid) {
128        Some(start) => start == root.start,
129        None => crate::process::orphaned_group_alive(root.pid),
130    }
131}
132
133/// Only srv's own scope (`agentmux-srv-<pid>.scope`) under the cgroup
134/// mount: the path comes from a file, so it must not name anything else.
135#[cfg(target_os = "linux")]
136fn is_srv_scope(scope: &Path, srv_pid: u32) -> bool {
137    scope.starts_with("/sys/fs/cgroup")
138        && !scope.components().any(|c| matches!(c, std::path::Component::ParentDir))
139        && scope.file_name().is_some_and(|n| n == format!("agentmux-srv-{srv_pid}.scope").as_str())
140}
141
142/// Write `1` to `cgroup.kill` in every `agent-*` cgroup in `scope`; srv's
143/// own cgroup and anything else in the scope are left alone. Returns how
144/// many were killed. Public for srv's cgroup tests.
145#[cfg(target_os = "linux")]
146pub fn kill_agent_cgroups(scope: &Path) -> usize {
147    let Ok(entries) = std::fs::read_dir(scope) else { return 0 };
148    entries
149        .flatten()
150        .filter(|e| e.file_name().to_string_lossy().starts_with("agent-") && e.path().is_dir())
151        .filter(|e| std::fs::write(e.path().join("cgroup.kill"), "1").is_ok())
152        .count()
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158
159    fn temp_dir(name: &str) -> PathBuf {
160        let dir = std::env::temp_dir().join(format!("agent-roots-{name}-{}", std::process::id()));
161        let _ = std::fs::remove_dir_all(&dir);
162        std::fs::create_dir_all(&dir).unwrap();
163        dir
164    }
165
166    #[test]
167    fn write_then_read_round_trips_and_leaves_no_temp_file() {
168        let dir = temp_dir("roundtrip");
169        let roots = AgentRoots { srv_pid: 42, cgroup: None, roots: vec![Root { pid: 7, start: 9 }] };
170        write(&dir, &roots).unwrap();
171        assert_eq!(read(&dir), Some(roots));
172        let names: Vec<_> = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name()).collect();
173        assert_eq!(names, [FILE_NAME]);
174        remove(&dir);
175        assert_eq!(read(&dir), None);
176        let _ = std::fs::remove_dir_all(&dir);
177    }
178
179    #[cfg(target_os = "linux")]
180    #[test]
181    fn only_srvs_own_scope_is_accepted() {
182        let ok = Path::new("/sys/fs/cgroup/user.slice/user@1000.service/app.slice/agentmux-srv-77.scope");
183        assert!(is_srv_scope(ok, 77));
184        assert!(!is_srv_scope(ok, 78), "another srv's scope");
185        assert!(!is_srv_scope(Path::new("/sys/fs/cgroup/user.slice"), 77));
186        assert!(!is_srv_scope(Path::new("/tmp/agentmux-srv-77.scope"), 77));
187        assert!(!is_srv_scope(Path::new("/sys/fs/cgroup/../tmp/agentmux-srv-77.scope"), 77));
188    }
189
190    /// A CLI that exited while its helper lives on: the group is still ended.
191    #[cfg(unix)]
192    #[test]
193    fn kill_orphans_ends_the_helpers_of_a_cli_that_already_exited() {
194        use std::io::BufRead as _;
195        use std::os::unix::process::CommandExt as _;
196        let dir = temp_dir("leaderless");
197        // The CLI waits on its stdin, so it is still running while its start time is read (on a slow machine a
198        // CLI that had already exited has no start time to read); closing stdin lets it exit.
199        let mut cli = std::process::Command::new("sh")
200            .args(["-c", "sleep 30 & echo $!; read line"])
201            .stdin(std::process::Stdio::piped())
202            .stdout(std::process::Stdio::piped())
203            .process_group(0)
204            .spawn()
205            .unwrap();
206        let start = crate::process::process_start_time(cli.id()).unwrap();
207        let roots = AgentRoots { srv_pid: 4242, cgroup: None, roots: vec![Root { pid: cli.id(), start }] };
208        write(&dir, &roots).unwrap();
209        let mut line = String::new();
210        std::io::BufReader::new(cli.stdout.take().unwrap()).read_line(&mut line).unwrap();
211        let helper: u32 = line.trim().parse().unwrap();
212        drop(cli.stdin.take());
213        cli.wait().unwrap();
214        assert!(is_alive(&roots.roots[0]), "kept while the helper holds the group");
215
216        let done = kill_orphans(&dir, 4242).unwrap();
217        assert_eq!(done.groups, 1);
218        for _ in 0..100 {
219            if crate::process::process_start_time(helper).is_none() {
220                let _ = std::fs::remove_dir_all(&dir);
221                return;
222            }
223            std::thread::sleep(std::time::Duration::from_millis(20));
224        }
225        panic!("the helper {helper} survived the launcher's cleanup");
226    }
227
228    /// The launcher's fallback after srv died: a recorded CLI still running
229    /// is killed with its group; one whose start time no longer matches (a
230    /// reused pid) is left alone; a file from another srv is ignored.
231    #[cfg(unix)]
232    #[test]
233    fn kill_orphans_kills_only_the_recorded_process() {
234        use std::os::unix::process::{CommandExt as _, ExitStatusExt as _};
235        let dir = temp_dir("orphans");
236        let spawn = || std::process::Command::new("sleep").arg("30").process_group(0).spawn().unwrap();
237        let mut cli = spawn();
238        let mut bystander = spawn();
239        let start = crate::process::process_start_time(cli.id()).unwrap();
240        let other_start = crate::process::process_start_time(bystander.id()).unwrap();
241        let roots = AgentRoots {
242            srv_pid: 4242,
243            cgroup: None,
244            roots: vec![Root { pid: cli.id(), start }, Root { pid: bystander.id(), start: other_start + 1 }],
245        };
246        write(&dir, &roots).unwrap();
247
248        assert_eq!(kill_orphans(&dir, 4243), None, "another srv's file");
249        assert!(read(&dir).is_some(), "left in place");
250
251        let done = kill_orphans(&dir, 4242).unwrap();
252        assert_eq!(done, Cleanup { cgroups: 0, groups: 1, gone: 1 });
253        assert_eq!(cli.wait().unwrap().signal(), Some(libc::SIGKILL));
254        assert_eq!(bystander.try_wait().unwrap(), None, "a pid whose start time differs is not touched");
255        assert_eq!(read(&dir), None, "deleted after cleanup");
256
257        bystander.kill().unwrap();
258        bystander.wait().unwrap();
259        let _ = std::fs::remove_dir_all(&dir);
260    }
261}