Skip to main content

agentmux_srv_core/backend/
claude_layout.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Where the Claude Code CLI keeps a conversation under a `CLAUDE_CONFIG_DIR`.
5//!
6//! One implementation, because every reader has to agree with the CLI byte for
7//! byte: a resume check that computes a different folder name than the CLI
8//! reports a transcript that is sitting on disk as unreachable, and the agent
9//! loses its native resume. Three copies of this rule used to disagree, and
10//! the one on the resume path was wrong for any working directory holding an
11//! underscore, a space or most other punctuation.
12
13/// The CLI keeps this many characters of the sanitized path before it
14/// appends a hash instead.
15const PROJECT_DIR_NAME_MAX: usize = 200;
16
17/// The folder under `<CLAUDE_CONFIG_DIR>/projects/` that holds the sessions
18/// the CLI ran with `cwd` as its working directory.
19///
20/// The CLI's rule (its `RC()`, read from the binary AgentMux 0.57.0 bundles,
21/// Claude Code v2.1.280):
22///
23/// ```js
24/// function TQ(e){let r=0;for(let n=0;n<e.length;n++)r=(r<<5)-r+e.charCodeAt(n)|0;return r}
25/// function RC(e){let n=e.replace(/[^a-zA-Z0-9]/g,"-");
26///   if(n.length<=200)return n;return`${n.slice(0,200)}-${Math.abs(TQ(e)).toString(36)}`}
27/// ```
28///
29/// JavaScript strings are UTF-16, so the rule works on UTF-16 code units: a
30/// character outside the Basic Multilingual Plane (an emoji) becomes two
31/// dashes, not one.
32///
33/// `cwd` must be the path as the CLI sees it — already expanded, not a
34/// `~`-shorthand.
35pub fn project_dir_name(cwd: &str) -> String {
36    let name: String = cwd
37        .encode_utf16()
38        .map(|unit| match u8::try_from(unit) {
39            Ok(b) if b.is_ascii_alphanumeric() => b as char,
40            _ => '-',
41        })
42        .collect();
43    if name.len() <= PROJECT_DIR_NAME_MAX {
44        return name;
45    }
46    // Every character of `name` is ASCII, so slicing by bytes is slicing by
47    // characters.
48    format!(
49        "{}-{}",
50        &name[..PROJECT_DIR_NAME_MAX],
51        radix_36(path_hash(cwd))
52    )
53}
54
55/// `Math.abs(TQ(cwd))`: 31·h + c over UTF-16 code units, wrapping at 32 bits
56/// (Java's `String.hashCode`). `i32::MIN`'s absolute value doesn't fit an
57/// `i32`, and JavaScript numbers don't wrap, so the magnitude is returned
58/// unsigned.
59fn path_hash(s: &str) -> u32 {
60    let mut hash: i32 = 0;
61    for unit in s.encode_utf16() {
62        hash = hash
63            .wrapping_shl(5)
64            .wrapping_sub(hash)
65            .wrapping_add(i32::from(unit));
66    }
67    hash.unsigned_abs()
68}
69
70/// `Number.prototype.toString(36)` for a non-negative integer.
71fn radix_36(mut n: u32) -> String {
72    const DIGITS: &[u8; 36] = b"0123456789abcdefghijklmnopqrstuvwxyz";
73    if n == 0 {
74        return "0".to_string();
75    }
76    let mut buf = Vec::new();
77    while n > 0 {
78        buf.push(DIGITS[(n % 36) as usize]);
79        n /= 36;
80    }
81    buf.reverse();
82    String::from_utf8(buf).expect("base-36 digits are ASCII")
83}
84
85/// The directory the CLI names a working directory's auto-memory folder
86/// after — not the working directory itself, unlike its sessions. The CLI's
87/// rule (its `defaultPath()`, Claude Code v2.1.280):
88///
89/// ```js
90/// g = this.canonicalWcRootForProject(r) ?? Ur(r) ?? r   // r: the process cwd
91/// function Ur(e){let n=Un(e);if(!n)return null;return eQ(uu().canonicalRootByRoot,n,ke)}
92/// ```
93///
94/// That is: the physical working directory, walked up to the nearest `.git`
95/// (a directory or a file), and — for a linked worktree, whose `.git` is a
96/// `gitdir:` file — on to the main checkout that owns it. So every
97/// subdirectory and every linked worktree of one repository shares the
98/// repository root's memory folder.
99///
100/// Returns the working directory unchanged when it isn't in a repository.
101///
102/// A folder a container agent can write is named after its own path alone:
103/// that agent's memory is a folder AgentMux binds into its container, so
104/// nothing the agent can write decides which one it is. No file in the
105/// folder is read, no folder above it is looked at, and a link in a part of
106/// the path such an agent can write is not followed. A linked worktree whose
107/// repository such an agent can write keeps its own root, for the same reason.
108pub fn memory_project_root(cwd: &std::path::Path) -> std::path::PathBuf {
109    memory_project_root_with(cwd, &crate::backend::fs_ops::container_folders::written_by_a_container_agent)
110}
111
112/// [`memory_project_root`], with `written` saying whether a container agent
113/// can write a folder.
114pub fn memory_project_root_with(cwd: &std::path::Path, written: &dyn Fn(&std::path::Path) -> bool) -> std::path::PathBuf {
115    if written(cwd) {
116        // Inside another such folder, a part of its own path can be written too.
117        return if cwd.parent().is_some_and(written) { as_written(cwd) } else { physical_dir(cwd) };
118    }
119    let cwd = physical_dir(cwd);
120    match git_root(&cwd) {
121        Some(root) => canonical_worktree_root(&root, written),
122        None => cwd,
123    }
124}
125
126/// `dir` as it is written: absolute, with `.` and `..` taken out, and nothing
127/// looked up on the disk.
128fn as_written(dir: &std::path::Path) -> std::path::PathBuf {
129    use std::path::Component;
130    let absolute = std::path::absolute(dir).unwrap_or_else(|_| dir.to_path_buf());
131    let mut out = std::path::PathBuf::new();
132    for part in absolute.components() {
133        match part {
134            Component::CurDir => {}
135            Component::ParentDir => {
136                out.pop();
137            }
138            other => out.push(other),
139        }
140    }
141    out
142}
143
144/// The working directory as the CLI's process sees it (`process.cwd()`):
145/// symlinks resolved. On Windows `canonicalize` returns a `\\?\` verbatim
146/// path the CLI never sees, and the current directory keeps links as given.
147pub fn physical_dir(cwd: &std::path::Path) -> std::path::PathBuf {
148    if cfg!(windows) {
149        cwd.to_path_buf()
150    } else {
151        cwd.canonicalize().unwrap_or_else(|_| cwd.to_path_buf())
152    }
153}
154
155/// Whether the repository whose main checkout is `root` has linked
156/// worktrees — each of which shares `root`'s memory folder.
157pub fn has_linked_worktrees(root: &std::path::Path) -> bool {
158    std::fs::read_dir(root.join(".git").join("worktrees")).is_ok_and(|mut d| d.next().is_some())
159}
160
161/// The nearest directory at or above `dir` holding a `.git` directory or
162/// file (the CLI's `Gt`).
163fn git_root(dir: &std::path::Path) -> Option<std::path::PathBuf> {
164    dir.ancestors()
165        .find(|d| std::fs::metadata(d.join(".git")).is_ok_and(|m| m.is_dir() || m.is_file()))
166        .map(std::path::Path::to_path_buf)
167}
168
169/// For a linked worktree, the main checkout that owns it; otherwise `root`
170/// (the CLI's `ke`/`Ht`). Anything that doesn't check out — a `.git` file
171/// that isn't `gitdir:`, a missing `commondir`, a worktree whose `gitdir`
172/// doesn't point back — leaves `root` as it is, as the CLI does. So does a
173/// repository a container agent can write (`written`).
174fn canonical_worktree_root(root: &std::path::Path, written: &dyn Fn(&std::path::Path) -> bool) -> std::path::PathBuf {
175    use std::path::{Path, PathBuf};
176    fn read_trimmed(p: &Path) -> Option<String> {
177        std::fs::read_to_string(p).ok().map(|s| s.trim().to_string())
178    }
179    let resolve = || -> Option<PathBuf> {
180        let git_file = read_trimmed(&root.join(".git"))?;
181        let git_dir = real_path(&root.join(git_file.strip_prefix("gitdir:")?.trim()));
182        if written(&git_dir) {
183            return None;
184        }
185        let common = real_path(&git_dir.join(read_trimmed(&git_dir.join("commondir"))?));
186        if written(&common) {
187            return None;
188        }
189        if git_dir.parent()? != common.join("worktrees") {
190            return None;
191        }
192        let back = real_path(&git_dir.join(read_trimmed(&git_dir.join("gitdir"))?));
193        if back != real_path(root).join(".git") {
194            return None;
195        }
196        if common.file_name()? != ".git" {
197            // A bare repository's worktree: the repository itself, unless it
198            // is somehow a checkout too.
199            return (!common.join(".git").exists()).then_some(common);
200        }
201        common.parent().map(Path::to_path_buf)
202    };
203    resolve().unwrap_or_else(|| root.to_path_buf())
204}
205
206/// `p` with symlinks resolved, as the CLI's process would name it. On
207/// Windows `canonicalize` returns a `\\?\` verbatim path, which names the
208/// folder `----C--repo` where the CLI, seeing `C:\repo`, names it
209/// `C--repo`. Tests that build a working directory take it from here too:
210/// a raw `canonicalize` gives them a path no real cwd has (#3749).
211pub fn real_path(p: &std::path::Path) -> std::path::PathBuf {
212    without_verbatim_prefix(p.canonicalize().unwrap_or_else(|_| p.to_path_buf()))
213}
214
215/// `p` without a leading `\\?\`. A verbatim UNC path (`\\?\UNC\server\…`)
216/// is kept: dropping only the prefix would leave `UNC\server\…`, which is
217/// not the path the CLI sees.
218fn without_verbatim_prefix(p: std::path::PathBuf) -> std::path::PathBuf {
219    match p.to_str().and_then(|s| s.strip_prefix(r"\\?\")) {
220        Some(rest) if !rest.starts_with("UNC\\") => std::path::PathBuf::from(rest),
221        _ => p,
222    }
223}
224
225#[cfg(test)]
226pub(crate) mod tests {
227    use super::*;
228
229    // Every expected value below was produced by the CLI's own `RC()`
230    // (quoted on `project_dir_name`), run under Node — not by this module.
231
232    #[test]
233    fn a_windows_agent_directory() {
234        assert_eq!(
235            project_dir_name(r"C:\Users\user\.agentmux\agents\agent3-0630k"),
236            "C--Users-user--agentmux-agents-agent3-0630k"
237        );
238    }
239
240    #[test]
241    fn a_posix_path_keeps_the_dashes_inside_a_segment() {
242        assert_eq!(
243            project_dir_name("/home/u/.agentmux/agents/foo-bar"),
244            "-home-u--agentmux-agents-foo-bar"
245        );
246    }
247
248    #[test]
249    fn underscores_and_spaces_become_dashes() {
250        assert_eq!(
251            project_dir_name("/home/u/my_project dir"),
252            "-home-u-my-project-dir"
253        );
254    }
255
256    #[test]
257    fn non_ascii_letters_and_punctuation_become_dashes() {
258        assert_eq!(
259            project_dir_name("C:\\code\\caf\u{e9} (old)@2~x"),
260            "C--code-caf---old--2-x"
261        );
262    }
263
264    #[test]
265    fn a_character_outside_the_bmp_becomes_two_dashes() {
266        assert_eq!(project_dir_name("/x/\u{1F600}y"), "-x---y");
267    }
268
269    #[test]
270    fn a_long_path_is_cut_at_200_and_hashed() {
271        let cwd = format!("/home/u/{}repo", "deeply_nested/".repeat(20));
272        let got = project_dir_name(&cwd);
273        assert_eq!(
274            got,
275            "-home-u-deeply-nested-deeply-nested-deeply-nested-deeply-nested-deeply-nested-\
276             deeply-nested-deeply-nested-deeply-nested-deeply-nested-deeply-nested-deeply-nested-\
277             deeply-nested-deeply-nested-deeply-nes-fygn57"
278        );
279        assert_eq!(got.len(), 207);
280    }
281
282    #[test]
283    fn a_long_windows_path_is_cut_at_200_and_hashed() {
284        let cwd = format!(r"C:\Users\user\{}", "a".repeat(230));
285        assert_eq!(
286            project_dir_name(&cwd),
287            format!("C--Users-user-{}-eqzdy0", "a".repeat(186))
288        );
289    }
290
291    #[test]
292    fn exactly_200_characters_is_not_hashed() {
293        let cwd = "a".repeat(200);
294        assert_eq!(project_dir_name(&cwd), cwd);
295    }
296
297    #[test]
298    fn the_hash_magnitude_of_i32_min_does_not_wrap() {
299        // JavaScript's Math.abs(-2147483648) is 2147483648; an i32 `abs`
300        // would overflow.
301        assert_eq!(radix_36(i32::MIN.unsigned_abs()), "zik0zk");
302        assert_eq!(radix_36(0), "0");
303    }
304
305    // The prefix rule is string handling, so it is checked on every
306    // platform — PR CI runs no tests on Windows (ci-pr.yml).
307    #[test]
308    fn a_verbatim_drive_path_loses_its_prefix() {
309        use std::path::PathBuf;
310        assert_eq!(without_verbatim_prefix(PathBuf::from(r"\\?\C:\repo")), PathBuf::from(r"C:\repo"));
311    }
312
313    #[test]
314    fn a_verbatim_unc_path_and_a_plain_path_are_kept() {
315        use std::path::PathBuf;
316        for p in [r"\\?\UNC\server\share\repo", r"C:\repo", "/home/u/repo"] {
317            assert_eq!(without_verbatim_prefix(PathBuf::from(p)), PathBuf::from(p));
318        }
319    }
320
321    /// A repository with one commit, and a linked worktree of it outside it,
322    /// as the CLI's process would see them ([`real_path`]).
323    pub(crate) fn repo_with_worktree(base: &std::path::Path) -> (std::path::PathBuf, std::path::PathBuf) {
324        repo_and_worktree_at(&base.join("repo"), &base.join("wt"))
325    }
326
327    /// [`repo_with_worktree`], at the two folders named.
328    pub(crate) fn repo_and_worktree_at(repo: &std::path::Path, wt: &std::path::Path) -> (std::path::PathBuf, std::path::PathBuf) {
329        std::fs::create_dir_all(repo.join("sub")).unwrap();
330        let git = |args: &[&str]| {
331            use agentmux_common::win32::NoWindow;
332            let mut cmd = std::process::Command::new("git");
333            cmd.args(["-c", "user.email=a@b", "-c", "user.name=a"]).args(args).current_dir(repo);
334            cmd.no_window();
335            let out = cmd.output().unwrap();
336            assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
337        };
338        git(&["init", "-q"]);
339        std::fs::write(repo.join("sub").join("x"), "x").unwrap();
340        git(&["add", "."]);
341        git(&["commit", "-qm", "x"]);
342        git(&["worktree", "add", "-q", wt.to_str().unwrap()]);
343        (real_path(repo), real_path(wt))
344    }
345
346    #[test]
347    fn memory_is_keyed_by_the_main_checkout_for_subdirectories_and_worktrees() {
348        let base = tempfile::tempdir().unwrap();
349        let (repo, wt) = repo_with_worktree(base.path());
350        assert_eq!(memory_project_root(&repo), repo);
351        assert_eq!(memory_project_root(&repo.join("sub")), repo);
352        assert_eq!(memory_project_root(&wt), repo, "a linked worktree shares the main checkout's memory");
353        assert_eq!(memory_project_root(&wt.join("sub")), repo);
354    }
355
356    /// A folder a container agent can write is keyed by its own path, whatever it holds: a linked worktree
357    /// (a `.git` file that points elsewhere) does not get the main checkout's memory, even one whose path
358    /// differs from its own only by an ending, and a folder below a repository's top does not get the top's.
359    #[test]
360    fn a_folder_a_container_agent_can_write_is_keyed_by_its_own_path() {
361        let base = tempfile::tempdir().unwrap();
362        let (repo, wt) = repo_with_worktree(base.path());
363        let none = |_: &std::path::Path| false;
364        let the_worktree = |p: &std::path::Path| p.starts_with(&wt);
365        assert_eq!(memory_project_root_with(&wt, &none), repo, "on the host a linked worktree shares the main checkout's");
366        assert_eq!(memory_project_root_with(&wt, &the_worktree), wt);
367        let below = |p: &std::path::Path| p.starts_with(repo.join("sub"));
368        assert_eq!(memory_project_root_with(&repo.join("sub"), &below), repo.join("sub"), "nothing above it is looked at");
369
370        // A workspace `w` that is a linked worktree of `w-b` and of nothing else: the folder of `w`, never of `w-b` or `w.b`.
371        for ending in ["-b", ".b"] {
372            let other = tempfile::tempdir().unwrap();
373            let (main, w) = repo_and_worktree_at(&other.path().join(format!("w{ending}")), &other.path().join("w"));
374            let name = |root: &std::path::Path| project_dir_name(&root.to_string_lossy());
375            assert_eq!(memory_project_root_with(&w, &none), main, "on the host it shares the main checkout's");
376            let got = memory_project_root_with(&w, &|p| p.starts_with(&w));
377            assert_eq!(got, w);
378            assert_ne!(name(&got), name(&main), "{ending}");
379        }
380    }
381
382    /// What a container agent's workspace was keyed by before stays its key: a workspace that is no
383    /// repository, and one that is a repository of its own, keep the folder they had.
384    #[test]
385    fn a_container_agents_workspace_keeps_the_folder_it_had() {
386        let base = tempfile::tempdir().unwrap();
387        let plain = real_path(base.path()).join("plain");
388        std::fs::create_dir_all(&plain).unwrap();
389        let (repo, _) = repo_with_worktree(base.path());
390        for workspace in [plain, repo] {
391            let before = memory_project_root_with(&workspace, &|_| false);
392            let now = memory_project_root_with(&workspace, &|p| p.starts_with(&workspace));
393            assert_eq!(now, before);
394            assert_eq!(now, workspace);
395        }
396    }
397
398    /// A worktree on the host whose repository a container agent can write keeps its own root.
399    #[test]
400    fn a_worktree_of_a_repository_a_container_agent_can_write_keeps_its_own_root() {
401        let base = tempfile::tempdir().unwrap();
402        let (repo, wt) = repo_with_worktree(base.path());
403        assert_eq!(memory_project_root_with(&wt, &|p| p.starts_with(&repo)), wt);
404    }
405
406    /// Inside another folder a container agent can write, a link in the path is not followed.
407    #[cfg(unix)]
408    #[test]
409    fn a_link_in_a_path_a_container_agent_can_write_is_not_followed() {
410        let base = tempfile::tempdir().unwrap();
411        let outer = real_path(base.path()).join("outer");
412        let elsewhere = real_path(base.path()).join("elsewhere");
413        std::fs::create_dir_all(&outer).unwrap();
414        std::fs::create_dir_all(&elsewhere).unwrap();
415        let inner = outer.join("inner");
416        std::os::unix::fs::symlink(&elsewhere, &inner).unwrap();
417        assert_eq!(memory_project_root_with(&inner, &|p| p.starts_with(&outer)), inner);
418        assert_eq!(memory_project_root_with(&outer.join("x").join("..").join("inner"), &|p| p.starts_with(&outer)), inner);
419        // The agent's own workspace, inside no other: its path is not the agent's to write, and resolves as before.
420        let link = real_path(base.path()).join("link");
421        std::os::unix::fs::symlink(&elsewhere, &link).unwrap();
422        assert_eq!(memory_project_root_with(&link, &|p| p == link), elsewhere);
423    }
424
425    #[test]
426    fn outside_a_repository_memory_is_keyed_by_the_physical_directory() {
427        let base = tempfile::tempdir().unwrap();
428        let real = real_path(base.path()).join("plain");
429        std::fs::create_dir_all(&real).unwrap();
430        assert_eq!(memory_project_root(&real), real);
431        #[cfg(unix)]
432        {
433            let link = base.path().join("link");
434            std::os::unix::fs::symlink(&real, &link).unwrap();
435            assert_eq!(memory_project_root(&link), real);
436        }
437    }
438
439    #[test]
440    fn a_git_file_that_is_not_a_linked_worktree_keeps_its_own_root() {
441        let base = tempfile::tempdir().unwrap();
442        let dir = real_path(base.path()).join("odd");
443        std::fs::create_dir_all(&dir).unwrap();
444        std::fs::write(dir.join(".git"), "gitdir: ../nowhere\n").unwrap();
445        assert_eq!(memory_project_root(&dir), dir);
446    }
447}