Skip to main content

agentmux_srv_core/backend/
identity_spawn.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Which spawned agent processes carry an identity token — identity M4a
5//! (`docs/specs/SPEC_AGENT_IDENTITY_CARRIED_NOT_DERIVED_2026_09_23.md`
6//! §6.5.6).
7//!
8//! Two measurements, because request-side counters cannot gate anything: an
9//! unattributed request from the UI and one from a tokenless agent look the
10//! same (§6.5.1).
11//!
12//! - **`spawn.no_token.<path>`** counts process spawns, per controller, of
13//!   an agent that has a row (a UID) but got no `AGENTMUX_AGENT_TOKEN` — the
14//!   gap M4b closes, gated on these reaching zero. "Has a row" is decided by
15//!   the store, not by the environment: the gap paths (`agent.send`, App
16//!   Server) are exactly the ones whose environment carries no
17//!   `AGENTMUX_AGENT_UID` although their block has a row (adversarial review
18//!   of #3571). **`spawn.no_row.<path>`**
19//!   counts spawns with no row at all (quick-launch panes, template-based
20//!   continuations before M4b binds them), kept apart so the gate can be met.
21//!   Recorded where a process is actually started, never where an
22//!   environment is merely built: a turn delivered to a running process
23//!   rebuilds the environment without spawning anything (review on #3571).
24//! - **`live.tokenless_or_unknown`** counts live registered agents (with a
25//!   row, so they *should* carry a token) whose process is not known to carry
26//!   one — including a process spawned before this srv started, which never
27//!   passes a spawn site again. M4d and M5 wait for this to drain to zero,
28//!   not for a counter that merely stops moving.
29
30use std::collections::HashMap;
31use std::sync::{Arc, Mutex, OnceLock};
32
33use crate::backend::reactive::AgentRegistration;
34use crate::backend::storage::store::Store;
35
36static CARRIED_BY_BLOCK: OnceLock<Mutex<HashMap<String, bool>>> = OnceLock::new();
37
38fn carried_by_block() -> &'static Mutex<HashMap<String, bool>> {
39    CARRIED_BY_BLOCK.get_or_init(Default::default)
40}
41
42/// Record that this srv spawned a process on `block_id`, and whether it
43/// carried a token. `no_token_site` names the launch path's counter; `None`
44/// for a path that is not an agent launch by itself (a terminal pane, where
45/// an agent CLI is only one possibility — the live gauge covers that case).
46pub(crate) fn record_spawn(
47    block_id: &str,
48    carried_token: bool,
49    no_token_site: Option<&'static str>,
50) {
51    if block_id.is_empty() {
52        return;
53    }
54    carried_by_block()
55        .lock()
56        .unwrap_or_else(|e| e.into_inner())
57        .insert(block_id.to_string(), carried_token);
58    if !carried_token {
59        if let Some(site) = no_token_site {
60            crate::backend::agent_resolve::record_uid_fallback(site);
61        }
62    }
63}
64
65/// Drop `block_id`'s record when its processes are released
66/// (`blockcontroller::release_block_processes`), so the map is bounded by
67/// open blocks, not by every block ever opened.
68pub(crate) fn forget_block(block_id: &str) {
69    carried_by_block()
70        .lock()
71        .unwrap_or_else(|e| e.into_inner())
72        .remove(block_id);
73}
74
75/// The controller a process was spawned by — the `<path>` in the counters.
76#[derive(Debug, Clone, Copy)]
77pub(crate) enum SpawnPath {
78    Persistent,
79    Subprocess,
80    Acp,
81    AppServer,
82    Container,
83}
84
85/// This channel's object store, for deciding whether a spawned block has a
86/// row. Attached once at boot (`bootstrap/stores.rs`), beside the token index, so
87/// `record_process_spawn`'s callers need not pass a store.
88static ROW_STORE: OnceLock<Arc<Store>> = OnceLock::new();
89
90pub fn attach_row_store(store: Arc<Store>) {
91    let _ = ROW_STORE.set(store);
92}
93
94/// The object store [`attach_row_store`] attached; `None` before boot does.
95pub fn row_store() -> Option<&'static Arc<Store>> {
96    ROW_STORE.get()
97}
98
99/// Whether `block_id` shows an agent that has a row — the same block → row
100/// resolution `build_persistent_spawn_env` uses, which also finds the row a
101/// template-based continuation folded into. A synchronous store read; spawn
102/// paths call it only when the environment carries no UID.
103pub(crate) fn block_has_row(block_id: &str) -> bool {
104    ROW_STORE
105        .get()
106        .is_some_and(|store| store_block_has_row(store, block_id))
107}
108
109/// [`block_has_row`] against a given store. A store fault answers "has a
110/// row" (counted): a gate must never read clear because a read failed.
111pub fn store_block_has_row(store: &Store, block_id: &str) -> bool {
112    match store.instance_get_active_for_block(block_id) {
113        Ok(Some(instance)) => !instance.id.trim().is_empty(),
114        Ok(None) => false,
115        Err(e) => {
116            crate::backend::agent_resolve::record_uid_fallback("identity.row_lookup_error");
117            tracing::warn!(block_id, error = %e, "identity: block row lookup failed — counted as row-backed");
118            true
119        }
120    }
121}
122
123/// Record a process spawn on `block_id` from the environment it was
124/// actually given. Call at the point the process is started.
125pub(crate) fn record_process_spawn(block_id: &str, path: SpawnPath, env: &HashMap<String, String>) {
126    record_process_spawn_with(block_id, path, env, block_has_row);
127}
128
129fn record_process_spawn_with(
130    block_id: &str,
131    path: SpawnPath,
132    env: &HashMap<String, String>,
133    has_row: impl FnOnce(&str) -> bool,
134) {
135    let has = |k: &str| env.get(k).is_some_and(|v| !v.trim().is_empty());
136    let carried = has("AGENTMUX_AGENT_TOKEN");
137    // A token implies a row (tokens are minted for rows); otherwise a carried
138    // UID does, and failing both, the store decides.
139    let row = carried || has("AGENTMUX_AGENT_UID") || has_row(block_id);
140    let site = match (row, path) {
141        (true, SpawnPath::Persistent) => "spawn.no_token.persistent",
142        (true, SpawnPath::Subprocess) => "spawn.no_token.subprocess",
143        (true, SpawnPath::Acp) => "spawn.no_token.acp",
144        (true, SpawnPath::AppServer) => "spawn.no_token.app_server",
145        (true, SpawnPath::Container) => "spawn.no_token.container",
146        (false, SpawnPath::Persistent) => "spawn.no_row.persistent",
147        (false, SpawnPath::Subprocess) => "spawn.no_row.subprocess",
148        (false, SpawnPath::Acp) => "spawn.no_row.acp",
149        (false, SpawnPath::AppServer) => "spawn.no_row.app_server",
150        (false, SpawnPath::Container) => "spawn.no_row.container",
151    };
152    record_spawn(block_id, carried, Some(site));
153}
154
155/// Whether the process this srv last spawned on `block_id` carried a token;
156/// `None` if this srv has not spawned one there.
157pub(crate) fn carried_token(block_id: &str) -> Option<bool> {
158    carried_by_block()
159        .lock()
160        .unwrap_or_else(|e| e.into_inner())
161        .get(block_id)
162        .copied()
163}
164
165/// The two live gauges over `registrations`:
166/// `(tokenless_or_unknown, unidentified)`. An agent with a row whose process
167/// is not known to carry a token counts toward the first; an agent with no
168/// row (a quick-launch pane — outside the identity system, §6.5.6) toward
169/// the second. A registration without a UID is not taken as row-less on its
170/// word: a block driven only through `agent.send` registers without one
171/// although it has a row, so `has_row` asks the store. `is_live` filters out
172/// registrations whose block no longer runs anything here, so a stale
173/// registration cannot hold the gauge up.
174pub fn live_gauges(
175    registrations: &[AgentRegistration],
176    is_live: impl Fn(&str) -> bool,
177    has_row: impl Fn(&str) -> bool,
178) -> (usize, usize) {
179    let mut tokenless_or_unknown = 0;
180    let mut unidentified = 0;
181    for reg in registrations {
182        if !is_live(&reg.block_id) {
183            continue;
184        }
185        if carried_token(&reg.block_id) == Some(true) {
186            continue;
187        }
188        if reg.uid.is_some() || has_row(&reg.block_id) {
189            tokenless_or_unknown += 1;
190        } else {
191            unidentified += 1;
192        }
193    }
194    (tokenless_or_unknown, unidentified)
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200
201    fn reg(block: &str, uid: Option<&str>) -> AgentRegistration {
202        let h = crate::backend::reactive::handler::ReactiveHandler::new();
203        h.register_agent_full("AgentY", block, None, 0, None, uid, "test.m4a")
204            .unwrap();
205        h.list_agents().into_iter().next().unwrap()
206    }
207
208    /// A row-backed agent counts until this srv has seen it spawned with a
209    /// token; one spawned before this srv started stays "unknown" — the case
210    /// spawn counters alone would miss. A row-less pane is counted apart.
211    #[test]
212    fn live_gauges_count_row_backed_agents_not_known_to_carry_a_token() {
213        let (with, without, unknown, rowless) = (
214            "m4a-blk-with",
215            "m4a-blk-without",
216            "m4a-blk-unknown",
217            "m4a-blk-rowless",
218        );
219        record_spawn(with, true, Some("test.m4a.no_token"));
220        record_spawn(without, false, Some("test.m4a.no_token"));
221        let regs = vec![
222            reg(with, Some("uid-1")),
223            reg(without, Some("uid-2")),
224            reg(unknown, Some("uid-3")),
225            reg(rowless, None),
226        ];
227        let no_row = |_: &str| false;
228        assert_eq!(live_gauges(&regs, |_| true, no_row), (2, 1));
229        // A registration whose block runs nothing here does not count.
230        assert_eq!(live_gauges(&regs, |b| b != unknown, no_row), (1, 1));
231        // A registration without a UID whose block has a row (an
232        // `agent.send`-only block) is tokenless, not unidentified.
233        assert_eq!(live_gauges(&regs, |_| true, |b| b == rowless), (3, 0));
234        assert_eq!(carried_token(with), Some(true));
235        assert_eq!(carried_token(unknown), None);
236    }
237
238    /// Classified from the environment the process actually got: a UID
239    /// without a token is the gap; no UID at all is a row-less spawn.
240    #[test]
241    fn a_spawn_is_classified_from_its_actual_environment() {
242        let env = |pairs: &[(&str, &str)]| -> HashMap<String, String> {
243            pairs
244                .iter()
245                .map(|(k, v)| (k.to_string(), v.to_string()))
246                .collect()
247        };
248        record_process_spawn(
249            "m4a-blk-env-tok",
250            SpawnPath::Persistent,
251            &env(&[("AGENTMUX_AGENT_UID", "u"), ("AGENTMUX_AGENT_TOKEN", "t")]),
252        );
253        assert_eq!(carried_token("m4a-blk-env-tok"), Some(true));
254        let count = |site: &str| {
255            crate::backend::agent_resolve::uid_fallback_counts()
256                .into_iter()
257                .find(|(s, _)| *s == site)
258                .map_or(0, |(_, n)| n)
259        };
260        let (gap, rowless) = (count("spawn.no_token.acp"), count("spawn.no_row.acp"));
261        record_process_spawn(
262            "m4a-blk-env-gap",
263            SpawnPath::Acp,
264            &env(&[("AGENTMUX_AGENT_UID", "u")]),
265        );
266        record_process_spawn_with("m4a-blk-env-rowless", SpawnPath::Acp, &env(&[]), |_| false);
267        assert!(count("spawn.no_token.acp") > gap);
268        assert!(count("spawn.no_row.acp") > rowless);
269        assert_eq!(carried_token("m4a-blk-env-gap"), Some(false));
270    }
271
272    /// The gap paths (`agent.send`, App Server) spawn with no
273    /// `AGENTMUX_AGENT_UID` although their block has a row: the store
274    /// decides, so they count as the gap, not as row-less (adversarial
275    /// review of #3571 — otherwise the M4b gate passes trivially).
276    #[test]
277    fn a_row_backed_spawn_without_a_carried_uid_is_the_gap() {
278        let count = |site: &str| {
279            crate::backend::agent_resolve::uid_fallback_counts()
280                .into_iter()
281                .find(|(s, _)| *s == site)
282                .map_or(0, |(_, n)| n)
283        };
284        let (gap, rowless) = (
285            count("spawn.no_token.app_server"),
286            count("spawn.no_row.app_server"),
287        );
288        let mut asked = None;
289        record_process_spawn_with(
290            "m4a-blk-appserver",
291            SpawnPath::AppServer,
292            &HashMap::new(),
293            |b| {
294                asked = Some(b.to_string());
295                true
296            },
297        );
298        assert_eq!(asked.as_deref(), Some("m4a-blk-appserver"));
299        assert_eq!(count("spawn.no_token.app_server"), gap + 1);
300        assert_eq!(count("spawn.no_row.app_server"), rowless);
301
302        // A token alone implies a row; the store is not asked.
303        let before = count("spawn.no_row.container");
304        record_process_spawn_with(
305            "m4a-blk-container",
306            SpawnPath::Container,
307            &[("AGENTMUX_AGENT_TOKEN".to_string(), "t".to_string())]
308                .into_iter()
309                .collect(),
310            |_| panic!("not asked"),
311        );
312        assert_eq!(carried_token("m4a-blk-container"), Some(true));
313        assert_eq!(count("spawn.no_row.container"), before);
314    }
315
316    /// Releasing a block's processes drops its record (ReAgent P2 on #3571:
317    /// the map must not grow with every pane ever opened).
318    #[test]
319    fn releasing_a_block_forgets_its_record() {
320        record_spawn("m4a-blk-closed", true, None);
321        crate::backend::blockcontroller::release_block_processes("m4a-blk-closed");
322        assert_eq!(carried_token("m4a-blk-closed"), None);
323    }
324}