Skip to main content

agentmux_srv_core/backend/
pane_env.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Instance identity must not be inheritable by the processes a pane spawns.
5//!
6//! # The defect this closes
7//!
8//! Both pane-spawn paths build their environment by inheriting srv's, and srv's
9//! environment is where the launcher injects the whole instance identity set
10//! (`DataPaths::to_env_vars` — data dir, config dir, cache dir, channel, runtime
11//! mode) and where srv adds more of its own (`AGENTMUX_DATA_HOME`,
12//! `AGENTMUX_CONFIG_HOME`, `AGENTMUX_LOCAL_URL`).
13//!
14//! * terminal panes: `portable_pty::CommandBuilder` seeds from
15//!   `std::env::vars_os()`, so `.env()` calls are overrides on a full copy.
16//! * agent panes: `tokio::process::Command` inherits by default.
17//!
18//! So every `AGENTMUX_*` variable reached every pane, and therefore every
19//! process launched from one — including another AgentMux build, which then
20//! adopted the launching instance's identity instead of the one baked into it.
21//! Confirmed live: a 0.56.3 build launched from a pane wrote into a 0.56.2
22//! instance's channel. That is invariant I6 breached through a channel I1–I6
23//! never named, because they enumerate OS objects and directories and treat the
24//! threat as "a new launch must not crash a running one" — this is neither.
25//!
26//! Full analysis, including the five prior documents that identified this and
27//! left it open:
28//! `docs/retro/retro-env-inheritance-instance-isolation-breach-2026-09-17.md`.
29//!
30//! # The rule
31//!
32//! An `AGENTMUX_*` variable crosses into a pane only if it is on [`PANE_ENV_KEEP`]
33//! — an allowlist, not a denylist, so a variable added later is excluded by
34//! default rather than leaking until someone remembers to deny it. That
35//! direction is the whole point: the previous state of the world was an
36//! implicit allow-everything.
37//!
38//! This strips only what would arrive *by inheritance*. Callers apply their own
39//! explicit `.env()` values afterwards, which is why the terminal path can strip
40//! nearly everything — it re-sets what it needs a few lines later.
41
42/// `AGENTMUX_*` variables permitted to reach a pane by inheritance.
43///
44/// Derived from an exhaustive audit of every `process.env` read in
45/// `backend/shellintegration/` (`muxsh`, `muxlog`, `muxspect`, `muxopen`,
46/// `lib/muxclient.mjs`) plus the shell rc scripts. Each entry needs a reason;
47/// anything without one does not belong here.
48pub const PANE_ENV_KEEP: &[&str] = &[
49    // The instance's own loopback API, and the key to it. `lib/muxclient.mjs`
50    // reads exactly these two, and every helper CLI goes through it.
51    //
52    // These remain the largest residual coupling: a process that inherits both
53    // holds an authenticated handle to the instance that spawned it. Replacing
54    // them with a per-invocation handoff is tracked as follow-up in the retro
55    // (§9.4) — it is a redesign of how helpers reach the server, not a strip.
56    "AGENTMUX_LOCAL_URL",
57    "AGENTMUX_AUTH_KEY",
58    // Which pane the helper is speaking for.
59    "AGENTMUX_BLOCKID",
60    "AGENTMUX_TABID",
61    // Prompt hook + `muxlog` banner (bash.sh/zsh.sh/fish.fish/pwsh.ps1).
62    // With the other two, which build a pane runs in ([`build_info`]).
63    "AGENTMUX_VERSION",
64    "AGENTMUX_BUILD",
65    "AGENTMUX_INSTANCE_CHANNEL",
66    "AGENTMUX_LOG_DIR",
67    // Agent identity: the OSC-16162 prompt hook, external tooling that
68    // selects credentials per agent, and bashwrap's per-instance cwd-state
69    // file key.
70    //
71    // AGENTMUX_AGENT_COLOR/AGENTMUX_AGENT_TEXT_COLOR decommissioned
72    // 2026-09-20 (SPEC_AGENT_HEADER_COLOR_UNIFICATION_2026_09_20.md) — the
73    // only consumer was the frontend's env-var-driven pane header/border
74    // color detection, itself replaced by reusing the agent's persisted
75    // `ui:color` (SPEC_AGENT_COLOR_2026_08_08.md). Nothing reads these two
76    // keys downstream of the OSC-16162 `cmd:env` payload anymore.
77    "AGENTMUX_AGENT_ID",
78    "AGENTMUX_AGENT_SLUG",
79    "AGENTMUX_AGENT_DISPLAY",
80    "AGENTMUX_INSTANCE_SLUG",
81];
82
83/// What AppRun's start sets for this AgentMux's own files, which nothing a pane
84/// starts should inherit: `APPIMAGE`, `APPDIR`, `OWD` and `ARGV0` name this
85/// AppImage (another build started from the pane would think it is it, and
86/// `update::install` would take it for this AppImage), and `LD_LIBRARY_PATH`
87/// carries this version's `usr/bin`, whose `libcef.so` any program started
88/// there would load. Both AppRun and the tarball's `agentmux.sh` only *prepend*
89/// to the user's own `LD_LIBRARY_PATH`, so only that entry is removed.
90const APPIMAGE_ENV: &[&str] = &["APPIMAGE", "APPDIR", "OWD", "ARGV0"];
91
92/// The environment changes that take AgentMux's own launch settings out of a
93/// child's: `(key, new value)`, `None` removing the variable. `var` reads this
94/// process's environment; `own_bin` is where its binaries are (`usr/bin`).
95fn launch_env_edits_for(var: &dyn Fn(&str) -> Option<String>, own_bin: &[std::path::PathBuf]) -> Vec<(String, Option<String>)> {
96    let mut edits = Vec::new();
97    if var("APPIMAGE").is_some_and(|v| !v.is_empty()) {
98        edits.extend(APPIMAGE_ENV.iter().map(|k| (k.to_string(), None)));
99    }
100    if let Some(paths) = var("LD_LIBRARY_PATH") {
101        let own: Vec<String> = own_bin.iter().map(|p| p.to_string_lossy().trim_end_matches('/').to_string()).collect();
102        let kept: Vec<&str> = paths.split(':').filter(|e| !own.iter().any(|o| e.trim_end_matches('/') == o)).collect();
103        if kept.len() != paths.split(':').count() {
104            let kept: Vec<&str> = kept.into_iter().filter(|e| !e.is_empty()).collect();
105            edits.push(("LD_LIBRARY_PATH".to_string(), (!kept.is_empty()).then(|| kept.join(":"))));
106        }
107    }
108    edits
109}
110
111/// [`launch_env_edits_for`] for this process: its binaries are in its own
112/// folder, and in `$APPDIR` or AppRun's extraction under `usr/bin`.
113fn launch_env_edits() -> Vec<(String, Option<String>)> {
114    let mut own_bin: Vec<std::path::PathBuf> = std::env::current_exe().ok().and_then(|e| e.parent().map(std::path::Path::to_path_buf)).into_iter().collect();
115    for root in ["APPDIR", "AGENTMUX_EXTRACTED_RUN"] {
116        own_bin.extend(std::env::var_os(root).filter(|r| !r.is_empty()).map(|r| std::path::PathBuf::from(r).join("usr/bin")));
117    }
118    launch_env_edits_for(&|k| std::env::var(k).ok(), &own_bin)
119}
120
121/// The nesting sentinel. Presence tells a launcher started from a pane to
122/// ignore ambient `AGENTMUX_*` and re-derive from its own exe path
123/// (`crates/launcher/src/data_dir.rs`).
124pub const NESTING_SENTINEL_KEY: &str = "AGENTMUX";
125
126/// Names a container platform puts in a process's environment that lead to the container's own cloud credentials (the path of
127/// its credentials endpoint is the whole capability to ask for them) or to the container's metadata. Nothing srv starts for an
128/// agent or a pane has a use for them, and a process that held one could act as the container's role, so none crosses into a
129/// pane or an external program. The container should not start srv with them at all (a process's initial environment is
130/// readable by every process of the same user); this is the second line, for what srv starts.
131pub const CONTAINER_CREDENTIAL_ENV: &[&str] = &[
132    "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",
133    "AWS_CONTAINER_CREDENTIALS_FULL_URI",
134    "AWS_CONTAINER_AUTHORIZATION_TOKEN",
135    "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE",
136    "ECS_CONTAINER_METADATA_URI",
137    "ECS_CONTAINER_METADATA_URI_V4",
138    "ECS_AGENT_URI",
139];
140
141/// Keys in *this process's* environment that must not cross into a pane.
142///
143/// Computed from the live environment rather than a hardcoded list, so a
144/// variable introduced anywhere — including by a dependency or a future
145/// `set_var` — is stripped without anyone updating this file.
146pub fn keys_to_strip() -> Vec<String> {
147    std::env::vars_os()
148        .filter_map(|(k, _)| k.into_string().ok())
149        .filter(|k| should_strip(k))
150        .collect()
151}
152
153/// Is `key` an AgentMux variable that must not be inherited by a pane?
154pub fn should_strip(key: &str) -> bool {
155    if CONTAINER_CREDENTIAL_ENV.contains(&key) {
156        return true;
157    }
158    if !key.starts_with("AGENTMUX") {
159        return false;
160    }
161    // The sentinel is set deliberately by both spawn paths; never strip it.
162    if key == NESTING_SENTINEL_KEY {
163        return false;
164    }
165    !PANE_ENV_KEEP.contains(&key)
166}
167
168
169/// Apply the policy to a PTY command: strip inherited identity, then mark the
170/// child as running inside AgentMux.
171///
172/// Exists so a caller cannot apply half of it. The first version of this fix
173/// inlined the strip at ONE of `shell/lifecycle.rs`'s three `CommandBuilder`
174/// branches, leaving the direct-spawn path (agent CLIs launched with args) and
175/// the shell-wrapped `cmd` path fully leaking — caught in review as a P0.
176/// Call this once on the finished command instead.
177///
178/// Safe to call after the caller's own `.env()` values: everything a pane
179/// legitimately sets is on [`PANE_ENV_KEEP`], so nothing it just set is removed,
180/// and a launch setting the caller set itself (`LD_LIBRARY_PATH`, say) is kept
181/// ([`apply_edits_pty`]).
182pub fn sanitize_pty_command(c: &mut portable_pty::CommandBuilder) {
183    for key in keys_to_strip() {
184        c.env_remove(&key);
185    }
186    apply_launch_env_pty(c);
187    c.env(NESTING_SENTINEL_KEY, "1");
188    for (key, value) in build_info() {
189        c.env(key, value);
190    }
191}
192
193/// Which AgentMux a pane runs in, set on every process a pane starts so an
194/// agent can say so without reading it out of a log path:
195/// - `AGENTMUX_VERSION`: the release version (`0.59.16`). The shell helpers
196///   also use it to name log pointer files, so it stays the plain version.
197/// - `AGENTMUX_BUILD`: the exact build: a local portable's label
198///   (`0.59.16+g2a5424fe2.20261008T234046.81801`), else the version.
199/// - `AGENTMUX_INSTANCE_CHANNEL`: the channel this instance runs in (`stable`,
200///   or a local build's own channel). Information only: `AGENTMUX_CHANNEL`,
201///   which says where an instance keeps its data, never reaches a pane, and
202///   nothing reads this one to choose a data directory.
203pub fn build_info() -> &'static [(&'static str, String)] {
204    static INFO: std::sync::OnceLock<Vec<(&'static str, String)>> = std::sync::OnceLock::new();
205    INFO.get_or_init(|| {
206        let version = env!("CARGO_PKG_VERSION").to_string();
207        let build = std::env::current_exe()
208            .ok()
209            .and_then(|exe| exe.parent().and_then(agentmux_common::runtime_mode::portable_build_label))
210            .unwrap_or_else(|| version.clone());
211        let mut info = vec![("AGENTMUX_VERSION", version), ("AGENTMUX_BUILD", build)];
212        if let Some(channel) = std::env::var("AGENTMUX_CHANNEL").ok().filter(|c| !c.trim().is_empty()) {
213            info.push(("AGENTMUX_INSTANCE_CHANNEL", channel));
214        }
215        info
216    })
217}
218
219/// `sanitize_pty_command` for a `tokio::process::Command` — agent subprocesses,
220/// and the `/api/v1/shell/create` runner behind the MCP `Shell` tool, which is
221/// how CLAUDE.md tells agents to launch `task dev` / `task package`. That path
222/// was missed entirely by the first revision of this fix (ReAgent P0), which is
223/// notable because it is the single most likely way for an agent to start a
224/// second instance.
225pub fn sanitize_process_command(cmd: &mut tokio::process::Command) {
226    for key in keys_to_strip() {
227        cmd.env_remove(&key);
228    }
229    apply_launch_env(cmd.as_std_mut());
230    cmd.env(NESTING_SENTINEL_KEY, "1");
231    for (key, value) in build_info() {
232        cmd.env(key, value);
233    }
234}
235
236
237/// Strip **every** `AGENTMUX_*` variable, including the in-pane helper keep-set.
238///
239/// For processes that are neither ours nor helpers: provider CLIs launched for
240/// OAuth login (`server/identity_auth_spawn.rs`). Those are third-party,
241/// network-connected binaries, so even [`PANE_ENV_KEEP`] is too generous —
242/// `AGENTMUX_LOCAL_URL` would hand them this instance's API endpoint, and
243/// `AGENTMUX_AUTH_KEY` the credential to it. `muxsh` needs those; `claude
244/// login` does not.
245///
246/// The nesting sentinel is still set: it carries no identity, and it stops a
247/// launcher started anywhere below from adopting ambient state.
248pub fn sanitize_external_command(cmd: &mut tokio::process::Command) {
249    for key in all_agentmux_keys() {
250        cmd.env_remove(&key);
251    }
252    apply_launch_env(cmd.as_std_mut());
253    cmd.env(NESTING_SENTINEL_KEY, "1");
254}
255
256/// `sanitize_external_command` for a PTY command.
257pub fn sanitize_external_pty_command(c: &mut portable_pty::CommandBuilder) {
258    for key in all_agentmux_keys() {
259        c.env_remove(&key);
260    }
261    apply_launch_env_pty(c);
262    c.env(NESTING_SENTINEL_KEY, "1");
263}
264
265/// Every `AGENTMUX*` key in this process's environment except the sentinel, and the container's credential names.
266fn all_agentmux_keys() -> Vec<String> {
267    std::env::vars_os()
268        .filter_map(|(k, _)| k.into_string().ok())
269        .filter(|k| (k.starts_with("AGENTMUX") && k != NESTING_SENTINEL_KEY) || CONTAINER_CREDENTIAL_ENV.contains(&k.as_str()))
270        .collect()
271}
272
273
274/// `sanitize_external_command` for a synchronous `std::process::Command`.
275///
276/// Needed because not every external spawn is async — `npm install` in
277/// `backend/cli_install.rs` is a blocking `.output()` call, and it runs
278/// arbitrary postinstall scripts.
279pub fn sanitize_external_std_command(cmd: &mut std::process::Command) {
280    for key in all_agentmux_keys() {
281        cmd.env_remove(&key);
282    }
283    apply_launch_env(cmd);
284    cmd.env(NESTING_SENTINEL_KEY, "1");
285}
286
287/// Take AgentMux's own launch settings out of `cmd`'s environment
288/// ([`launch_env_edits`]): what it inherits, never what the caller set on it.
289fn apply_launch_env(cmd: &mut std::process::Command) {
290    apply_edits(cmd, launch_env_edits());
291}
292
293/// [`apply_launch_env`] with the edits given. A key the command sets explicitly
294/// (a pane's own `LD_LIBRARY_PATH`, set before this runs) is left as it is.
295fn apply_edits(cmd: &mut std::process::Command, edits: Vec<(String, Option<String>)>) {
296    let explicit: Vec<String> =
297        cmd.get_envs().filter(|(_, v)| v.is_some()).map(|(k, _)| k.to_string_lossy().into_owned()).collect();
298    for (key, value) in edits.into_iter().filter(|(k, _)| !explicit.contains(k)) {
299        match value {
300            Some(v) => cmd.env(key, v),
301            None => cmd.env_remove(key),
302        };
303    }
304}
305
306/// [`apply_launch_env`] for a PTY command.
307fn apply_launch_env_pty(c: &mut portable_pty::CommandBuilder) {
308    apply_edits_pty(c, launch_env_edits());
309}
310
311/// [`apply_edits`] for a PTY command, whose environment starts as a copy of this
312/// process's: only what was added on top of that counts as set by the caller.
313fn apply_edits_pty(c: &mut portable_pty::CommandBuilder, edits: Vec<(String, Option<String>)>) {
314    let explicit: Vec<String> = c.iter_extra_env_as_str().map(|(k, _)| k.to_string()).collect();
315    for (key, value) in edits.into_iter().filter(|(k, _)| !explicit.contains(k)) {
316        match value {
317            Some(v) => c.env(key, v),
318            None => c.env_remove(key),
319        };
320    }
321}
322
323/// Build a provider-CLI command with this instance's identity already stripped.
324///
325/// Sanitizing HERE rather than at each call site is deliberate. This factory has
326/// eight callers across srv (agent spawn, ACP, app-server, persistent
327/// controller, session probe, auth check, version probe), and none of them
328/// contains a literal `Command::new` — so a grep for spawn constructors, which
329/// is how the other sites in this codebase were audited, cannot see them. Five
330/// review rounds on PR #3326 each found a spawn the previous fix had missed;
331/// this one was invisible to the verification command the spec recommends.
332/// A factory is the one place a fix cannot be half-applied.
333///
334/// Pane policy, not strict: most callers launch an agent CLI that legitimately
335/// uses the in-pane helpers. Call sites that spawn the CLI as a plain
336/// third-party binary (auth checks, version probes) tighten this to
337/// `sanitize_external_command` on top, which only removes more.
338pub fn make_cli_cmd(cli_path: &str) -> tokio::process::Command {
339    let mut cmd = agentmux_common::make_cli_cmd(cli_path);
340    sanitize_process_command(&mut cmd);
341    cmd
342}
343
344#[cfg(test)]
345mod spawn_site_coverage {
346    //! Invariant I7: an instance's identity must not be inheritable by the
347    //! processes it spawns.
348    //!
349    //! The tests below this module check the *policy* — which variables get
350    //! stripped. Nothing checked the *call sites*, and that is the gap that let
351    //! this class of bug survive five write-ups: the policy was never the hard
352    //! part, applying it at a NEW spawn site was. Both P0s on the original fix
353    //! were exactly that.
354    //!
355    //! # Why an exact inventory rather than "does this file sanitize?"
356    //!
357    //! The first version of this test asked, per file, whether any sanitizer
358    //! appeared anywhere in it. That is too weak, and reagent was right to
359    //! block on it (#3365 P1): a file that already sanitizes one command
360    //! passes wholesale, so a new unsanitized spawn added beside it is invisible
361    //! — and that describes most non-trivial spawn files in the crate.
362    //!
363    //! Per-*occurrence* matching does not work either, and `shell/lifecycle.rs`
364    //! shows why: it builds four `CommandBuilder`s as `c` and sanitizes once,
365    //! later, at a choke point as `cmd`. That is the correct pattern, and any
366    //! syntactic per-site rule flags it. Proving it needs dataflow analysis.
367    //!
368    //! So this pins the whole surface instead: every `(file, program)` pair that
369    //! constructs a process, with an exact count and a stated classification.
370    //! A new spawn anywhere changes the map and fails, regardless of what its
371    //! neighbours do. Removing one fails too, so the table cannot rot.
372    //!
373    //! Adding a spawn is then a two-line diff: sanitize it, and say so here.
374
375    use std::collections::BTreeMap;
376    use std::path::{Path, PathBuf};
377
378    /// Ways a process gets constructed in this crate.
379    const SPAWN_MARKERS: &[&str] = &["CommandBuilder::new", "process::Command::new", "Command::new("];
380
381    /// Recognised classifications. The prefix is load-bearing: `sanitized:`
382    /// entries are cross-checked against the file actually calling a sanitizer, and `allowlisted:` ones (the
383    /// environment is cleared and only a named list is passed) against the file calling `env_clear()`.
384    const CLASSES: &[&str] = &["sanitized:", "allowlisted:", "probe:", "test:", "own-exe:", "not a spawn:", "mixed:"];
385
386    /// Every process spawn in srv: `(file, program, count, classification)`.
387    ///
388    /// `program` is the literal text between `new(` and the first `,` or `)`,
389    /// which is stable across edits in a way line numbers are not.
390    const SPAWN_INVENTORY: &[(&str, &str, usize, &str)] = &[
391        ("src/identity/gh_agent_token.rs", "&exe", 3,
392         "sanitized: the host's `gh-agent token` for a container agent's repository, sanitize_external_command (it is told only the agent id); and its `scan-push`, which judges a container's push from data on stdin, sanitize_external_command, run in a temp directory with fixed arguments; and its `pr merge`, which srv runs for a container agent with arguments it builds itself, sanitize_external_command, run in a temp directory"),
393        ("src/identity/aws_broker/mint.rs", "&spec.program", 1,
394         "sanitized: the host program that mints a container agent's AWS session (aws configure export-credentials, or a grant's own recipe), sanitize_external_command, then only an allowlist of the environment is passed on"),
395        ("src/backend/app_version.rs", "\"/usr/bin/plutil\"", 1,
396         "sanitized: macOS only: reads a binary Info.plist's version for Browse (`plutil -extract CFBundleShortVersionString`), sanitize_external_std_command, no input, output parsed then discarded"),
397        ("src/open_cli.rs", "\"open\"", 1,
398         "sanitized: `agentmux-srv open` starts the person's browser (macOS) at the sign-in line, sanitize_external_std_command"),
399        ("src/open_cli.rs", "\"rundll32\"", 1,
400         "sanitized: `agentmux-srv open` starts the person's browser (Windows) at the sign-in line, sanitize_external_std_command"),
401        ("src/agentmux_cli/main.rs", "&srv", 2,
402         "own-exe: `agentmux` runs the server program of its own install (`migrate --prepare`, and the `open` and `logout` sign-in client); the command drops every AGENTMUX_* variable of the shell it runs in before it spawns anything"),
403        ("src/agentmux_cli/main.rs", "srv", 1,
404         "own-exe: `agentmux run` becomes the server program of its own install (exec), with the channel's own folders in its environment; the shell's AGENTMUX_* variables were dropped first"),
405        ("src/agentmux_cli/keyring_probe.rs", "srv", 1,
406         "own-exe: `agentmux setup` on Linux runs `agentmux-srv probe-keychain` of its own install, once on a first run, to learn whether the keychain answers (it stores, reads back and deletes one test entry); no input, a few seconds' wait, output (one word) read then discarded; the shell's AGENTMUX_* variables were dropped first"),
407        ("src/backend/lan/firewall_setup.rs", "helper", 1,
408         "own-exe: Windows only, when the person clicks Set up in the AgentMux window: runs `agentmux.exe --configure-lan-firewall` of its own install (the folder above this program's), which asks Windows for administrator permission itself and adds two port rules; no input, its last stderr line is read and shown, no environment is added"),
409        ("src/agentmuxw.rs", "agentmux", 1,
410         "own-exe: `agentmuxw`, the Windows logon task's program, runs the `agentmux.exe` in its own folder with `run` and a channel name, and nothing else; no environment is added"),
411        ("src/agentmux_cli/main.rs", "exe", 1,
412         "own-exe: `agentmux start` runs `agentmux run` in the background from its own executable; the shell's AGENTMUX_* variables were dropped first"),
413        ("src/agentmux_cli/service.rs", "program", 1,
414         "mixed: `agentmux setup` and `start`/`stop` drive the person's own service manager (systemctl --user, launchctl) at their command, to install, start or stop the server's user service; no agent code runs through it, and nothing of the environment is added"),
415        ("src/agentmux_cli/uninstall.rs", "\"cmd.exe\"", 1,
416         "own-exe: `agentmux uninstall` on Windows starts a hidden `cmd` that waits a few seconds and removes the install folder this command ran from, after the command has ended (a running program's own file cannot be deleted); the path was checked to be the install folder and to hold no character `cmd` acts on, and no input or environment is passed on"),
417        ("src/agentmux_cli/doctor.rs", "\"node\"", 1,
418         "probe: `agentmux doctor` asks the installed Node.js its version (`node --version`) to compare it with the least the new-agent panel needs; no input, output parsed then discarded, no agent code runs through it"),
419        ("src/agentmux_cli/process.rs", "\"ps\"", 1,
420         "probe: names the program of one process id on macOS (`ps -o comm= -p <pid>`), to check it is the server before it is signalled; no input but the id, no environment passed on"),
421        ("src/open_cli.rs", "\"xdg-open\"", 1,
422         "sanitized: `agentmux-srv open` starts the person's browser (Linux) at the sign-in line, sanitize_external_std_command"),
423        ("src/server/files_root.rs", "\"cmd\"", 1,
424         "test: Windows only; makes a junction in a temp folder with mklink /J to prove a link swapped in after a pane opened is refused"),
425        ("src/server/agent_folder_open.rs", "\"cmd\"", 1,
426         "test: Windows only; makes a junction in a temp folder with mklink /J to prove a link opened from a pane is followed to where it leads before it is placed"),
427        ("src/server/agent_media_files.rs", "\"cmd\"", 1,
428         "test: Windows only; makes a junction in a temp folder with mklink /J to prove a link swapped in after a message's file was found is not followed"),
429        ("src/backend/blockcontroller/subprocess/container_spawn.rs", "&argv[0]", 1,
430         "test: Unix only; runs the container turn launcher on the host to prove an exported function reaches the provider"),
431        ("src/agents/runner.rs", "bin", 1,
432         "sanitized: agent CLI subprocess, sanitize_process_command"),
433        ("src/backend/skill_import.rs", "\"git\"", 1,
434         "sanitized: a shallow clone of a skill repository to import, sanitize_external_command (third-party network program, needs no instance identity)"),
435        ("src/backend/attachments/extract.rs", "exe", 1,
436         "sanitized: our own binary re-run as `__extract` to parse one attachment in isolation; it needs no instance identity, so sanitize_external_std_command"),
437        ("src/backend/file_icons/pool.rs", "exe", 1,
438         "sanitized: our own binary re-run as `__file_icons` to ask the system for a file type's icon in isolation; it needs no instance identity, so sanitize_external_std_command"),
439        ("src/backend/attachments/extract.rs", "harness", 1,
440         "test: re-runs the test harness as a child that sleeps, to prove the extraction deadline kills it"),
441        ("src/backend/spawn_env/endpoint.rs", "\"claude\"", 1,
442         "test: builds a command only to read the environment it would get, to prove an emptied login variable is removed from it; never spawned"),
443        ("src/http_client_tests.rs", "std::env::current_exe(", 1,
444         "test: re-runs the test harness as a child whose SSL_CERT_FILE names an empty, a valid or a replaced certificate bundle, because the machine's certificates are read from the environment when a client is built; the child makes requests to a loopback server only"),
445        ("src/backend/storage/muxbus.rs", "std::env::current_exe(", 1,
446         "test: re-runs the test harness as children that save and read one keychain sign-in at once (ignored; real keychain)"),
447        ("src/backend/storage/filestore/tests_checkpoint.rs", "std::env::current_exe(", 1,
448         "test: Unix only; re-runs the test harness as a child that tries the database's write lock, to prove reading the WAL index leaves a transaction's lock in place"),
449        ("src/backend/storage/filestore/tests_tail_slack.rs", "std::env::current_exe(", 1,
450         "test: re-runs the test harness as a child that appends lines in a loop until the test kills it, to prove a transcript reads back whole after a kill mid-append"),
451        ("src/backend/gpu/nvml.rs", "\"cc\"", 1,
452         "test: Linux only; compiles a tiny fake NVIDIA library (a C file written to a temp folder, fixed arguments) so the NVML calls can be exercised without a GPU; skipped where there is no C compiler"),
453        ("src/backend/git_program_settings.rs", "\"git\"", 1,
454         "sanitized: reads the person's own system and global git configuration for their ssh command, signing programs and editors (`git config --show-scope --get-regexp`, outside any repository), sanitize_external_std_command; no input, output parsed then discarded"),
455        ("src/backend/git_program_settings_tests.rs", "tool", 1,
456         "test: runs git on a pseudoterminal in a scratch repository whose own configuration names marker programs, to prove no pager it names runs; no agent code"),
457        ("src/backend/git_program_settings_tests.rs", "program", 1,
458         "test: runs git in a scratch repository whose own configuration names marker programs, with none of the person's configuration, to prove they do not run; loopback addresses only, no agent code"),
459        ("src/backend/memory/dream_model_tests.rs", "program", 1,
460         "test: runs stock programs (`cat` or `findstr` to echo its input; `sleep` or `ping` as a child that never reads it or never ends) to prove the model call gives its prompt and reads its output, and that its one deadline stops a stalled child and its process group; fixed arguments, no agent code"),
461        ("src/backend/transcript/framer_tests.rs", "&exe", 1,
462         "test: re-runs the test harness as writer, framer and reader children on one scratch store (ignored; the multi-process stress)"),
463        ("src/backend/transcript/framer_tests.rs", "\"ping\"", 1,
464         "test: a short-lived process whose environment the framer reads, to prove a srv on another home does not block; no agent code"),
465        ("src/backend/transcript/framer_tests.rs", "\"sleep\"", 1,
466         "test: a short-lived process whose environment the framer reads, to prove a srv on another home does not block; no agent code"),
467        ("src/backend/blockcontroller/app_server.rs", "fake_server_binary(", 1,
468         "test: runs the fixture server built above; lives and dies with the test"),
469        ("src/backend/remote/ssh.rs", "ssh", 1,
470         "probe: `ssh -V` for the client's version (forced askpass), output parsed then discarded"),
471        ("src/backend/remote/host.rs", "&self.ssh_path", 1,
472         "sanitized: a durable SSH pane's ssh (attach, end, helper install: one ssh_command), the same sanitize_process_command"),
473        ("src/backend/blockcontroller/persistent/tests/eager_resume.rs", "\"taskkill\"", 1,
474         "test: the eager-resume harness's Drop force-kills its stub CLI on Windows so a failed assertion cannot leave it running"),
475        ("src/backend/blockcontroller/persistent/tests/eager_resume.rs", "\"kill\"", 1,
476         "test: the same Drop teardown on Unix"),
477        ("src/backend/blockcontroller/persistent/tests/send_input.rs", "\"echo\"", 1,
478         "not a spawn: appears inside a comment explaining why `echo` cannot be spawned directly"),
479        ("src/backend/blockcontroller/shell/spawn_command.rs", "\"/bin/sh\"", 1,
480         "sanitized: Unix fallback shell, covered by the same single sanitize_pty_command"),
481        ("src/backend/blockcontroller/shell/spawn_command.rs", "\"cmd.exe\"", 1,
482         "sanitized: Windows fallback shell, covered by the same single sanitize_pty_command"),
483        ("src/backend/blockcontroller/shell/lifecycle.rs", "\"shell-under-test\"", 1,
484         "not a spawn: global_cmd_env_tests builds a CommandBuilder only to read back the cmd:env applied to it; never spawned"),
485        ("src/backend/blockcontroller/shell/spawn_command.rs", "&program", 1,
486         "sanitized: pane PTY, one choke-point sanitize_pty_command covers all four builders here"),
487        ("src/backend/blockcontroller/shell/spawn_command.rs", "&shell_path", 1,
488         "sanitized: the configured login shell, covered by the same sanitize_pty_command"),
489        ("src/backend/blockcontroller/shell/spawn_command.rs", "\"wsl.exe\"", 1,
490         "sanitized: a WSL pane's wsl.exe, covered by the same sanitize_pty_command"),
491        ("src/backend/shells.rs", "&c.path", 1,
492         "probe: each installed shell's `--version` for Settings' default-shell list, output parsed then discarded"),
493        ("src/backend/blockcontroller/shell/ssh_pane.rs", "ssh_path", 1,
494         "sanitized: an SSH pane's system ssh, built here and sanitized by lifecycle.rs's sanitize_pty_command"),
495        ("src/backend/blockcontroller/shell/container_pane.rs", "\"docker\"", 1,
496         "sanitized: a container agent's drawer shell, `docker exec` on a PTY, sanitize_pty_command here, then only the shell's own identity env and DOCKER_HOST added"),
497        ("src/backend/blockcontroller/shell/tests.rs", "\"sleep\"", 1,
498         "test: disposable `sleep 30` made its own process-group leader, to prove a group-kill reaches an isolated group"),
499        ("src/bootstrap/watchers.rs", "\"sleep\"", 1,
500         "test: disposable `sleep 60` the launcher-watcher test waits on through a pidfd, to prove a signal doesn't end the wait"),
501        ("src/backend/claude_layout.rs", "\"git\"", 1,
502         "test: builds a throwaway repository with a linked worktree in a temp dir, to check the CLI's memory-folder rule"),
503        ("src/backend/container/mounts/credential_mode.rs", "\"sh\"", 1,
504         "test: Unix only; runs the container's credential-tightening script against a temp dir, to prove what it changes and what it leaves"),
505        ("src/backend/container/cli.rs", "\"sh\"", 2,
506         "test: Unix only; runs the container CLI install and check scripts against a stub npm in a temp dir, to prove they are idempotent and write no marker on failure"),
507        ("src/backend/container/cli_release_tests.rs", "\"sh\"", 3,
508         "test: Unix only; runs the container download and uv install scripts against a fake curl in a temp dir, to prove the hash check, the size cap and the marker-last order"),
509        ("src/backend/container/cli_release_tests.rs", "\"tar\"", 2,
510         "test: Unix only; builds throwaway tarballs in a temp dir (one with a `..` member) as the download script tests' fixtures"),
511        ("src/backend/container_task_probe.rs", "\"sh\"", 1,
512         "test: Linux only; runs the probe's script against this test's own pid and a pid no process has, to prove what it prints"),
513        ("src/backend/lsp/supervisor.rs", "&resolved", 1,
514         "sanitized: language server, sanitize_process_command"),
515        ("src/backend/lsp/supervisor.rs", "\"ping\"", 1,
516         "test: Windows only; a disposable `ping -n 120 127.0.0.1` stands for a running language server, to prove the last client to stop ends the process"),
517        ("src/backend/lsp/supervisor.rs", "\"sleep\"", 1,
518         "test: Unix only; a disposable `sleep 120` stands for a running language server, to prove the last client to stop ends the process"),
519        ("src/backend/mcp_probe.rs", "command", 1,
520         "sanitized: MCP server probe, sanitize_process_command"),
521        ("src/backend/process_tracker/windows.rs", "\"cmd\"", 2,
522         "test: a short-lived child placed in a Job Object, to check the below-normal priority limit applies to it and that listing the job reads its parent, path and memory"),
523        ("src/backend/container/keychain_credentials.rs", "\"/usr/bin/security\"", 1,
524         "sanitized: macOS only; the Keychain read and write of a container agent's login, sanitize_external_std_command (the tool needs no instance identity)"),
525        ("src/backend/container/keychain_credentials/tests.rs", "\"/usr/bin/security\"", 5,
526         "test: macOS only; the ignored live tests add and delete their own throwaway entries in the real login keychain"),
527        ("src/identity/secret_store.rs", "\"/usr/bin/security\"", 1,
528         "test: adds a keychain entry that trusts no app, for the macOS needs-consent test (ignored; real keychain)"),
529        ("src/server/keychain_probe.rs", "\"/usr/bin/security\"", 1,
530         "sanitized: macOS only; asks which keychain is the user's default before a Claude sign-in (`security default-keychain -d user`), sanitize_external_command (it keeps HOME, which is what it checks), output parsed then discarded"),
531        ("src/server/app_api/blockstats.rs", "\"ping\"", 1,
532         "test: a disposable child (Windows) registered as a pane's shell, so the stats tooltip test has a Tower task to read"),
533        ("src/server/app_api/blockstats.rs", "\"sleep\"", 1,
534         "test: the same disposable child on Unix"),
535        ("src/backend/process_tracker/registry.rs", "\"cmd\"", 5,
536         "test: disposable children for the job-object tracker (assign, adopt, CPU accounting)"),
537        ("src/backend/process_tracker/registry.rs", "\"sh\"", 3,
538         "test: disposable child for the job-object tracker; two more read their own nice level (the agent-priority tests)"),
539        ("src/backend/process_tracker/registry.rs", "&argv[0]", 1,
540         "test: runs the nice-wrapped PTY argv and reads its nice level"),
541        ("src/backend/process_tracker/registry.rs", "\"ping\"", 1,
542         "test: a disposable child (Windows) put in an agent's or a terminal's tree, for the which-agent's-tree test"),
543        ("src/backend/process_tracker/registry.rs", "\"sleep\"", 1,
544         "test: the same disposable child on Unix"),
545        ("src/server/peer_process.rs", "\"lsof\"", 1,
546         "sanitized: macOS only; asks which process holds the other end of a loopback connection (`lsof -i`), sanitize_external_std_command, no input, output parsed then discarded"),
547        ("src/backend/process_tracker/scan.rs", "\"sh\"", 1,
548         "test: disposable children the scan tracker tests find and kill"),
549        ("src/backend/process_tracker/cgroup_linux.rs", "\"sleep\"", 2,
550         "test: the argv the PTY-wrap test wraps, and a child the listing test describes; never spawned as built"),
551        ("src/backend/process_tracker/roots_file.rs", "\"sleep\"", 1,
552         "test: a stand-in agent CLI the roots-file prune test records and kills"),
553        ("src/backend/process_tracker/cgroup_linux.rs", "&argv[0]", 1,
554         "test: runs the wrapped argv the cgroup tests track and kill"),
555        ("src/backend/process_tracker/cgroup_linux.rs", "\"sh\"", 2,
556         "test: disposable children the cgroup tests track and kill"),
557        ("src/sagas/close_pane.rs", "\"cmd\"", 2,
558         "test: stand-in background dev servers (Stop ends one; a failed Stop keeps one)"),
559        ("src/sagas/close_pane.rs", "\"sh\"", 2,
560         "test: stand-in background dev servers (Stop ends one; a failed Stop keeps one)"),
561        ("src/server/agent_resources.rs", "\"cmd\"", 2,
562         "test: children for the survivor check and the forced tree kill"),
563        ("src/server/agent_resources.rs", "\"sh\"", 2,
564         "test: children for the survivor check and the forced tree kill"),
565        ("src/backend/remote/helper_install.rs", "\"sh\"", 2,
566         "test: runs the install scripts in a real sh against a temp home"),
567        ("src/backend/fs_ops/host_jobs.rs", "\"mkfifo\"", 1,
568         "test: makes a FIFO for the host transfer tests (Linux only)"),
569        ("src/backend/tower/remote.rs", "\"wsl.exe\"", 1,
570         "sanitized: Tower's helper inside a WSL distribution, sanitize_external_command"),
571        ("src/backend/remote/wsl.rs", "\"wsl.exe\"", 1,
572         "probe: `wsl.exe --list --quiet`, output parsed then discarded"),
573        ("src/backend/remote/address.rs", "\"wsl.exe\"", 1,
574         "sanitized: a WSL pane's address (`cat /proc/net/...`), sanitize_external_command"),
575        ("src/backend/remote/address.rs", "binary", 1,
576         "sanitized: an SSH pane's host (`ssh -G`), sanitize_external_command"),
577        ("src/backend/shell_node.rs", "\"cmd\"", 1,
578         "sanitized: persistent shell node, choke-point sanitize_process_command"),
579        ("src/backend/shell_node.rs", "\"sh\"", 1,
580         "sanitized: Unix branch of the same node, one sanitize_process_command covers both"),
581        ("src/backend/shell_node.rs", "program", 1,
582         "sanitized: an agent Shell run elsewhere (wsl.exe for WSL, ssh for SSH), the same sanitize_process_command"),
583        ("src/backend/update/download.rs", "tar_exe(", 2,
584         "sanitized: the system tar unpacks a downloaded Linux release, sanitize_external_command (a Windows release is decoded in srv, update::unpack); the other is the Linux test that builds its tarball"),
585        ("src/backend/tool_store.rs", "\"where\"", 2,
586         "probe: Windows PATH lookup for a tool; output parsed for a path, never executed"),
587        ("src/backend/tool_store.rs", "\"which\"", 2,
588         "probe: Unix PATH lookup for a tool; output parsed for a path, never executed"),
589        ("src/backend/tool_store.rs", "cmd", 1,
590         "sanitized: probe_version runs a third-party binary, strict policy (this PR)"),
591        ("src/crash_monitor.rs", "&exe", 1,
592         "own-exe: re-spawns OUR OWN binary as the crash monitor; it must stay this instance, so inheritance is the requirement here, not the defect"),
593        ("src/crash_monitor.rs", "std::env::current_exe(", 1,
594         "test: re-runs the test harness as a child that hardens itself, to prove its crash dump is still written"),
595        ("src/backend/cli_install.rs", "\"cmd\"", 1,
596         "sanitized: shell wrapper for npm install, sanitize_external_std_command"),
597        ("src/backend/cli_install.rs", "\"npm\"", 1,
598         "sanitized: npm runs arbitrary postinstall scripts, sanitize_external_std_command"),
599        ("src/backend/cli_prune.rs", "\"ps\"", 1,
600         "sanitized: lists running command lines to see which installed CLI is in use, sanitize_external_std_command"),
601        ("src/server/cli_handlers.rs", "\"where\"", 2,
602         "probe: Windows availability check for npm before install; runs nothing else"),
603        ("src/server/cli_handlers.rs", "\"which\"", 2,
604         "probe: Unix availability check for npm before install; runs nothing else"),
605        ("src/backend/fs_ops/git.rs", "\"git\"", 6,
606         "mixed: git_command (Files pane git markers, agents' work facts) is sanitize_external_command'd, and set to fetch nothing and allow no transport; five are this file's own #[cfg(test)] module"),
607        ("src/backend/work_facts/git.rs", "\"git\"", 1,
608         "test: builds a throwaway repository in a temp dir to check the work-facts probe; production git goes through fs_ops::git's run_git"),
609        ("src/backend/fs_ops/platform.rs", "\"explorer.exe\"", 2,
610         "sanitized: Files pane open/reveal (file manager, default app), sanitize_external_std_command in platform::spawn_detached"),
611        ("src/backend/fs_ops/platform.rs", "\"open\"", 2,
612         "sanitized: Files pane open/reveal (file manager, default app), sanitize_external_std_command in platform::spawn_detached"),
613        ("src/backend/fs_ops/platform.rs", "\"xdg-open\"", 3,
614         "sanitized: Files pane open/reveal (file manager, default app), sanitize_external_std_command in platform::spawn_detached"),
615        ("src/backend/fs_ops/platform.rs", "\"dbus-send\"", 1,
616         "sanitized: Linux reveal asks the file manager over D-Bus to select the file, sanitize_external_std_command in platform::succeeds_within"),
617        ("src/backend/fs_ops/platform.rs", "\"agentmux-no-such-program-for-this-test\"", 1,
618         "test: a program that does not exist, to prove a missing program is not a success"),
619        ("src/backend/fs_ops/platform.rs", "\"false\"", 1,
620         "test: exits non-zero, to prove a failing program is not a success"),
621        ("src/backend/fs_ops/platform.rs", "\"sleep\"", 1,
622         "test: runs past the limit, to prove it is stopped and is not a success"),
623        ("src/backend/fs_ops/platform.rs", "\"true\"", 1,
624         "test: exits zero, to prove a succeeding program is a success"),
625        ("src/backend/fs_watch/pool.rs", "\"wsl.exe\"", 2,
626         "test: an ignored test writes and removes a file inside a WSL distro"),
627        ("src/server/streamed_browser/chromium.rs", "&binary", 1,
628         "allowlisted: the streamed Browser pane's Chromium (unix only): it opens pages from the web, so its environment is cleared and only a short named list (chromium.rs ENV_KEEP) is passed, never srv's own"),
629        ("src/server/streamed_browser/screen/session.rs", "program", 1,
630         "allowlisted: the screen-mode Browser pane's Xvfb, window manager and Chrome (unix only): the environment is cleared and only the same short named list as the streamed pane (chromium.rs ENV_KEEP) plus DISPLAY is passed, never srv's own"),
631        ("src/server/editor_handlers/file_io.rs", "\"explorer.exe\"", 1,
632         "sanitized: file manager, strict policy (I7 fix, this PR)"),
633        ("src/server/editor_handlers/file_io.rs", "\"open\"", 1,
634         "sanitized: file manager, strict policy (I7 fix, this PR)"),
635        ("src/server/identity_auth_spawn_steps.rs", "&spawn_program", 1,
636         "sanitized: provider OAuth CLI under a PTY (the resolved npm shim), strict policy"),
637        ("src/server/identity_auth_spawn_steps.rs", "cli_path", 1,
638         "sanitized: provider OAuth CLI, strict policy"),
639        ("src/server/install_task.rs", "if cfg!(windows", 1,
640         "sanitized: installer shell, sanitize_external_command"),
641        ("src/server/shell_handlers.rs", "&shell", 1,
642         "sanitized: /api/v1/shell/create runner (resolved POSIX shell), sanitize_process_command"),
643        ("src/server/system_install_handlers.rs", "\"apt-cache\"", 1,
644         "probe: package-manager availability query, no install"),
645        ("src/server/system_install_handlers.rs", "\"brew\"", 1,
646         "probe: package-manager availability query, no install"),
647        ("src/server/system_install_handlers.rs", "\"winget\"", 1,
648         "probe: package-manager availability query, no install"),
649        ("src/server/system_install_handlers.rs", "&step.program", 1,
650         "sanitized: package-manager install step, sanitize_external_command"),
651        ("src/server/system_install_handlers.rs", "program", 1,
652         "not a spawn: appears inside this module's header comment describing the argv rule"),
653        ("src/server/voice.rs", "&cli", 1,
654         "sanitized: voice CLI, sanitize_process_command"),
655        ("src/test_support.rs", "\"rustc\"", 1,
656         "test: builds the fixture App Server binary once per source hash, shared by the app_server tests"),
657        ("src/util.rs", "\"cmd\"", 3,
658         "mixed: one is open_browser's sanitized Windows branch; two are in this file's own #[cfg(test)] module"),
659        ("src/util.rs", "\"open\"", 1,
660         "sanitized: browser launch, strict policy (I7 fix, this PR)"),
661        ("src/util.rs", "\"xdg-open\"", 1,
662         "sanitized: browser launch, strict policy (I7 fix, this PR)"),
663    ];
664
665    fn rs_files(dir: &Path, out: &mut Vec<PathBuf>) {
666        let Ok(entries) = std::fs::read_dir(dir) else { return };
667        for entry in entries.flatten() {
668            let path = entry.path();
669            if path.is_dir() {
670                rs_files(&path, out);
671            } else if path.extension().is_some_and(|e| e == "rs") {
672                out.push(path);
673            }
674        }
675    }
676
677    /// `Command::new(` must not match `AgentCommand::new(` — a substring hit
678    /// preceded by an identifier character is a different type.
679    fn line_spawns(line: &str) -> bool {
680        for marker in SPAWN_MARKERS {
681            let mut from = 0;
682            while let Some(idx) = line[from..].find(marker) {
683                let at = from + idx;
684                let prev_is_ident = at > 0
685                    && line[..at]
686                        .chars()
687                        .next_back()
688                        .is_some_and(|c| c.is_alphanumeric() || c == '_');
689                if !prev_is_ident {
690                    return true;
691                }
692                from = at + marker.len();
693            }
694        }
695        false
696    }
697
698    /// The text between `new(` and the first `,` or `)`.
699    fn program_of(line: &str) -> String {
700        let Some(at) = line.find("new(") else { return "?".to_string() };
701        let rest = &line[at + 4..];
702        let end = rest.find([',', ')']).unwrap_or(rest.len());
703        rest[..end].trim().to_string()
704    }
705
706    fn actual_inventory() -> BTreeMap<(String, String), usize> {
707        let mut files = Vec::new();
708        for root in crate::test_support::server_package_dirs() {
709            let mut own = Vec::new();
710            rs_files(&root.join("src"), &mut own);
711            files.extend(own.into_iter().map(|file| (root.clone(), file)));
712        }
713        assert!(files.len() > 50, "source walk found only {} files — the walk is broken", files.len());
714
715        let mut map: BTreeMap<(String, String), usize> = BTreeMap::new();
716        for (root, file) in &files {
717            let rel = file.strip_prefix(root).unwrap_or(file).to_string_lossy().replace('\\', "/");
718            // This file defines the sanitizers and names the markers; it does
719            // not spawn.
720            if rel.ends_with("backend/pane_env.rs") {
721                continue;
722            }
723            let Ok(src) = std::fs::read_to_string(file) else { continue };
724            for line in src.lines() {
725                if line_spawns(line) {
726                    *map.entry((rel.clone(), program_of(line))).or_default() += 1;
727                }
728            }
729        }
730        map
731    }
732
733    #[test]
734    fn the_spawn_surface_matches_the_inventory_exactly() {
735        let actual = actual_inventory();
736        let expected: BTreeMap<(String, String), usize> = SPAWN_INVENTORY
737            .iter()
738            .map(|(f, p, c, _)| ((f.to_string(), p.to_string()), *c))
739            .collect();
740
741        let mut problems = Vec::new();
742        for (key, count) in &actual {
743            match expected.get(key) {
744                None => problems.push(format!(
745                    "NEW spawn site: {} -> Command::new({}) x{count}",
746                    key.0, key.1
747                )),
748                Some(exp) if exp != count => problems.push(format!(
749                    "COUNT changed: {} -> Command::new({}): inventory says {exp}, source has {count}",
750                    key.0, key.1
751                )),
752                _ => {}
753            }
754        }
755        for key in expected.keys() {
756            if !actual.contains_key(key) {
757                problems.push(format!("STALE entry (no longer in source): {} -> {}", key.0, key.1));
758            }
759        }
760
761        assert!(
762            problems.is_empty(),
763            "I7: srv's process-spawn surface changed.\n  {}\n\n\
764             If you added a spawn: apply the right `pane_env::sanitize_*` to it, then add \n\
765             it to SPAWN_INVENTORY with a classification. If you removed one, drop its row. \n\
766             The inventory is pinned deliberately — a new spawn must not be able to hide \n\
767             beside an already-sanitized one (#3365 P1). Background: \n\
768             docs/retro/retro-env-inheritance-instance-isolation-breach-2026-09-17.md",
769            problems.join("\n  ")
770        );
771    }
772
773    #[test]
774    fn every_inventory_row_is_classified_and_justified() {
775        let packages = crate::test_support::server_package_dirs();
776        for (file, program, _, reason) in SPAWN_INVENTORY {
777            assert!(
778                CLASSES.iter().any(|c| reason.starts_with(c)),
779                "{file} -> {program}: reason must start with one of {CLASSES:?}, got {reason:?}"
780            );
781            assert!(
782                reason.len() > 30,
783                "{file} -> {program}: needs a real reason, got {reason:?}"
784            );
785            // A row claiming to be sanitized must be in a file that sanitizes.
786            // Cheap, and it catches a table that says one thing while the code
787            // does another.
788            if reason.starts_with("sanitized:") {
789                let src = packages
790                    .iter()
791                    .find_map(|root| std::fs::read_to_string(root.join(file)).ok())
792                    .expect("read inventory file");
793                assert!(
794                    SANITIZERS_FOR_AUDIT.iter().any(|s| src.contains(s)),
795                    "{file} -> {program} is classified `sanitized:` but the file calls no sanitizer"
796                );
797            }
798            // A row claiming an allow-list must be in a file that clears the environment first.
799            if reason.starts_with("allowlisted:") {
800                let src = packages
801                    .iter()
802                    .find_map(|root| std::fs::read_to_string(root.join(file)).ok())
803                    .expect("read inventory file");
804                assert!(
805                    src.contains(".env_clear()"),
806                    "{file} -> {program} is classified `allowlisted:` but the file does not clear the environment"
807                );
808            }
809        }
810    }
811
812    const SANITIZERS_FOR_AUDIT: &[&str] = &[
813        "sanitize_pty_command",
814        "sanitize_process_command",
815        "sanitize_external_command",
816        "sanitize_external_pty_command",
817        "sanitize_external_std_command",
818    ];
819}
820
821#[cfg(test)]
822mod tests {
823    use super::*;
824
825    fn edits(env: &[(&str, &str)], own: &[&str]) -> Vec<(String, Option<String>)> {
826        let own: Vec<std::path::PathBuf> = own.iter().map(std::path::PathBuf::from).collect();
827        launch_env_edits_for(&|k| env.iter().find(|(n, _)| *n == k).map(|(_, v)| v.to_string()), &own)
828    }
829
830    #[test]
831    fn a_pane_loses_the_appimages_own_settings_and_keeps_the_users_library_path() {
832        let own = ["/home/u/.local/share/agentmux/extracted/0.59.30/usr/bin"];
833        let none = |k: &str| (k.to_string(), None);
834        // From an AppImage: its names go, and only its own entry of the path.
835        let e = edits(
836            &[
837                ("APPIMAGE", "/home/u/AgentMux.AppImage"),
838                ("LD_LIBRARY_PATH", "/home/u/.local/share/agentmux/extracted/0.59.30/usr/bin:/opt/cuda/lib64:/usr/local/lib"),
839            ],
840            &own,
841        );
842        for k in ["APPIMAGE", "APPDIR", "OWD", "ARGV0"] {
843            assert!(e.contains(&none(k)), "{k}");
844        }
845        assert!(e.contains(&("LD_LIBRARY_PATH".to_string(), Some("/opt/cuda/lib64:/usr/local/lib".to_string()))), "{e:?}");
846        // Only our own entry: the variable goes entirely.
847        let e = edits(&[("LD_LIBRARY_PATH", "/home/u/.local/share/agentmux/extracted/0.59.30/usr/bin/")], &own);
848        assert_eq!(e, vec![("LD_LIBRARY_PATH".to_string(), None)]);
849        // The tarball's: no APPIMAGE, but the same path entry.
850        let e = edits(&[("LD_LIBRARY_PATH", "/opt/AgentMux/usr/bin:/lib")], &["/opt/AgentMux/usr/bin"]);
851        assert_eq!(e, vec![("LD_LIBRARY_PATH".to_string(), Some("/lib".to_string()))]);
852    }
853
854    #[test]
855    fn what_a_pane_sets_itself_is_kept_and_only_what_it_inherits_is_edited() {
856        let edits = vec![
857            ("LD_LIBRARY_PATH".to_string(), None),
858            ("APPIMAGE".to_string(), None),
859            ("OWD".to_string(), Some("rewritten".to_string())),
860        ];
861        // A PTY command: its own LD_LIBRARY_PATH survives, the others are edited.
862        let mut pty = portable_pty::CommandBuilder::new("sh");
863        pty.env("LD_LIBRARY_PATH", "/opt/cuda/lib64");
864        apply_edits_pty(&mut pty, edits.clone());
865        assert_eq!(pty.get_env("LD_LIBRARY_PATH").and_then(|v| v.to_str()), Some("/opt/cuda/lib64"));
866        assert_eq!(pty.get_env("APPIMAGE"), None);
867        assert_eq!(pty.get_env("OWD").and_then(|v| v.to_str()), Some("rewritten"));
868        // A process command, the same.
869        let mut std_cmd = std::process::Command::new("sh");
870        std_cmd.env("LD_LIBRARY_PATH", "/opt/cuda/lib64").env("APPIMAGE", "/set/by/the/pane");
871        apply_edits(&mut std_cmd, edits);
872        let envs: std::collections::HashMap<_, _> =
873            std_cmd.get_envs().map(|(k, v)| (k.to_string_lossy().into_owned(), v.map(|v| v.to_string_lossy().into_owned()))).collect();
874        assert_eq!(envs["LD_LIBRARY_PATH"].as_deref(), Some("/opt/cuda/lib64"));
875        assert_eq!(envs["APPIMAGE"].as_deref(), Some("/set/by/the/pane"), "a pane that sets APPIMAGE itself keeps it");
876        assert_eq!(envs["OWD"].as_deref(), Some("rewritten"));
877    }
878
879    #[test]
880    fn nothing_is_touched_when_the_environment_has_none_of_it() {
881        assert!(edits(&[], &["/opt/AgentMux/usr/bin"]).is_empty());
882        assert!(edits(&[("LD_LIBRARY_PATH", "/opt/cuda/lib64")], &["/opt/AgentMux/usr/bin"]).is_empty());
883        // ARGV0 or OWD of something else, with no AppImage, stay.
884        assert!(edits(&[("ARGV0", "busybox"), ("OWD", "/x")], &[]).is_empty());
885        assert!(edits(&[("APPIMAGE", "")], &[]).is_empty());
886    }
887
888    /// The four variables behind the confirmed failures in the retro. If any of
889    /// these is ever added to the keep-set, the breach reopens.
890    #[test]
891    fn the_identity_vars_that_caused_the_breach_are_stripped() {
892        for key in [
893            "AGENTMUX_CHANNEL",        // a build joined the launching instance's channel
894            "AGENTMUX_DATA_DIR",       // …and its data dir
895            "AGENTMUX_DATA_HOME",      // a dev srv resolved another instance's data dir
896            "AGENTMUX_EXTRACTED_RUN",  // a fresh AppImage ran the previous build's binary
897            "AGENTMUX_CONFIG_DIR",
898            "AGENTMUX_CONFIG_HOME",
899            "AGENTMUX_CEF_CACHE_DIR",
900            "AGENTMUX_INSTANCE_DIR",
901            "AGENTMUX_INSTANCE_RUNTIME_DIR",
902            "AGENTMUX_AGENTS_DIR",
903            "AGENTMUX_RUNTIME_MODE",
904            "AGENTMUX_CLONE_ID",
905            "AGENTMUX_APP_PATH",
906            "AGENTMUX_SRV_PIPE_PATH",
907            "AGENTMUX_SPLASH_READY_FILE",
908            "AGENTMUX_HOME_OVERRIDE",
909        ] {
910            assert!(should_strip(key), "{key} must not be inheritable by a pane");
911        }
912    }
913
914    #[test]
915    fn the_helper_keep_set_survives() {
916        for key in PANE_ENV_KEEP {
917            assert!(!should_strip(key), "{key} is required by an in-pane helper");
918        }
919    }
920
921    /// An allowlist, not a denylist: a variable nobody has thought about yet
922    /// must be excluded by default. This is the property that makes the fix
923    /// survive variable #21 — the previous behaviour was allow-everything.
924    #[test]
925    fn an_unknown_agentmux_var_is_stripped_by_default() {
926        assert!(should_strip("AGENTMUX_SOME_FUTURE_IDENTITY_VAR"));
927    }
928
929    #[test]
930    fn non_agentmux_vars_are_left_alone() {
931        for key in ["PATH", "HOME", "TERM", "SSH_AUTH_SOCK", "LANG", "SystemRoot", "AGENT_ID"] {
932            assert!(!should_strip(key), "{key} is not ours to strip");
933        }
934    }
935
936    /// The sentinel is what tells a nested launcher to ignore ambient vars.
937    /// Stripping it would re-open the hole it exists to close.
938    #[test]
939    fn the_nesting_sentinel_is_never_stripped() {
940        assert!(!should_strip(NESTING_SENTINEL_KEY));
941    }
942
943    /// The external policy must be stricter than the pane one: a provider CLI
944    /// doing OAuth has no business holding this instance's API endpoint, and
945    /// would hold its credential too if one were present in the environment.
946    #[test]
947    fn the_external_policy_strips_even_the_helper_keep_set() {
948        std::env::set_var("AGENTMUX_LOCAL_URL", "http://127.0.0.1:1");
949        let stripped = all_agentmux_keys();
950        assert!(stripped.iter().any(|k| k == "AGENTMUX_LOCAL_URL"),
951            "external processes must not receive the instance API endpoint");
952        assert!(!stripped.iter().any(|k| k == NESTING_SENTINEL_KEY),
953            "the sentinel carries no identity and must survive");
954        std::env::remove_var("AGENTMUX_LOCAL_URL");
955    }
956
957    /// An agent asked "which AgentMux are you in?" reads it from its env.
958    #[test]
959    fn a_pane_is_told_which_build_it_runs_in() {
960        let mut cmd = tokio::process::Command::new("agent");
961        sanitize_process_command(&mut cmd);
962        let envs: std::collections::BTreeMap<String, String> = cmd
963            .as_std()
964            .get_envs()
965            .filter_map(|(k, v)| Some((k.to_str()?.to_string(), v?.to_str()?.to_string())))
966            .collect();
967        let version = env!("CARGO_PKG_VERSION");
968        assert_eq!(envs["AGENTMUX_VERSION"], version, "the plain version: log pointer files are named by it");
969        assert!(envs["AGENTMUX_BUILD"].starts_with(version));
970        assert!(!envs.contains_key("AGENTMUX_CHANNEL"), "the data channel itself still never reaches a pane");
971    }
972
973    /// A container's credential variables are not an agent's or a pane's to hold, in a pane's environment or an external program's.
974    #[test]
975    fn a_containers_credential_variables_are_stripped_from_panes_and_external_programs() {
976        for key in CONTAINER_CREDENTIAL_ENV {
977            assert!(should_strip(key), "{key} is stripped from a pane");
978            std::env::set_var(key, "/v2/credentials/test-only");
979        }
980        assert!(keys_to_strip().iter().any(|k| k == "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"));
981        let external = all_agentmux_keys();
982        for key in CONTAINER_CREDENTIAL_ENV {
983            assert!(external.iter().any(|k| k == key), "{key} is stripped from an external program");
984        }
985        let mut cmd = std::process::Command::new("noop");
986        for key in CONTAINER_CREDENTIAL_ENV {
987            cmd.env(key, "inherited");
988        }
989        sanitize_external_std_command(&mut cmd);
990        for key in CONTAINER_CREDENTIAL_ENV {
991            assert_eq!(cmd.get_envs().find(|(k, _)| *k == std::ffi::OsStr::new(key)).map(|(_, v)| v), Some(None), "{key} is removed from the command");
992        }
993        for key in CONTAINER_CREDENTIAL_ENV {
994            std::env::remove_var(key);
995        }
996    }
997
998    #[test]
999    fn keys_to_strip_reads_the_live_environment() {
1000        std::env::set_var("AGENTMUX_TEST_ONLY_LEAK", "1");
1001        assert!(keys_to_strip().iter().any(|k| k == "AGENTMUX_TEST_ONLY_LEAK"));
1002        std::env::remove_var("AGENTMUX_TEST_ONLY_LEAK");
1003    }
1004}