agentmux_srv_core/backend/process_tracker/mod.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Agent-spawned process tracking.
5//!
6//! Gives the host a complete, authoritative view of what each agent CLI
7//! has forked — backgrounded shells, dev servers, Docker containers,
8//! file watchers, nested bash/python/node children, etc. The goal is
9//! end-user visibility: a user running multiple agents can see in one
10//! place what's still running on their machine, and kill it reliably
11//! when they're done.
12//!
13//! The API is a platform-agnostic trait, one impl per platform. Terminals a
14//! person types in get the no-op `StubTracker` everywhere but Windows (see
15//! `AgentProcessRegistry::ensure_tracker_kind`).
16//!
17//! | Platform | Impl | Mechanism | Confidence |
18//! |----------|-----------------|--------------------------------------------|------------|
19//! | Windows | `JobObjectTracker` | `CreateJobObject` + `AssignProcessToJobObject` + `TerminateJobObject` | high |
20//! | Linux | `CgroupTracker` | cgroup v2 per agent in srv's delegated user scope; `cgroup.procs` / `cgroup.kill` | high |
21//! | Linux, no delegated cgroup; macOS | `ScanTracker` | process table: descendants of the CLI + the inherited `AGENTMUX_BLOCKID` env tag | best effort |
22//! | other | `StubTracker` | no-op | none |
23//!
24//! The frontend's swarm panel surfaces the confidence level so users know
25//! when tracking may miss escaped descendants.
26//!
27//! See `docs/analysis/agent-spawned-process-tracking-2026-10-07.md`.
28
29use std::collections::{HashMap, HashSet};
30use std::sync::Arc;
31
32pub mod registry;
33
34#[cfg(windows)]
35pub mod windows;
36
37#[cfg(target_os = "linux")]
38pub mod cgroup_linux;
39
40#[cfg(unix)]
41pub mod roots_file;
42
43pub mod scan;
44
45// `stub` is defined inline below; there is no separate `stub` file. A file-form
46// `pub mod stub;` here would collide with it (E0428) and break `task dev`.
47
48/// A single process tracked by the host — PID + metadata enriched
49/// per-platform. The frontend renders one row per entry.
50#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
51#[ts(export, export_to = "../../../frontend/types/rpc/")]
52pub struct TrackedProcess {
53 pub pid: u32,
54 /// Full command line, or best approximation. May be empty if the
55 /// platform doesn't expose it cheaply (macOS without `libproc`).
56 pub command: String,
57 /// Working-set / RSS in bytes. 0 if unavailable.
58 #[ts(type = "number")]
59 pub rss_bytes: u64,
60 /// Unix ms of process creation, 0 if unavailable.
61 #[ts(type = "number")]
62 pub started_at_ms: u64,
63 /// Parent PID, if the platform exposes it. Drives
64 /// [`agent_started`]'s ancestry walk.
65 pub parent_pid: Option<u32>,
66 /// The executable alone (path or name), which [`agent_started`]
67 /// classifies by: `command` may be a whole argv (`/bin/bash -c npm
68 /// test`). Empty means `command` is the executable.
69 #[serde(skip)]
70 #[ts(skip)]
71 pub exe: String,
72}
73
74impl TrackedProcess {
75 fn image(&self) -> String {
76 image_name(if self.exe.is_empty() { &self.command } else { &self.exe })
77 }
78}
79
80/// Lowercased executable name without directory or `.exe` suffix —
81/// `C:\Program Files\Git\bin\bash.exe` → `bash`.
82fn image_name(command: &str) -> String {
83 let base = command.rsplit(['\\', '/']).next().unwrap_or(command);
84 let base = base.to_ascii_lowercase();
85 base.strip_suffix(".exe").map(str::to_string).unwrap_or(base)
86}
87
88/// Interpreters an agent runs its tool commands through (Claude Code's Bash
89/// tool spawns `bash.exe -c ...` directly under `claude.exe`; Codex/Gemini
90/// use `powershell`/`cmd`).
91fn is_shell(p: &TrackedProcess) -> bool {
92 matches!(
93 p.image().as_str(),
94 "bash" | "sh" | "dash" | "zsh" | "fish" | "cmd" | "powershell" | "pwsh" | "nu"
95 )
96}
97
98/// Filter a tracker's raw membership down to the processes the agent
99/// started through its tools — what the Swarm list, the pane-close
100/// confirmation and the process events should count.
101///
102/// The raw job also holds the agent's own plumbing: the CLI itself
103/// (`roots` — every PID handed to `assign_process`), its `conhost.exe`, and
104/// MCP servers such as `agentmux-mcp.exe` (direct non-shell children of the
105/// root, plus their own conhosts/children). Counting those made every idle
106/// agent report ~3 processes and every pane close ask for confirmation.
107///
108/// Rule: drop roots and `conhost`; keep a process iff walking its parents
109/// inside the job passes through a shell before reaching a root. A root
110/// that is itself a shell (terminal blocks) counts as that shell. A chain
111/// that hits a parent no longer in the job — a launching shell that exited
112/// (`npm run dev &`), or a root that exited (a terminal's shell, a
113/// respawned CLI) — is kept: those orphans are exactly what the user needs
114/// to see.
115pub fn agent_started(members: Vec<TrackedProcess>, roots: &HashSet<u32>) -> Vec<TrackedProcess> {
116 let by_pid: HashMap<u32, &TrackedProcess> = members.iter().map(|p| (p.pid, p)).collect();
117 let keep: HashSet<u32> = members
118 .iter()
119 .filter(|p| !roots.contains(&p.pid) && p.image() != "conhost")
120 .filter(|p| {
121 let mut cur = *p;
122 // Bounded walk: a PID-reuse cycle can't spin forever.
123 for _ in 0..=members.len() {
124 if is_shell(cur) {
125 return true;
126 }
127 let Some(parent) = cur.parent_pid else { return true };
128 if roots.contains(&parent) {
129 // A root that has exited leaves an orphan like any other
130 // missing parent — keep it (ReAgent P1 on #3430).
131 return by_pid.get(&parent).is_none_or(|r| is_shell(r));
132 }
133 match by_pid.get(&parent) {
134 Some(next) => cur = next,
135 None => return true,
136 }
137 }
138 false
139 })
140 .map(|p| p.pid)
141 .collect();
142 members.into_iter().filter(|p| keep.contains(&p.pid)).collect()
143}
144
145/// Opaque per-agent handle returned by the tracker when we wrap a spawn.
146/// Held inside `AgentProcessRegistry` for the lifetime of the pane;
147/// dropped when the pane closes or the agent exits.
148#[allow(dead_code)]
149pub trait TrackerHandle: Send + Sync {
150 /// Add a freshly-spawned process to the tracked tree. Called by the
151 /// controller immediately after `tokio::process::Command::spawn`.
152 /// Descendants created AFTER this call are caught automatically;
153 /// descendants created BEFORE (in the ~1ms race window) escape.
154 /// No-op in the stub impl — platforms without a real tracker
155 /// silently accept the PID and move on.
156 fn assign_process(&self, pid: u32) -> Result<(), String>;
157
158 /// Enumerate the current members of this tracked tree.
159 ///
160 /// Must be cheap enough to poll every ~2s. On Windows this is a
161 /// single Job Object query; the planned Linux and macOS impls would
162 /// read `cgroup.procs` and scan sysctl respectively.
163 fn list_members(&self) -> Vec<TrackedProcess>;
164
165 /// Forcibly terminate every process in this tracked tree.
166 fn kill_tree(&self);
167
168 /// Terminate a single process by PID, if it's a member of this tree.
169 /// Returns `true` if the PID was known and the kill was attempted.
170 fn kill_pid(&self, pid: u32) -> bool;
171
172 /// Describes how confidently this platform tracks descendants.
173 /// Surfaced to the UI so the user can tell when tracking is
174 /// best-effort and escape-prone.
175 fn confidence(&self) -> TrackingConfidence;
176
177 /// Run every process in this tree at below-normal CPU priority (`on`), or
178 /// back at normal. Descendants inherit it and cannot raise it themselves.
179 /// Windows only (a Job Object priority-class limit); a no-op elsewhere: on
180 /// Linux and macOS the priority is set at spawn instead
181 /// (`registry::place_spawn`, nice `AGENT_NICE_LEVEL`), where it is inherited too.
182 /// See `docs/analysis/ANALYSIS_SRV_HTTP_STALL_IO_DRIVER_STARVATION_2026_09_26.md` §8.3.
183 fn set_below_normal_priority(&self, _on: bool) -> Result<(), String> {
184 Ok(())
185 }
186
187 /// Ask every member to exit (SIGTERM): the graceful step a teardown
188 /// takes before [`kill_tree`](Self::kill_tree). `false` where the
189 /// platform has no graceful signal for a whole tree yet (Windows), so
190 /// there is nothing to wait for.
191 fn terminate(&self) -> bool {
192 false
193 }
194
195 /// How many processes the tree holds right now, the agent's own CLI and
196 /// plumbing included: what a teardown waits to reach zero.
197 fn member_count(&self) -> usize {
198 self.list_members().len()
199 }
200
201 /// The tree's PIDs alone, plumbing included, without the per-process
202 /// enrichment `list_members` does: what Tower reads every refresh
203 /// (SPEC_TOWER_TASK_MANAGER_PANE_2026_10_08.md §5).
204 fn member_pids(&self) -> Vec<u32> {
205 self.list_members().into_iter().map(|p| p.pid).collect()
206 }
207
208 /// CPU time the whole tree has used, in nanoseconds, **including members
209 /// that have exited** (a Job Object's accounting, a cgroup's `cpu.stat`),
210 /// so a burst of short-lived build processes isn't lost between two
211 /// samples. `None` where the platform keeps no such account.
212 fn cpu_time_ns(&self) -> Option<u64> {
213 None
214 }
215
216 /// Where a child about to be spawned joins the tree before it execs
217 /// (Linux: the cgroup's `cgroup.procs`), so nothing it forks can slip
218 /// out between spawn and [`assign_process`](Self::assign_process).
219 /// `None`: only the after-spawn assignment.
220 fn spawn_target(&self) -> Option<std::path::PathBuf> {
221 None
222 }
223}
224
225/// How reliable this platform's tracker is.
226#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, ts_rs::TS)]
227#[ts(export, export_to = "../../../frontend/types/rpc/")]
228#[serde(rename_all = "snake_case")]
229pub enum TrackingConfidence {
230 /// Descendants can't escape the tracker. Windows Job Objects +
231 /// Linux cgroups v2.
232 #[cfg_attr(not(any(windows, target_os = "linux")), allow(dead_code))] // Only those two trackers build it.
233 High,
234 /// Descendants can escape via `setsid`, launchd, etc. macOS.
235 BestEffort,
236 /// Platform has no tracker. No guarantees.
237 None,
238}
239
240/// Factory: returns a platform-appropriate tracker handle that will
241/// accept the next-spawned process and everything it forks.
242///
243/// Call once per agent pane; reuse the handle across multiple turns of
244/// the `SubprocessController` so children from any turn are all tracked
245/// under the same umbrella.
246/// `agent`: the block runs an agent, not a terminal a person types in (see
247/// `AgentProcessRegistry::ensure_tracker_kind`). Every Unix tells them apart;
248/// Windows gives both a Job Object.
249pub fn new_tracker(block_id: &str, agent: bool) -> Arc<dyn TrackerHandle> {
250 #[cfg(windows)]
251 {
252 match windows::JobObjectTracker::new(block_id) {
253 Ok(t) => Arc::new(t),
254 Err(e) => {
255 tracing::error!(
256 block_id = %block_id,
257 error = %e,
258 "[process-tracker] JobObjectTracker init failed — falling back to best-effort tracking"
259 );
260 if agent {
261 Arc::new(scan::ScanTracker::new(block_id))
262 } else {
263 Arc::new(stub::StubTracker)
264 }
265 }
266 }
267 }
268 #[cfg(target_os = "linux")]
269 {
270 if let Some(root) = cgroup_linux::root().filter(|_| agent) {
271 match cgroup_linux::CgroupTracker::new(root, block_id) {
272 Ok(t) => return Arc::new(t),
273 Err(e) => tracing::warn!(block_id = %block_id, error = %e, "[process-tracker] cgroup tracker init failed"),
274 }
275 }
276 if agent {
277 return Arc::new(scan::ScanTracker::new(block_id));
278 }
279 Arc::new(stub::StubTracker)
280 }
281 #[cfg(all(unix, not(target_os = "linux")))]
282 {
283 if agent {
284 return Arc::new(scan::ScanTracker::new(block_id));
285 }
286 Arc::new(stub::StubTracker)
287 }
288 #[cfg(not(any(windows, unix)))]
289 {
290 let _ = (block_id, agent);
291 Arc::new(stub::StubTracker)
292 }
293}
294
295pub mod stub {
296 //! No-op tracker used on unsupported platforms, and on Windows when
297 //! `JobObjectTracker::new` fails (e.g. the process is not elevated enough
298 //! to create a job object). All operations succeed silently;
299 //! `list_members` always returns empty. Confidence reports `None` so the
300 //! UI can inform the user that tracking is disabled.
301
302 use super::{TrackedProcess, TrackerHandle, TrackingConfidence};
303
304 pub struct StubTracker;
305
306 impl TrackerHandle for StubTracker {
307 fn assign_process(&self, _pid: u32) -> Result<(), String> {
308 Ok(())
309 }
310 fn list_members(&self) -> Vec<TrackedProcess> {
311 Vec::new()
312 }
313 fn kill_tree(&self) {}
314 fn kill_pid(&self, _pid: u32) -> bool {
315 false
316 }
317 fn confidence(&self) -> TrackingConfidence {
318 TrackingConfidence::None
319 }
320 }
321}
322
323#[cfg(test)]
324mod tests {
325 use super::*;
326
327 fn proc(pid: u32, parent: Option<u32>, command: &str) -> TrackedProcess {
328 TrackedProcess {
329 pid,
330 command: command.to_string(),
331 rss_bytes: 0,
332 started_at_ms: 0,
333 parent_pid: parent,
334 exe: String::new(),
335 }
336 }
337
338 fn pids(v: &[TrackedProcess]) -> Vec<u32> {
339 let mut p: Vec<u32> = v.iter().map(|p| p.pid).collect();
340 p.sort();
341 p
342 }
343
344 /// The live tree of an idle Claude agent (observed after #3425): nothing
345 /// in it was started by the agent.
346 fn idle_claude() -> Vec<TrackedProcess> {
347 vec![
348 proc(10, Some(1), r"C:\Users\u\.local\bin\claude.exe"),
349 proc(11, Some(10), r"C:\Windows\System32\conhost.exe"),
350 proc(12, Some(10), r"C:\Program Files\AgentMux\agentmux-mcp.exe"),
351 proc(13, Some(12), r"C:\Windows\System32\conhost.exe"),
352 ]
353 }
354
355 #[test]
356 fn idle_agent_has_no_agent_started_processes() {
357 assert!(agent_started(idle_claude(), &HashSet::from([10])).is_empty());
358 }
359
360 #[test]
361 fn bash_tool_command_and_its_descendants_count() {
362 let mut members = idle_claude();
363 members.push(proc(20, Some(10), r"C:\Program Files\Git\bin\bash.exe"));
364 members.push(proc(21, Some(20), r"C:\Program Files\nodejs\node.exe"));
365 members.push(proc(22, Some(21), r"C:\Program Files\nodejs\node.exe"));
366 assert_eq!(pids(&agent_started(members, &HashSet::from([10]))), vec![20, 21, 22]);
367 }
368
369 #[test]
370 fn mcp_server_and_its_children_do_not_count() {
371 let mut members = idle_claude();
372 members.push(proc(30, Some(10), r"C:\Program Files\nodejs\node.exe"));
373 members.push(proc(31, Some(30), r"C:\Program Files\nodejs\node.exe"));
374 assert!(agent_started(members, &HashSet::from([10])).is_empty());
375 }
376
377 #[test]
378 fn orphan_whose_launching_shell_exited_still_counts() {
379 // `npm run dev &` — the bash that launched it is gone, the server lives on.
380 let mut members = idle_claude();
381 members.push(proc(40, Some(39), r"C:\Program Files\nodejs\node.exe"));
382 assert_eq!(pids(&agent_started(members, &HashSet::from([10]))), vec![40]);
383 }
384
385 #[test]
386 fn orphan_of_an_exited_root_still_counts() {
387 // A terminal's shell (root 80) backgrounded a server, then exited.
388 let members = vec![proc(81, Some(80), r"C:\Program Files\nodejs\node.exe")];
389 assert_eq!(pids(&agent_started(members, &HashSet::from([80]))), vec![81]);
390 }
391
392 #[test]
393 fn terminal_block_rooted_at_a_shell_counts_its_direct_children() {
394 let members = vec![
395 proc(50, Some(1), r"C:\Program Files\PowerShell\7\pwsh.exe"),
396 proc(51, Some(50), r"C:\Windows\System32\conhost.exe"),
397 proc(52, Some(50), r"C:\Program Files\nodejs\node.exe"),
398 ];
399 assert_eq!(pids(&agent_started(members, &HashSet::from([50]))), vec![52]);
400 }
401
402 #[test]
403 fn respawned_agent_excludes_every_root() {
404 // Old and new CLI PIDs were both assigned; neither is agent-started.
405 let mut members = idle_claude();
406 members.push(proc(60, Some(1), r"C:\Users\u\.local\bin\claude.exe"));
407 assert!(agent_started(members, &HashSet::from([10, 60])).is_empty());
408 }
409
410 /// Linux and macOS report the whole argv as `command`; the shell is
411 /// recognised from `exe`.
412 #[test]
413 fn a_shell_reported_with_its_argv_is_still_a_shell() {
414 let argv = |pid, parent, exe: &str, command: &str| TrackedProcess { exe: exe.to_string(), ..proc(pid, parent, command) };
415 let members = vec![
416 argv(10, Some(1), "/usr/bin/node", "node /usr/lib/claude/cli.js --input-format stream-json"),
417 argv(20, Some(10), "/bin/bash", "/bin/bash -c npm test"),
418 argv(21, Some(20), "/usr/bin/node", "node /repo/node_modules/.bin/vitest"),
419 ];
420 assert_eq!(pids(&agent_started(members, &HashSet::from([10]))), vec![20, 21]);
421 }
422
423 #[test]
424 fn parent_pid_cycle_terminates() {
425 let members = vec![proc(70, Some(71), r"C:\x\a.exe"), proc(71, Some(70), r"C:\x\b.exe")];
426 assert!(agent_started(members, &HashSet::new()).is_empty());
427 }
428}