1use std::path::{Path, PathBuf};
2
3pub fn safe_canonicalize(path: &Path) -> std::io::Result<PathBuf> {
9 if !may_probe_path(path) {
22 return Ok(path.to_path_buf());
23 }
24 canonicalize_raw(path)
25}
26
27pub(crate) fn canonicalize_raw(path: &Path) -> std::io::Result<PathBuf> {
31 let canon = std::fs::canonicalize(path)?;
32 Ok(strip_verbatim(canon))
33}
34
35pub fn safe_canonicalize_or_self(path: &Path) -> PathBuf {
37 safe_canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
38}
39
40pub fn canonicalize_secure(path: &Path) -> std::io::Result<PathBuf> {
47 canonicalize_raw(path)
48}
49
50pub fn canonicalize_secure_or_self(path: &Path) -> PathBuf {
52 canonicalize_secure(path).unwrap_or_else(|_| path.to_path_buf())
53}
54
55pub fn safe_canonicalize_bounded(path: &Path, timeout_ms: u64) -> PathBuf {
62 canonicalize_bounded_with(path, timeout_ms, safe_canonicalize_or_self)
63}
64
65pub fn canonicalize_secure_bounded(path: &Path, timeout_ms: u64) -> PathBuf {
69 canonicalize_bounded_with(path, timeout_ms, canonicalize_secure_or_self)
70}
71
72fn canonicalize_bounded_with(
76 path: &Path,
77 timeout_ms: u64,
78 resolve: fn(&Path) -> PathBuf,
79) -> PathBuf {
80 use super::io_health;
81
82 let path_str = path.to_string_lossy();
83 if io_health::is_slow_mount(&path_str) && io_health::recent_freeze_count() > 0 {
84 return resolve(path);
85 }
86
87 let effective_timeout =
88 io_health::adaptive_timeout(std::time::Duration::from_millis(timeout_ms));
89
90 let path_owned = path.to_path_buf();
91 let (tx, rx) = std::sync::mpsc::channel();
92 let _ = std::thread::Builder::new()
93 .name("canonicalize-bounded".into())
94 .spawn(move || {
95 let _ = tx.send(resolve(&path_owned));
96 });
97 if let Ok(canonical) = rx.recv_timeout(effective_timeout) {
98 canonical
99 } else {
100 io_health::record_freeze();
101 tracing::warn!(
102 "[SECURITY] canonicalize timed out ({}ms) for {}; PathJail checks on \
103 uncanonicalized paths may be less reliable",
104 effective_timeout.as_millis(),
105 path.display()
106 );
107 path.to_path_buf()
108 }
109}
110
111pub fn strip_verbatim(path: PathBuf) -> PathBuf {
114 let s = path.to_string_lossy();
115 if let Some(stripped) = strip_verbatim_str(&s) {
116 PathBuf::from(stripped)
117 } else {
118 path
119 }
120}
121
122pub fn strip_verbatim_str(path: &str) -> Option<String> {
125 let normalized = path.replace('\\', "/");
126
127 if let Some(rest) = normalized.strip_prefix("//?/UNC/") {
128 Some(format!("//{rest}"))
129 } else {
130 normalized
131 .strip_prefix("//?/")
132 .map(std::string::ToString::to_string)
133 }
134}
135
136fn translate_msys_drive_prefix(p: &str) -> Option<String> {
145 if p.len() >= 3
146 && p.starts_with('/')
147 && p.as_bytes()[1].is_ascii_alphabetic()
148 && p.as_bytes()[2] == b'/'
149 {
150 let drive = p.as_bytes()[1].to_ascii_uppercase() as char;
151 Some(format!("{drive}:{}", &p[2..]))
152 } else {
153 None
154 }
155}
156
157pub fn normalize_tool_path_lexical(path: &str) -> String {
163 let mut p = match strip_verbatim_str(path) {
164 Some(stripped) => stripped,
165 None => path.to_string(),
166 };
167
168 if cfg!(windows)
169 && let Some(translated) = translate_msys_drive_prefix(&p)
170 {
171 p = translated;
172 } else if !cfg!(windows) {
173 p = unescape_shell_path(&p);
174 }
175
176 p = p.replace('\\', "/");
177
178 while p.contains("//") && !p.starts_with("//") {
180 p = p.replace("//", "/");
181 }
182
183 if p.len() > 1 && p.ends_with('/') && !p.ends_with(":/") {
185 p.pop();
186 }
187
188 p
189}
190
191fn unescape_shell_path(path: &str) -> String {
199 let trimmed = path.trim();
200 let unquoted = [('\'', '\''), ('"', '"')]
201 .iter()
202 .find_map(|&(open, close)| {
203 trimmed
204 .strip_prefix(open)
205 .and_then(|rest| rest.strip_suffix(close))
206 .filter(|inner| !inner.is_empty())
207 })
208 .unwrap_or(path);
209 if !unquoted.contains('\\') {
210 return unquoted.to_string();
211 }
212 let mut out = String::with_capacity(unquoted.len());
213 let mut chars = unquoted.chars().peekable();
214 while let Some(c) = chars.next() {
215 if c == '\\'
216 && let Some(&next) = chars.peek()
217 && matches!(
218 next,
219 ' ' | '('
220 | ')'
221 | '['
222 | ']'
223 | '{'
224 | '}'
225 | '&'
226 | '\''
227 | '"'
228 | '$'
229 | '!'
230 | '#'
231 | ';'
232 | '*'
233 | '?'
234 | '<'
235 | '>'
236 | '|'
237 | '~'
238 | '`'
239 | '='
240 )
241 {
242 out.push(next);
243 chars.next();
244 continue;
245 }
246 out.push(c);
247 }
248 out
249}
250
251pub fn normalize_tool_path(path: &str) -> String {
257 let mut p = normalize_tool_path_lexical(path);
258
259 let is_absolute = p.starts_with('/') || (p.len() >= 3 && p.as_bytes()[1] == b':');
265 let is_root_only = p == "/" || (p.len() <= 3 && p.ends_with('/') && is_absolute);
266 if is_absolute
267 && !is_root_only
268 && !crate::core::io_health::is_slow_mount(&p)
269 && may_probe_path(Path::new(&*p))
270 && let Ok(canonical) = safe_canonicalize(Path::new(&*p))
271 {
272 let canonical_str = canonical.to_string_lossy().replace('\\', "/");
273 if !canonical_str.is_empty() {
274 p = canonical_str;
275 }
276 }
277
278 p
279}
280
281pub const AGENT_CONFIG_DIRS: &[&str] = &[
288 ".claude",
289 ".codex",
290 ".codebuddy",
291 ".codewhale",
292 ".copilot",
293 ".cursor",
294 ".windsurf",
295 ".gemini",
296 ".lmstudio",
297];
298
299pub fn is_agent_config_dir(dir: &Path) -> bool {
307 let s = dir.to_string_lossy().replace('\\', "/");
308 AGENT_CONFIG_DIRS.iter().any(|name| {
309 let segment = format!("/{name}");
310 s.match_indices(&segment).any(|(at, _)| {
311 let tail = &s[at + segment.len()..];
312 (tail.is_empty() || tail.starts_with('/')) && !is_worktree_checkout_tail(tail)
313 })
314 })
315}
316
317fn is_worktree_checkout_tail(tail: &str) -> bool {
319 tail.strip_prefix("/worktrees/")
320 .and_then(|rest| rest.split('/').next())
321 .is_some_and(|name| !name.is_empty())
322}
323
324fn is_wsl_windows_user_profile(dir: &Path) -> bool {
325 let normalized = dir.to_string_lossy();
326 if !normalized.starts_with("/mnt/") {
327 return false;
328 }
329
330 let mut components = normalized
331 .split('/')
332 .filter(|component| !component.is_empty());
333 let (Some(mount), Some(drive), Some(users), Some(username)) = (
334 components.next(),
335 components.next(),
336 components.next(),
337 components.next(),
338 ) else {
339 return false;
340 };
341
342 mount.eq_ignore_ascii_case("mnt")
343 && drive.len() == 1
344 && drive.as_bytes()[0].is_ascii_alphabetic()
345 && users.eq_ignore_ascii_case("users")
346 && !username.is_empty()
347 && components.next().is_none()
348}
349
350pub fn is_broad_or_unsafe_root(dir: &Path) -> bool {
356 if let Some(home) = dirs::home_dir()
357 && dir == home
358 {
359 return true;
360 }
361 if is_wsl_windows_user_profile(dir) {
362 return true;
363 }
364 let s = dir.to_string_lossy();
365 if s == "/" || s == "\\" || s == "." {
366 return true;
367 }
368 is_agent_config_dir(dir)
369}
370
371pub const PROJECT_MARKERS: &[&str] = &[
373 ".git",
374 "Cargo.toml",
375 "package.json",
376 "go.mod",
377 "pyproject.toml",
378 "setup.py",
379 "pom.xml",
380 "build.gradle",
381 "Makefile",
382 "project.godot",
383 ".lean-ctx.toml",
384 ".planning",
385];
386
387pub fn has_project_marker(dir: &Path) -> bool {
394 if !may_probe_path(dir) {
395 return false;
396 }
397 PROJECT_MARKERS.iter().any(|m| dir.join(m).exists())
398}
399
400pub fn is_symlink_or_reparse(meta: &std::fs::Metadata) -> bool {
408 if meta.file_type().is_symlink() {
409 return true;
410 }
411 #[cfg(windows)]
412 {
413 use std::os::windows::fs::MetadataExt;
414 const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0400;
415 meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0
416 }
417 #[cfg(not(windows))]
418 false
419}
420
421pub fn is_tcc_sensitive_home_dir(dir: &Path) -> bool {
430 let Some(home) = dirs::home_dir() else {
431 return false;
432 };
433 if dir == home {
434 return true;
435 }
436 if dir.parent() != Some(home.as_path()) {
437 return false;
438 }
439 matches!(
440 dir.file_name().and_then(|n| n.to_str()),
441 Some("Documents" | "Desktop" | "Downloads")
442 )
443}
444
445pub fn is_under_tcc_protected_dir(path: &Path) -> bool {
453 if !cfg!(target_os = "macos") {
454 return false;
455 }
456 let Some(home) = dirs::home_dir() else {
457 return false;
458 };
459 ["Documents", "Desktop", "Downloads"]
460 .iter()
461 .any(|magic| path.starts_with(home.join(magic)))
462}
463
464pub fn process_is_tcc_standalone() -> bool {
478 #[cfg(target_os = "macos")]
479 {
480 if let Ok(v) = std::env::var("LEAN_CTX_TCC_STANDALONE") {
484 match v.trim() {
485 "1" | "true" => return true,
486 "0" | "false" => return false,
487 _ => {}
488 }
489 }
490 if std::env::var_os(crate::core::tcc_guard_sandbox::SEATBELT_SENTINEL).is_some() {
498 return true;
499 }
500 (unsafe { libc::getppid() }) == 1
502 }
503 #[cfg(not(target_os = "macos"))]
504 {
505 false
506 }
507}
508
509pub fn may_probe_path(path: &Path) -> bool {
517 !(process_is_tcc_standalone() && is_under_tcc_protected_dir(path))
518}
519
520pub fn has_multi_repo_children(dir: &Path) -> bool {
523 if is_tcc_sensitive_home_dir(dir) || !may_probe_path(dir) {
529 return false;
530 }
531 let Ok(entries) = std::fs::read_dir(dir) else {
532 return false;
533 };
534 let count = entries
535 .filter_map(Result::ok)
536 .filter(|e| e.file_type().is_ok_and(|ft| ft.is_dir()))
537 .filter(|e| has_project_marker(&e.path()))
538 .take(2)
539 .count();
540 count >= 2
541}
542
543pub fn is_data_dir_collision(project_root: &Path) -> bool {
547 if is_broad_or_unsafe_root(project_root) {
548 return true;
549 }
550 if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
551 let project_lean_ctx = project_root.join(".lean-ctx");
552 if project_lean_ctx == data_dir || data_dir.starts_with(&project_lean_ctx) {
553 return true;
554 }
555 }
556 false
557}
558
559pub fn safe_project_data_dir(project_root: &Path) -> Result<PathBuf, String> {
562 if is_data_dir_collision(project_root) {
563 return Err(format!(
564 "project root {} collides with global data directory; \
565 skipping project-scoped write",
566 project_root.display()
567 ));
568 }
569 Ok(project_root.join(".lean-ctx"))
570}
571
572#[cfg(test)]
573mod tests {
574 use super::*;
575
576 #[test]
577 fn strip_regular_verbatim() {
578 let p = PathBuf::from(r"\\?\C:\Users\dev\project");
579 let result = strip_verbatim(p);
580 assert_eq!(result, PathBuf::from("C:/Users/dev/project"));
581 }
582
583 #[test]
584 fn tcc_sensitive_home_dir_matches_home_and_magic_dirs() {
585 let Some(home) = dirs::home_dir() else {
586 return;
587 };
588 assert!(is_tcc_sensitive_home_dir(&home));
590 assert!(is_tcc_sensitive_home_dir(&home.join("Documents")));
591 assert!(is_tcc_sensitive_home_dir(&home.join("Desktop")));
592 assert!(is_tcc_sensitive_home_dir(&home.join("Downloads")));
593 }
594
595 #[test]
596 fn tcc_sensitive_home_dir_allows_real_projects() {
597 let Some(home) = dirs::home_dir() else {
598 return;
599 };
600 assert!(!is_tcc_sensitive_home_dir(
603 &home.join("Documents").join("my-project")
604 ));
605 assert!(!is_tcc_sensitive_home_dir(&home.join("code")));
606 assert!(!is_tcc_sensitive_home_dir(&home.join("Projects")));
607 }
608
609 #[test]
610 #[cfg(target_os = "macos")]
611 fn under_tcc_protected_dir_matches_nested_paths() {
612 let Some(home) = dirs::home_dir() else {
613 return;
614 };
615 assert!(is_under_tcc_protected_dir(&home.join("Documents")));
617 assert!(is_under_tcc_protected_dir(
618 &home.join("Documents/deep/nested/project")
619 ));
620 assert!(is_under_tcc_protected_dir(&home.join("Desktop/scratch")));
621 assert!(is_under_tcc_protected_dir(&home.join("Downloads/x.zip")));
622 assert!(!is_under_tcc_protected_dir(&home));
624 assert!(!is_under_tcc_protected_dir(&home.join("code/project")));
625 assert!(!is_under_tcc_protected_dir(Path::new("/tmp/Documents")));
626 }
627
628 #[test]
629 #[cfg(target_os = "macos")]
630 #[serial_test::serial]
631 fn tcc_standalone_blocks_probes_under_protected_dirs() {
632 let _env_lock = crate::core::data_dir::test_env_lock();
638 let Some(home) = dirs::home_dir() else {
639 return;
640 };
641 let doc_proj = home.join("Documents/some-project");
642
643 crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "1");
644 assert!(process_is_tcc_standalone());
645 assert!(!may_probe_path(&doc_proj));
646 assert!(may_probe_path(Path::new("/tmp/some-project")));
648 assert!(!has_project_marker(&doc_proj));
650
651 crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "0");
652 assert!(!process_is_tcc_standalone());
653 assert!(may_probe_path(&doc_proj));
654 crate::test_env::remove_var("LEAN_CTX_TCC_STANDALONE");
655 }
656
657 #[test]
658 #[cfg(target_os = "macos")]
659 #[serial_test::serial]
660 fn tcc_standalone_detected_via_seatbelt_sentinel() {
661 let _env_lock = crate::core::data_dir::test_env_lock();
662 let Some(home) = dirs::home_dir() else {
663 return;
664 };
665 let doc_proj = home.join("Documents/some-project");
666
667 crate::test_env::remove_var("LEAN_CTX_TCC_STANDALONE");
672 crate::test_env::set_var(crate::core::tcc_guard_sandbox::SEATBELT_SENTINEL, "1");
673 assert!(process_is_tcc_standalone());
674 assert!(!may_probe_path(&doc_proj));
675 crate::test_env::remove_var(crate::core::tcc_guard_sandbox::SEATBELT_SENTINEL);
676
677 assert!(!process_is_tcc_standalone());
680 }
681
682 #[test]
683 #[cfg(target_os = "macos")]
684 #[serial_test::serial]
685 fn tcc_standalone_skips_canonicalize_under_protected_dirs() {
686 let _env_lock = crate::core::data_dir::test_env_lock();
687 let Some(home) = dirs::home_dir() else {
688 return;
689 };
690 let missing = home.join("Documents/lean-ctx-tcc-test-does-not-exist-xyzzy");
696
697 crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "1");
698 let guarded = safe_canonicalize(&missing);
699 assert!(
700 guarded.is_ok(),
701 "standalone safe_canonicalize must short-circuit (no stat) under ~/Documents"
702 );
703 assert_eq!(guarded.unwrap(), missing);
704 assert_eq!(safe_canonicalize_or_self(&missing), missing);
705
706 let tmp_missing = Path::new("/tmp/lean-ctx-tcc-test-does-not-exist-xyzzy");
708 assert!(safe_canonicalize(tmp_missing).is_err());
709
710 crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "0");
713 assert!(safe_canonicalize(&missing).is_err());
714
715 crate::test_env::remove_var("LEAN_CTX_TCC_STANDALONE");
716 }
717
718 #[test]
719 #[cfg(target_os = "macos")]
720 #[serial_test::serial]
721 fn canonicalize_secure_bypasses_tcc_guard_for_pathjail() {
722 let _env_lock = crate::core::data_dir::test_env_lock();
723 let Some(home) = dirs::home_dir() else {
730 return;
731 };
732 let missing = home.join("Documents/lean-ctx-secure-canon-does-not-exist-xyzzy");
733
734 crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "1");
735 assert_eq!(safe_canonicalize(&missing).unwrap(), missing);
737 assert!(
741 canonicalize_secure(&missing).is_err(),
742 "canonicalize_secure must bypass the TCC guard and touch the filesystem"
743 );
744 assert_eq!(canonicalize_secure_or_self(&missing), missing);
745 crate::test_env::remove_var("LEAN_CTX_TCC_STANDALONE");
746 }
747
748 #[test]
749 fn strip_unc_verbatim() {
750 let p = PathBuf::from(r"\\?\UNC\server\share\dir");
751 let result = strip_verbatim(p);
752 assert_eq!(result, PathBuf::from("//server/share/dir"));
753 }
754
755 #[test]
756 fn no_prefix_unchanged() {
757 let p = PathBuf::from("/home/user/project");
758 let result = strip_verbatim(p.clone());
759 assert_eq!(result, p);
760 }
761
762 #[test]
763 fn windows_drive_unchanged() {
764 let p = PathBuf::from("C:/Users/dev");
765 let result = strip_verbatim(p.clone());
766 assert_eq!(result, p);
767 }
768
769 #[test]
770 fn strip_str_regular() {
771 assert_eq!(
772 strip_verbatim_str(r"\\?\E:\code\lean-ctx"),
773 Some("E:/code/lean-ctx".to_string())
774 );
775 }
776
777 #[test]
778 fn strip_str_unc() {
779 assert_eq!(
780 strip_verbatim_str(r"\\?\UNC\myserver\data"),
781 Some("//myserver/data".to_string())
782 );
783 }
784
785 #[test]
786 fn strip_str_forward_slash_variant() {
787 assert_eq!(
788 strip_verbatim_str("//?/C:/Users/dev"),
789 Some("C:/Users/dev".to_string())
790 );
791 }
792
793 #[test]
794 fn strip_str_no_prefix() {
795 assert_eq!(strip_verbatim_str("/home/user"), None);
796 }
797
798 #[test]
799 fn safe_canonicalize_or_self_nonexistent() {
800 let p = Path::new("/this/path/should/not/exist/xyzzy");
801 let result = safe_canonicalize_or_self(p);
802 assert_eq!(result, p.to_path_buf());
803 }
804
805 #[test]
808 fn msys_drive_prefix_translation() {
809 assert_eq!(
810 translate_msys_drive_prefix("/c/Users/ABC").as_deref(),
811 Some("C:/Users/ABC")
812 );
813 assert_eq!(
814 translate_msys_drive_prefix("/D/Program Files").as_deref(),
815 Some("D:/Program Files")
816 );
817 assert_eq!(translate_msys_drive_prefix("/usr/local/bin"), None);
818 assert_eq!(translate_msys_drive_prefix("/c"), None);
819 assert_eq!(translate_msys_drive_prefix("c/Users"), None);
820 }
821
822 #[cfg(windows)]
823 #[test]
824 fn normalize_msys_path_to_native() {
825 assert_eq!(
826 normalize_tool_path("/c/Users/ABC/AppData/lean-ctx"),
827 "C:/Users/ABC/AppData/lean-ctx"
828 );
829 assert_eq!(
830 normalize_tool_path("/D/Program Files/lean-ctx.exe"),
831 "D:/Program Files/lean-ctx.exe"
832 );
833 }
834
835 #[cfg(not(windows))]
838 #[test]
839 fn normalize_single_letter_unix_path_untouched() {
840 assert_eq!(
841 normalize_tool_path_lexical("/c/Users/me/proj"),
842 "/c/Users/me/proj"
843 );
844 assert_eq!(
845 normalize_tool_path_lexical("/x/projects/app/src"),
846 "/x/projects/app/src"
847 );
848 }
849
850 #[test]
851 fn normalize_native_windows_path_unchanged() {
852 assert_eq!(
853 normalize_tool_path("C:/Users/ABC/lean-ctx.exe"),
854 "C:/Users/ABC/lean-ctx.exe"
855 );
856 }
857
858 #[test]
859 fn normalize_backslash_windows_path() {
860 assert_eq!(
861 normalize_tool_path(r"C:\Users\ABC\lean-ctx.exe"),
862 "C:/Users/ABC/lean-ctx.exe"
863 );
864 }
865
866 #[test]
867 fn normalize_unix_path_unchanged() {
868 assert_eq!(
869 normalize_tool_path("/usr/local/bin/lean-ctx"),
870 "/usr/local/bin/lean-ctx"
871 );
872 }
873
874 #[cfg(not(windows))]
875 #[test]
876 fn normalize_unescapes_shell_quoting_on_unix() {
877 assert_eq!(
878 normalize_tool_path_lexical(r"/Users/me/Pfadi\ Scouting/app/main.ts"),
879 "/Users/me/Pfadi Scouting/app/main.ts",
880 "an escaped space must not become a separator"
881 );
882 assert_eq!(
883 normalize_tool_path_lexical(r"/srv/\(group\)/a\&b.txt"),
884 "/srv/(group)/a&b.txt"
885 );
886 assert_eq!(
887 normalize_tool_path_lexical("'/Users/me/My Project/src'"),
888 "/Users/me/My Project/src"
889 );
890 assert_eq!(normalize_tool_path_lexical("\"/tmp/a b\""), "/tmp/a b");
891 assert_eq!(
892 normalize_tool_path_lexical("'"),
893 "'",
894 "a lone quote is a name"
895 );
896 }
897
898 #[test]
899 fn normalize_windows_path_with_spaces_and_backslashes() {
900 assert_eq!(
904 normalize_tool_path(r"C:\Users\My Name\My Project\src\main.rs"),
905 "C:/Users/My Name/My Project/src/main.rs"
906 );
907 assert_eq!(
908 normalize_tool_path(r"C:\Program Files\app\config.toml"),
909 "C:/Program Files/app/config.toml"
910 );
911 }
912
913 #[test]
914 fn normalize_double_slashes() {
915 assert_eq!(
916 normalize_tool_path("C:/Users//ABC//lean-ctx"),
917 "C:/Users/ABC/lean-ctx"
918 );
919 }
920
921 #[test]
922 fn normalize_trailing_slash_removed() {
923 assert_eq!(normalize_tool_path("C:/Users/ABC/"), "C:/Users/ABC");
924 assert_eq!(
925 normalize_tool_path_lexical("/tmp/nonexistent-dir-xyzzy/"),
926 "/tmp/nonexistent-dir-xyzzy"
927 );
928 }
929
930 #[test]
931 fn normalize_root_slash_preserved() {
932 assert_eq!(normalize_tool_path("/"), "/");
933 }
934
935 #[test]
936 fn normalize_drive_root_preserved() {
937 assert_eq!(normalize_tool_path("C:/"), "C:/");
938 }
939
940 #[test]
941 fn normalize_verbatim_with_msys() {
942 assert_eq!(normalize_tool_path(r"\\?\C:\Users\dev"), "C:/Users/dev");
943 }
944
945 #[test]
946 fn broad_root_rejects_home() {
947 if let Some(home) = dirs::home_dir() {
948 assert!(is_broad_or_unsafe_root(&home));
949 }
950 }
951
952 #[test]
953 fn broad_root_rejects_wsl_windows_user_profile() {
954 assert!(is_broad_or_unsafe_root(Path::new("/mnt/c/Users/dev")));
955 assert!(!is_broad_or_unsafe_root(Path::new(
956 "/mnt/c/Users/dev/projects/my-app"
957 )));
958 }
959
960 #[test]
961 fn broad_root_rejects_filesystem_root() {
962 assert!(is_broad_or_unsafe_root(Path::new("/")));
963 }
964
965 #[test]
966 fn broad_root_rejects_dot() {
967 assert!(is_broad_or_unsafe_root(Path::new(".")));
968 }
969
970 #[test]
971 fn broad_root_rejects_agent_dirs() {
972 assert!(is_broad_or_unsafe_root(Path::new("/home/user/.claude")));
973 assert!(is_broad_or_unsafe_root(Path::new("/home/user/.codex")));
974 }
975
976 #[test]
977 fn broad_root_rejects_copilot_and_friends() {
978 assert!(is_broad_or_unsafe_root(Path::new("/home/user/.copilot")));
981 assert!(is_broad_or_unsafe_root(Path::new("/home/user/.cursor")));
982 assert!(is_broad_or_unsafe_root(Path::new("/home/user/.windsurf")));
983 assert!(is_broad_or_unsafe_root(Path::new("/home/user/.gemini")));
984 assert!(is_broad_or_unsafe_root(Path::new("/home/user/.lmstudio")));
985 }
986
987 #[test]
988 fn agent_config_dir_matches_every_known_client() {
989 for name in AGENT_CONFIG_DIRS {
990 let leaf = format!("/home/user/{name}");
991 assert!(is_agent_config_dir(Path::new(&leaf)), "{leaf}");
992 let nested = format!("/home/user/{name}/mcp");
993 assert!(is_agent_config_dir(Path::new(&nested)), "{nested}");
994 }
995 }
996
997 #[test]
998 fn claude_code_worktree_checkout_is_not_agent_config() {
999 for p in [
1002 "/repo/.claude/worktrees/fix-x",
1003 "/repo/.claude/worktrees/fix-x/rust/src",
1004 r"C:\repo\.claude\worktrees\fix-x",
1005 ] {
1006 assert!(!is_agent_config_dir(Path::new(p)), "{p}");
1007 assert!(!is_broad_or_unsafe_root(Path::new(p)), "{p}");
1008 }
1009 for p in [
1010 "/repo/.claude/worktrees",
1011 "/repo/.claude/worktrees/",
1012 "/repo/.claude/settings",
1013 "/repo/.claude/worktrees/fix-x/.claude",
1014 "/repo/.claude/worktrees/fix-x/.codex/mcp",
1015 "/home/user/.claude/worktreesx/a",
1016 ] {
1017 assert!(is_agent_config_dir(Path::new(p)), "{p}");
1018 }
1019 assert!(!is_agent_config_dir(Path::new("/repo/.claudex/a")));
1020 }
1021
1022 #[test]
1023 fn agent_config_dir_matches_windows_backslash() {
1024 assert!(is_agent_config_dir(Path::new(r"C:\Users\me\.copilot")));
1026 assert!(is_agent_config_dir(Path::new(r"C:\Users\me\.copilot\mcp")));
1027 }
1028
1029 #[test]
1030 fn agent_config_dir_ignores_real_projects() {
1031 assert!(!is_agent_config_dir(Path::new("/home/user/code/lean-ctx")));
1032 assert!(!is_agent_config_dir(Path::new(r"C:\src\app")));
1033 }
1034
1035 #[test]
1036 fn broad_root_allows_project_subdir() {
1037 let tmp = tempfile::tempdir().unwrap();
1038 let subdir = tmp.path().join("my-project");
1039 std::fs::create_dir_all(&subdir).unwrap();
1040 assert!(!is_broad_or_unsafe_root(&subdir));
1041 }
1042
1043 #[test]
1044 fn broad_root_allows_home_subdirs() {
1045 if let Some(home) = dirs::home_dir() {
1046 let subdir = home.join("projects").join("my-app");
1047 assert!(!is_broad_or_unsafe_root(&subdir));
1048 }
1049 }
1050
1051 #[test]
1052 fn data_dir_collision_rejects_home() {
1053 if let Some(home) = dirs::home_dir() {
1054 assert!(is_data_dir_collision(&home));
1055 }
1056 }
1057
1058 #[test]
1059 fn data_dir_collision_allows_normal_project() {
1060 let tmp = tempfile::tempdir().unwrap();
1061 let project = tmp.path().join("my-project");
1062 std::fs::create_dir_all(&project).unwrap();
1063 assert!(!is_data_dir_collision(&project));
1064 }
1065
1066 #[test]
1067 fn has_project_marker_detects_git() {
1068 let tmp = tempfile::tempdir().unwrap();
1069 let root = tmp.path().join("repo");
1070 std::fs::create_dir_all(&root).unwrap();
1071 assert!(!has_project_marker(&root));
1072 std::fs::create_dir(root.join(".git")).unwrap();
1073 assert!(has_project_marker(&root));
1074 }
1075
1076 #[test]
1077 fn has_project_marker_detects_cargo_toml() {
1078 let tmp = tempfile::tempdir().unwrap();
1079 let root = tmp.path().join("rust-project");
1080 std::fs::create_dir_all(&root).unwrap();
1081 std::fs::write(root.join("Cargo.toml"), "[package]").unwrap();
1082 assert!(has_project_marker(&root));
1083 }
1084
1085 #[test]
1086 fn has_project_marker_detects_godot_project() {
1087 let tmp = tempfile::tempdir().unwrap();
1088 let root = tmp.path().join("godot-game");
1089 std::fs::create_dir_all(&root).unwrap();
1090 std::fs::write(root.join("project.godot"), "config_version=5\n").unwrap();
1091 assert!(has_project_marker(&root));
1092 }
1093
1094 #[test]
1095 fn multi_repo_children_needs_two() {
1096 let tmp = tempfile::tempdir().unwrap();
1097 let parent = tmp.path().join("code");
1098 std::fs::create_dir_all(&parent).unwrap();
1099
1100 assert!(!has_multi_repo_children(&parent));
1102
1103 let repo1 = parent.join("repo1");
1105 std::fs::create_dir_all(repo1.join(".git")).unwrap();
1106 assert!(!has_multi_repo_children(&parent));
1107
1108 let repo2 = parent.join("repo2");
1110 std::fs::create_dir_all(repo2.join(".git")).unwrap();
1111 assert!(has_multi_repo_children(&parent));
1112 }
1113
1114 #[test]
1115 fn multi_repo_children_ignores_files() {
1116 let tmp = tempfile::tempdir().unwrap();
1117 let parent = tmp.path().join("mixed");
1118 std::fs::create_dir_all(&parent).unwrap();
1119
1120 let repo1 = parent.join("repo1");
1122 std::fs::create_dir_all(repo1.join(".git")).unwrap();
1123 std::fs::write(parent.join("not-a-repo"), "file").unwrap();
1124 assert!(!has_multi_repo_children(&parent));
1125
1126 let repo2 = parent.join("repo2");
1128 std::fs::create_dir_all(&repo2).unwrap();
1129 std::fs::write(repo2.join("package.json"), "{}").unwrap();
1130 assert!(has_multi_repo_children(&parent));
1131 }
1132
1133 #[test]
1134 fn multi_repo_children_nonexistent_dir() {
1135 assert!(!has_multi_repo_children(Path::new("/nonexistent/path/xyz")));
1136 }
1137
1138 #[test]
1139 fn regular_file_is_not_symlink_or_reparse() {
1140 let tmp = tempfile::tempdir().unwrap();
1141 let file = tmp.path().join("plain.txt");
1142 std::fs::write(&file, "x").unwrap();
1143 let meta = std::fs::symlink_metadata(&file).unwrap();
1144 assert!(!is_symlink_or_reparse(&meta));
1145 }
1146
1147 #[cfg(unix)]
1148 #[test]
1149 fn unix_symlink_is_detected() {
1150 let tmp = tempfile::tempdir().unwrap();
1151 let target = tmp.path().join("target.txt");
1152 std::fs::write(&target, "x").unwrap();
1153 let link = tmp.path().join("link.txt");
1154 std::os::unix::fs::symlink(&target, &link).unwrap();
1155 let meta = std::fs::symlink_metadata(&link).unwrap();
1156 assert!(is_symlink_or_reparse(&meta));
1157 }
1158
1159 #[cfg(windows)]
1162 #[test]
1163 fn windows_symlink_is_detected() {
1164 let tmp = tempfile::tempdir().unwrap();
1165 let target = tmp.path().join("target.txt");
1166 std::fs::write(&target, "x").unwrap();
1167 let link = tmp.path().join("link.txt");
1168 if std::os::windows::fs::symlink_file(&target, &link).is_err() {
1169 eprintln!("skipping: symlink creation not permitted on this runner");
1170 return;
1171 }
1172 let meta = std::fs::symlink_metadata(&link).unwrap();
1173 assert!(is_symlink_or_reparse(&meta));
1174 }
1175}