Skip to main content

agentmux_srv_core/backend/work_facts/
paths.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Path and repository-name handling for work facts: one spelling for every
5//! path (forward slashes, no trailing slash), repository-relative paths so
6//! two clones of the same repository compare equal, `owner/repo` from a
7//! remote URL, and where bashwrap keeps an agent's live working folder.
8
9use std::collections::HashMap;
10use std::path::{Path, PathBuf};
11
12/// bashwrap's override for its cwd state file (`crates/bashwrap/src/bash_wrap.rs`,
13/// `CWD_STATE_FILE_OVERRIDE_ENV`). When a block's env sets it, that is the file.
14const CWD_STATE_FILE_OVERRIDE_ENV: &str = "AGENTMUX_BASHWRAP_CWD_STATE_FILE";
15
16/// One spelling for a path: `\` becomes `/`, an MSYS `/c/...` becomes
17/// `C:/...`, repeated slashes collapse and a trailing slash goes.
18pub fn normalize_path(raw: &str) -> String {
19    let mut s = raw.trim().replace('\\', "/");
20    // On Windows, `/c/Users/...` (Git Bash) is `C:/Users/...`.
21    let b = s.as_bytes();
22    if cfg!(windows) && b.len() >= 2 && b[0] == b'/' && b[1].is_ascii_alphabetic() && (b.len() == 2 || b[2] == b'/')
23    {
24        s = format!("{}:{}", (b[1] as char).to_ascii_uppercase(), &s[2..]);
25    }
26    let unc = s.starts_with("//");
27    let mut out = String::with_capacity(s.len());
28    let mut prev_slash = false;
29    for c in s.chars() {
30        if c == '/' && prev_slash {
31            continue;
32        }
33        prev_slash = c == '/';
34        out.push(c);
35    }
36    if unc {
37        out.insert(0, '/');
38    }
39    // `C:/` keeps its slash; `/` alone stays `/`.
40    while out.len() > 1 && out.ends_with('/') && !out.ends_with(":/") {
41        out.pop();
42    }
43    out
44}
45
46/// Whether `raw` names an absolute path in any of the spellings agents use.
47pub fn is_absolute(raw: &str) -> bool {
48    let s = raw.trim().replace('\\', "/");
49    let b = s.as_bytes();
50    s.starts_with('/') || (b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':')
51}
52
53/// Paths compare without case on Windows, where the file system does.
54fn same_text(a: &str, b: &str) -> bool {
55    if cfg!(windows) {
56        a.eq_ignore_ascii_case(b)
57    } else {
58        a == b
59    }
60}
61
62/// `path` relative to `root` (both normalized), or `None` when it isn't
63/// inside it. The root itself is `""`.
64pub fn relative_to(path: &str, root: &str) -> Option<String> {
65    let (path, root) = (normalize_path(path), normalize_path(root));
66    if root.is_empty() || path.len() < root.len() || !path.is_char_boundary(root.len()) {
67        return None;
68    }
69    let (head, rest) = path.split_at(root.len());
70    if !same_text(head, &root) {
71        return None;
72    }
73    if rest.is_empty() {
74        return Some(String::new());
75    }
76    if root.ends_with('/') {
77        return Some(rest.to_string());
78    }
79    rest.strip_prefix('/').map(str::to_string)
80}
81
82/// A repository-relative path as a caller typed it: forward slashes, no
83/// leading `./` or `/`, no trailing slash. `.` is the whole repository (`""`).
84pub fn clean_relative(raw: &str) -> String {
85    let mut s = normalize_path(raw);
86    while let Some(rest) = s.strip_prefix("./") {
87        s = rest.to_string();
88    }
89    if s == "." {
90        s.clear();
91    }
92    s.trim_start_matches('/').to_string()
93}
94
95/// Whether the repository-relative `file` is `target` or inside it. An empty
96/// target is the whole repository. A file ending in `/` is an untracked
97/// folder git reported whole, which matches anything inside it too.
98pub fn path_matches(file: &str, target: &str) -> bool {
99    if target.is_empty() {
100        return true;
101    }
102    let file_dir = file.strip_suffix('/');
103    let file = file_dir.unwrap_or(file);
104    if same_text(file, target) {
105        return true;
106    }
107    let inside = |outer: &str, inner: &str| {
108        inner.len() > outer.len()
109            && inner.is_char_boundary(outer.len())
110            && same_text(&inner[..outer.len()], outer)
111            && inner.as_bytes()[outer.len()] == b'/'
112    };
113    inside(target, file) || (file_dir.is_some() && inside(file, target))
114}
115
116/// The key of a repository, lowercase, from a remote URL in any of git's spellings (`https://host/owner/repo.git`,
117/// `git@host:owner/repo`, `ssh://...`), or from an `owner/repo` a caller typed. Credentials in a URL never survive.
118///
119/// A GitHub remote (`github.com`) and a typed `owner/repo` are `owner/repo`: the key the GitHub-facing code (the PR
120/// poller, `pr_link`, the PR finder) accepts. A remote on any other host is `remote:<host>/<path>` with its whole path
121/// (a GitLab subgroup keeps its group), which that code never takes for a GitHub repository: the last two segments of
122/// a GitLab project's path name some unrelated GitHub repository, or none.
123pub fn normalize_repo(raw: &str) -> Option<String> {
124    let s = raw.trim().trim_end_matches('/');
125    let s = if s.starts_with("remote:") { s } else { s.strip_suffix(".git").unwrap_or(s) };
126    // The host (when the text names one) and everything after it: the part after `://host/`, or after the `:` of an
127    // scp-style `user@host:path`.
128    let (host, path) = if let Some(remote) = s.strip_prefix("remote:") {
129        let (host, path) = remote.split_once('/')?;
130        (Some(host.to_ascii_lowercase()), path)
131    } else if let Some((scheme, rest)) = s.split_once("://") {
132        if scheme.eq_ignore_ascii_case("file") {
133            return None;
134        }
135        let (authority, path) = rest.split_once('/')?;
136        (Some(host_of(authority)), path)
137    } else if let Some((head, rest)) = s.split_once(':') {
138        if head.contains('/') || is_absolute(s) {
139            return None;
140        }
141        (Some(host_of(head)), rest)
142    } else {
143        (None, s)
144    };
145    let parts: Vec<&str> = path.split('/').filter(|p| !p.is_empty()).collect();
146    if parts.len() < 2 {
147        return None;
148    }
149    let ok = |p: &str| p.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
150    match host.filter(|h| !is_github(h)) {
151        // Another host: the whole path, under the host's name.
152        Some(host) => {
153            let host_ok = !host.is_empty() && host.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '.'));
154            (host_ok && parts.iter().all(|p| ok(p))).then(|| format!("remote:{host}/{}", parts.join("/")).to_ascii_lowercase())
155        }
156        None => {
157            let (owner, repo) = (parts[parts.len() - 2], parts[parts.len() - 1]);
158            (ok(owner) && ok(repo)).then(|| format!("{owner}/{repo}").to_ascii_lowercase())
159        }
160    }
161}
162
163/// The host of a URL's authority (`user:password@host:port`) or of an scp-style `user@host`, lowercase.
164fn host_of(authority: &str) -> String {
165    let after_user = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
166    after_user.split(':').next().unwrap_or_default().to_ascii_lowercase()
167}
168
169/// Whether a remote's host is GitHub's own (not an Enterprise Server: the poller reads `api.github.com` only): its web
170/// and SSH-over-443 names, and a host alias from an SSH config (`github.com-work`, the usual way to keep several GitHub
171/// accounts), which names no dot after `github.com-`.
172fn is_github(host: &str) -> bool {
173    matches!(host, "github.com" | "www.github.com" | "ssh.github.com") || host.strip_prefix("github.com-").is_some_and(|alias| !alias.is_empty() && !alias.contains('.'))
174}
175
176/// The key bashwrap names an agent's cwd state file by: the block's
177/// `AGENTMUX_INSTANCE_SLUG`, else its `AGENTMUX_AGENT_ID`, else the
178/// registered agent id; sanitized the way bashwrap does.
179fn cwd_state_key(env: &HashMap<String, String>, agent_id: &str) -> String {
180    let non_empty = |k: &str| env.get(k).map(|v| v.trim()).filter(|v| !v.is_empty());
181    let key = non_empty("AGENTMUX_INSTANCE_SLUG")
182        .or_else(|| non_empty("AGENTMUX_AGENT_ID"))
183        .unwrap_or(agent_id);
184    key.chars()
185        .map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' })
186        .collect()
187}
188
189/// Where bashwrap keeps this agent's live working folder:
190/// `~/.agentmux/state/bashwrap-cwd/<key>.cwd`, unless the env overrides it.
191pub fn cwd_state_file(home: &Path, env: &HashMap<String, String>, agent_id: &str) -> PathBuf {
192    if let Some(over) = env.get(CWD_STATE_FILE_OVERRIDE_ENV).filter(|v| !v.trim().is_empty()) {
193        return PathBuf::from(over.trim());
194    }
195    home.join(".agentmux")
196        .join("state")
197        .join("bashwrap-cwd")
198        .join(format!("{}.cwd", cwd_state_key(env, agent_id)))
199}
200
201/// The agent's working folder: the live one bashwrap recorded when it names
202/// a folder that still exists, else the folder it started in (`cmd:cwd`).
203pub fn working_folder(
204    home: Option<&Path>,
205    env: &HashMap<String, String>,
206    agent_id: &str,
207    start_folder: &str,
208) -> Option<String> {
209    let live = home
210        .map(|h| cwd_state_file(h, env, agent_id))
211        .and_then(|f| std::fs::read_to_string(f).ok())
212        .map(|s| s.trim().to_string())
213        .filter(|s| !s.is_empty() && Path::new(s).is_dir());
214    if let Some(live) = live {
215        return Some(normalize_path(&live));
216    }
217    let start = start_folder.trim();
218    if start.is_empty() {
219        return None;
220    }
221    let start = match (start.strip_prefix("~/"), home) {
222        (Some(rest), Some(h)) => h.join(rest).to_string_lossy().into_owned(),
223        _ => start.to_string(),
224    };
225    Some(normalize_path(&start))
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231
232    #[test]
233    fn normalizes_every_spelling_of_a_path() {
234        assert_eq!(normalize_path(r"C:\Users\a\repo\"), "C:/Users/a/repo");
235        if cfg!(windows) {
236            assert_eq!(normalize_path("/c/Users/a/repo"), "C:/Users/a/repo");
237        } else {
238            assert_eq!(normalize_path("/c/Users/a/repo"), "/c/Users/a/repo");
239        }
240        assert_eq!(normalize_path("C:/"), "C:/");
241        assert_eq!(normalize_path("/home//a/repo/"), "/home/a/repo");
242        assert_eq!(normalize_path(r"\\server\share\x"), "//server/share/x");
243        assert_eq!(normalize_path("/"), "/");
244    }
245
246    #[test]
247    fn relative_to_strips_the_root_and_rejects_outsiders() {
248        assert_eq!(relative_to(r"C:\w\repo\crates\a.rs", "C:/w/repo").as_deref(), Some("crates/a.rs"));
249        assert_eq!(relative_to("C:/w/repo", "C:/w/repo").as_deref(), Some(""));
250        assert_eq!(relative_to("C:/w/repo2/a.rs", "C:/w/repo"), None, "a sibling with a longer name is outside");
251        assert_eq!(relative_to("C:/w/other/a.rs", "C:/w/repo"), None);
252        assert_eq!(relative_to("/a.rs", "/").as_deref(), Some("a.rs"));
253    }
254
255    #[cfg(windows)]
256    #[test]
257    fn relative_to_ignores_case_on_windows() {
258        assert_eq!(relative_to("c:/W/Repo/a.rs", "C:/w/repo").as_deref(), Some("a.rs"));
259    }
260
261    #[test]
262    fn cleans_a_typed_relative_path() {
263        assert_eq!(clean_relative("./crates/srv/"), "crates/srv");
264        assert_eq!(clean_relative(r"crates\srv\a.rs"), "crates/srv/a.rs");
265        assert_eq!(clean_relative("."), "");
266    }
267
268    #[test]
269    fn a_folder_matches_what_is_inside_it_and_nothing_else() {
270        assert!(path_matches("crates/srv/a.rs", "crates/srv/a.rs"));
271        assert!(path_matches("crates/srv/a.rs", "crates/srv"));
272        assert!(path_matches("crates/srv/a.rs", ""));
273        assert!(!path_matches("crates/srv2/a.rs", "crates/srv"), "a prefix is not a folder");
274        assert!(!path_matches("crates", "crates/srv"));
275        // An untracked folder git reported whole contains the target.
276        assert!(path_matches("notes/new/", "notes/new/plan.txt"));
277        assert!(path_matches("notes/new/", "notes"));
278        assert!(!path_matches("notes/newer/", "notes/new"));
279    }
280
281    #[test]
282    fn repo_names_come_from_every_remote_spelling() {
283        for url in [
284            "https://github.com/AgentMuxAI/agentmux.git",
285            "https://x-access-token:secret@github.com/agentmuxai/agentmux",
286            "git@github.com:agentmuxai/agentmux.git",
287            "ssh://git@github.com/agentmuxai/agentmux.git",
288            "agentmuxai/agentmux",
289            "https://github.com/agentmuxai/agentmux/",
290        ] {
291            assert_eq!(normalize_repo(url).as_deref(), Some("agentmuxai/agentmux"), "{url}");
292        }
293        assert_eq!(normalize_repo("agentmux"), None);
294        assert_eq!(normalize_repo("C:/w/repo"), None, "a local path is not a repository name");
295        assert_eq!(normalize_repo(""), None);
296    }
297
298    #[test]
299    fn a_remote_on_another_host_is_never_the_github_repository_of_the_same_name() {
300        for (url, key) in [
301            ("https://gitlab.com/group/api.git", "remote:gitlab.com/group/api"),
302            ("https://gitlab.com/group/api.git.git", "remote:gitlab.com/group/api.git"),
303            ("git@gitlab.com:group/api.git", "remote:gitlab.com/group/api"),
304            ("https://gitlab.com/group/sub/api", "remote:gitlab.com/group/sub/api"),
305            ("ssh://git@git.example.org:2222/team/api.git", "remote:git.example.org/team/api"),
306            ("https://user:secret@gitea.local/Team/API/", "remote:gitea.local/team/api"),
307            ("https://github.mycorp.com/team/api.git", "remote:github.mycorp.com/team/api"),
308            ("https://notgithub.com/team/api", "remote:notgithub.com/team/api"),
309        ] {
310            let got = normalize_repo(url);
311            assert_eq!(got.as_deref(), Some(key), "{url}");
312            assert_eq!(normalize_repo(got.as_deref().unwrap()), got, "{url} must normalize idempotently");
313            assert!(crate::backend::storage::work_card_prs::github_repo(key).is_none(), "{key} is not a GitHub repository");
314        }
315        assert_eq!(normalize_repo("https://gitea.local/lonely.git"), None, "a path of one segment names no repository");
316        assert_eq!(normalize_repo("https://github.com/AgentMuxAI/agentmux.git").as_deref(), Some("agentmuxai/agentmux"));
317        assert_eq!(normalize_repo("https://www.github.com/a/b").as_deref(), Some("a/b"));
318    }
319
320    #[test]
321    fn every_spelling_of_a_github_host_is_the_github_repository() {
322        for url in [
323            "git@github.com-work:AgentMuxAI/agentmux.git",
324            "git@github.com-personal:agentmuxai/agentmux",
325            "ssh://git@ssh.github.com:443/agentmuxai/agentmux.git",
326            "git@ssh.github.com:agentmuxai/agentmux.git",
327        ] {
328            assert_eq!(normalize_repo(url).as_deref(), Some("agentmuxai/agentmux"), "{url}");
329        }
330        // A dotted name after `github.com-` is a host of its own, not an alias in an SSH config.
331        assert_eq!(normalize_repo("https://github.com-evil.example.org/team/api").as_deref(), Some("remote:github.com-evil.example.org/team/api"));
332    }
333
334    #[test]
335    fn the_cwd_state_file_follows_bashwraps_naming() {
336        let home = Path::new("/h");
337        let mut env = HashMap::new();
338        let file = |env: &HashMap<String, String>| cwd_state_file(home, env, "AgentY");
339        assert_eq!(file(&env), Path::new("/h/.agentmux/state/bashwrap-cwd/AgentY.cwd"));
340        env.insert("AGENTMUX_AGENT_ID".to_string(), "Agent Y".to_string());
341        assert_eq!(file(&env), Path::new("/h/.agentmux/state/bashwrap-cwd/Agent_Y.cwd"));
342        env.insert("AGENTMUX_INSTANCE_SLUG".to_string(), "agenty-0629j".to_string());
343        assert_eq!(file(&env), Path::new("/h/.agentmux/state/bashwrap-cwd/agenty-0629j.cwd"));
344        env.insert(CWD_STATE_FILE_OVERRIDE_ENV.to_string(), "/tmp/x.cwd".to_string());
345        assert_eq!(file(&env), Path::new("/tmp/x.cwd"));
346    }
347
348    #[test]
349    fn the_live_folder_wins_over_the_start_folder_only_while_it_exists() {
350        let home = tempfile::tempdir().unwrap();
351        let live = tempfile::tempdir().unwrap();
352        let env = HashMap::new();
353        let state = cwd_state_file(home.path(), &env, "A");
354        std::fs::create_dir_all(state.parent().unwrap()).unwrap();
355
356        assert_eq!(working_folder(Some(home.path()), &env, "A", "/start").as_deref(), Some("/start"));
357        std::fs::write(&state, live.path().to_string_lossy().as_bytes()).unwrap();
358        assert_eq!(
359            working_folder(Some(home.path()), &env, "A", "/start"),
360            Some(normalize_path(&live.path().to_string_lossy()))
361        );
362        std::fs::write(&state, "/no/such/folder/anywhere").unwrap();
363        assert_eq!(working_folder(Some(home.path()), &env, "A", "/start").as_deref(), Some("/start"));
364        assert_eq!(working_folder(Some(home.path()), &env, "A", ""), None);
365    }
366}