1use 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#[cfg(any(test, feature = "test-support"))]
36static MARKS_DIR_FOR_TEST: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None);
37
38#[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
44fn 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}
54const 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
63fn 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
74pub 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 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
101pub 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
110fn 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
124fn 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
134pub 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
144fn decided(place: &Place, holds_one: bool, marked: bool) -> bool {
147 !matches!(place, Place::Host) || holds_one || marked
148}
149
150pub 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
159fn provider_of(meta: &MetaMapType) -> String {
162 meta_get_string(meta, "agentProvider", "").trim().to_string()
163}
164
165pub 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
177pub fn not_refused(meta: &MetaMapType) -> Result<(), String> {
180 refusal(meta).map_or(Ok(()), Err)
181}
182
183pub 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
194pub fn workflow_refusal(work_dir: &Path) -> Option<String> {
199 holds_in(&work_dir.to_string_lossy()).then(|| WORKFLOW_REFUSAL.to_string())
200}
201
202pub 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
205pub 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
208pub 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
211fn 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
220pub fn is_outside(exe: &Path, work_dir: &str) -> bool {
222 outside(exe, &spellings(&expanded(work_dir)))
223}
224
225fn 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 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
263fn 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
272pub fn with_the_command_by_path(config: &str, work_dir: &str) -> String {
277 with_commands_by_path(config, work_dir).0
278}
279
280pub 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
298pub fn names_the_command_by_path(config: &str) -> bool {
302 commands_all(config, &|command| Path::new(command).is_absolute())
303}
304
305pub 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
312fn 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
323pub 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
332fn shown(name: &str) -> String {
334 name.chars().filter(|c| !c.is_control()).take(LONGEST_NAME).collect()
335}
336
337fn 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
345pub 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 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 #[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 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 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 #[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 #[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 #[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 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 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 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 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 #[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 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 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 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 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}