Skip to main content

agentmux_srv_core/backend/process_tracker/
registry.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `AgentProcessRegistry` — app-wide map from block_id → tracker handle.
5//!
6//! Created once at host startup, passed into each `SubprocessController`
7//! / `PersistentSubprocessController` instance so it can wrap spawns
8//! in its per-block job. Polled periodically from a background task
9//! that emits `agent:process-added` / `agent:process-exited` events to
10//! the frontend's swarm activity panel.
11//!
12//! Centralizing this here (rather than one tracker per controller)
13//! means the lifetime of the tracker matches the lifetime of the pane
14//! — multiple turns on the same block share the same job, so
15//! descendants from turn N are still visible on turn N+1.
16
17use std::collections::{HashMap, HashSet};
18use std::sync::{Arc, OnceLock};
19
20use parking_lot::Mutex;
21
22use super::{agent_started, new_tracker, TrackedProcess, TrackerHandle, TrackingConfidence};
23use crate::backend::mps;
24
25/// Host-wide registry, set once at startup. Exposed as a global so
26/// `SubprocessController` / `PersistentSubprocessController` can reach
27/// it without threading an `Arc` through every constructor + test site.
28/// Tests that don't initialize it see `None` and silently skip
29/// tracker registration — the job-object spawn path no-ops cleanly.
30static GLOBAL: OnceLock<Arc<AgentProcessRegistry>> = OnceLock::new();
31
32pub fn set_global(registry: Arc<AgentProcessRegistry>) {
33    let _ = GLOBAL.set(registry);
34}
35
36pub fn global() -> Option<Arc<AgentProcessRegistry>> {
37    GLOBAL.get().cloned()
38}
39
40/// Assign a freshly-spawned child PID to `block_id`'s tracker, creating the
41/// tracker if needed. The single call site every `Controller` impl should use
42/// immediately after its own spawn — no-ops silently if the registry global
43/// isn't initialized (tests), and with a warn log if the platform tracker
44/// rejects the PID, since this is opportunistic enrichment, not a liveness signal on
45/// its own (see `broker::process::ProcessStatus`'s own doc comment).
46pub fn track_spawned(block_id: &str, pid: u32) {
47    track(block_id, pid, false);
48}
49
50fn track(block_id: &str, pid: u32, agent: bool) {
51    let Some(registry) = global() else { return };
52    if let Err(e) = registry.assign_kind(block_id, pid, agent) {
53        tracing::warn!(
54            block_id = %block_id,
55            pid = pid,
56            err = %e,
57            "[process-tracker] assign_process failed"
58        );
59    }
60}
61
62/// Put a process srv spawned on an agent's behalf (`Shell()`, `!cmd`) into
63/// that agent's tracker, so it dies with the agent like anything the agent
64/// started itself (SPEC_AGENT_TEARDOWN_SINGLE_PATH_2026_10_01.md §6.5). Unlike
65/// [`track_spawned`] it never creates a tracker (a block with no agent process
66/// has nothing to join) and doesn't mark the PID as a root, so the process
67/// still counts as something the agent started. Best-effort, like
68/// [`track_spawned`].
69pub fn track_adopted(block_id: &str, pid: u32) {
70    if block_id.is_empty() {
71        return;
72    }
73    let Some(registry) = global() else { return };
74    if let Err(e) = registry.adopt(block_id, pid) {
75        tracing::warn!(block_id = %block_id, pid = pid, err = %e, "[process-tracker] adopt failed");
76    }
77}
78
79/// Make a child about to be spawned for `block_id` join its tracker before it
80/// execs, so nothing it forks escapes between spawn and [`track_spawned`]
81/// (Linux: the agent's cgroup). `create`: start the block's tracker if it has
82/// none (an agent's own CLI); otherwise join only an existing one (`Shell()`,
83/// `!cmd`, like [`track_adopted`]). Still call `track_spawned*` /
84/// `track_adopted` after the spawn: that records the PID and covers platforms
85/// with no pre-exec placement.
86///
87/// An agent's own CLI (`create`) also leads its own process group on Unix,
88/// so a signal to its group (its own, or one of its tools') can't reach srv,
89/// and its teardown (`process::kill_child_and_group`) takes its MCP servers
90/// too. The launcher finds these groups through `agent_roots` if srv dies
91/// without closing them.
92pub fn place_spawn(block_id: &str, cmd: &mut tokio::process::Command, create: bool) {
93    #[cfg(unix)]
94    if create {
95        cmd.process_group(0);
96        if let Some(level) = spawn_nice() {
97            nice_before_exec(cmd, level);
98        }
99    }
100    #[cfg(target_os = "linux")]
101    if let Some(target) = spawn_target(block_id, create) {
102        super::cgroup_linux::join_before_exec(cmd, target);
103    }
104    #[cfg(not(target_os = "linux"))]
105    let _ = (block_id, cmd, create);
106}
107
108/// The nice level an agent's process tree runs at on Unix while
109/// `agent:belownormalpriority` is on. Measured on Linux (2026-10-24): with
110/// agent builds at normal priority the page's long tasks were 4x idle and an
111/// `AgentInput` took 2 s at the median; at nice 10 both were back within a
112/// third of idle, and 19 did no better.
113#[cfg(unix)]
114pub const AGENT_NICE_LEVEL: i32 = 10;
115
116/// The nice level for an agent spawn made now: [`AGENT_NICE_LEVEL`] when the
117/// live setting is on, `None` when it is off or no registry is attached
118/// (tests, early boot), like [`track_spawned_agent`].
119#[cfg(unix)]
120fn spawn_nice() -> Option<i32> {
121    global()?.agent_nice()
122}
123
124/// Make a child about to be spawned run at nice level `level` (never lower
125/// than it already has: an unprivileged `setpriority` can't reduce niceness,
126/// so a srv started niced keeps it). Everything the child forks inherits it
127/// and cannot lower it. Only `setpriority`, which is async-signal-safe, runs
128/// between fork and exec; a failure is not fatal.
129#[cfg(unix)]
130fn nice_before_exec(cmd: &mut tokio::process::Command, level: i32) {
131    // SAFETY: the hook calls only `setpriority`, on no allocated memory.
132    unsafe {
133        cmd.pre_exec(move || {
134            libc::setpriority(libc::PRIO_PROCESS, 0, level);
135            Ok(())
136        });
137    }
138}
139
140/// Wrap a PTY command's argv so it runs at `nice -n level` (`portable_pty`
141/// has no pre-exec hook). The wrapper `exec`s, so the PID is the agent's.
142/// Leaves an empty argv alone: that is the user's default shell, never an agent.
143#[cfg(unix)]
144fn nice_wrap_argv(argv: &mut Vec<std::ffi::OsString>, level: i32) {
145    if argv.is_empty() {
146        return;
147    }
148    let mut wrapped: Vec<std::ffi::OsString> = vec!["/usr/bin/env".into(), "nice".into(), "-n".into(), level.to_string().into()];
149    wrapped.append(argv);
150    *argv = wrapped;
151}
152
153/// An agent CLI srv runs outside any block's tracker (the Drone runner, the
154/// ambient side call): it too leads its own process group on Unix, like
155/// [`place_spawn`]'s, so its kill takes its helpers and a signal to its group
156/// can't reach srv. Call [`record_untracked_cli`] once it is spawned.
157pub fn own_process_group(cmd: &mut tokio::process::Command) {
158    #[cfg(unix)]
159    cmd.process_group(0);
160    #[cfg(not(unix))]
161    let _ = cmd;
162}
163
164/// Record a CLI spawned with [`own_process_group`] for the launcher
165/// (`roots_file`), which ends it if srv dies first.
166pub fn record_untracked_cli(pid: Option<u32>) {
167    #[cfg(unix)]
168    if let Some(pid) = pid {
169        debug_assert!(agentmux_common::process::leads_own_group(pid), "{pid} should lead its own process group");
170        if global().is_some() {
171            super::roots_file::record(pid);
172        }
173    }
174    #[cfg(not(unix))]
175    let _ = pid;
176}
177
178/// How a spawn joins its block's tracker (see [`spawn_tracked`]).
179#[derive(Clone, Copy, Debug, PartialEq, Eq)]
180pub enum Join {
181    /// The agent's own process: starts the block's tracker if needed and is
182    /// recorded as a root ([`track_spawned_agent`]).
183    Agent,
184    /// Started on an agent's behalf (`Shell()`, `!cmd`): joins an existing
185    /// tracker only ([`track_adopted`]).
186    Adopted,
187}
188
189/// Spawn `cmd` for `block_id` already inside the block's tracker, so nothing
190/// it starts can escape between spawn and assignment: on Linux it joins the
191/// cgroup before exec ([`place_spawn`]); on Windows it starts suspended, is
192/// assigned to the job, then resumed. The one way an agent-side tokio spawn
193/// should start (the Codex App Server, which spawns internally, uses
194/// [`place_spawn`] and [`track_spawned_agent`]).
195pub fn spawn_tracked(block_id: &str, cmd: &mut tokio::process::Command, join: Join) -> std::io::Result<tokio::process::Child> {
196    place_spawn(block_id, cmd, join == Join::Agent);
197    #[cfg(windows)]
198    let suspended = start_suspended(block_id, cmd, join == Join::Agent);
199    let child = cmd.spawn()?;
200    if let Some(pid) = child.id() {
201        match join {
202            Join::Agent => track_spawned_agent(block_id, pid),
203            Join::Adopted => track_adopted(block_id, pid),
204        }
205        // Resumed whether or not the assignment worked: a child left
206        // suspended would never run.
207        #[cfg(windows)]
208        if suspended {
209            if let Err(e) = agentmux_common::win32::resume_main_thread(pid) {
210                let mut child = child;
211                let _ = child.start_kill();
212                return Err(std::io::Error::other(format!("resume suspended child {pid}: {e}")));
213            }
214        }
215    }
216    Ok(child)
217}
218
219/// Make `cmd` start suspended when the block has (or, `create`, gets) a Job
220/// Object to put it in first. Agent-side spawns set no creation flag but
221/// `CREATE_NO_WINDOW`, which this keeps.
222#[cfg(windows)]
223fn start_suspended(block_id: &str, cmd: &mut tokio::process::Command, create: bool) -> bool {
224    use windows_sys::Win32::System::Threading::{CREATE_NO_WINDOW, CREATE_SUSPENDED};
225    let Some(registry) = global() else { return false };
226    if block_id.is_empty() {
227        return false;
228    }
229    let tracker = if create {
230        Some(registry.ensure_tracker_kind(block_id, true))
231    } else {
232        registry.inner.lock().get(block_id).map(|e| e.tracker.clone())
233    };
234    if !tracker.is_some_and(|t| t.confidence() == TrackingConfidence::High) {
235        return false;
236    }
237    cmd.creation_flags(CREATE_NO_WINDOW | CREATE_SUSPENDED);
238    true
239}
240
241/// [`place_spawn`] for an agent's PTY spawn, which has no pre-exec hook: the
242/// command is wrapped to join first (`cgroup_linux::join_before_exec_pty`).
243pub fn place_pty_spawn(block_id: &str, cmd: &mut portable_pty::CommandBuilder) {
244    // Before the cgroup wrapper, so the wrapper stays the outermost command.
245    #[cfg(unix)]
246    if let Some(level) = spawn_nice() {
247        nice_wrap_argv(cmd.get_argv_mut(), level);
248    }
249    #[cfg(target_os = "linux")]
250    if let Some(target) = spawn_target(block_id, true) {
251        super::cgroup_linux::join_before_exec_pty(cmd, target);
252    }
253    #[cfg(not(target_os = "linux"))]
254    let _ = (block_id, cmd);
255}
256
257/// Where a spawn for `block_id` joins its agent's tree, if anywhere.
258#[cfg(target_os = "linux")]
259fn spawn_target(block_id: &str, create: bool) -> Option<std::path::PathBuf> {
260    if block_id.is_empty() {
261        return None;
262    }
263    let registry = global()?;
264    let tracker = if create {
265        Some(registry.ensure_tracker_kind(block_id, true))
266    } else {
267        registry.inner.lock().get(block_id).map(|e| e.tracker.clone())
268    };
269    tracker?.spawn_target()
270}
271
272/// Settings key: run agents' process trees at below-normal CPU priority so
273/// their builds and tests yield to AgentMux (and the user's foreground apps)
274/// under contention, while still using every idle core. Default on. Windows:
275/// a Job Object priority class. Linux and macOS: nice [`AGENT_NICE_LEVEL`]
276/// set at spawn ([`place_spawn`], [`place_pty_spawn`]).
277pub const SETTING_AGENT_BELOW_NORMAL_PRIORITY: &str = "agent:belownormalpriority";
278
279/// [`track_spawned`] for an **agent** process: also applies the agent CPU
280/// priority policy to the block's whole tree. Terminal panes a human types in
281/// keep calling [`track_spawned`] and are never deprioritized.
282pub fn track_spawned_agent(block_id: &str, pid: u32) {
283    track(block_id, pid, true);
284    let Some(registry) = global() else { return };
285    #[cfg(unix)]
286    super::roots_file::record(pid);
287    let on = registry.agent_below_normal_priority();
288    if let Err(e) = registry.set_below_normal_priority(block_id, on) {
289        tracing::warn!(block_id = %block_id, err = %e, "[process-tracker] could not set job CPU priority");
290    }
291}
292
293/// One block's tracked tree, as [`AgentProcessRegistry::members_by_block`]
294/// reports it.
295#[derive(Debug, Clone)]
296pub struct BlockMembers {
297    pub block_id: String,
298    pub pids: Vec<u32>,
299    /// The PIDs assigned as the block's own process (the agent CLI or shell).
300    pub roots: HashSet<u32>,
301    pub confidence: TrackingConfidence,
302    pub cpu_time_ns: Option<u64>,
303}
304
305pub struct AgentProcessRegistry {
306    inner: Mutex<HashMap<String, RegistryEntry>>,
307    broker: Option<Arc<mps::Broker>>,
308    /// Live settings, read per spawn so a settings.json change applies to the
309    /// next agent spawn. `None` in tests and before bootstrap wires it.
310    config: Mutex<Option<Arc<crate::backend::wconfig::ConfigState>>>,
311}
312
313struct RegistryEntry {
314    tracker: Arc<dyn TrackerHandle>,
315    /// An agent's block (its tree is the agent's), not a terminal a person types in.
316    agent: bool,
317    /// Last-known PID set from the most recent poll. Used to diff
318    /// against the current set so we only emit events for
319    /// additions/removals — not on every poll tick.
320    last_pids: HashSet<u32>,
321    /// Every PID handed to `assign` — the agent CLI itself, one per
322    /// (re)spawn. `agent_started` excludes them and their non-shell
323    /// children (MCP servers) from what we report.
324    roots: HashSet<u32>,
325}
326
327impl AgentProcessRegistry {
328    pub fn new(broker: Option<Arc<mps::Broker>>) -> Self {
329        Self {
330            inner: Mutex::new(HashMap::new()),
331            broker,
332            config: Mutex::new(None),
333        }
334    }
335
336    /// Attach the live settings (bootstrap).
337    pub fn set_config(&self, config: Arc<crate::backend::wconfig::ConfigState>) {
338        *self.config.lock() = Some(config);
339    }
340
341    /// The `agent:belownormalpriority` setting; `true` when unset or when no
342    /// settings are attached.
343    pub fn agent_below_normal_priority(&self) -> bool {
344        self.config
345            .lock()
346            .as_ref()
347            .and_then(|c| c.get_settings().extra.get(SETTING_AGENT_BELOW_NORMAL_PRIORITY).and_then(|v| v.as_bool()))
348            .unwrap_or(true)
349    }
350
351    /// The nice level an agent's process tree runs at on Unix: [`AGENT_NICE_LEVEL`]
352    /// while `agent:belownormalpriority` is on, `None` while it is off.
353    #[cfg(unix)]
354    pub fn agent_nice(&self) -> Option<i32> {
355        self.agent_below_normal_priority().then_some(AGENT_NICE_LEVEL)
356    }
357
358    /// Apply (or lift) the below-normal priority limit on `block_id`'s tree.
359    pub fn set_below_normal_priority(&self, block_id: &str, on: bool) -> Result<(), String> {
360        let tracker = self.ensure_tracker(block_id);
361        tracker.set_below_normal_priority(on)
362    }
363
364    /// Ensure a tracker exists for this block. Idempotent — calling
365    /// twice for the same block returns the existing tracker so the
366    /// job survives controller re-creation (e.g. on /clear).
367    pub fn ensure_tracker(&self, block_id: &str) -> Arc<dyn TrackerHandle> {
368        self.ensure_tracker_kind(block_id, false)
369    }
370
371    /// [`ensure_tracker`](Self::ensure_tracker) for an agent's block
372    /// (`agent`) or a terminal a person types in. The kind matters on every
373    /// Unix, where an agent gets a cgroup or the best-effort scan tracker (its
374    /// whole tree ends with it) and a terminal keeps Unix semantics: what the
375    /// user `nohup`s outlives it.
376    pub fn ensure_tracker_kind(&self, block_id: &str, agent: bool) -> Arc<dyn TrackerHandle> {
377        let mut map = self.inner.lock();
378        if let Some(entry) = map.get_mut(block_id) {
379            entry.agent |= agent;
380            return entry.tracker.clone();
381        }
382        let tracker = new_tracker(block_id, agent);
383        map.insert(
384            block_id.to_string(),
385            RegistryEntry {
386                tracker: tracker.clone(),
387                agent,
388                last_pids: HashSet::new(),
389                roots: HashSet::new(),
390            },
391        );
392        tracing::info!(
393            block_id = %block_id,
394            confidence = ?tracker.confidence(),
395            "[process-tracker] registered tracker"
396        );
397        tracker
398    }
399
400    /// Assign a freshly-spawned agent/shell PID to `block_id`'s tracker
401    /// (creating it if needed) and remember it as a root.
402    /// The tracker is an agent's or a terminal's (see
403    /// [`ensure_tracker_kind`](Self::ensure_tracker_kind)).
404    pub fn assign_kind(&self, block_id: &str, pid: u32, agent: bool) -> Result<(), String> {
405        let tracker = self.ensure_tracker_kind(block_id, agent);
406        tracker.assign_process(pid)?;
407        if let Some(entry) = self.inner.lock().get_mut(block_id) {
408            entry.roots.insert(pid);
409        }
410        Ok(())
411    }
412
413    /// Add `pid` to `block_id`'s tracker if it has one, without marking it a
414    /// root. `Ok(false)` when the block has no tracker.
415    pub fn adopt(&self, block_id: &str, pid: u32) -> Result<bool, String> {
416        let tracker = match self.inner.lock().get(block_id) {
417            Some(e) => e.tracker.clone(),
418            None => return Ok(false),
419        };
420        tracker.assign_process(pid)?;
421        Ok(true)
422    }
423
424    /// Drop a block's tracker — call when the pane closes. The tracker's
425    /// Drop impl kills the whole process tree (`KILL_ON_JOB_CLOSE` on
426    /// Windows, `cgroup.kill` on Linux; nothing on the stub).
427    pub fn remove(&self, block_id: &str) {
428        let mut map = self.inner.lock();
429        if map.remove(block_id).is_some() {
430            tracing::info!(block_id = %block_id, "[process-tracker] dropped tracker on pane close");
431        }
432    }
433
434    /// `(tracked block count, summed last-known PID count across all
435    /// blocks)` — diagnostic-only, for the periodic `mem_attribution` log
436    /// (`sysinfo.rs`) to correlate against commit/handle growth. A block
437    /// count that grows without bound (no matching `remove` on pane close)
438    /// or a PID count far exceeding what's actually open would both be
439    /// visible here well before the commit-side symptom is undeniable.
440    #[cfg(any(windows, test))]
441    pub fn stats(&self) -> (usize, usize) {
442        let map = self.inner.lock();
443        let pids: usize = map.values().map(|e| e.last_pids.len()).sum();
444        (map.len(), pids)
445    }
446
447    /// Processes the agent started through its tools (see
448    /// [`agent_started`]) — for the RPC endpoint, Swarm and the pane-close
449    /// confirmation. Excludes the CLI itself, conhost and MCP servers;
450    /// `kill_tree` still takes all of them.
451    pub fn list_block(&self, block_id: &str) -> Vec<TrackedProcess> {
452        let (tracker, roots) = match self.inner.lock().get(block_id) {
453            Some(e) => (e.tracker.clone(), e.roots.clone()),
454            None => return Vec::new(),
455        };
456        agent_started(tracker.list_members(), &roots)
457    }
458
459    /// The block of the agent whose process tree holds any of `pids` (a process and its ancestors), if one does. Terminals
460    /// a person types in are not agents' trees. The trackers are queried outside the registry lock.
461    pub fn agent_block_holding(&self, pids: &[u32]) -> Option<String> {
462        let trackers: Vec<(String, Arc<dyn TrackerHandle>)> =
463            self.inner.lock().iter().filter(|(_, e)| e.agent).map(|(id, e)| (id.clone(), e.tracker.clone())).collect();
464        trackers.into_iter().find(|(_, t)| t.member_pids().iter().any(|m| pids.contains(m))).map(|(id, _)| id)
465    }
466
467    /// The PIDs in every agent block's process tree, each with its block.
468    pub fn agent_member_pids(&self) -> Vec<(String, u32)> {
469        let trackers: Vec<(String, Arc<dyn TrackerHandle>)> =
470            self.inner.lock().iter().filter(|(_, e)| e.agent).map(|(id, e)| (id.clone(), e.tracker.clone())).collect();
471        trackers.into_iter().flat_map(|(id, t)| t.member_pids().into_iter().map(move |pid| (id.clone(), pid))).collect()
472    }
473
474    /// Whether any block is tracked (a cheap check before a process-table read).
475    pub fn has_tracked_blocks(&self) -> bool {
476        !self.inner.lock().is_empty()
477    }
478
479    /// Every tracked block's members for Tower: PIDs (plumbing included), the
480    /// roots, the tracker's confidence and the tree's CPU account. The trackers
481    /// are queried outside the registry lock.
482    pub fn members_by_block(&self) -> Vec<BlockMembers> {
483        let entries: Vec<(String, Arc<dyn TrackerHandle>, HashSet<u32>)> = self
484            .inner
485            .lock()
486            .iter()
487            .map(|(id, e)| (id.clone(), e.tracker.clone(), e.roots.clone()))
488            .collect();
489        entries
490            .into_iter()
491            .map(|(block_id, tracker, roots)| BlockMembers {
492                pids: tracker.member_pids(),
493                cpu_time_ns: tracker.cpu_time_ns(),
494                confidence: tracker.confidence(),
495                block_id,
496                roots,
497            })
498            .collect()
499    }
500
501    /// Confidence of a block's tracker — drives the "tracking is
502    /// best-effort on macOS" badge in the swarm UI.
503    pub fn confidence_of(&self, block_id: &str) -> TrackingConfidence {
504        self.inner
505            .lock()
506            .get(block_id)
507            .map(|e| e.tracker.confidence())
508            .unwrap_or(TrackingConfidence::None)
509    }
510
511    /// Ask everything in `block_id`'s tree to exit (SIGTERM on Linux), the
512    /// graceful step before [`remove`](Self::remove) kills what's left.
513    /// `false` when nothing was asked (no tracker, or no graceful signal).
514    pub fn terminate(&self, block_id: &str) -> bool {
515        let tracker = self.inner.lock().get(block_id).map(|e| e.tracker.clone());
516        tracker.is_some_and(|t| t.terminate())
517    }
518
519    /// Every process in `block_id`'s tree, plumbing included; 0 without a
520    /// tracker.
521    pub fn member_count(&self, block_id: &str) -> usize {
522        let tracker = self.inner.lock().get(block_id).map(|e| e.tracker.clone());
523        tracker.map_or(0, |t| t.member_count())
524    }
525
526    /// Kill the entire process tree for a given block. Returns `true`
527    /// if a tracker was found (the kill was dispatched). Does NOT
528    /// synchronously wait for descendants to actually exit — the
529    /// poller's next tick will pick up the state changes and emit
530    /// `agent:process-exited` events the frontend can react to.
531    pub fn kill_tree(&self, block_id: &str) -> bool {
532        let tracker = self.inner.lock().get(block_id).map(|e| e.tracker.clone());
533        match tracker {
534            Some(t) => {
535                t.kill_tree();
536                true
537            }
538            None => false,
539        }
540    }
541
542    /// Kill a single PID if it's a member of the given block's tree.
543    /// Returns `true` if the tracker was found and the PID matched.
544    pub fn kill_pid(&self, block_id: &str, pid: u32) -> bool {
545        let tracker = self.inner.lock().get(block_id).map(|e| e.tracker.clone());
546        match tracker {
547            Some(t) => t.kill_pid(pid),
548            None => false,
549        }
550    }
551
552    /// Poll every tracked block's membership and diff against the
553    /// last-known set. Emits `agent:process-added` / `-exited` events
554    /// for each delta.
555    ///
556    /// Called by a background Tokio task on a ~2s interval.
557    pub fn poll_and_emit(&self) {
558        #[cfg(unix)]
559        super::roots_file::prune();
560        let mut map = self.inner.lock();
561        for (block_id, entry) in map.iter_mut() {
562            let current_members = agent_started(entry.tracker.list_members(), &entry.roots);
563            let current_pids: HashSet<u32> = current_members.iter().map(|p| p.pid).collect();
564
565            for added_pid in current_pids.difference(&entry.last_pids) {
566                if let Some(p) = current_members.iter().find(|p| p.pid == *added_pid) {
567                    if let Some(broker) = &self.broker {
568                        let added = crate::backend::mps_events::ProcessAddedEvent { block_id: block_id.clone(), process: p.clone() };
569                        broker.publish_event::<crate::backend::mps_events::AgentProcessAdded>(&added, vec![format!("block:{}", block_id)], 0);
570                    }
571                }
572            }
573            for removed_pid in entry.last_pids.difference(&current_pids) {
574                if let Some(broker) = &self.broker {
575                    let exited = crate::backend::mps_events::ProcessExitedEvent { block_id: block_id.clone(), pid: *removed_pid };
576                    broker.publish_event::<crate::backend::mps_events::AgentProcessExited>(&exited, vec![format!("block:{}", block_id)], 0);
577                }
578            }
579
580            entry.last_pids = current_pids;
581        }
582    }
583
584}
585
586/// Spawn the polling task. It holds the registry weakly and ends once the
587/// registry's last `Arc` is dropped (host shutdown). ~2s cadence balances
588/// latency (new processes show up fast) with CPU overhead (job queries are
589/// cheap but not free).
590pub fn spawn_poller(registry: Arc<AgentProcessRegistry>) -> tokio::task::JoinHandle<()> {
591    let registry = Arc::downgrade(&registry);
592    tokio::spawn(async move {
593        let mut interval = tokio::time::interval(std::time::Duration::from_secs(2));
594        interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
595        loop {
596            interval.tick().await;
597            let Some(registry) = registry.upgrade() else { break };
598            // Per-process OS queries for every tracked block plus a
599            // system-wide process snapshot, under two mutexes — never on an
600            // async worker (see `backend::blocking`). Awaited, so still one
601            // pass at a time.
602            if let Err(e) = tokio::task::spawn_blocking(move || registry.poll_and_emit()).await {
603                tracing::warn!(error = %e, "[process-tracker] poll task failed");
604            }
605        }
606    })
607}
608
609#[cfg(test)]
610mod tests {
611    use super::*;
612
613    #[test]
614    fn agent_cpu_priority_policy_defaults_on_and_follows_the_setting() {
615        let reg = AgentProcessRegistry::new(None);
616        // No settings attached (tests, early boot): on.
617        assert!(reg.agent_below_normal_priority());
618
619        let config = Arc::new(crate::backend::wconfig::ConfigState::with_config(
620            crate::backend::wconfig::build_default_config(),
621        ));
622        reg.set_config(Arc::clone(&config));
623        // Key absent: on.
624        assert!(reg.agent_below_normal_priority());
625
626        let mut settings = config.get_settings();
627        settings.extra.insert(SETTING_AGENT_BELOW_NORMAL_PRIORITY.to_string(), serde_json::json!(false));
628        config.update_settings(settings.clone());
629        assert!(!reg.agent_below_normal_priority(), "read live, not captured");
630
631        settings.extra.insert(SETTING_AGENT_BELOW_NORMAL_PRIORITY.to_string(), serde_json::json!(true));
632        config.update_settings(settings);
633        assert!(reg.agent_below_normal_priority());
634    }
635
636    fn sleeper() -> std::process::Child {
637        #[cfg(windows)]
638        let mut cmd = std::process::Command::new("ping");
639        #[cfg(windows)]
640        cmd.args(["-n", "30", "127.0.0.1"]);
641        #[cfg(not(windows))]
642        let mut cmd = std::process::Command::new("sleep");
643        #[cfg(not(windows))]
644        cmd.arg("30");
645        cmd.stdout(std::process::Stdio::null()).spawn().expect("a process to track")
646    }
647
648    /// A process in an agent's tree is found, with the block it belongs to; one in a terminal a person types in, or in no tree, is not.
649    #[test]
650    fn an_agents_tree_holds_its_processes_and_a_terminals_does_not() {
651        let reg = AgentProcessRegistry::new(None);
652        let (mut agent, mut terminal) = (sleeper(), sleeper());
653        reg.assign_kind("agent-block", agent.id(), true).unwrap();
654        reg.assign_kind("terminal-block", terminal.id(), false).unwrap();
655        assert_eq!(reg.agent_block_holding(&[agent.id()]).as_deref(), Some("agent-block"));
656        assert_eq!(reg.agent_block_holding(&[u32::MAX - 1, agent.id()]).as_deref(), Some("agent-block"), "any process of the chain");
657        assert_eq!(reg.agent_block_holding(&[terminal.id()]), None, "a terminal's tree is not an agent's");
658        assert_eq!(reg.agent_block_holding(&[u32::MAX - 1]), None);
659        reg.remove("agent-block");
660        reg.remove("terminal-block");
661        let _ = (agent.kill(), terminal.kill());
662        let _ = (agent.wait(), terminal.wait());
663    }
664
665    #[cfg(unix)]
666    #[test]
667    fn agent_nice_follows_the_setting() {
668        let reg = AgentProcessRegistry::new(None);
669        assert_eq!(reg.agent_nice(), Some(AGENT_NICE_LEVEL), "on when no settings are attached");
670
671        let config = Arc::new(crate::backend::wconfig::ConfigState::with_config(
672            crate::backend::wconfig::build_default_config(),
673        ));
674        reg.set_config(Arc::clone(&config));
675        let mut settings = config.get_settings();
676        settings.extra.insert(SETTING_AGENT_BELOW_NORMAL_PRIORITY.to_string(), serde_json::json!(false));
677        config.update_settings(settings.clone());
678        assert_eq!(reg.agent_nice(), None, "off, read live");
679        settings.extra.insert(SETTING_AGENT_BELOW_NORMAL_PRIORITY.to_string(), serde_json::json!(true));
680        config.update_settings(settings);
681        assert_eq!(reg.agent_nice(), Some(AGENT_NICE_LEVEL));
682    }
683
684    #[cfg(unix)]
685    #[test]
686    fn a_pty_argv_is_wrapped_in_nice_and_an_empty_one_is_left_alone() {
687        let mut argv: Vec<std::ffi::OsString> = vec!["claude".into(), "--flag".into()];
688        nice_wrap_argv(&mut argv, 10);
689        assert_eq!(argv, ["/usr/bin/env", "nice", "-n", "10", "claude", "--flag"]);
690        let mut shell: Vec<std::ffi::OsString> = Vec::new();
691        nice_wrap_argv(&mut shell, 10);
692        assert!(shell.is_empty(), "the user's default shell is never wrapped");
693    }
694
695    /// Nice value (field 19 of /proc/<pid>/stat) from a stat line; the command
696    /// name in field 2 may hold spaces, so count from the closing parenthesis.
697    #[cfg(target_os = "linux")]
698    fn nice_of_stat(stat: &str) -> i32 {
699        let rest = &stat[stat.rfind(')').expect("stat has a command name") + 2..];
700        rest.split(' ').nth(16).expect("stat has a nice field").parse().expect("nice is a number")
701    }
702
703    #[cfg(target_os = "linux")]
704    fn own_nice() -> i32 {
705        nice_of_stat(&std::fs::read_to_string("/proc/self/stat").unwrap())
706    }
707
708    /// The nice value of a grandchild: `sh` starts `cut`, which reads its own stat.
709    #[cfg(target_os = "linux")]
710    const GRANDCHILD_NICE: &str = "cut -d' ' -f19 /proc/self/stat";
711
712    #[cfg(target_os = "linux")]
713    #[tokio::test]
714    async fn an_agent_spawn_runs_at_nice_10_and_its_children_inherit_it() {
715        let mut cmd = tokio::process::Command::new("sh");
716        cmd.arg("-c").arg(GRANDCHILD_NICE);
717        nice_before_exec(&mut cmd, AGENT_NICE_LEVEL);
718        let out = cmd.output().await.unwrap();
719        assert!(out.status.success());
720        let nice: i32 = String::from_utf8_lossy(&out.stdout).trim().parse().unwrap();
721        // Never lower than the test process's own (a niced CI runner keeps it).
722        assert_eq!(nice, own_nice().max(AGENT_NICE_LEVEL));
723    }
724
725    /// Negative control: the same spawn without the hook is at the parent's nice,
726    /// so the test above detects the hook, not a niced test runner.
727    #[cfg(target_os = "linux")]
728    #[tokio::test]
729    async fn without_the_hook_a_spawn_keeps_the_parents_priority() {
730        let out = tokio::process::Command::new("sh").arg("-c").arg(GRANDCHILD_NICE).output().await.unwrap();
731        let nice: i32 = String::from_utf8_lossy(&out.stdout).trim().parse().unwrap();
732        assert_eq!(nice, own_nice());
733    }
734
735    #[cfg(target_os = "linux")]
736    #[test]
737    fn a_wrapped_pty_command_runs_at_nice() {
738        let mut argv: Vec<std::ffi::OsString> = vec!["sh".into(), "-c".into(), GRANDCHILD_NICE.into()];
739        nice_wrap_argv(&mut argv, AGENT_NICE_LEVEL);
740        let out = std::process::Command::new(&argv[0]).args(&argv[1..]).output().unwrap();
741        assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
742        let nice: i32 = String::from_utf8_lossy(&out.stdout).trim().parse().unwrap();
743        // `nice -n 10` adds 10, capped at 19.
744        assert_eq!(nice, (own_nice() + AGENT_NICE_LEVEL).min(19));
745    }
746
747    #[test]
748    fn track_spawned_is_a_safe_no_op_without_a_global_registry() {
749        // `GLOBAL` is only ever set by `bootstrap/network.rs` at real host
750        // startup — never in this test binary — so this exercises the exact
751        // "tests silently skip tracker registration" behavior the doc comment
752        // on `GLOBAL` promises. Must not panic.
753        track_spawned("test-block-track-spawned-no-global", 999_999);
754    }
755
756    #[test]
757    fn stats_reflects_tracked_block_count_and_drops_on_remove() {
758        // A fresh, non-global registry (not `global()`) — this counts
759        // entries this test itself created, not whatever other tests
760        // running in parallel have registered against the process-wide
761        // `GLOBAL`. `stats()` backs the `mem_attribution` diagnostic log
762        // (sysinfo.rs) added while investigating a 2026-09-20 leak report.
763        let registry = AgentProcessRegistry::new(None);
764        assert_eq!(registry.stats(), (0, 0), "empty registry");
765
766        registry.ensure_tracker("block-a");
767        assert_eq!(registry.stats(), (1, 0), "one block, no poll yet so no known pids");
768
769        registry.ensure_tracker("block-b");
770        assert_eq!(registry.stats().0, 2, "two distinct blocks tracked");
771
772        // Re-registering the same block is idempotent (per ensure_tracker's
773        // own doc comment) — must not double-count.
774        registry.ensure_tracker("block-a");
775        assert_eq!(registry.stats().0, 2, "re-registering an existing block does not grow the count");
776
777        registry.remove("block-a");
778        assert_eq!(registry.stats().0, 1, "removed block no longer counted");
779    }
780
781    // This test used to be `#[ignore]`d as "environment-dependent", blaming
782    // the agent-shell harness's own job object. That was wrong: the Windows
783    // tracker opened the process with 0x0200 (PROCESS_SET_INFORMATION) where
784    // AssignProcessToJobObject needs PROCESS_SET_QUOTA (0x0100), so EVERY
785    // assignment failed with Access Denied — in the shipped app too (no
786    // production log ever shows "assigned process to job"). Nested jobs are
787    // fine; the access mask wasn't. Keep this test running so it can't
788    // silently break again. Windows-only: elsewhere `new_tracker` is still
789    // the membership-less stub, so there is nothing to observe (Codex P1 on
790    // #3425).
791    #[test]
792    #[cfg(windows)]
793    fn ensure_tracker_and_assign_process_track_a_real_short_lived_child() {
794        // Uses a fresh, non-global `AgentProcessRegistry` (not `track_spawned`'s
795        // `global()` path) so this doesn't touch the process-wide `GLOBAL`
796        // OnceLock other tests in this binary may rely on being unset.
797        //
798        // Spawns a real, disposable child (rather than assigning the test
799        // process's own PID) because `JobObjectTracker`'s Drop impl closes the
800        // job handle, which fires `KILL_ON_JOB_CLOSE` on Windows — assigning
801        // the test runner's own PID would kill the test process the moment
802        // the registry (and its tracker) drops at the end of this test.
803        // Alive for a few seconds, so it can't exit (and make the assignment
804        // race a dead process) before `assign_process` runs; killed below.
805        let mut child = if cfg!(windows) {
806            std::process::Command::new("cmd")
807                .args(["/C", "ping -n 2 127.0.0.1 > nul & ping -n 10 127.0.0.1 > nul"])
808                .spawn()
809        } else {
810            std::process::Command::new("sh")
811                .args(["-c", "sleep 10"])
812                .spawn()
813        }
814        .expect("failed to spawn a disposable test child");
815        let pid = child.id();
816
817        let registry = AgentProcessRegistry::new(None);
818        registry
819            .assign_kind("test-block-real-spawn", pid, false)
820            .expect("assign should succeed for a live child we just spawned");
821
822        let raw = registry.ensure_tracker("test-block-real-spawn").list_members();
823        assert!(
824            raw.iter().any(|p| p.pid == pid),
825            "expected pid {pid} to be a job member after assign"
826        );
827
828        // The root itself is plumbing, not agent-started; the `ping` its shell
829        // launches is. The second ping starts ~1s in, well after assignment,
830        // so it can't slip through the spawn/assign race.
831        let is_ping = |p: &TrackedProcess| p.command.to_ascii_lowercase().ends_with("ping.exe");
832        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
833        let started = loop {
834            let listed = registry.list_block("test-block-real-spawn");
835            if listed.iter().any(is_ping) || std::time::Instant::now() > deadline {
836                break listed;
837            }
838            std::thread::sleep(std::time::Duration::from_millis(100));
839        };
840        assert!(
841            !started.iter().any(|p| p.pid == pid),
842            "the assigned root must not be listed as agent-started"
843        );
844        assert!(
845            started.iter().any(|p| is_ping(p) && p.parent_pid == Some(pid)),
846            "expected the shell's ping child in list_block, got {started:?}"
847        );
848
849        // Reap before `registry` drops, so KILL_ON_JOB_CLOSE has nothing left
850        // to terminate.
851        let _ = child.kill();
852        let _ = child.wait();
853    }
854
855    #[test]
856    fn adopt_never_creates_a_tracker() {
857        let registry = AgentProcessRegistry::new(None);
858        assert_eq!(registry.adopt("no-such-block", std::process::id()), Ok(false));
859        assert_eq!(registry.stats().0, 0, "adopt must not register a tracker");
860    }
861
862    /// A `Shell()` process adopted into an agent's tracker is listed as
863    /// agent-started and dies when the agent's tracker is released
864    /// (agent_teardown spec §6.5).
865    #[test]
866    #[cfg(windows)]
867    fn an_adopted_process_is_listed_and_dies_with_the_agent() {
868        let spawn = || {
869            std::process::Command::new("cmd")
870                .args(["/C", "ping -n 30 127.0.0.1 > nul"])
871                .spawn()
872                .expect("failed to spawn a disposable test child")
873        };
874        let (mut agent, mut shell) = (spawn(), spawn());
875        let registry = AgentProcessRegistry::new(None);
876        registry.assign_kind("test-block-adopt", agent.id(), false).expect("assign the agent root");
877        assert_eq!(registry.adopt("test-block-adopt", shell.id()), Ok(true));
878
879        let listed = registry.list_block("test-block-adopt");
880        assert!(
881            listed.iter().any(|p| p.pid == shell.id()),
882            "an adopted shell is agent-started, not a root: {listed:?}"
883        );
884
885        registry.remove("test-block-adopt");
886        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
887        while shell.try_wait().ok().flatten().is_none() && std::time::Instant::now() < deadline {
888            std::thread::sleep(std::time::Duration::from_millis(50));
889        }
890        assert!(shell.try_wait().ok().flatten().is_some(), "releasing the agent's tracker must end the adopted shell");
891        let _ = agent.kill();
892        let _ = agent.wait();
893    }
894
895    /// `spawn_tracked`'s Windows path: a child started suspended is in the
896    /// job before it runs, and runs once resumed (it never stays stuck).
897    #[tokio::test]
898    #[cfg(windows)]
899    async fn a_suspended_child_is_assigned_then_resumed_and_runs() {
900        use windows_sys::Win32::System::Threading::{CREATE_NO_WINDOW, CREATE_SUSPENDED};
901        let tracker = super::super::windows::JobObjectTracker::new("test-suspended").unwrap();
902        let mut cmd = tokio::process::Command::new("cmd");
903        cmd.args(["/C", "exit 7"]).creation_flags(CREATE_NO_WINDOW | CREATE_SUSPENDED);
904        let mut child = cmd.spawn().expect("spawn suspended");
905        let pid = child.id().unwrap();
906        tracker.assign_process(pid).unwrap();
907        assert!(tracker.list_members().iter().any(|p| p.pid == pid), "in the job before it runs");
908        agentmux_common::win32::resume_main_thread(pid).unwrap();
909        let status = tokio::time::timeout(std::time::Duration::from_secs(10), child.wait())
910            .await
911            .expect("the resumed child ran and exited")
912            .unwrap();
913        assert_eq!(status.code(), Some(7));
914    }
915
916    /// The job's CPU account grows while a member works and keeps that time
917    /// after the member exits, which a per-process sum would lose.
918    #[test]
919    #[cfg(windows)]
920    fn a_jobs_cpu_time_keeps_what_exited_members_used() {
921        let tracker = super::super::windows::JobObjectTracker::new("test-job-cpu").unwrap();
922        assert_eq!(tracker.cpu_time_ns(), Some(0), "an empty job has used nothing");
923        // A busy child: cmd counting to two million (a second or more of CPU),
924        // then exiting.
925        let mut child = std::process::Command::new("cmd")
926            .args(["/C", "for /L %i in (1,1,2000000) do @rem"])
927            .spawn()
928            .expect("spawn cmd");
929        tracker.assign_process(child.id()).unwrap();
930        let _ = child.wait();
931        let used = tracker.cpu_time_ns().unwrap();
932        assert!(used >= 300_000_000, "the exited member's CPU time is kept: {used} ns");
933        assert!(tracker.member_pids().is_empty(), "nothing is left running");
934    }
935
936    /// After `kill_tree` the job stays usable: a respawned process is still
937    /// assigned and listed.
938    #[test]
939    #[cfg(windows)]
940    fn a_job_still_tracks_after_kill_tree() {
941        let spawn = || {
942            std::process::Command::new("cmd")
943                .args(["/C", "ping -n 30 127.0.0.1 > nul"])
944                .spawn()
945                .expect("failed to spawn a disposable test child")
946        };
947        let tracker = super::super::windows::JobObjectTracker::new("test-kill-keeps-job").unwrap();
948        let mut first = spawn();
949        tracker.assign_process(first.id()).unwrap();
950        tracker.kill_tree();
951        let _ = first.wait();
952        let mut second = spawn();
953        tracker.assign_process(second.id()).expect("the job still accepts processes");
954        assert!(tracker.list_members().iter().any(|p| p.pid == second.id()));
955        tracker.kill_tree();
956        let _ = second.wait();
957    }
958
959    /// The poller holds the registry weakly: once the last `Arc` is gone, its
960    /// next tick ends the task instead of polling a registry nobody owns.
961    #[tokio::test]
962    async fn the_poller_ends_when_its_registry_is_dropped() {
963        let registry = Arc::new(AgentProcessRegistry::new(None));
964        let poller = spawn_poller(Arc::clone(&registry));
965        // Let it poll once while the registry is alive.
966        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
967        assert!(!poller.is_finished(), "polls while the registry lives");
968        drop(registry);
969        tokio::time::timeout(std::time::Duration::from_secs(10), poller)
970            .await
971            .expect("the poller ends after its registry is dropped")
972            .unwrap();
973    }
974}