Skip to main content

agentmux_srv_core/backend/
background_set.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What an agent has running in the background while no turn is in flight
5//! (`docs/specs/SPEC_AGENT_STATE_BACKGROUND_WORK_2026_11_01.md` §5, §9 step 1).
6//!
7//! **Shadow only.** This decides nothing yet: no state, no surface reads it. Every
8//! [`SAMPLE_EVERY_MS`] the fleet look hands over the agents that read Idle, and for each this works out
9//! the set it would call Background and logs when an agent enters or leaves it (target
10//! `background_shadow`), with a count for App health to read later ([`shadow_counts`]). A week of that
11//! log sets the denylist and the grace period (D7) before the state is switched on.
12//!
13//! Two sources in this step: the declared background shells (`db_background_tasks` rows still
14//! `running`) and the process trees an agent left behind (the pane's tracker). Background subagents and
15//! Monitor come with the state itself (the Monitor's task type is not verified, §5).
16
17use std::collections::HashMap;
18use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
19use std::sync::{Arc, Mutex, OnceLock};
20
21use crate::backend::background_work;
22use crate::backend::process_tracker::TrackedProcess;
23use crate::backend::storage::background_tasks::{BackgroundTask, BackgroundTaskStatus};
24use crate::backend::storage::store::Store;
25
26/// A process tree counts once it has run this long: a command that is about to finish is not background work.
27pub const GRACE_MS: u64 = 30_000;
28/// A declared background shell with no pid to check counts for this long, then no more (rows have stuck
29/// `running` before, #2518).
30const NO_PID_FOR_MS: i64 = 30 * 60 * 1000;
31/// How often the shadow looks. The tracker read is not free and a minute of latency costs nothing here.
32const SAMPLE_EVERY_MS: u64 = 10_000;
33/// Daemons that outlive the command that started them and are not work the agent waits on (sccache, a git
34/// fsmonitor, build servers). A command line containing one of these is left out. The shadow log is what
35/// completes this list (D7).
36const DENY: [&str; 7] = ["sccache", "fsmonitor--daemon", "vbcscompiler", "mspdbsrv", "gradle daemon", "buildkitd", "rust-analyzer"];
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum Kind {
40    /// A shell command the agent put in the background (`run_in_background`).
41    Shell,
42    /// A process tree the agent's call left behind.
43    Process,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct Item {
48    pub kind: Kind,
49    pub label: String,
50    pub started_at_ms: u64,
51}
52
53fn denied(label: &str) -> bool {
54    let l = label.to_ascii_lowercase();
55    DENY.iter().any(|d| l.contains(d))
56}
57
58/// The trees among `members` that count: past the grace period, and not a daemon on the denylist.
59pub fn from_tracker(now_ms: u64, members: &[TrackedProcess]) -> Vec<Item> {
60    background_work::trees("", "", members)
61        .into_iter()
62        .filter(|w| !denied(&w.label) && (w.started_at_ms == 0 || now_ms.saturating_sub(w.started_at_ms) >= GRACE_MS))
63        .map(|w| Item { kind: Kind::Process, label: w.label, started_at_ms: w.started_at_ms })
64        .collect()
65}
66
67/// The declared background shells that still run: a row counts while its pid is in the tracker, or, with
68/// no pid, for [`NO_PID_FOR_MS`].
69pub fn from_tasks(now_ms: i64, tasks: &[BackgroundTask], members: &[TrackedProcess]) -> Vec<Item> {
70    tasks
71        .iter()
72        .filter(|t| t.status == BackgroundTaskStatus::Running)
73        .filter(|t| match t.pid {
74            Some(pid) => members.iter().any(|m| i64::from(m.pid) == pid),
75            None => now_ms.saturating_sub(t.started_at_ms) < NO_PID_FOR_MS,
76        })
77        .map(|t| Item { kind: Kind::Shell, label: t.label.clone(), started_at_ms: t.started_at_ms.max(0) as u64 })
78        .collect()
79}
80
81/// `members` without the processes of a declared shell's tree: its pid and everything below it. The shell
82/// is counted once, as the shell.
83fn without_declared(tasks: &[BackgroundTask], members: &[TrackedProcess]) -> Vec<TrackedProcess> {
84    let mut claimed: Vec<u32> = members
85        .iter()
86        .filter(|m| tasks.iter().any(|t| t.status == BackgroundTaskStatus::Running && t.pid == Some(i64::from(m.pid))))
87        .map(|m| m.pid)
88        .collect();
89    let mut i = 0;
90    while i < claimed.len() {
91        let parent = claimed[i];
92        let children: Vec<u32> =
93            members.iter().filter(|m| m.parent_pid == Some(parent) && !claimed.contains(&m.pid)).map(|m| m.pid).collect();
94        claimed.extend(children);
95        i += 1;
96    }
97    members.iter().filter(|m| !claimed.contains(&m.pid)).cloned().collect()
98}
99
100/// Everything one agent has in the background now: the declared shells, then the trees left behind that
101/// are not one of those shells.
102pub fn set_of(now_ms: u64, tasks: &[BackgroundTask], members: &[TrackedProcess]) -> Vec<Item> {
103    let mut items = from_tasks(now_ms as i64, tasks, members);
104    items.extend(from_tracker(now_ms, &without_declared(tasks, members)));
105    items
106}
107
108/// What the agent in pane `block_id` has running in the background now: its declared background shells and the process
109/// trees its calls left behind, past the grace period and not a daemon on the denylist. Empty when none, or when the
110/// tracker or the store is not up. Blocking: reads the tracker and the store.
111pub fn for_block(block_id: &str, now_ms: u64) -> Vec<Item> {
112    let Some(registry) = crate::backend::process_tracker::registry::global() else { return Vec::new() };
113    let members = registry.list_block(block_id);
114    let store = STORE.get();
115    let tasks = store.and_then(|s| s.background_task_list_for_block(block_id).ok()).unwrap_or_default();
116    let in_container: Vec<String> = store
117        .and_then(|s| s.background_container_running().ok())
118        .unwrap_or_default()
119        .into_iter()
120        .filter(|c| c.block_id == block_id)
121        .map(|c| c.id)
122        .collect();
123    with_container_shells(set_of(now_ms, &tasks, &members), &tasks, &in_container)
124}
125
126/// `items` and the declared shells of a container agent that still run: the host cannot see their processes (the
127/// pid is the container's own, kept apart), so they count while the container-side check says they run, however
128/// long that is. `in_container` is the ids of the running calls the container filed a pid for.
129fn with_container_shells(mut items: Vec<Item>, tasks: &[BackgroundTask], in_container: &[String]) -> Vec<Item> {
130    for t in tasks.iter().filter(|t| t.status == BackgroundTaskStatus::Running && t.pid.is_none() && in_container.contains(&t.id)) {
131        let item = Item { kind: Kind::Shell, label: t.label.clone(), started_at_ms: t.started_at_ms.max(0) as u64 };
132        if !items.contains(&item) {
133            items.push(item);
134        }
135    }
136    items
137}
138
139/// Who entered or left the would-be Background set since the last look, and how long each who left was in it.
140/// `before` is the set (block id → when it entered) the last look left; `now` is this look's.
141fn changes(before: &mut HashMap<String, u64>, now: &HashMap<String, u64>, at_ms: u64) -> (Vec<String>, Vec<(String, u64)>) {
142    let entered: Vec<String> = now.keys().filter(|b| !before.contains_key(*b)).cloned().collect();
143    let left: Vec<(String, u64)> =
144        before.iter().filter(|(b, _)| !now.contains_key(*b)).map(|(b, since)| (b.clone(), at_ms.saturating_sub(*since))).collect();
145    let next: HashMap<String, u64> = now.keys().map(|b| (b.clone(), before.get(b).copied().unwrap_or(at_ms))).collect();
146    *before = next;
147    (entered, left)
148}
149
150static STORE: OnceLock<Arc<Store>> = OnceLock::new();
151static LAST_SAMPLE_MS: AtomicU64 = AtomicU64::new(0);
152static IN_SET: AtomicU32 = AtomicU32::new(0);
153static ENTERED: AtomicU64 = AtomicU64::new(0);
154static SET: Mutex<Option<HashMap<String, u64>>> = Mutex::new(None);
155
156/// Where the declared background shells are read from. Called once, with the fleet source.
157pub fn watch(store: Arc<Store>) {
158    let _ = STORE.set(store);
159}
160
161/// How many agents are in the would-be Background set now, and how many times an agent has entered it
162/// since srv started.
163pub fn shadow_counts() -> (u32, u64) {
164    (IN_SET.load(Ordering::Relaxed), ENTERED.load(Ordering::Relaxed))
165}
166
167/// One look, from the fleet's once-a-second observation: `idle` is the agents that read Idle (agent, block).
168/// Only every [`SAMPLE_EVERY_MS`]. Blocking: reads the tracker and the store.
169pub fn shadow_sample(idle: &[(String, String)], now_ms: u64) {
170    let last = LAST_SAMPLE_MS.load(Ordering::Relaxed);
171    if now_ms.saturating_sub(last) < SAMPLE_EVERY_MS || LAST_SAMPLE_MS.compare_exchange(last, now_ms, Ordering::Relaxed, Ordering::Relaxed).is_err() {
172        return;
173    }
174    let Some(registry) = crate::backend::process_tracker::registry::global() else { return };
175    let mut now: HashMap<String, u64> = HashMap::new();
176    let mut named: HashMap<String, (String, Item, usize)> = HashMap::new();
177    for (agent, block_id) in idle {
178        let members = registry.list_block(block_id);
179        let tasks = STORE.get().and_then(|s| s.background_task_list_for_block(block_id).ok()).unwrap_or_default();
180        let items = set_of(now_ms, &tasks, &members);
181        if let Some(first) = items.first().cloned() {
182            now.insert(block_id.clone(), now_ms);
183            named.insert(block_id.clone(), (agent.clone(), first, items.len()));
184        }
185    }
186    let (entered, left) = {
187        let mut guard = SET.lock().unwrap_or_else(|e| e.into_inner());
188        changes(guard.get_or_insert_with(HashMap::new), &now, now_ms)
189    };
190    for block_id in &entered {
191        if let Some((agent, first, n)) = named.get(block_id) {
192            ENTERED.fetch_add(1, Ordering::Relaxed);
193            tracing::info!(target: "background_shadow", agent = %agent, kind = ?first.kind, items = n, first = %first.label, "would be Background");
194        }
195    }
196    for (block_id, for_ms) in &left {
197        tracing::info!(target: "background_shadow", block = %block_id, for_s = for_ms / 1000, "no longer would be Background");
198    }
199    IN_SET.store(now.len() as u32, Ordering::Relaxed);
200}
201
202#[cfg(test)]
203#[path = "background_set_tests.rs"]
204mod tests;