Skip to main content

agentmux_srv_core/backend/process_tracker/
roots_file.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! srv's side of `agentmux_common::agent_roots`: the running agent CLIs, each
5//! the leader of its own process group, written to `<data_dir>/agent-roots.json`
6//! so the launcher can end them if srv dies without closing them.
7//!
8//! Recorded when an agent CLI is tracked ([`super::registry::track_spawned_agent`]),
9//! pruned on the registry poller's tick once a CLI has exited, and deleted by
10//! [`finish`] at srv's clean exit when no CLI is left.
11
12use std::path::PathBuf;
13
14use agentmux_common::agent_roots::{self, AgentRoots, Root};
15use parking_lot::Mutex;
16
17struct State {
18    data_dir: PathBuf,
19    file: AgentRoots,
20}
21
22static STATE: Mutex<Option<State>> = Mutex::new(None);
23
24/// Record a freshly spawned agent CLI.
25pub fn record(pid: u32) {
26    let Some(start) = agentmux_common::process::process_start_time(pid) else { return };
27    let mut guard = STATE.lock();
28    let state = guard.get_or_insert_with(|| State {
29        data_dir: crate::backend::base::get_mux_data_dir(),
30        file: AgentRoots { srv_pid: std::process::id(), ..AgentRoots::default() },
31    });
32    state.file.roots.retain(|r| r.pid != pid);
33    state.file.roots.push(Root { pid, start });
34    save(state);
35}
36
37/// Drop the CLIs that have exited. Called from the registry poller.
38pub fn prune() {
39    let mut guard = STATE.lock();
40    let Some(state) = guard.as_mut() else { return };
41    if prune_exited(&mut state.file) {
42        save(state);
43    }
44}
45
46/// srv's clean exit, after every agent was closed: delete the file, or, if a
47/// CLI outlived the teardown's cap, keep it (pruned) for the launcher.
48pub fn finish() {
49    let mut guard = STATE.lock();
50    let Some(state) = guard.as_mut() else { return };
51    prune_exited(&mut state.file);
52    if state.file.roots.is_empty() {
53        agent_roots::remove(&state.data_dir);
54    } else {
55        tracing::warn!(left = state.file.roots.len(), "[process-tracker] agent CLIs still running at exit; left for the launcher");
56        save(state);
57    }
58}
59
60/// Remove every root whose group is gone: the CLI exited and nothing it started
61/// still holds its group, or its pid was reused. True when anything was removed.
62fn prune_exited(file: &mut AgentRoots) -> bool {
63    let before = file.roots.len();
64    file.roots.retain(agentmux_common::agent_roots::is_alive);
65    file.roots.len() != before
66}
67
68fn save(state: &mut State) {
69    #[cfg(target_os = "linux")]
70    {
71        state.file.cgroup = super::cgroup_linux::root().map(|p| p.to_path_buf());
72    }
73    if let Err(e) = agent_roots::write(&state.data_dir, &state.file) {
74        tracing::warn!(error = %e, "[process-tracker] could not write {}", agent_roots::FILE_NAME);
75    }
76}
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81
82    #[test]
83    fn prune_drops_exited_and_reused_pids_only() {
84        let mut child = std::process::Command::new("sleep").arg("30").spawn().unwrap();
85        let start = agentmux_common::process::process_start_time(child.id()).unwrap();
86        let mut file = AgentRoots {
87            srv_pid: 1,
88            cgroup: None,
89            roots: vec![Root { pid: child.id(), start }, Root { pid: child.id(), start: start + 1 }],
90        };
91        assert!(prune_exited(&mut file), "the reused pid is dropped");
92        assert_eq!(file.roots, [Root { pid: child.id(), start }]);
93        assert!(!prune_exited(&mut file), "nothing more while it runs");
94        child.kill().unwrap();
95        child.wait().unwrap();
96        assert!(prune_exited(&mut file));
97        assert!(file.roots.is_empty());
98    }
99}