Skip to main content

agentmux_srv_core/backend/container/
mounts.rs

1//! The mounts of a container agent's home: the per-agent volume, the bound account's
2//! credentials, and the agent's Personal Memory folder.
3
4pub mod caches;
5pub mod credential_mode;
6pub mod dev_exec;
7pub mod host_name;
8pub mod read_exec;
9pub mod writable;
10pub(super) use self::host_name::host_name_for_new_container;
11
12use bollard::exec::{CreateExecOptions, StartExecOptions, StartExecResults};
13use bollard::models::{Mount, MountTypeEnum};
14use futures_util::StreamExt as _;
15
16use super::{
17    normalize_host_path, ContainerManager, ContainerMountSpec, CLAUDE_CREDENTIALS_FILE, CONTAINER_CLAUDE_DIR,
18    CONTAINER_WORKSPACE_DIR,
19};
20
21/// Where Claude in the container reads and writes the agent's Personal Memory: the folder
22/// it names for its working directory, [`CONTAINER_WORKSPACE_DIR`], under its config dir.
23pub(crate) fn container_memory_dir() -> String {
24    let project = crate::backend::claude_layout::project_dir_name(CONTAINER_WORKSPACE_DIR);
25    format!("{CONTAINER_CLAUDE_DIR}/projects/{project}/memory")
26}
27
28/// The folder a native session of this agent keeps its Personal Memory in, for
29/// [`ContainerMountSpec::memory_host_dir`]: created if it is not there yet (Docker refuses a
30/// bind whose source is missing) and resolved through symlinks on Linux and macOS, so the
31/// daemon is given the real directory. `None` when `working_dir` is empty.
32pub(crate) fn personal_memory_host_dir(claude_config_dir: Option<&str>, working_dir: &str) -> Option<String> {
33    if working_dir.is_empty() {
34        return None;
35    }
36    // The workspace of a container agent, whether or not its pane is in the store yet: the folder is named
37    // after the workspace's own path, never after anything in it.
38    let workspace = crate::backend::base::expand_home_dir_safe(working_dir);
39    let written = |dir: &std::path::Path| {
40        dir.starts_with(&workspace) || crate::backend::fs_ops::container_folders::written_by_a_container_agent(dir)
41    };
42    let dir = crate::backend::memory::native_files::memory_dir_for_cwd_with(claude_config_dir.unwrap_or(""), working_dir, &written);
43    if let Err(e) = std::fs::create_dir_all(&dir) {
44        tracing::warn!(dir = %dir.display(), error = %e, "container agent: can't create the Personal Memory folder; not mounting it");
45        return None;
46    }
47    let dir = if cfg!(windows) { dir } else { dir.canonicalize().unwrap_or(dir) };
48    Some(dir.to_string_lossy().into_owned())
49}
50
51/// Whether the agent is pointed at the gateway's key route (an API-key account). Decided from where its requests go, never
52/// from whether its token is still live: a token that has ended must not make the agent look like a plan agent.
53fn on_the_key_route(env_vars: &std::collections::HashMap<String, String>) -> bool {
54    env_vars.get("ANTHROPIC_BASE_URL").is_some_and(|url| super::key_route::names_key_route(url))
55}
56
57impl ContainerMountSpec {
58    /// The host side of every folder this spec binds into the container, besides the container's own copy of the login.
59    pub fn bound_host_dirs(&self) -> Vec<String> {
60        [
61            &self.workspace_host_dir,
62            &self.memory_host_dir,
63            &self.mcp_config_host_dir,
64            &self.github_hooks_host_dir,
65            &self.aws_config_host_dir,
66            &self.aws_tools_host_dir,
67        ]
68        .into_iter()
69        .flatten()
70        .cloned()
71        .collect()
72    }
73
74    /// What an agent started with `env_vars` in `working_dir` gets mounted: its bound
75    /// account's credentials, its workspace, and, for an agent with a Claude config dir,
76    /// its Personal Memory. A `~/...` working dir (what `agent.open` records for an agent with
77    /// none of its own) is expanded here, against the AgentMux home an isolated instance
78    /// overrides: Docker takes only an absolute bind source.
79    pub fn for_agent(env_vars: &std::collections::HashMap<String, String>, working_dir: &str) -> Self {
80        let working_dir = crate::backend::base::expand_home_dir_safe(working_dir).to_string_lossy().into_owned();
81        let working_dir = working_dir.as_str();
82        let config_dir = env_vars.get("CLAUDE_CONFIG_DIR").map(String::as_str).filter(|d| !d.is_empty());
83        // An agent on an API key has no login of its own: the folder it runs in is the provider's default one, and whatever
84        // sign-in that holds is the person's, never the container's. Its memory folder is still shared.
85        let login_dir = config_dir.filter(|_| !on_the_key_route(env_vars));
86        Self {
87            // Never the account's own file: the start of the container gives it a copy of its own (`keychain_credentials`).
88            claude_config_host_dir: None,
89            staged_login_config_dir: login_dir
90                .filter(|dir| cfg!(target_os = "macos") || super::credentials_dir_if_file_backed(dir).is_some())
91                .map(str::to_string),
92            workspace_host_dir: Some(working_dir.to_string()).filter(|d| !d.is_empty()),
93            memory_host_dir: config_dir.and_then(|dir| personal_memory_host_dir(Some(dir), working_dir)),
94            mcp_config_host_dir: crate::backend::mcp_config_file::relocated_path(working_dir)
95                .filter(|path| path.is_file())
96                .and_then(|path| path.parent().map(|dir| dir.to_string_lossy().into_owned())),
97            github_hooks_host_dir: crate::identity::github_tokens::container_git_hooks().map(|d| d.to_string_lossy().into_owned()),
98            aws_config_host_dir: crate::identity::aws_broker::container::config_dir(),
99            aws_tools_host_dir: env_vars.get("AGENTMUX_AGENT_ID").and_then(|slug| crate::identity::aws_broker::tools::config_dir_for(slug)),
100            limits: Default::default(),
101        }
102    }
103}
104
105impl ContainerManager {
106    /// The daemon connection, for services that sit beside the container manager (the dev relay).
107    pub(crate) fn docker(&self) -> &bollard::Docker {
108        &self.inner.docker
109    }
110
111    /// Hands the folders above the memory mount to the user the container runs turns as.
112    /// Docker creates them as root inside the per-agent volume, and Claude could not then
113    /// write its session files into `projects/<workspace>/`. Best-effort: a failure, or a
114    /// non-zero exit, is logged and the container carries on.
115    pub(super) async fn own_memory_parents(&self, container_name: &str, spec: &ContainerMountSpec) {
116        if spec.memory_host_dir.as_deref().is_none_or(str::is_empty) {
117            return;
118        }
119        let memory = container_memory_dir();
120        let Some(project) = memory.strip_suffix("/memory") else { return };
121        let Some(projects) = project.rsplit_once('/').map(|(p, _)| p) else { return };
122        let Some((uid, gid)) = self.exec_identity(container_name).await else {
123            tracing::warn!(container = container_name, "container agent: can't tell which user runs turns; the memory folder's parents stay root-owned");
124            return;
125        };
126        let script = format!("chown {uid}:{gid} '{projects}' '{project}'");
127        let outcome = async {
128            let exec = self
129                .inner
130                .docker
131                .create_exec(
132                    container_name,
133                    CreateExecOptions {
134                        user: Some("root"),
135                        cmd: Some(vec!["sh", "-c", &script]),
136                        attach_stdout: Some(true),
137                        attach_stderr: Some(true),
138                        ..Default::default()
139                    },
140                )
141                .await?;
142            if let StartExecResults::Attached { mut output, .. } = self
143                .inner
144                .docker
145                .start_exec(&exec.id, Some(StartExecOptions { detach: false, ..Default::default() }))
146                .await?
147            {
148                while output.next().await.is_some() {}
149            }
150            self.inspect_exec(&exec.id).await
151        }
152        .await;
153        match outcome {
154            Ok(Some(0)) => {}
155            Ok(code) => tracing::warn!(container = container_name, ?code, "container agent: handing the memory folder's parents to the turn user failed"),
156            Err(e) => tracing::warn!(container = container_name, error = %e, "container agent: couldn't hand the memory folder's parents to the turn user"),
157        }
158    }
159}
160
161/// The named volume that is a container agent's provider home (`CONTAINER_CLAUDE_DIR`).
162pub fn claude_volume_name(container_name: &str) -> String {
163    format!("agentmux-claude-{container_name}")
164}
165
166/// The mounts that make up the agent's home dir inside the container.
167///
168/// The per-agent named volume stays mounted at [`CONTAINER_CLAUDE_DIR`] exactly
169/// as before, and a bound account contributes ONE extra mount: this container's own
170/// copy of its `.credentials.json`, bind-mounted as a single file on top of that volume.
171///
172/// Binding the account's whole config dir over `…/.claude` would be the more
173/// obvious shape, and it does NOT work — both failures verified live on
174/// 2026-09-02 against `ghcr.io/agentmuxai/agent-claude:latest`:
175///
176///  1. That dir's `projects` entry is a symlink into the shared identities tree,
177///     which does not resolve in-container (`ls` → "No such file or directory").
178///  2. Shadowing it with a nested volume at `…/.claude/projects` SILENTLY does
179///     not mount — Docker will not mount over a path that is a symlink inside a
180///     bind mount. `mount` shows only the parent 9p bind, and the CLI is left
181///     writing session state through the broken link. Chowning does not help;
182///     there is nothing there to chown.
183///
184/// Keeping the volume and binding just the credential file avoids both, and
185/// preserves the existing ownership story: the volume is initialised from the
186/// image, so `projects`/`sessions` stay writable by uid 1000. Verified end to
187/// end — a container agent using this shape completed a real turn against the
188/// bound account (`"result":"AUTH_OK"`, `is_error: false`).
189///
190/// Known limitation — HOST UID PARITY. A bind preserves the host file's owner
191/// and mode (`.credentials.json` is typically 0600), while the image always
192/// execs as `agent`, uid 1000. On a host whose AgentMux user is not uid 1000,
193/// the container cannot read the token and authentication stays broken there.
194///
195/// That is deliberately NOT worked around here. It is the container design's
196/// pre-existing, documented assumption — "`agent` non-root user (UID 1000) …
197/// Host filesystem UID parity" (SPEC_CONTAINER_PANE_SUPPORT_2026_06_11.md §
198/// "What claw's containers provide"; the Dockerfile renames node:22-slim's
199/// uid-1000 user for exactly this) — and the `/workspace` bind below has the
200/// identical problem: at uid != 1000 the agent cannot write its own workspace
201/// either. Special-casing credentials would fix one symptom of that assumption
202/// and leave the other, while adding a second provisioning path to maintain.
203/// The real fix is to exec as the host uid/gid, which is an architectural change
204/// affecting every mount, and belongs in its own PR.
205///
206/// Known limitation: a single-file bind follows the inode. If the CLI ever
207/// replaces `.credentials.json` by atomic rename rather than writing in place, a
208/// refreshed token would land on the host but not be seen by the running
209/// container until it is recreated. Reads — the case that was totally broken —
210/// are unaffected.
211pub(super) fn agent_home_mounts(container_name: &str, spec: &ContainerMountSpec) -> Vec<Mount> {
212    let mut mounts = vec![Mount {
213        target: Some(CONTAINER_CLAUDE_DIR.to_string()),
214        source: Some(claude_volume_name(container_name)),
215        typ: Some(MountTypeEnum::VOLUME),
216        read_only: Some(false),
217        ..Default::default()
218    }];
219
220    if let Some(host_dir) = spec.claude_config_host_dir.as_deref().filter(|d| !d.is_empty()) {
221        let host_dir = normalize_host_path(host_dir);
222        mounts.push(Mount {
223            target: Some(format!("{CONTAINER_CLAUDE_DIR}/{CLAUDE_CREDENTIALS_FILE}")),
224            source: Some(format!("{}/{CLAUDE_CREDENTIALS_FILE}", host_dir.trim_end_matches('/'))),
225            typ: Some(MountTypeEnum::BIND),
226            // Writable: the CLI refreshes its own token. The source is this container's own copy of the account's
227            // login, never the account's file, and a refresh in it is taken back by the account and the other
228            // containers' copies (`keychain_credentials::write_back`).
229            read_only: Some(false),
230            ..Default::default()
231        });
232    }
233    if let Some(host_dir) = spec.memory_host_dir.as_deref().filter(|d| !d.is_empty()) {
234        mounts.push(Mount {
235            target: Some(container_memory_dir()),
236            source: Some(normalize_host_path(host_dir)),
237            typ: Some(MountTypeEnum::BIND),
238            read_only: Some(false),
239            ..Default::default()
240        });
241    }
242    if let Some(host_dir) = spec.mcp_config_host_dir.as_deref().filter(|d| !d.is_empty()) {
243        // Read-only: the agent's MCP config is srv's, and a container must never rewrite it.
244        // The folder, so a file replaced by an atomic write is seen (a single-file bind is not).
245        mounts.push(Mount {
246            target: Some(crate::backend::container::CONTAINER_MCP_CONFIG_DIR.to_string()),
247            source: Some(normalize_host_path(host_dir)),
248            typ: Some(MountTypeEnum::BIND),
249            read_only: Some(true),
250            ..Default::default()
251        });
252    }
253    if let Some(host_dir) = spec.github_hooks_host_dir.as_deref().filter(|d| !d.is_empty()) {
254        // Read-only: the push scan is not the agent's to edit.
255        mounts.push(Mount {
256            target: Some(crate::identity::github_tokens::CONTAINER_HOOKS_DIR.to_string()),
257            source: Some(normalize_host_path(host_dir)),
258            typ: Some(MountTypeEnum::BIND),
259            read_only: Some(true),
260            ..Default::default()
261        });
262    }
263    // Read-only: the grants and the host's CLIs are the host's to change, not the agent's.
264    let aws = [
265        (spec.aws_config_host_dir.as_deref(), crate::identity::aws_broker::container::CONTAINER_AWS_DIR),
266        (spec.aws_tools_host_dir.as_deref(), crate::identity::aws_broker::tools::CONTAINER_TOOLS_DIR),
267    ];
268    for (host_dir, target) in aws.into_iter().filter_map(|(d, t)| Some((d.filter(|d| !d.is_empty())?, t))) {
269        mounts.push(Mount {
270            target: Some(target.to_string()),
271            source: Some(normalize_host_path(host_dir)),
272            typ: Some(MountTypeEnum::BIND),
273            read_only: Some(true),
274            ..Default::default()
275        });
276    }
277    mounts
278}
279
280/// Every mount target the container manager owns. Anything NOT in here (the caller's `agent:container_volumes`) is
281/// the user's business and is never a reason to rebuild their container.
282pub(super) fn owned_mount_targets() -> [String; 7] {
283    [
284        CONTAINER_CLAUDE_DIR.to_string(),
285        format!("{CONTAINER_CLAUDE_DIR}/{CLAUDE_CREDENTIALS_FILE}"),
286        CONTAINER_WORKSPACE_DIR.to_string(),
287        crate::backend::container::CONTAINER_MCP_CONFIG_DIR.to_string(),
288        crate::identity::github_tokens::CONTAINER_HOOKS_DIR.to_string(),
289        crate::identity::aws_broker::container::CONTAINER_AWS_DIR.to_string(),
290        crate::identity::aws_broker::tools::CONTAINER_TOOLS_DIR.to_string(),
291    ]
292}
293
294/// Whether the drift check looks at `target`: the AWS mounts count only where the host sets them, so a host that
295/// shares no AWS never has its containers rebuilt for it.
296pub(super) fn is_checked(spec: &ContainerMountSpec, target: &str) -> bool {
297    use crate::identity::aws_broker::{container::CONTAINER_AWS_DIR, tools::CONTAINER_TOOLS_DIR};
298    match target {
299        CONTAINER_AWS_DIR => spec.aws_config_host_dir.is_some(),
300        CONTAINER_TOOLS_DIR => spec.aws_tools_host_dir.is_some(),
301        _ => true,
302    }
303}
304
305#[cfg(test)]
306mod itest;
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311    use std::collections::HashMap;
312
313    fn bind_at<'a>(mounts: &'a [Mount], target: &str) -> Option<&'a Mount> {
314        mounts.iter().find(|m| m.target.as_deref() == Some(target))
315    }
316
317    #[test]
318    fn claude_reads_memory_from_the_folder_it_names_for_the_workspace() {
319        assert_eq!(container_memory_dir(), "/home/agent/.claude/projects/-workspace/memory");
320    }
321
322    /// The relocated MCP config is mounted as its FOLDER: a single-file bind would keep the old
323    /// inode across an atomic rewrite, leaving the container on a stale config (#3680).
324    #[test]
325    fn the_relocated_mcp_config_is_a_read_only_folder_bind() {
326        let with = ContainerMountSpec { mcp_config_host_dir: Some("/host/.agentmux/mcp/abc".into()), ..Default::default() };
327        let mounts = agent_home_mounts("agentmux-abc", &with);
328        let mount = bind_at(&mounts, crate::backend::container::CONTAINER_MCP_CONFIG_DIR).expect("the config folder is mounted");
329        assert_eq!(mount.source.as_deref(), Some("/host/.agentmux/mcp/abc"));
330        assert_eq!(mount.read_only, Some(true), "the config is srv's to write");
331        let without = ContainerMountSpec::default();
332        assert!(bind_at(&agent_home_mounts("agentmux-abc", &without), crate::backend::container::CONTAINER_MCP_CONFIG_DIR).is_none());
333    }
334
335    #[test]
336    fn the_git_hooks_are_a_read_only_bind_and_only_when_there_are_some() {
337        let with = ContainerMountSpec { github_hooks_host_dir: Some("/host/github-hooks".into()), ..Default::default() };
338        let mounts = agent_home_mounts("agentmux-abc", &with);
339        let hooks = bind_at(&mounts, crate::identity::github_tokens::CONTAINER_HOOKS_DIR).expect("the hooks are mounted");
340        assert_eq!(hooks.source.as_deref(), Some("/host/github-hooks"));
341        assert_eq!(hooks.read_only, Some(true), "the scan is not the agent's to edit");
342        for none in [None, Some(String::new())] {
343            let without = ContainerMountSpec { github_hooks_host_dir: none, ..Default::default() };
344            assert!(bind_at(&agent_home_mounts("agentmux-abc", &without), crate::identity::github_tokens::CONTAINER_HOOKS_DIR).is_none());
345        }
346    }
347
348    #[test]
349    fn an_account_with_a_login_is_given_a_copy_of_it_and_never_its_own_file() {
350        let account = tempfile::tempdir().unwrap();
351        let env = |dir: &std::path::Path| HashMap::from([("CLAUDE_CONFIG_DIR".to_string(), dir.to_string_lossy().into_owned())]);
352        let without = ContainerMountSpec::for_agent(&env(account.path()), "");
353        assert_eq!(without.claude_config_host_dir, None);
354        assert_eq!(without.staged_login_config_dir.is_some(), cfg!(target_os = "macos"), "only macOS keeps a login outside a file");
355        std::fs::write(account.path().join(CLAUDE_CREDENTIALS_FILE), "{}").unwrap();
356        let with = ContainerMountSpec::for_agent(&env(account.path()), "");
357        assert_eq!(with.claude_config_host_dir, None, "the container's own copy is made at its start, so the spec names no file");
358        assert_eq!(with.staged_login_config_dir.as_deref(), Some(account.path().to_str().unwrap()), "the account whose login is copied");
359        assert_eq!(ContainerMountSpec::for_agent(&HashMap::new(), "").staged_login_config_dir, None, "no bound account, nothing to stage");
360    }
361
362    #[test]
363    fn an_agent_on_an_api_key_mounts_no_login_from_the_folder_it_runs_in_and_still_shares_its_memory() {
364        use crate::backend::model_gateway::{catalog::KEY_ROUTE_ID, token, PATH_PREFIX};
365        // The provider's default folder: the person's own sign-in may be in it, as a file or in the macOS Keychain.
366        let default_dir = tempfile::tempdir().unwrap();
367        std::fs::write(default_dir.path().join(CLAUDE_CREDENTIALS_FILE), "{}").unwrap();
368        let work = tempfile::tempdir().unwrap();
369        let mut env = HashMap::from([("CLAUDE_CONFIG_DIR".to_string(), default_dir.path().to_string_lossy().into_owned())]);
370        let plan = ContainerMountSpec::for_agent(&env, work.path().to_str().unwrap());
371        assert!(plan.staged_login_config_dir.is_some(), "a plan account's login is copied for the container");
372        let key_token = token::renew_for_account("km-slug", "km-def", KEY_ROUTE_ID, "km-acct", None);
373        env.insert("ANTHROPIC_AUTH_TOKEN".to_string(), key_token);
374        env.insert("ANTHROPIC_BASE_URL".to_string(), format!("http://127.0.0.1:1{PATH_PREFIX}{KEY_ROUTE_ID}"));
375        let key = ContainerMountSpec::for_agent(&env, work.path().to_str().unwrap());
376        assert_eq!(key.claude_config_host_dir, None, "no credentials file is given to a key agent's container");
377        assert_eq!(key.staged_login_config_dir, None, "and no login is copied for it");
378        assert_eq!(key.memory_host_dir, plan.memory_host_dir, "its Personal Memory folder is shared as before");
379        assert!(key.memory_host_dir.is_some());
380        // A model route does not make an agent a key agent.
381        let mut model = env.clone();
382        model.insert("ANTHROPIC_AUTH_TOKEN".to_string(), token::token_for("km-model-slug", "km-model-def", "openrouter"));
383        model.insert("ANTHROPIC_BASE_URL".to_string(), format!("http://127.0.0.1:1{PATH_PREFIX}openrouter"));
384        assert!(ContainerMountSpec::for_agent(&model, work.path().to_str().unwrap()).staged_login_config_dir.is_some());
385        token::revoke("km-model-def", "openrouter");
386        token::revoke("km-def", KEY_ROUTE_ID);
387    }
388
389    #[test]
390    fn an_agent_on_an_api_key_mounts_no_login_even_when_its_token_has_ended() {
391        use crate::backend::model_gateway::{catalog::KEY_ROUTE_ID, token, PATH_PREFIX};
392        let default_dir = tempfile::tempdir().unwrap();
393        std::fs::write(default_dir.path().join(CLAUDE_CREDENTIALS_FILE), "{}").unwrap();
394        let work = tempfile::tempdir().unwrap();
395        let ended = token::renew_for_account("ke-slug", "ke-def", KEY_ROUTE_ID, "ke-acct", None);
396        token::revoke("ke-def", KEY_ROUTE_ID);
397        assert_eq!(token::grant_for(&ended), None);
398        let base = ("ANTHROPIC_BASE_URL".to_string(), format!("http://127.0.0.1:1{PATH_PREFIX}{KEY_ROUTE_ID}"));
399        let config = ("CLAUDE_CONFIG_DIR".to_string(), default_dir.path().to_string_lossy().into_owned());
400        // The token has ended, and in another case there is none: either way the agent is still on the key route.
401        for token in [Some(ended), None] {
402            let mut env = HashMap::from([base.clone(), config.clone()]);
403            if let Some(t) = token {
404                env.insert("ANTHROPIC_AUTH_TOKEN".to_string(), t);
405            }
406            let plan = ContainerMountSpec::for_agent(&env, work.path().to_str().unwrap());
407            assert_eq!(plan.claude_config_host_dir, None, "the person's own sign-in is never mounted for a key agent");
408            assert_eq!(plan.staged_login_config_dir, None);
409        }
410    }
411
412    #[test]
413    fn the_memory_folder_is_one_bind_and_only_when_there_is_one() {
414        let with = ContainerMountSpec { memory_host_dir: Some("/host/mem".into()), ..Default::default() };
415        let mounts = agent_home_mounts("agentmux-abc", &with);
416        let memory = bind_at(&mounts, &container_memory_dir()).expect("memory is mounted");
417        assert_eq!(memory.source.as_deref(), Some("/host/mem"));
418        assert_eq!(memory.typ, Some(MountTypeEnum::BIND));
419        assert_eq!(memory.read_only, Some(false));
420        // Nothing wider than that one folder: no identity dir, no projects dir.
421        assert!(bind_at(&mounts, &format!("{CONTAINER_CLAUDE_DIR}/projects")).is_none());
422        assert_eq!(mounts.len(), 2, "the volume and the memory folder");
423
424        for none in [None, Some(String::new())] {
425            let without = ContainerMountSpec { memory_host_dir: none, ..Default::default() };
426            assert!(bind_at(&agent_home_mounts("agentmux-abc", &without), &container_memory_dir()).is_none());
427        }
428    }
429
430    #[test]
431    fn the_host_folder_is_where_a_native_session_keeps_memory_and_is_created() {
432        let root = std::env::temp_dir().join(format!("agentmux-p5-{}", std::process::id()));
433        let config = root.join("claude");
434        let work = root.join("work");
435        std::fs::create_dir_all(&work).unwrap();
436        let got = personal_memory_host_dir(Some(&config.to_string_lossy()), &work.to_string_lossy()).expect("a folder");
437        let want = crate::backend::memory::native_files::memory_dir_for_cwd(&config.to_string_lossy(), &work.to_string_lossy());
438        assert!(want.is_dir(), "created, so Docker has a source to bind");
439        // Windows passes the folder through as it is (a canonical path there has the verbatim prefix, which
440        // Docker doesn't take); elsewhere symlinks are resolved.
441        let expected = if cfg!(windows) { want.clone() } else { want.canonicalize().unwrap() };
442        assert_eq!(std::path::Path::new(&got), expected);
443        assert_eq!(personal_memory_host_dir(Some(&config.to_string_lossy()), ""), None);
444        let _ = std::fs::remove_dir_all(&root);
445    }
446
447    /// The folder bound as a container agent's memory is the one of its workspace's own path, whatever the
448    /// workspace holds: a workspace that is a linked worktree does not get the main checkout's.
449    #[test]
450    fn the_memory_folder_is_named_after_the_workspaces_path_whatever_it_holds() {
451        let base = tempfile::tempdir().unwrap();
452        let config = base.path().join("claude");
453        let (repo, worktree) = crate::backend::claude_layout::tests::repo_with_worktree(base.path());
454        let plain = crate::backend::claude_layout::real_path(base.path()).join("plain");
455        std::fs::create_dir_all(&plain).unwrap();
456        let name = |dir: &std::path::Path| crate::backend::claude_layout::project_dir_name(&dir.to_string_lossy());
457        for workspace in [&worktree, &repo, &plain] {
458            let bound = personal_memory_host_dir(Some(&config.to_string_lossy()), &workspace.to_string_lossy()).expect("a folder");
459            let project = std::path::Path::new(&bound).parent().unwrap().file_name().unwrap().to_string_lossy().into_owned();
460            assert_eq!(project, name(workspace), "{}", workspace.display());
461        }
462        assert_ne!(name(&worktree), name(&repo));
463    }
464
465    #[test]
466    fn a_tilde_working_dir_is_mounted_as_the_absolute_folder_it_names() {
467        let _guard = crate::test_support::ISOLATED_AUTH_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
468        let fake = tempfile::tempdir().unwrap();
469        let prior = std::env::var_os("AGENTMUX_HOME_OVERRIDE");
470        std::env::set_var("AGENTMUX_HOME_OVERRIDE", fake.path());
471        let isolated = ContainerMountSpec::for_agent(&HashMap::new(), "~/.agentmux/agents/aria");
472        std::env::remove_var("AGENTMUX_HOME_OVERRIDE");
473        let normal = ContainerMountSpec::for_agent(&HashMap::new(), "~/.agentmux/agents/aria");
474        if let Some(p) = prior {
475            std::env::set_var("AGENTMUX_HOME_OVERRIDE", p);
476        }
477        assert_eq!(isolated.workspace_host_dir.as_deref().map(std::path::Path::new), Some(fake.path().join("agents").join("aria").as_path()));
478        let normal = normal.workspace_host_dir.unwrap();
479        assert!(std::path::Path::new(&normal).is_absolute() && !normal.contains('~'), "{normal}");
480    }
481
482    #[test]
483    fn an_agent_without_a_claude_config_dir_gets_no_memory_mount() {
484        let spec = ContainerMountSpec::for_agent(&HashMap::new(), "/some/work");
485        assert_eq!(spec.memory_host_dir, None);
486        assert_eq!(spec.workspace_host_dir.as_deref(), Some("/some/work"));
487    }
488}