Skip to main content

agentmux_srv/server/
agent_resources.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4// What an agent owns — the one inventory
5// (docs/specs/SPEC_AGENT_TEARDOWN_SINGLE_PATH_2026_10_01.md §6.1).
6//
7// Everything that answers "what does this agent own?" reads it: the teardown
8// (`sagas::agent_teardown`), and — as later phases wire them — the close
9// dialog, the `/quit` summary and Swarm. It covers the sources srv tracks;
10// `Shell()` and `!cmd` processes appear under `processes` since they join the
11// agent's tracker (§6.5). [`survivors`] re-checks a snapshot after a teardown
12// (§6.2 step 8).
13
14use serde::Serialize;
15
16use crate::backend::storage::cron::CronJob;
17pub use crate::backend::work_claims::holds_claim;
18pub(crate) use crate::backend::work_claims::claims_held_by;
19use crate::server::AppState;
20
21/// One process the agent started (the CLI or a descendant), from its
22/// block's process tracker.
23#[derive(Clone, Debug, Default, Serialize, PartialEq, Eq)]
24pub struct ProcessEntry {
25    pub pid: u32,
26    pub command: String,
27    /// Unix ms; 0 if the platform doesn't expose it. With `pid`, identifies
28    /// the process across a later re-check (PID reuse).
29    pub started_at_ms: u64,
30}
31
32/// A `run_in_background` Bash command the agent declared (bashwrap).
33#[derive(Clone, Debug, Default, Serialize, PartialEq, Eq)]
34pub struct BackgroundTaskEntry {
35    pub id: String,
36    pub label: String,
37    pub pid: Option<i64>,
38    /// Unix ms, when bashwrap first saw it.
39    pub started_at_ms: i64,
40    /// Unix ms, the last time bashwrap saw it still running.
41    pub last_seen_ms: i64,
42}
43
44/// A srv-spawned `Shell()` session the agent started.
45#[derive(Clone, Debug, Default, Serialize, PartialEq, Eq)]
46pub struct ShellEntry {
47    pub shell_id: String,
48    pub cmd: String,
49}
50
51/// Everything one agent owns, at one moment.
52#[derive(Clone, Debug, Default, Serialize, PartialEq, Eq)]
53pub struct AgentResources {
54    pub block_id: String,
55    /// The CLI and every process it started that the tracker sees (R1, R2).
56    pub processes: Vec<ProcessEntry>,
57    /// Still-running declared background tasks (the R2 subset, e.g. `task dev`).
58    pub background_tasks: Vec<BackgroundTaskEntry>,
59    /// Running `Shell()` sessions (R3).
60    pub shell_sessions: Vec<ShellEntry>,
61    /// Sub-blocks, e.g. PtyShell drawers (R4).
62    pub sub_blocks: Vec<String>,
63    /// A container agent's container (R6), by name.
64    pub container: Option<String>,
65    /// The agent's working directory (`cmd:cwd`), empty if unset: where the
66    /// Docker Compose projects it may have started live.
67    pub cwd: String,
68}
69
70/// Who an agent is, for the work-queue and cron sources, which are keyed by
71/// identity rather than block.
72#[derive(Clone, Debug, Default)]
73pub struct AgentIdentity {
74    pub agent_id: String,
75    pub uid: Option<String>,
76}
77
78impl AgentIdentity {
79    /// Resolve while the block is still registered: a teardown unregisters it.
80    pub fn of(state: &AppState, block_id: &str) -> Self {
81        let reg = state.reactive_handler.get_agent_by_block(block_id);
82        Self {
83            agent_id: reg.as_ref().map(|a| a.agent_id.clone()).unwrap_or_default(),
84            uid: reg.and_then(|a| a.uid),
85        }
86    }
87
88    /// The name to show: the agent id, else the block id.
89    pub fn label(&self, block_id: &str) -> String {
90        if self.agent_id.is_empty() { block_id.to_string() } else { self.agent_id.clone() }
91    }
92}
93
94/// The process-side inventory of `block_id`: in-memory reads plus two
95/// local-store (SQLite) reads, so call it off the async workers
96/// (`spawn_blocking`), as the teardown does.
97pub fn snapshot(state: &AppState, block_id: &str) -> AgentResources {
98    let mut processes: Vec<ProcessEntry> = state
99        .process_tracker
100        .list_block(block_id)
101        .into_iter()
102        .map(|p| ProcessEntry { pid: p.pid, command: p.command, started_at_ms: p.started_at_ms })
103        .collect();
104    // The Windows tracker doesn't record start times; take them from the OS,
105    // so a later re-check can tell a reused PID from the same process.
106    let missing: Vec<u32> = processes.iter().filter(|p| p.started_at_ms == 0).map(|p| p.pid).collect();
107    if !missing.is_empty() {
108        let times = start_times(&missing);
109        // One that already exited has no start time to record; keeping it
110        // with 0 ("unknown") would let a later check match a reused PID.
111        processes.retain_mut(|p| {
112            if p.started_at_ms == 0 {
113                match times.get(&p.pid) {
114                    Some(t) => p.started_at_ms = *t,
115                    None => return false,
116                }
117            }
118            true
119        });
120    }
121    let background_tasks = state
122        .mstore
123        .background_task_list_for_block(block_id)
124        .unwrap_or_default()
125        .into_iter()
126        .filter(|t| t.ended_at_ms.is_none())
127        .map(|t| BackgroundTaskEntry { id: t.id, label: t.label, pid: t.pid, started_at_ms: t.started_at_ms, last_seen_ms: t.last_seen_ms })
128        .collect();
129    let shell_sessions = state
130        .shell_sessions
131        .list_active()
132        .into_iter()
133        .filter(|s| s.block_id == block_id)
134        .map(|s| ShellEntry { shell_id: s.shell_id, cmd: s.cmd })
135        .collect();
136    let block = state.mstore.get::<crate::backend::obj::Block>(block_id).ok().flatten();
137    let container = block.as_ref().and_then(container_of);
138    let cwd = block
139        .as_ref()
140        .map(|b| crate::backend::obj::meta_get_string(&b.meta, "cmd:cwd", ""))
141        .unwrap_or_default();
142    let sub_blocks = block.and_then(|b| b.subblockids).unwrap_or_default();
143    AgentResources { block_id: block_id.to_string(), processes, background_tasks, shell_sessions, sub_blocks, container, cwd }
144}
145
146/// The container a container agent's block runs in (`agentMode` =
147/// `container`), named from its `agentId` as the launch path names it.
148pub fn container_of(block: &crate::backend::obj::Block) -> Option<String> {
149    crate::backend::container::container_of_meta(&block.meta)
150}
151
152/// Is `container` used by a live controller other than `block_id`'s (the same
153/// agent open in a second pane)? Store reads: call off the async workers.
154pub fn container_shared(state: &AppState, block_id: &str, container: &str) -> bool {
155    crate::backend::blockcontroller::get_all_controllers()
156        .into_keys()
157        .filter(|id| id != block_id)
158        .filter_map(|id| state.mstore.get::<crate::backend::obj::Block>(&id).ok().flatten())
159        .any(|b| container_of(&b).as_deref() == Some(container))
160}
161
162/// Start time (Unix ms, at the OS's one-second resolution) of each of `pids`
163/// that is running now; a PID that isn't running is absent. One targeted OS
164/// query.
165pub fn start_times(pids: &[u32]) -> std::collections::HashMap<u32, u64> {
166    if pids.is_empty() {
167        return Default::default();
168    }
169    let list: Vec<sysinfo::Pid> = pids.iter().map(|p| sysinfo::Pid::from_u32(*p)).collect();
170    let mut sys = sysinfo::System::new();
171    sys.refresh_processes_specifics(
172        sysinfo::ProcessesToUpdate::Some(&list),
173        true,
174        sysinfo::ProcessRefreshKind::nothing(),
175    );
176    sys.processes().iter().map(|(pid, p)| (pid.as_u32(), p.start_time() * 1000)).collect()
177}
178
179/// The processes of a snapshot that are still running: the same PID with the
180/// same start time. A PID the OS has since reused for another process is not
181/// a survivor (spec §8).
182pub fn survivors(before: &[ProcessEntry]) -> Vec<ProcessEntry> {
183    let pids: Vec<u32> = before.iter().map(|p| p.pid).collect();
184    let live = start_times(&pids);
185    before
186        .iter()
187        .filter(|p| live.get(&p.pid).is_some_and(|now| same_start(p.started_at_ms, *now)))
188        .cloned()
189        .collect()
190}
191
192/// The PIDs of `tasks` that are still that task (spec §8, PID reuse).
193///
194/// A process that was already running when bashwrap last saw the task
195/// running IS the task's process: the OS can't reuse a PID while its owner is
196/// alive. So the test is "started no later than `last_seen_ms`", which also
197/// holds for a task that started long after it was declared (a tool call
198/// waiting on a permission prompt). A reused PID started after the task was
199/// last seen, and is left alone.
200pub fn live_background_pids(tasks: &[BackgroundTaskEntry]) -> Vec<u32> {
201    let pids: Vec<u32> = tasks.iter().filter_map(|t| t.pid.and_then(|p| u32::try_from(p).ok())).filter(|p| *p > 1).collect();
202    let live = start_times(&pids);
203    tasks
204        .iter()
205        .filter_map(|t| {
206            let pid = u32::try_from(t.pid?).ok()?;
207            let started = *live.get(&pid)?;
208            // The OS reports start times in whole seconds.
209            (started <= (t.last_seen_ms.max(t.started_at_ms).max(0) as u64) + 1_000).then_some(pid)
210        })
211        .collect()
212}
213
214/// Kill `pid` and every descendant at once (SIGKILL on Unix, TerminateProcess
215/// on Windows), leaves first, after re-checking that `pid` is still the
216/// process started at `started_at_ms` (0 = unknown, judged by PID alone).
217/// One OS snapshot. Returns how many processes it signalled.
218pub fn force_kill_tree(pid: u32, started_at_ms: u64) -> usize {
219    let mut sys = sysinfo::System::new();
220    sys.refresh_processes_specifics(sysinfo::ProcessesToUpdate::All, true, sysinfo::ProcessRefreshKind::nothing());
221    let root = sysinfo::Pid::from_u32(pid);
222    match sys.process(root) {
223        Some(p) if same_start(started_at_ms, p.start_time() * 1000) => {}
224        _ => return 0, // gone, or the PID now belongs to another process
225    }
226    let procs: Vec<ProcLink> = sys.processes().iter().map(|(id, p)| (id.as_u32(), p.parent().map(|pp| pp.as_u32()), p.start_time())).collect();
227    // Parents come before their children in the tree: kill deepest first.
228    tree_of(pid, &procs)
229        .iter()
230        .rev()
231        .filter(|id| {
232            sys.process(sysinfo::Pid::from_u32(**id)).is_some_and(|p| p.kill_with(sysinfo::Signal::Kill).unwrap_or_else(|| p.kill()))
233        })
234        .count()
235}
236
237/// One process of a snapshot: its PID, the PID it names as its parent, and its start time in whole
238/// seconds (0 = unknown).
239type ProcLink = (u32, Option<u32>, u64);
240
241/// `root` and its descendants, each parent before its children.
242///
243/// A process is taken as a child only if it started no earlier than the parent it names. On Windows
244/// a process keeps naming its parent's PID after the parent has exited, and the OS gives a freed PID
245/// to the next new process, so a stranger can name `root`, or one of its descendants, as its parent.
246/// Such stale links can also form a loop, so no process is taken twice. A start time that is not
247/// known rules nothing out.
248fn tree_of(root: u32, procs: &[ProcLink]) -> Vec<u32> {
249    let started: std::collections::HashMap<u32, u64> = procs.iter().map(|(pid, _, start)| (*pid, *start)).collect();
250    let mut tree = vec![root];
251    let mut i = 0;
252    while i < tree.len() {
253        let parent = tree[i];
254        let parent_start = started.get(&parent).copied().unwrap_or(0);
255        let children: Vec<u32> = procs
256            .iter()
257            .filter(|(pid, names, start)| *names == Some(parent) && (*start == 0 || *start >= parent_start) && !tree.contains(pid))
258            .map(|(pid, _, _)| *pid)
259            .collect();
260        tree.extend(children);
261        i += 1;
262    }
263    tree
264}
265
266/// `recorded` 0 means the start time wasn't known; the OS reports seconds.
267fn same_start(recorded_ms: u64, now_ms: u64) -> bool {
268    recorded_ms == 0 || recorded_ms.abs_diff(now_ms) <= 1000
269}
270
271/// Does a claim held by (`claimed_by`, `claimed_by_uid`) belong to the agent?
272/// Does a cron job aimed at (`target`, `target_uid`) deliver to the agent?
273/// By UID when the job has one, else by name (case-insensitive, like agent
274/// addressing).
275pub fn cron_targets(target: &str, target_uid: &str, agent_id: &str, uid: Option<&str>) -> bool {
276    match uid.filter(|u| !u.is_empty()) {
277        Some(u) if !target_uid.is_empty() => target_uid == u,
278        _ => !agent_id.is_empty() && target.eq_ignore_ascii_case(agent_id),
279    }
280}
281
282/// Names of the cron jobs targeting the agent (R8).
283pub(crate) fn crons_targeting(jobs: &[CronJob], agent_id: &str, uid: Option<&str>) -> Vec<String> {
284    jobs.iter()
285        .filter(|j| cron_targets(&j.target, &j.target_uid, agent_id, uid))
286        .map(|j| j.name.clone())
287        .collect()
288}
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293
294    #[test]
295    fn a_live_process_survives_and_a_reused_pid_does_not() {
296        let me = std::process::id();
297        let started = *start_times(&[me]).get(&me).expect("this process is running");
298        assert!(started > 0);
299        let entry = |started_at_ms| ProcessEntry { pid: me, command: "test".into(), started_at_ms };
300        assert_eq!(survivors(&[entry(started)]).len(), 1, "same pid, same start: still running");
301        assert_eq!(survivors(&[entry(0)]).len(), 1, "unknown start time: judged by pid");
302        assert!(survivors(&[entry(started - 60_000)]).is_empty(), "same pid, other start: a reused pid");
303    }
304
305    #[test]
306    fn a_background_task_pid_counts_only_while_it_is_that_task() {
307        let me = std::process::id();
308        let started = *start_times(&[me]).get(&me).unwrap() as i64;
309        let task = |started_at_ms, last_seen_ms| BackgroundTaskEntry {
310            id: "t".into(),
311            label: "task dev".into(),
312            pid: Some(me as i64),
313            started_at_ms,
314            last_seen_ms,
315        };
316        assert_eq!(live_background_pids(&[task(started + 500, started + 500)]), vec![me], "seen just after it started");
317        assert_eq!(
318            live_background_pids(&[task(started - 60_000, started + 10_000)]),
319            vec![me],
320            "declared a minute before it started (a permission prompt), seen running since: still the task"
321        );
322        assert!(
323            live_background_pids(&[task(started - 60_000, started - 30_000)]).is_empty(),
324            "last seen before this process started: the PID was reused"
325        );
326        let no_pid = BackgroundTaskEntry { pid: None, ..task(started, started) };
327        assert!(live_background_pids(&[no_pid]).is_empty());
328    }
329
330    #[test]
331    fn a_tree_is_the_root_and_what_it_started_parents_first() {
332        // root 10 started 4 and 5; 5 started 6. 7 belongs to someone else.
333        let procs = [(10, Some(1), 100), (4, Some(10), 100), (5, Some(10), 101), (6, Some(5), 102), (7, Some(1), 90)];
334        let tree = tree_of(10, &procs);
335        assert_eq!(tree[0], 10);
336        let place = |pid: u32| tree.iter().position(|p| *p == pid).unwrap_or_else(|| panic!("{pid} is not in {tree:?}"));
337        assert!(place(5) < place(6), "a parent comes before its child: {tree:?}");
338        assert_eq!(tree.len(), 4, "{tree:?}");
339        // A root the snapshot does not list is still the root, alone.
340        assert_eq!(tree_of(99, &procs), vec![99]);
341    }
342
343    /// A PID is given to a new process after its owner exits, and a process whose parent has exited
344    /// still names that PID: it is not a child of whoever has the PID now.
345    #[test]
346    fn a_process_that_started_before_the_parent_it_names_is_not_its_child() {
347        // 20 started at 500. 30 has been running since 100 and names 20: its real parent had that PID.
348        // 31 is 30's own child. 21 is 20's real child. 22 names 20 with no start time known.
349        let procs = [(20, Some(1), 500), (30, Some(20), 100), (31, Some(30), 150), (21, Some(20), 500), (22, Some(20), 0)];
350        let mut tree = tree_of(20, &procs);
351        tree.sort_unstable();
352        assert_eq!(tree, vec![20, 21, 22]);
353    }
354
355    /// Stale parent PIDs can name each other; the walk still ends, with each process once.
356    #[test]
357    fn processes_that_name_each_other_as_parent_are_walked_once() {
358        let procs = [(40, Some(41), 100), (41, Some(40), 100), (42, Some(42), 100)];
359        let mut tree = tree_of(40, &procs);
360        tree.sort_unstable();
361        assert_eq!(tree, vec![40, 41]);
362        assert_eq!(tree_of(42, &procs), vec![42], "a process that names itself");
363    }
364
365    /// The verify step's forced kill takes the whole tree, and a child that
366    /// would ignore a polite signal still dies.
367    #[test]
368    fn force_kill_tree_takes_the_child_too() {
369        use std::time::{Duration, Instant};
370        #[cfg(windows)]
371        let (mut parent, child_name) =
372            (std::process::Command::new("cmd").args(["/C", "ping -n 30 127.0.0.1 > nul"]).spawn().unwrap(), "ping");
373        #[cfg(unix)]
374        let (mut parent, child_name) =
375            (std::process::Command::new("sh").args(["-c", "trap '' TERM; sleep 30 & wait"]).spawn().unwrap(), "sleep");
376        let pid = parent.id();
377        // The shell's child, by name, with its start time (whole seconds). By parent alone it could be
378        // the shell's console host on Windows, or a process whose own parent once had the shell's PID.
379        let child_of = |pid: u32| {
380            let mut sys = sysinfo::System::new();
381            sys.refresh_processes_specifics(sysinfo::ProcessesToUpdate::All, true, sysinfo::ProcessRefreshKind::nothing());
382            sys.processes()
383                .iter()
384                .find(|(_, p)| {
385                    p.parent() == Some(sysinfo::Pid::from_u32(pid)) && p.name().to_string_lossy().to_ascii_lowercase().starts_with(child_name)
386                })
387                .map(|(id, p)| (id.as_u32(), p.start_time()))
388        };
389        let until = Instant::now() + Duration::from_secs(10);
390        let mut child = None;
391        while child.is_none() && Instant::now() < until {
392            std::thread::sleep(Duration::from_millis(100));
393            child = child_of(pid);
394        }
395        let (child, child_started_s) = child.expect("the shell started its child");
396        // Not before the second after the child's start: a process that gets the child's PID once it
397        // is dead then has a later start time, and cannot be taken for the child below.
398        let now_s = agentmux_common::time::now_secs_u64;
399        let until = Instant::now() + Duration::from_secs(5);
400        while now_s() <= child_started_s && Instant::now() < until {
401            std::thread::sleep(Duration::from_millis(50));
402        }
403
404        assert_eq!(force_kill_tree(pid, 60_000), 0, "a start time that doesn't match: not this process, nothing killed");
405        // Children go first; a shell whose child died may exit on its own
406        // before its turn, so count >= 1 and check both are gone below.
407        assert!(force_kill_tree(pid, 0) >= 1);
408
409        // The parent, by its handle: the wait is bounded, and a PID alone may be another process by now.
410        let until = Instant::now() + Duration::from_secs(10);
411        let mut exited = parent.try_wait().unwrap().is_some();
412        while !exited && Instant::now() < until {
413            std::thread::sleep(Duration::from_millis(50));
414            exited = parent.try_wait().unwrap().is_some();
415        }
416        if !exited {
417            let _ = parent.kill();
418            let _ = parent.wait();
419        }
420        assert!(exited, "the parent is gone");
421        // The child, by PID and start time.
422        let child_runs = || start_times(&[child]).get(&child).is_some_and(|started_ms| *started_ms == child_started_s * 1000);
423        let until = Instant::now() + Duration::from_secs(10);
424        while child_runs() && Instant::now() < until {
425            std::thread::sleep(Duration::from_millis(50));
426        }
427        assert!(!child_runs(), "the child is gone");
428    }
429
430    #[test]
431    fn only_a_container_agent_has_a_container() {
432        let block = |meta: &[(&str, &str)]| crate::backend::obj::Block {
433            meta: meta.iter().map(|(k, v)| (k.to_string(), serde_json::json!(v))).collect(),
434            ..Default::default()
435        };
436        assert_eq!(
437            container_of(&block(&[("agentMode", "container"), ("agentId", "lark")])).as_deref(),
438            Some(crate::backend::container::container_name_for_slug("lark").as_str())
439        );
440        assert_eq!(container_of(&block(&[("agentMode", "host"), ("agentId", "lark")])), None);
441        assert_eq!(container_of(&block(&[("agentMode", "container")])), None, "no agentId, no name");
442    }
443
444    /// A start time of 0 means "unknown" and matches whatever process the OS gives that PID next, and
445    /// Windows hands a freed PID out at once (another test spawning), so the entry carries the real start
446    /// time. The OS also takes a moment to stop listing an exited process: wait for it up to a deadline
447    /// rather than assume it is gone the instant `wait` returns.
448    #[test]
449    fn an_exited_process_is_not_a_survivor() {
450        // Waits on its piped stdin (kept open until the kill), so there is no grandchild to leave behind.
451        #[cfg(windows)]
452        let mut child = std::process::Command::new("cmd").args(["/C", "set /p x="]).stdin(std::process::Stdio::piped()).spawn().unwrap();
453        #[cfg(unix)]
454        let mut child = std::process::Command::new("sh").args(["-c", "read x"]).stdin(std::process::Stdio::piped()).spawn().unwrap();
455        let pid = child.id();
456        let until = std::time::Instant::now() + std::time::Duration::from_secs(10);
457        let mut started_at_ms = 0;
458        while started_at_ms == 0 && std::time::Instant::now() < until {
459            started_at_ms = start_times(&[pid]).get(&pid).copied().unwrap_or(0);
460            if started_at_ms == 0 {
461                std::thread::sleep(std::time::Duration::from_millis(25));
462            }
463        }
464        assert_ne!(started_at_ms, 0, "the running child has a start time");
465        let entry = ProcessEntry { pid, command: "gone".into(), started_at_ms };
466        assert_eq!(survivors(std::slice::from_ref(&entry)).len(), 1, "a running process is a survivor");
467        child.kill().unwrap();
468        child.wait().unwrap();
469        drop(child);
470        let until = std::time::Instant::now() + std::time::Duration::from_secs(10);
471        while !survivors(std::slice::from_ref(&entry)).is_empty() && std::time::Instant::now() < until {
472            std::thread::sleep(std::time::Duration::from_millis(25));
473        }
474        assert!(survivors(std::slice::from_ref(&entry)).is_empty(), "an exited process is not a survivor");
475    }
476}