1use std::collections::HashMap;
10use std::path::{Path, PathBuf};
11
12const CWD_STATE_FILE_OVERRIDE_ENV: &str = "AGENTMUX_BASHWRAP_CWD_STATE_FILE";
15
16pub fn normalize_path(raw: &str) -> String {
19 let mut s = raw.trim().replace('\\', "/");
20 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 while out.len() > 1 && out.ends_with('/') && !out.ends_with(":/") {
41 out.pop();
42 }
43 out
44}
45
46pub 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
53fn 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
62pub 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
82pub 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
95pub 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
116pub 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 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 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
163fn 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
169fn 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
176fn 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
189pub 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
201pub 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 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 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}