Skip to main content

agentmux_srv_core/backend/
mcp_folder_rule.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The MCP servers of a host agent whose folder a container agent can write.
5//!
6//! A host agent's CLI starts the MCP servers of its config on this computer. Where a container agent can write
7//! the agent's working folder or a folder beneath it, or has run in that folder, the host agent gets only the
8//! servers AgentMux writes:
9//!
10//! - its config is kept outside the folder (`mcp_config_file::host_config_path`), and the folder's own
11//!   `.mcp.json` is neither merged into it nor handed to a harness (`mcp_config_file::read_for_turn`);
12//! - a Claude Code turn is told to use that config alone (`agent_mcp_flag`), and the config names the
13//!   `agentmux` command by its path ([`with_the_command_by_path`]);
14//! - any other harness, and any agent whose CLI is started by a terminal, session or app-server controller,
15//!   is not started there ([`refusal`], [`turn_refusal`]): what it reads from its folder is its own, and
16//!   AgentMux has no switch for it;
17//! - the pane says which servers of the folder's file were left out ([`left_out`], `cli_notice`).
18//!
19//! "Can write" is asked of [`container_folders`](crate::backend::fs_ops::container_folders), as the Editor's
20//! language servers ask it; where that can't be told, the rule holds. "Has run in it" is a mark kept in the
21//! shared folder ([`mark`]), so the rule still holds when the agent is switched to the host, or another host agent
22//! is given the folder, a folder in it or a folder that holds it. A folder no container agent has to do with
23//! is not touched by any of this.
24
25use std::path::{Path, PathBuf};
26
27use agentmux_common::mcp_config_path as shared;
28use serde_json::Value;
29
30use crate::backend::fs_ops::container_folders::{holds_a_container_agents_folder, place, Place};
31use crate::backend::obj::{meta_get_string, MetaMapType};
32
33/// A test's own folder for the marks, set with its data home (`mcp_config_file::with_data_home`). A test
34/// build never reads or writes the real shared folder: with none set there are no marks.
35#[cfg(any(test, feature = "test-support"))]
36static MARKS_DIR_FOR_TEST: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None);
37
38/// Sets the folder a test's marks are kept in, and returns the one set before.
39#[cfg(any(test, feature = "test-support"))]
40pub fn set_marks_dir_for_test(dir: Option<PathBuf>) -> Option<PathBuf> {
41    std::mem::replace(&mut *MARKS_DIR_FOR_TEST.lock().unwrap_or_else(|e| e.into_inner()), dir)
42}
43
44/// The folder the marks are kept in: in the shared folder (`resolve_shared_container_agent_folders_dir`), so
45/// every version and channel of an install reads the same ones, an upgrade and the removal of an old version
46/// leave them, and so does the deletion of an agent. It is bound into no container. One file per spelling of
47/// a marked folder, named by that spelling's key; it holds the folder's spellings, one a line.
48fn marks_dir() -> Option<PathBuf> {
49    #[cfg(any(test, feature = "test-support"))]
50    return MARKS_DIR_FOR_TEST.lock().unwrap_or_else(|e| e.into_inner()).clone();
51    #[cfg(not(any(test, feature = "test-support")))]
52    return crate::registry::paths::resolve_shared_container_agent_folders_dir();
53}
54/// The most servers a pane row names, and the most characters of one name: they are read from the folder's
55/// own file.
56const MOST_NAMES: usize = 20;
57const LONGEST_NAME: usize = 64;
58
59fn expanded(work_dir: &str) -> String {
60    crate::backend::blockcontroller::core::expand_home_dir(work_dir)
61}
62
63/// The spellings `expanded` is compared under: as written and as the filesystem names it, so one folder
64/// written another way (letter case and a trailing separator on Windows, a link or junction to it) is the
65/// same folder here.
66fn spellings(expanded: &str) -> Vec<String> {
67    shared::spellings(Path::new(expanded))
68}
69
70fn mark_file(spelling: &str) -> Option<PathBuf> {
71    Some(marks_dir()?.join(shared::spelling_key(spelling)))
72}
73
74/// Record that a container agent runs with `work_dir` as its folder. The mark stays: from now on a host agent
75/// in that folder, in one beneath it or in one that holds it gets only the servers AgentMux writes.
76/// Best-effort; a failure is logged.
77pub fn mark(work_dir: &str) {
78    if work_dir.trim().is_empty() {
79        return;
80    }
81    let all = spellings(&expanded(work_dir));
82    let text = all.join("\n");
83    for path in all.iter().filter_map(|spelling| mark_file(spelling)) {
84        if path.is_file() {
85            continue;
86        }
87        // Whole or not at all: a reader in another AgentMux never sees half a mark.
88        let half = path.with_extension(format!("{}.tmp", std::process::id()));
89        let written = path
90            .parent()
91            .map_or(Ok(()), std::fs::create_dir_all)
92            .and_then(|()| std::fs::write(&half, &text))
93            .and_then(|()| std::fs::rename(&half, &path));
94        if let Err(e) = written {
95            let _ = std::fs::remove_file(&half);
96            tracing::warn!(work_dir, error = %e, "the folder could not be marked as a container agent's");
97        }
98    }
99}
100
101/// [`mark`] the folder of an agent whose definition just changed from `old` to `new`, when that moved it from
102/// a container to the host: the folder was the container's until now. An agent with no folder of its own named
103/// is marked by its turns in the container.
104pub fn mark_when_moved_to_the_host(old: &crate::backend::storage::AgentDefinition, new: &crate::backend::storage::AgentDefinition) {
105    if old.runtime().is_container() && !new.runtime().is_container() {
106        mark(&old.working_directory);
107    }
108}
109
110/// Every spelling a mark records.
111fn marked_folders() -> Vec<String> {
112    let Some(entries) = marks_dir().and_then(|dir| std::fs::read_dir(dir).ok()) else {
113        return Vec::new();
114    };
115    entries
116        .flatten()
117        .filter(|entry| entry.path().extension().is_none())
118        .filter_map(|entry| std::fs::read_to_string(entry.path()).ok())
119        .flat_map(|text| text.lines().map(str::to_string).collect::<Vec<_>>())
120        .filter(|line| !line.is_empty())
121        .collect()
122}
123
124/// Whether `expanded` carries the mark, lies in a folder that does, or holds one that does.
125fn marked(expanded: &str) -> bool {
126    let asked = spellings(expanded);
127    if asked.iter().any(|spelling| mark_file(spelling).is_some_and(|path| path.is_file())) {
128        return true;
129    }
130    let recorded = marked_folders();
131    asked.iter().any(|a| recorded.iter().any(|r| shared::spelled_within(a, r) || shared::spelled_within(r, a)))
132}
133
134/// Whether a host agent in `work_dir` gets only the servers AgentMux writes: a container agent can write the
135/// folder or one beneath it, or has run in it, or that can't be told. Reads the disk and the store.
136pub fn holds_in(work_dir: &str) -> bool {
137    if work_dir.trim().is_empty() {
138        return false;
139    }
140    let dir = expanded(work_dir);
141    decided(&place(&dir), holds_a_container_agents_folder(&dir), marked(&dir))
142}
143
144/// The rule from its three answers: where the folder is, whether a container agent's folder lies beneath it,
145/// and whether it carries the mark. Anything but a plain host folder, with nothing beneath and no mark, has it.
146fn decided(place: &Place, holds_one: bool, marked: bool) -> bool {
147    !matches!(place, Place::Host) || holds_one || marked
148}
149
150/// The working folder of the host agent on a pane with `meta`, expanded, when the rule holds for it.
151pub fn folder_of(meta: &MetaMapType) -> Option<String> {
152    if crate::backend::runtime_adapter::RuntimeKind::of_block_meta(meta).is_container() {
153        return None;
154    }
155    let work_dir = meta_get_string(meta, "cmd:cwd", "");
156    holds_in(&work_dir).then(|| expanded(&work_dir))
157}
158
159/// The pane's harness as its meta names it: empty for a pane that is no agent's. A name no harness answers
160/// to is still an agent's, so it is refused like the rest.
161fn provider_of(meta: &MetaMapType) -> String {
162    meta_get_string(meta, "agentProvider", "").trim().to_string()
163}
164
165/// Why the agent on a pane with `meta` is not started on this computer by a controller that starts its CLI
166/// itself (a terminal agent, a session agent, an app-server agent): the rule holds for its folder, and nothing
167/// on that path keeps a CLI to AgentMux's config, whatever the harness. `None` for a container agent, for a
168/// pane that is no agent's, and for every other folder.
169pub fn refusal(meta: &MetaMapType) -> Option<String> {
170    if provider_of(meta).is_empty() {
171        return None;
172    }
173    folder_of(meta)?;
174    Some(REFUSAL.to_string())
175}
176
177/// `Err` with [`refusal`]'s reason when the agent on a pane with `meta` is not started on this computer: the
178/// first line of a controller's start whose CLI starts with it.
179pub fn not_refused(meta: &MetaMapType) -> Result<(), String> {
180    refusal(meta).map_or(Ok(()), Err)
181}
182
183/// Why a turn of the agent on a pane with `meta` is not started on this computer: as [`refusal`], except for
184/// Claude Code, whose turn goes on because the flags it is started with keep it to AgentMux's config
185/// (`agent_mcp_flag`). Asked only where those flags are added (`agent_runtime::with_runtime_flags`): the turn
186/// of a turn-based agent, and the start of its process ahead of a turn.
187pub fn turn_refusal(meta: &MetaMapType) -> Option<String> {
188    if crate::backend::providers::resolve_provider_alias(&provider_of(meta)) == "claude" {
189        return None;
190    }
191    refusal(meta).map(|_| TURN_REFUSAL.to_string())
192}
193
194/// Why a step of a workflow that runs an agent in `work_dir` is not started on this computer: the rule holds for
195/// the folder, and the step's Claude Code is started with no flags of AgentMux's, so nothing keeps it to AgentMux's
196/// settings, servers and instructions. `work_dir` is the folder the step starts in, as it is: the caller gives the
197/// working folder of the process when the step names none. `None` for every other folder.
198pub fn workflow_refusal(work_dir: &Path) -> Option<String> {
199    holds_in(&work_dir.to_string_lossy()).then(|| WORKFLOW_REFUSAL.to_string())
200}
201
202/// What a workflow step is told when [`workflow_refusal`] stops its agent.
203pub const WORKFLOW_REFUSAL: &str = "A container agent can write in this step's folder, or has run in it, so this step's agent is not started on this computer there: it can't be kept to the settings, servers and instructions set in AgentMux. Run the step where its agent runs in a container, or give it a folder no container agent can write.";
204
205/// What a pane is told when [`refusal`] stops its agent.
206pub const REFUSAL: &str = "A container agent can write in this agent's folder, or has run in it, so this agent is not started on this computer there: an agent that runs as a terminal or as a session can't be kept to the settings and MCP servers set in AgentMux. Run this agent in a container, or give it a folder no container agent can write.";
207
208/// What a pane is told when [`turn_refusal`] stops its agent's turn.
209pub const TURN_REFUSAL: &str = "A container agent can write in this agent's folder, or has run in it, so this agent is not started on this computer there: only Claude Code can be kept to the settings and MCP servers set in AgentMux. Run this agent in a container, or give it a folder no container agent can write.";
210
211/// Whether `exe` may be named as a command in the config of a host agent in the folder spelled `folder`: an
212/// absolute path that is not in that folder and that no container agent can write.
213fn outside(exe: &Path, folder: &[String]) -> bool {
214    let Some(parent) = exe.parent() else { return false };
215    exe.is_absolute()
216        && !shared::spellings(exe).iter().any(|e| folder.iter().any(|f| shared::spelled_within(e, f)))
217        && matches!(place(&parent.to_string_lossy()), Place::Host)
218}
219
220/// Whether `exe` may be named as a command to a host agent of `work_dir` ([`outside`]).
221pub fn is_outside(exe: &Path, work_dir: &str) -> bool {
222    outside(exe, &spellings(&expanded(work_dir)))
223}
224
225/// `config` (the text of an MCP config) with every command named by a path: the `agentmux` entry's is `exe`,
226/// and any other server's bare name is what `found` answers for it. An entry whose command has no such path
227/// is taken out, and its name is returned. A command already written as an absolute path stays when `allowed`
228/// says so of it (it is outside the folder and no container agent can write it), and is taken out as one with
229/// no path when not. A config that is not a JSON object with servers is returned as it is.
230fn by_path(config: &str, exe: Option<&Path>, found: &dyn Fn(&str) -> Option<PathBuf>, allowed: &dyn Fn(&Path) -> bool) -> (String, Vec<String>) {
231    let Ok(was) = serde_json::from_str::<Value>(config) else { return (config.to_string(), Vec::new()) };
232    let mut doc = was.clone();
233    let Some(servers) = doc.get_mut("mcpServers").and_then(Value::as_object_mut) else { return (config.to_string(), Vec::new()) };
234    let mut taken_out = Vec::new();
235    for (name, entry) in servers.iter_mut() {
236        let Some(entry) = entry.as_object_mut() else { continue };
237        let path = if name == "agentmux" {
238            exe.map(Path::to_path_buf)
239        } else {
240            match entry.get("command").and_then(Value::as_str) {
241                // A server reached over the network has no command to name.
242                None => continue,
243                Some(command) if Path::new(command).is_absolute() => Some(PathBuf::from(command)).filter(|path| allowed(path)),
244                Some(command) => found(command),
245            }
246        };
247        match path {
248            Some(path) => {
249                entry.insert("command".to_string(), Value::String(path.to_string_lossy().into_owned()));
250            }
251            None => taken_out.push(name.clone()),
252        }
253    }
254    for name in &taken_out {
255        servers.remove(name);
256    }
257    if doc == was {
258        return (config.to_string(), taken_out);
259    }
260    (serde_json::to_string_pretty(&doc).unwrap_or_else(|_| config.to_string()), taken_out)
261}
262
263/// The program a bare command name stands for on this computer, looked up on srv's own `PATH` and never in a
264/// working folder; `None` for a name with a folder in it (a relative path) or one that is not found.
265fn on_path(command: &str) -> Option<PathBuf> {
266    if command.contains(['/', '\\']) {
267        return None;
268    }
269    which::which_in(command, std::env::var_os("PATH"), std::env::temp_dir()).ok().filter(|path| path.is_absolute())
270}
271
272/// `config` (the text of a host agent's MCP config) as it is written for `work_dir`, a folder the rule holds
273/// for: the `agentmux` entry's command is the absolute path of the `agentmux-mcp` that ships with this
274/// install, never a name. Where no such file ships outside the folder, the entry is taken out: no server
275/// rather than one found by name.
276pub fn with_the_command_by_path(config: &str, work_dir: &str) -> String {
277    with_commands_by_path(config, work_dir).0
278}
279
280/// [`with_the_command_by_path`], and the same for every other server of the config: a server the person set
281/// with a bare command (`npx`, `uvx`) is named by the path that name has on this computer's `PATH`, outside
282/// the folder. A server whose command has no such path is taken out, and the names of those are returned
283/// (the `agentmux` entry is not among them: it is AgentMux's own).
284pub fn with_commands_by_path(config: &str, work_dir: &str) -> (String, Vec<String>) {
285    let folder = spellings(&expanded(work_dir));
286    let exe = crate::backend::mcp_rewrite::shipped_exe().filter(|exe| outside(exe, &folder));
287    if exe.is_none() {
288        tracing::warn!(work_dir, "no agentmux-mcp ships outside this folder: the agent's config is written without the agentmux server");
289    }
290    let (text, mut taken_out) = by_path(config, exe.as_deref(), &|command| on_path(command).filter(|path| outside(path, &folder)), &|path| outside(path, &folder));
291    taken_out.retain(|name| name != "agentmux");
292    if !taken_out.is_empty() {
293        tracing::warn!(work_dir, count = taken_out.len(), "MCP servers set with a command that has no path outside this folder are left out of the agent's config");
294    }
295    (text, taken_out)
296}
297
298/// Whether `config` (the text of an MCP config) names every command it has by an absolute path (a server
299/// reached over the network has none): what a host turn in a folder the rule holds for is given, and nothing
300/// else.
301pub fn names_the_command_by_path(config: &str) -> bool {
302    commands_all(config, &|command| Path::new(command).is_absolute())
303}
304
305/// [`names_the_command_by_path`], and every command is a path outside `work_dir` that no container agent can
306/// write ([`outside`]): what a host turn in a folder the rule holds for is given.
307pub fn names_every_command_outside(config: &str, work_dir: &str) -> bool {
308    let folder = spellings(&expanded(work_dir));
309    commands_all(config, &|command| outside(Path::new(command), &folder))
310}
311
312/// Whether every server of `config` that has a command has one `ok` says yes to; false for text that is not a
313/// config.
314fn commands_all(config: &str, ok: &dyn Fn(&str) -> bool) -> bool {
315    let Ok(doc) = serde_json::from_str::<Value>(config) else { return false };
316    let Some(servers) = doc.get("mcpServers").and_then(Value::as_object) else { return true };
317    servers.values().all(|entry| match entry.get("command") {
318        None => true,
319        Some(command) => command.as_str().is_some_and(ok),
320    })
321}
322
323/// The text of `folder`'s own `.mcp.json` for a host agent that is defined from the folder (an import), which
324/// keeps the folder's servers as its own. `None` where the rule holds: the agent takes no server from the file.
325pub fn config_to_import(folder: &Path) -> Option<String> {
326    if holds_in(&folder.to_string_lossy()) {
327        return None;
328    }
329    std::fs::read_to_string(folder.join(crate::backend::mcp_config_file::MCP_JSON)).ok()
330}
331
332/// `name` as a pane row shows it: no control characters, and no longer than a name needs to be.
333fn shown(name: &str) -> String {
334    name.chars().filter(|c| !c.is_control()).take(LONGEST_NAME).collect()
335}
336
337/// The names of the `mcpServers` of `config` (a `.mcp.json`'s text).
338fn server_names(config: &str) -> Vec<String> {
339    serde_json::from_str::<Value>(config)
340        .ok()
341        .and_then(|doc| doc.get("mcpServers").and_then(Value::as_object).map(|servers| servers.keys().cloned().collect()))
342        .unwrap_or_default()
343}
344
345/// The servers of `folder`'s own `.mcp.json` that the agent's config (`ours`, its text) does not have: the
346/// ones a host agent there is not given. By name, sorted, at most [`MOST_NAMES`]. Only reads the file.
347pub fn left_out(folder: &str, ours: Option<&str>) -> Vec<String> {
348    let Ok(theirs) = std::fs::read_to_string(Path::new(folder).join(crate::backend::mcp_config_file::MCP_JSON)) else {
349        return Vec::new();
350    };
351    let ours = ours.map(server_names).unwrap_or_default();
352    let mut names: Vec<String> = server_names(&theirs).into_iter().filter(|name| !ours.contains(name)).map(|name| shown(&name)).filter(|name| !name.is_empty()).collect();
353    names.sort();
354    names.dedup();
355    names.truncate(MOST_NAMES);
356    names
357}
358
359#[cfg(test)]
360mod tests {
361    use super::*;
362    use crate::backend::fs_ops::container_folders::add_for_test;
363    use crate::backend::mcp_config_file::with_data_home;
364    use serde_json::json;
365
366    fn pane(mode: &str, provider: &str, cwd: &Path) -> MetaMapType {
367        [("agentMode", json!(mode)), ("agentProvider", json!(provider)), ("cmd:cwd", json!(cwd.to_string_lossy()))]
368            .into_iter()
369            .map(|(k, v)| (k.to_string(), v))
370            .collect()
371    }
372
373    #[test]
374    fn the_rule_holds_where_a_container_agent_can_write_and_nowhere_else() {
375        let (data, bound, own) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
376        add_for_test(bound.path(), "agentmux-rule-a", "/workspace");
377        with_data_home(data.path(), || {
378            assert!(holds_in(&bound.path().to_string_lossy()), "the folder the agent can write");
379            assert!(holds_in(&bound.path().join("src").to_string_lossy()), "a folder inside it");
380            assert!(!holds_in(&own.path().to_string_lossy()), "a folder no container agent has to do with");
381            assert!(!holds_in(""), "no folder, no rule");
382        });
383    }
384
385    #[test]
386    fn the_rule_holds_while_the_folders_place_cant_be_told() {
387        assert!(decided(&Place::Unknown, false, false), "unknown: the rule holds");
388        assert!(!decided(&Place::Host, false, false));
389        assert!(decided(&Place::Host, true, false) && decided(&Place::Host, false, true));
390    }
391
392    #[test]
393    fn the_rule_holds_for_a_root_that_holds_a_container_agents_folder() {
394        let (data, root) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
395        let inner = root.path().join("agents").join("aria");
396        std::fs::create_dir_all(&inner).unwrap();
397        add_for_test(&inner, "agentmux-rule-b", "/workspace");
398        with_data_home(data.path(), || {
399            assert!(holds_in(&root.path().to_string_lossy()), "a container agent's folder lies beneath it");
400            assert!(holds_in(&root.path().join("agents").to_string_lossy()));
401        });
402    }
403
404    #[test]
405    fn a_folder_a_container_agent_ran_in_keeps_the_rule() {
406        let (data, was) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
407        let dir = was.path().to_string_lossy().into_owned();
408        with_data_home(data.path(), || {
409            assert!(!holds_in(&dir));
410            mark(&dir);
411            mark(&dir);
412            assert!(holds_in(&dir), "no container has it now, and the rule still holds");
413            // Kept in the marks' own folder: not in the marked folder, and not in the folder of a relocated
414            // config, which a container is given (read-only).
415            let kept = mark_file(&spellings(&dir)[0]).unwrap();
416            assert!(kept.is_file() && !kept.starts_with(was.path()), "{kept:?}");
417            let given_to_a_container = crate::backend::mcp_config_file::relocated_dir(&dir).expect("a project's config folder");
418            assert!(!kept.starts_with(&given_to_a_container), "{given_to_a_container:?}");
419            assert!(!crate::backend::mcp_config_file::host_config_path(&dir).starts_with(&given_to_a_container), "nor is the host agent's config");
420        });
421    }
422
423    /// The mark is not one version's: made while one version's data root is in use, it holds under another's,
424    /// and neither data root has it.
425    #[test]
426    fn a_mark_made_by_one_version_holds_for_another() {
427        let (shared_dir, one, other, was) =
428            (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
429        let dir = was.path().to_string_lossy().into_owned();
430        fn files_under(root: &Path) -> usize {
431            std::fs::read_dir(root).map_or(0, |entries| {
432                entries.flatten().map(|e| if e.path().is_dir() { files_under(&e.path()) } else { 1 }).sum()
433            })
434        }
435        with_data_home(one.path(), || {
436            let before = set_marks_dir_for_test(Some(shared_dir.path().join("container-agent-folders")));
437            mark(&dir);
438            // Another version of the same install: its own data root, the same shared folder.
439            std::env::set_var("AGENTMUX_DATA_HOME", other.path());
440            let holds = holds_in(&dir);
441            set_marks_dir_for_test(before);
442            assert!(holds, "the mark is read from the shared folder");
443            assert_eq!(files_under(one.path()) + files_under(other.path()), 0, "no version's data root holds a mark");
444            assert_eq!(files_under(shared_dir.path()), spellings(&dir).len());
445        });
446    }
447
448    #[test]
449    fn only_a_host_agent_is_refused_and_only_there_and_a_turn_lets_claude_code_alone_through() {
450        let (data, bound, own) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
451        add_for_test(bound.path(), "agentmux-rule-c", "/workspace");
452        with_data_home(data.path(), || {
453            for provider in ["codex", "gemini", "opencode"] {
454                assert_eq!(turn_refusal(&pane("host", provider, bound.path())).as_deref(), Some(TURN_REFUSAL), "{provider}");
455                assert_eq!(turn_refusal(&pane("host", provider, own.path())), None, "{provider} in a folder of its own");
456                assert_eq!(turn_refusal(&pane("container", provider, bound.path())), None, "{provider} in the container");
457            }
458            assert_eq!(turn_refusal(&pane("host", "claude", bound.path())), None, "a Claude Code turn is kept to AgentMux's config instead");
459            // Where the CLI starts with its controller there are no such flags: every harness is refused.
460            for provider in ["claude", "codex", "gemini"] {
461                assert_eq!(refusal(&pane("host", provider, bound.path())).as_deref(), Some(REFUSAL), "{provider}");
462                assert_eq!(not_refused(&pane("host", provider, own.path())), Ok(()), "{provider} in a folder of its own");
463                assert_eq!(refusal(&pane("container", provider, bound.path())), None, "{provider} in the container");
464            }
465            assert_eq!(refusal(&pane("host", "", bound.path())), None, "a pane that is no agent's");
466            assert_eq!(turn_refusal(&pane("host", "", bound.path())), None);
467            assert_eq!(folder_of(&pane("host", "claude", bound.path())).map(PathBuf::from), Some(PathBuf::from(expanded(&bound.path().to_string_lossy()))));
468            assert_eq!(folder_of(&pane("container", "claude", bound.path())), None);
469        });
470    }
471
472    #[test]
473    fn a_workflow_step_is_refused_in_each_state_of_the_folder_the_rule_knows_and_nowhere_else() {
474        let (data, bound, own, holder, was) = (
475            tempfile::tempdir().unwrap(),
476            tempfile::tempdir().unwrap(),
477            tempfile::tempdir().unwrap(),
478            tempfile::tempdir().unwrap(),
479            tempfile::tempdir().unwrap(),
480        );
481        add_for_test(bound.path(), "agentmux-rule-wf-a", "/workspace");
482        let beneath = holder.path().join("agent");
483        std::fs::create_dir_all(&beneath).unwrap();
484        add_for_test(&beneath, "agentmux-rule-wf-b", "/workspace");
485        with_data_home(data.path(), || {
486            let marks = tempfile::tempdir().unwrap();
487            let before = set_marks_dir_for_test(Some(marks.path().to_path_buf()));
488            assert_eq!(workflow_refusal(bound.path()).as_deref(), Some(WORKFLOW_REFUSAL), "a folder a container agent can write");
489            assert_eq!(workflow_refusal(&beneath.join("sub")).as_deref(), Some(WORKFLOW_REFUSAL), "a folder in one");
490            assert_eq!(workflow_refusal(holder.path()).as_deref(), Some(WORKFLOW_REFUSAL), "a folder that holds one");
491            assert_eq!(workflow_refusal(own.path()), None, "a folder no container agent has to do with");
492            assert_eq!(workflow_refusal(was.path()), None, "before it carries the mark");
493            mark(&was.path().to_string_lossy());
494            assert_eq!(workflow_refusal(was.path()).as_deref(), Some(WORKFLOW_REFUSAL), "a folder a container agent has run in");
495            assert_eq!(workflow_refusal(&was.path().join("deeper")).as_deref(), Some(WORKFLOW_REFUSAL), "a folder in it");
496            set_marks_dir_for_test(before);
497        });
498    }
499
500    #[test]
501    fn the_servers_left_out_are_the_folders_own_by_name() {
502        let folder = tempfile::tempdir().unwrap();
503        let dir = folder.path().to_string_lossy().into_owned();
504        assert!(left_out(&dir, None).is_empty(), "no file, nothing left out");
505        let long = "n".repeat(200);
506        let theirs = json!({ "mcpServers": { "agentmux": { "command": "other" }, "zeta": {}, "alpha\u{7}": {}, long.as_str(): {} } });
507        std::fs::write(folder.path().join(".mcp.json"), theirs.to_string()).unwrap();
508        let ours = r#"{"mcpServers":{"agentmux":{"command":"agentmux-mcp"},"git":{}}}"#;
509        assert_eq!(left_out(&dir, Some(ours)), vec!["alpha".to_string(), "n".repeat(LONGEST_NAME), "zeta".to_string()]);
510        assert_eq!(left_out(&dir, None).len(), 4, "with no config of its own, every server of the file is left out");
511        std::fs::write(folder.path().join(".mcp.json"), "not json").unwrap();
512        assert!(left_out(&dir, Some(ours)).is_empty());
513        let many: serde_json::Map<String, Value> = (0..40).map(|i| (format!("s{i:02}"), json!({}))).collect();
514        std::fs::write(folder.path().join(".mcp.json"), json!({ "mcpServers": many }).to_string()).unwrap();
515        assert_eq!(left_out(&dir, Some(ours)).len(), MOST_NAMES);
516    }
517
518    #[test]
519    fn an_agent_moved_from_a_container_to_the_host_leaves_its_folder_marked() {
520        use crate::backend::storage::agents::test_agent_def;
521        let (data, moved, stays, never) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
522        let def = |agent_type: &str, folder: &Path| {
523            let mut def = test_agent_def("a-1", "Aria", "claude", agent_type, 1, "");
524            def.working_directory = folder.to_string_lossy().into_owned();
525            def
526        };
527        with_data_home(data.path(), || {
528            mark_when_moved_to_the_host(&def("container", moved.path()), &def("host", moved.path()));
529            assert!(holds_in(&moved.path().to_string_lossy()), "the folder was the container's until now");
530            mark_when_moved_to_the_host(&def("container", stays.path()), &def("container", stays.path()));
531            mark_when_moved_to_the_host(&def("host", never.path()), &def("host", never.path()));
532            mark_when_moved_to_the_host(&def("host", never.path()), &def("container", never.path()));
533            assert!(!holds_in(&stays.path().to_string_lossy()), "an agent that stays in its container marks its folder by its turns, not here");
534            assert!(!holds_in(&never.path().to_string_lossy()));
535        });
536    }
537
538    #[test]
539    fn an_import_takes_the_folders_servers_only_where_no_container_agent_has_to_do_with_it() {
540        let (data, own, bound, ran) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
541        let config = r#"{"mcpServers":{"theirs":{"command":"theirs-mcp"}}}"#;
542        for folder in [&own, &bound, &ran] {
543            std::fs::write(folder.path().join(".mcp.json"), config).unwrap();
544        }
545        add_for_test(bound.path(), "agentmux-rule-d", "/workspace");
546        with_data_home(data.path(), || {
547            mark(&ran.path().to_string_lossy());
548            assert_eq!(config_to_import(own.path()).as_deref(), Some(config), "as before");
549            assert_eq!(config_to_import(bound.path()), None, "a container agent can write it");
550            assert_eq!(config_to_import(ran.path()), None, "a container agent ran in it");
551        });
552    }
553
554    #[cfg(unix)]
555    fn link_dir(link: &Path, target: &Path) {
556        std::os::unix::fs::symlink(target, link).unwrap();
557    }
558
559    /// One mark, and the folder is found however it is written, and so are the folders in it and around it.
560    #[test]
561    fn the_mark_is_found_however_the_folder_is_written_and_for_folders_in_it_and_around_it() {
562        let (data, tmp) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
563        let was = tmp.path().join("Work").join("Agent");
564        let beside = tmp.path().join("Work").join("Other");
565        std::fs::create_dir_all(was.join("src")).unwrap();
566        std::fs::create_dir_all(&beside).unwrap();
567        let held = |folder: &Path| holds_in(&folder.to_string_lossy());
568        with_data_home(data.path(), || {
569            assert!(!held(&was) && !held(&was.join("src")) && !held(&tmp.path().join("Work")));
570            mark(&was.to_string_lossy());
571            assert!(held(&was));
572            assert!(held(&PathBuf::from(format!("{}{}", was.display(), std::path::MAIN_SEPARATOR))), "a trailing separator");
573            assert!(held(&was.join("src").join("..")), "a way round");
574            assert!(held(&was.join("src")), "a folder in it");
575            assert!(held(&was.join("not").join("there").join("yet")), "one in it that does not exist yet");
576            assert!(held(&tmp.path().join("Work")), "a folder that holds it");
577            assert!(!held(&beside), "a folder beside it");
578            #[cfg(windows)]
579            assert!(held(Path::new(&was.to_string_lossy().to_uppercase())), "another letter case");
580            #[cfg(unix)]
581            {
582                let link = tmp.path().join("link");
583                link_dir(&link, &was);
584                assert!(held(&link) && held(&link.join("src")), "a link to it");
585            }
586        });
587    }
588
589    /// The mark made through a link is the folder's own.
590    #[cfg(unix)]
591    #[test]
592    fn a_folder_marked_through_a_link_is_marked_itself() {
593        let (data, tmp) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
594        let real = tmp.path().join("real");
595        std::fs::create_dir_all(&real).unwrap();
596        let link = tmp.path().join("link");
597        link_dir(&link, &real);
598        with_data_home(data.path(), || {
599            mark(&link.to_string_lossy());
600            assert!(holds_in(&real.to_string_lossy()) && holds_in(&link.to_string_lossy()));
601        });
602    }
603
604    /// The `agentmux` command of a host agent's config there is a path outside the folder, never a name,
605    /// with a file of that name in the folder and beneath it.
606    #[test]
607    fn the_agentmux_command_is_named_by_a_path_outside_the_folder_or_not_at_all() {
608        let (folder, tools, bound) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
609        let name = if cfg!(windows) { "agentmux-mcp.exe" } else { "agentmux-mcp" };
610        let (planted, shipped, writable) = (folder.path().join(name), tools.path().join(name), bound.path().join(name));
611        for file in [&planted, &shipped, &writable] {
612            std::fs::write(file, b"x").unwrap();
613        }
614        add_for_test(bound.path(), "agentmux-rule-e", "/tools");
615        let config = r#"{"mcpServers":{"agentmux":{"type":"stdio","command":"agentmux-mcp","args":[],"env":{"AGENTMUX_AGENT_ID":"aria"}},"git":{"command":"git-mcp"}}}"#;
616        let the_folder = spellings(&folder.path().to_string_lossy());
617
618        assert!(outside(&shipped, &the_folder), "the one that ships with the install");
619        assert!(!outside(&planted, &the_folder), "a file of that name in the folder");
620        assert!(!outside(&folder.path().join("bin").join(name), &the_folder), "or beneath it");
621        assert!(!outside(&writable, &the_folder), "one a container agent can write");
622        assert!(!outside(Path::new(name), &the_folder), "a bare name");
623
624        // The person's own server, set with a bare name: `git-mcp` is on the PATH here, `gone-mcp` is not.
625        let git = tools.path().join(if cfg!(windows) { "git-mcp.exe" } else { "git-mcp" });
626        let found = |command: &str| (command == "git-mcp").then(|| git.clone());
627        let config = &config.replace(r#""git":{"command":"git-mcp"}"#, r#""git":{"command":"git-mcp","args":["--x"]},"gone":{"command":"gone-mcp"},"web":{"type":"http","url":"https://example.invalid/mcp"}"#);
628
629        let allowed = |path: &Path| outside(path, &the_folder);
630        let (text, taken_out) = by_path(config, Some(&shipped), &found, &allowed);
631        let written: Value = serde_json::from_str(&text).unwrap();
632        assert_eq!(written["mcpServers"]["agentmux"]["command"], json!(shipped.to_string_lossy()));
633        assert_eq!(written["mcpServers"]["agentmux"]["env"]["AGENTMUX_AGENT_ID"], "aria", "the rest of the entry stays");
634        assert_eq!(written["mcpServers"]["git"]["command"], json!(git.to_string_lossy()), "a bare name becomes the path it has on the PATH");
635        assert_eq!(written["mcpServers"]["git"]["args"], json!(["--x"]));
636        assert!(written["mcpServers"].get("gone").is_none(), "a name with no path is not kept as a name");
637        assert_eq!(taken_out, vec!["gone".to_string()]);
638        assert_eq!(written["mcpServers"]["web"]["url"], "https://example.invalid/mcp", "a server with no command stays");
639        assert!(names_the_command_by_path(&text));
640
641        let (text, taken_out) = by_path(config, None, &found, &allowed);
642        let without: Value = serde_json::from_str(&text).unwrap();
643        assert!(without["mcpServers"].get("agentmux").is_none(), "with none that ships outside the folder: no entry, not a name");
644        assert_eq!(taken_out, vec!["agentmux".to_string(), "gone".to_string()]);
645        assert!(names_the_command_by_path(&text));
646
647        // A command the person wrote as a path outside the folder stays; so does a config with nothing to change.
648        let own = tools.path().join(if cfg!(windows) { "own-server.exe" } else { "own-server" });
649        let by_hand = &json!({ "mcpServers": { "own": { "command": own.to_string_lossy() } } }).to_string();
650        assert_eq!(by_path(by_hand, Some(&shipped), &found, &allowed), (by_hand.clone(), Vec::new()));
651        // One written as a path in the folder, beneath it, or in a folder a container agent can write is not a
652        // path outside: it is taken out and named, like a bare name with none.
653        let inside = json!({ "mcpServers": {
654            "in-folder": { "command": planted.to_string_lossy() },
655            "beneath": { "command": folder.path().join("bin").join("srv").to_string_lossy() },
656            "writable": { "command": writable.to_string_lossy() },
657            "own": { "command": own.to_string_lossy() },
658        } })
659        .to_string();
660        let (text, mut taken_out) = by_path(&inside, Some(&shipped), &found, &allowed);
661        taken_out.sort();
662        let written: Value = serde_json::from_str(&text).unwrap();
663        assert_eq!(taken_out, vec!["beneath".to_string(), "in-folder".to_string(), "writable".to_string()]);
664        assert_eq!(written["mcpServers"].as_object().unwrap().keys().collect::<Vec<_>>(), vec!["own"]);
665        let dir = folder.path().to_string_lossy().into_owned();
666        assert!(names_every_command_outside(&text, &dir));
667        assert!(!names_every_command_outside(&inside, &dir), "a turn is not given a config that names one");
668        assert!(!names_every_command_outside(config, &dir), "nor one with a bare name");
669
670        assert!(!names_the_command_by_path(config), "a bare name is not handed to a turn there");
671        assert!(!names_the_command_by_path(r#"{"mcpServers":{"agentmux":{"command":"/abs/agentmux-mcp"},"git":{"command":"git-mcp"}}}"#), "nor is any other server's");
672        assert!(!names_the_command_by_path("not json"));
673        assert_eq!(by_path("not json", Some(&shipped), &found, &allowed).0, "not json");
674        assert_eq!(on_path("bin/tool"), None, "a relative path is not looked up");
675        assert_eq!(on_path("no-such-program-agentmux-test"), None);
676
677        // As a writer calls it: whatever ships on this computer, the result never names the command barely,
678        // and never by a path in the folder.
679        let data = tempfile::tempdir().unwrap();
680        with_data_home(data.path(), || {
681            let dir = folder.path().to_string_lossy().into_owned();
682            mark(&dir);
683            let text = with_the_command_by_path(config, &dir);
684            assert!(names_the_command_by_path(&text), "{text}");
685            let doc: Value = serde_json::from_str(&text).unwrap();
686            if let Some(command) = doc.pointer("/mcpServers/agentmux/command").and_then(Value::as_str) {
687                assert!(outside(Path::new(command), &the_folder), "{command}");
688            }
689        });
690    }
691
692    /// A container agent in its own folder, which is marked from its first turn: every place that finds a
693    /// host agent's config outside the folder leaves the container agent's alone or never runs for it.
694    #[test]
695    fn a_container_agent_in_its_own_marked_folder_keeps_the_file_in_its_folder() {
696        let (data, folder) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
697        let dir = folder.path().to_string_lossy().into_owned();
698        add_for_test(folder.path(), "agentmux-rule-f", "/workspace");
699        let in_folder = folder.path().join(".mcp.json");
700        let own = r#"{"mcpServers":{"agentmux":{"command":"agentmux-mcp","env":{"AGENTMUX_AGENT_ID":"loap-loap-2"}}}}"#;
701        std::fs::write(&in_folder, own).unwrap();
702        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
703        with_data_home(data.path(), || {
704            mark(&dir);
705            let container = pane("container", "claude", folder.path());
706            assert_eq!(folder_of(&container), None, "the rule is a host agent's");
707            assert_eq!(refusal(&container), None);
708            assert_eq!(turn_refusal(&container), None);
709
710            // The spawn environment names no host config for it.
711            let mut env = std::collections::HashMap::from([("AGENTMUX_MCP_CONFIG".to_string(), "stale".to_string())]);
712            crate::backend::spawn_env::block_identity::carry_agent_workdir_env(&mut env, &container);
713            assert!(!env.contains_key("AGENTMUX_MCP_CONFIG"), "{env:?}");
714            // The spawn's realign leaves its file as it is and writes none outside.
715            crate::backend::mcp_json_identity::realign_workspace_mcp_json(&store, &dir, "container", "loap-2");
716            assert_eq!(std::fs::read_to_string(&in_folder).unwrap(), own);
717            // Its turn gets no flag that points away from its folder.
718            let flags = crate::backend::agent_runtime::with_runtime_flags(&container, vec!["-p".to_string()]);
719            assert!(!flags.iter().any(|flag| flag.contains("mcp-config")), "{flags:?}");
720            // Its own config path is the file in its folder, and nothing was written for a host agent.
721            assert_eq!(crate::backend::mcp_config_file::relocated_path(&dir).is_none(), agentmux_common::mcp_config_path::is_agent_owned_workdir(folder.path()));
722            assert!(!crate::backend::mcp_config_file::host_config_path(&dir).exists(), "no host config was made by any of this");
723        });
724    }
725}