agentmux_srv_core/backend/process_tracker/
roots_file.rs1use 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
24pub 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
37pub 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
46pub 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
60fn 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}