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 }
173
174 p = p.replace('\\', "/");
175
176 while p.contains("//") && !p.starts_with("//") {
178 p = p.replace("//", "/");
179 }
180
181 if p.len() > 1 && p.ends_with('/') && !p.ends_with(":/") {
183 p.pop();
184 }
185
186 p
187}
188
189pub fn normalize_tool_path(path: &str) -> String {
195 let mut p = normalize_tool_path_lexical(path);
196
197 let is_absolute = p.starts_with('/') || (p.len() >= 3 && p.as_bytes()[1] == b':');
203 let is_root_only = p == "/" || (p.len() <= 3 && p.ends_with('/') && is_absolute);
204 if is_absolute
205 && !is_root_only
206 && !crate::core::io_health::is_slow_mount(&p)
207 && may_probe_path(Path::new(&*p))
208 && let Ok(canonical) = safe_canonicalize(Path::new(&*p))
209 {
210 let canonical_str = canonical.to_string_lossy().replace('\\', "/");
211 if !canonical_str.is_empty() {
212 p = canonical_str;
213 }
214 }
215
216 p
217}
218
219pub const AGENT_CONFIG_DIRS: &[&str] = &[
226 ".claude",
227 ".codex",
228 ".codebuddy",
229 ".codewhale",
230 ".copilot",
231 ".cursor",
232 ".windsurf",
233 ".gemini",
234 ".lmstudio",
235];
236
237pub fn is_agent_config_dir(dir: &Path) -> bool {
245 let s = dir.to_string_lossy().replace('\\', "/");
246 AGENT_CONFIG_DIRS.iter().any(|name| {
247 let segment = format!("/{name}");
248 s.match_indices(&segment).any(|(at, _)| {
249 let tail = &s[at + segment.len()..];
250 (tail.is_empty() || tail.starts_with('/')) && !is_worktree_checkout_tail(tail)
251 })
252 })
253}
254
255fn is_worktree_checkout_tail(tail: &str) -> bool {
257 tail.strip_prefix("/worktrees/")
258 .and_then(|rest| rest.split('/').next())
259 .is_some_and(|name| !name.is_empty())
260}
261
262fn is_wsl_windows_user_profile(dir: &Path) -> bool {
263 let normalized = dir.to_string_lossy();
264 if !normalized.starts_with("/mnt/") {
265 return false;
266 }
267
268 let mut components = normalized
269 .split('/')
270 .filter(|component| !component.is_empty());
271 let (Some(mount), Some(drive), Some(users), Some(username)) = (
272 components.next(),
273 components.next(),
274 components.next(),
275 components.next(),
276 ) else {
277 return false;
278 };
279
280 mount.eq_ignore_ascii_case("mnt")
281 && drive.len() == 1
282 && drive.as_bytes()[0].is_ascii_alphabetic()
283 && users.eq_ignore_ascii_case("users")
284 && !username.is_empty()
285 && components.next().is_none()
286}
287
288pub fn is_broad_or_unsafe_root(dir: &Path) -> bool {
294 if let Some(home) = dirs::home_dir()
295 && dir == home
296 {
297 return true;
298 }
299 if is_wsl_windows_user_profile(dir) {
300 return true;
301 }
302 let s = dir.to_string_lossy();
303 if s == "/" || s == "\\" || s == "." {
304 return true;
305 }
306 is_agent_config_dir(dir)
307}
308
309pub const PROJECT_MARKERS: &[&str] = &[
311 ".git",
312 "Cargo.toml",
313 "package.json",
314 "go.mod",
315 "pyproject.toml",
316 "setup.py",
317 "pom.xml",
318 "build.gradle",
319 "Makefile",
320 "project.godot",
321 ".lean-ctx.toml",
322 ".planning",
323];
324
325pub fn has_project_marker(dir: &Path) -> bool {
332 if !may_probe_path(dir) {
333 return false;
334 }
335 PROJECT_MARKERS.iter().any(|m| dir.join(m).exists())
336}
337
338pub fn is_symlink_or_reparse(meta: &std::fs::Metadata) -> bool {
346 if meta.file_type().is_symlink() {
347 return true;
348 }
349 #[cfg(windows)]
350 {
351 use std::os::windows::fs::MetadataExt;
352 const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0400;
353 meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0
354 }
355 #[cfg(not(windows))]
356 false
357}
358
359pub fn is_tcc_sensitive_home_dir(dir: &Path) -> bool {
368 let Some(home) = dirs::home_dir() else {
369 return false;
370 };
371 if dir == home {
372 return true;
373 }
374 if dir.parent() != Some(home.as_path()) {
375 return false;
376 }
377 matches!(
378 dir.file_name().and_then(|n| n.to_str()),
379 Some("Documents" | "Desktop" | "Downloads")
380 )
381}
382
383pub fn is_under_tcc_protected_dir(path: &Path) -> bool {
391 if !cfg!(target_os = "macos") {
392 return false;
393 }
394 let Some(home) = dirs::home_dir() else {
395 return false;
396 };
397 ["Documents", "Desktop", "Downloads"]
398 .iter()
399 .any(|magic| path.starts_with(home.join(magic)))
400}
401
402pub fn process_is_tcc_standalone() -> bool {
416 #[cfg(target_os = "macos")]
417 {
418 if let Ok(v) = std::env::var("LEAN_CTX_TCC_STANDALONE") {
422 match v.trim() {
423 "1" | "true" => return true,
424 "0" | "false" => return false,
425 _ => {}
426 }
427 }
428 if std::env::var_os(crate::core::tcc_guard_sandbox::SEATBELT_SENTINEL).is_some() {
436 return true;
437 }
438 (unsafe { libc::getppid() }) == 1
440 }
441 #[cfg(not(target_os = "macos"))]
442 {
443 false
444 }
445}
446
447pub fn may_probe_path(path: &Path) -> bool {
455 !(process_is_tcc_standalone() && is_under_tcc_protected_dir(path))
456}
457
458pub fn has_multi_repo_children(dir: &Path) -> bool {
461 if is_tcc_sensitive_home_dir(dir) || !may_probe_path(dir) {
467 return false;
468 }
469 let Ok(entries) = std::fs::read_dir(dir) else {
470 return false;
471 };
472 let count = entries
473 .filter_map(Result::ok)
474 .filter(|e| e.file_type().is_ok_and(|ft| ft.is_dir()))
475 .filter(|e| has_project_marker(&e.path()))
476 .take(2)
477 .count();
478 count >= 2
479}
480
481pub fn is_data_dir_collision(project_root: &Path) -> bool {
485 if is_broad_or_unsafe_root(project_root) {
486 return true;
487 }
488 if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
489 let project_lean_ctx = project_root.join(".lean-ctx");
490 if project_lean_ctx == data_dir || data_dir.starts_with(&project_lean_ctx) {
491 return true;
492 }
493 }
494 false
495}
496
497pub fn safe_project_data_dir(project_root: &Path) -> Result<PathBuf, String> {
500 if is_data_dir_collision(project_root) {
501 return Err(format!(
502 "project root {} collides with global data directory; \
503 skipping project-scoped write",
504 project_root.display()
505 ));
506 }
507 Ok(project_root.join(".lean-ctx"))
508}
509
510#[cfg(test)]
511mod tests {
512 use super::*;
513
514 #[test]
515 fn strip_regular_verbatim() {
516 let p = PathBuf::from(r"\\?\C:\Users\dev\project");
517 let result = strip_verbatim(p);
518 assert_eq!(result, PathBuf::from("C:/Users/dev/project"));
519 }
520
521 #[test]
522 fn tcc_sensitive_home_dir_matches_home_and_magic_dirs() {
523 let Some(home) = dirs::home_dir() else {
524 return;
525 };
526 assert!(is_tcc_sensitive_home_dir(&home));
528 assert!(is_tcc_sensitive_home_dir(&home.join("Documents")));
529 assert!(is_tcc_sensitive_home_dir(&home.join("Desktop")));
530 assert!(is_tcc_sensitive_home_dir(&home.join("Downloads")));
531 }
532
533 #[test]
534 fn tcc_sensitive_home_dir_allows_real_projects() {
535 let Some(home) = dirs::home_dir() else {
536 return;
537 };
538 assert!(!is_tcc_sensitive_home_dir(
541 &home.join("Documents").join("my-project")
542 ));
543 assert!(!is_tcc_sensitive_home_dir(&home.join("code")));
544 assert!(!is_tcc_sensitive_home_dir(&home.join("Projects")));
545 }
546
547 #[test]
548 #[cfg(target_os = "macos")]
549 fn under_tcc_protected_dir_matches_nested_paths() {
550 let Some(home) = dirs::home_dir() else {
551 return;
552 };
553 assert!(is_under_tcc_protected_dir(&home.join("Documents")));
555 assert!(is_under_tcc_protected_dir(
556 &home.join("Documents/deep/nested/project")
557 ));
558 assert!(is_under_tcc_protected_dir(&home.join("Desktop/scratch")));
559 assert!(is_under_tcc_protected_dir(&home.join("Downloads/x.zip")));
560 assert!(!is_under_tcc_protected_dir(&home));
562 assert!(!is_under_tcc_protected_dir(&home.join("code/project")));
563 assert!(!is_under_tcc_protected_dir(Path::new("/tmp/Documents")));
564 }
565
566 #[test]
567 #[cfg(target_os = "macos")]
568 #[serial_test::serial]
569 fn tcc_standalone_blocks_probes_under_protected_dirs() {
570 let _env_lock = crate::core::data_dir::test_env_lock();
576 let Some(home) = dirs::home_dir() else {
577 return;
578 };
579 let doc_proj = home.join("Documents/some-project");
580
581 crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "1");
582 assert!(process_is_tcc_standalone());
583 assert!(!may_probe_path(&doc_proj));
584 assert!(may_probe_path(Path::new("/tmp/some-project")));
586 assert!(!has_project_marker(&doc_proj));
588
589 crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "0");
590 assert!(!process_is_tcc_standalone());
591 assert!(may_probe_path(&doc_proj));
592 crate::test_env::remove_var("LEAN_CTX_TCC_STANDALONE");
593 }
594
595 #[test]
596 #[cfg(target_os = "macos")]
597 #[serial_test::serial]
598 fn tcc_standalone_detected_via_seatbelt_sentinel() {
599 let _env_lock = crate::core::data_dir::test_env_lock();
600 let Some(home) = dirs::home_dir() else {
601 return;
602 };
603 let doc_proj = home.join("Documents/some-project");
604
605 crate::test_env::remove_var("LEAN_CTX_TCC_STANDALONE");
610 crate::test_env::set_var(crate::core::tcc_guard_sandbox::SEATBELT_SENTINEL, "1");
611 assert!(process_is_tcc_standalone());
612 assert!(!may_probe_path(&doc_proj));
613 crate::test_env::remove_var(crate::core::tcc_guard_sandbox::SEATBELT_SENTINEL);
614
615 assert!(!process_is_tcc_standalone());
618 }
619
620 #[test]
621 #[cfg(target_os = "macos")]
622 #[serial_test::serial]
623 fn tcc_standalone_skips_canonicalize_under_protected_dirs() {
624 let _env_lock = crate::core::data_dir::test_env_lock();
625 let Some(home) = dirs::home_dir() else {
626 return;
627 };
628 let missing = home.join("Documents/lean-ctx-tcc-test-does-not-exist-xyzzy");
634
635 crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "1");
636 let guarded = safe_canonicalize(&missing);
637 assert!(
638 guarded.is_ok(),
639 "standalone safe_canonicalize must short-circuit (no stat) under ~/Documents"
640 );
641 assert_eq!(guarded.unwrap(), missing);
642 assert_eq!(safe_canonicalize_or_self(&missing), missing);
643
644 let tmp_missing = Path::new("/tmp/lean-ctx-tcc-test-does-not-exist-xyzzy");
646 assert!(safe_canonicalize(tmp_missing).is_err());
647
648 crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "0");
651 assert!(safe_canonicalize(&missing).is_err());
652
653 crate::test_env::remove_var("LEAN_CTX_TCC_STANDALONE");
654 }
655
656 #[test]
657 #[cfg(target_os = "macos")]
658 #[serial_test::serial]
659 fn canonicalize_secure_bypasses_tcc_guard_for_pathjail() {
660 let _env_lock = crate::core::data_dir::test_env_lock();
661 let Some(home) = dirs::home_dir() else {
668 return;
669 };
670 let missing = home.join("Documents/lean-ctx-secure-canon-does-not-exist-xyzzy");
671
672 crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "1");
673 assert_eq!(safe_canonicalize(&missing).unwrap(), missing);
675 assert!(
679 canonicalize_secure(&missing).is_err(),
680 "canonicalize_secure must bypass the TCC guard and touch the filesystem"
681 );
682 assert_eq!(canonicalize_secure_or_self(&missing), missing);
683 crate::test_env::remove_var("LEAN_CTX_TCC_STANDALONE");
684 }
685
686 #[test]
687 fn strip_unc_verbatim() {
688 let p = PathBuf::from(r"\\?\UNC\server\share\dir");
689 let result = strip_verbatim(p);
690 assert_eq!(result, PathBuf::from("//server/share/dir"));
691 }
692
693 #[test]
694 fn no_prefix_unchanged() {
695 let p = PathBuf::from("/home/user/project");
696 let result = strip_verbatim(p.clone());
697 assert_eq!(result, p);
698 }
699
700 #[test]
701 fn windows_drive_unchanged() {
702 let p = PathBuf::from("C:/Users/dev");
703 let result = strip_verbatim(p.clone());
704 assert_eq!(result, p);
705 }
706
707 #[test]
708 fn strip_str_regular() {
709 assert_eq!(
710 strip_verbatim_str(r"\\?\E:\code\lean-ctx"),
711 Some("E:/code/lean-ctx".to_string())
712 );
713 }
714
715 #[test]
716 fn strip_str_unc() {
717 assert_eq!(
718 strip_verbatim_str(r"\\?\UNC\myserver\data"),
719 Some("//myserver/data".to_string())
720 );
721 }
722
723 #[test]
724 fn strip_str_forward_slash_variant() {
725 assert_eq!(
726 strip_verbatim_str("//?/C:/Users/dev"),
727 Some("C:/Users/dev".to_string())
728 );
729 }
730
731 #[test]
732 fn strip_str_no_prefix() {
733 assert_eq!(strip_verbatim_str("/home/user"), None);
734 }
735
736 #[test]
737 fn safe_canonicalize_or_self_nonexistent() {
738 let p = Path::new("/this/path/should/not/exist/xyzzy");
739 let result = safe_canonicalize_or_self(p);
740 assert_eq!(result, p.to_path_buf());
741 }
742
743 #[test]
746 fn msys_drive_prefix_translation() {
747 assert_eq!(
748 translate_msys_drive_prefix("/c/Users/ABC").as_deref(),
749 Some("C:/Users/ABC")
750 );
751 assert_eq!(
752 translate_msys_drive_prefix("/D/Program Files").as_deref(),
753 Some("D:/Program Files")
754 );
755 assert_eq!(translate_msys_drive_prefix("/usr/local/bin"), None);
756 assert_eq!(translate_msys_drive_prefix("/c"), None);
757 assert_eq!(translate_msys_drive_prefix("c/Users"), None);
758 }
759
760 #[cfg(windows)]
761 #[test]
762 fn normalize_msys_path_to_native() {
763 assert_eq!(
764 normalize_tool_path("/c/Users/ABC/AppData/lean-ctx"),
765 "C:/Users/ABC/AppData/lean-ctx"
766 );
767 assert_eq!(
768 normalize_tool_path("/D/Program Files/lean-ctx.exe"),
769 "D:/Program Files/lean-ctx.exe"
770 );
771 }
772
773 #[cfg(not(windows))]
776 #[test]
777 fn normalize_single_letter_unix_path_untouched() {
778 assert_eq!(
779 normalize_tool_path_lexical("/c/Users/me/proj"),
780 "/c/Users/me/proj"
781 );
782 assert_eq!(
783 normalize_tool_path_lexical("/x/projects/app/src"),
784 "/x/projects/app/src"
785 );
786 }
787
788 #[test]
789 fn normalize_native_windows_path_unchanged() {
790 assert_eq!(
791 normalize_tool_path("C:/Users/ABC/lean-ctx.exe"),
792 "C:/Users/ABC/lean-ctx.exe"
793 );
794 }
795
796 #[test]
797 fn normalize_backslash_windows_path() {
798 assert_eq!(
799 normalize_tool_path(r"C:\Users\ABC\lean-ctx.exe"),
800 "C:/Users/ABC/lean-ctx.exe"
801 );
802 }
803
804 #[test]
805 fn normalize_unix_path_unchanged() {
806 assert_eq!(
807 normalize_tool_path("/usr/local/bin/lean-ctx"),
808 "/usr/local/bin/lean-ctx"
809 );
810 }
811
812 #[test]
813 fn normalize_windows_path_with_spaces_and_backslashes() {
814 assert_eq!(
818 normalize_tool_path(r"C:\Users\My Name\My Project\src\main.rs"),
819 "C:/Users/My Name/My Project/src/main.rs"
820 );
821 assert_eq!(
822 normalize_tool_path(r"C:\Program Files\app\config.toml"),
823 "C:/Program Files/app/config.toml"
824 );
825 }
826
827 #[test]
828 fn normalize_double_slashes() {
829 assert_eq!(
830 normalize_tool_path("C:/Users//ABC//lean-ctx"),
831 "C:/Users/ABC/lean-ctx"
832 );
833 }
834
835 #[test]
836 fn normalize_trailing_slash_removed() {
837 assert_eq!(normalize_tool_path("C:/Users/ABC/"), "C:/Users/ABC");
838 assert_eq!(
839 normalize_tool_path_lexical("/tmp/nonexistent-dir-xyzzy/"),
840 "/tmp/nonexistent-dir-xyzzy"
841 );
842 }
843
844 #[test]
845 fn normalize_root_slash_preserved() {
846 assert_eq!(normalize_tool_path("/"), "/");
847 }
848
849 #[test]
850 fn normalize_drive_root_preserved() {
851 assert_eq!(normalize_tool_path("C:/"), "C:/");
852 }
853
854 #[test]
855 fn normalize_verbatim_with_msys() {
856 assert_eq!(normalize_tool_path(r"\\?\C:\Users\dev"), "C:/Users/dev");
857 }
858
859 #[test]
860 fn broad_root_rejects_home() {
861 if let Some(home) = dirs::home_dir() {
862 assert!(is_broad_or_unsafe_root(&home));
863 }
864 }
865
866 #[test]
867 fn broad_root_rejects_wsl_windows_user_profile() {
868 assert!(is_broad_or_unsafe_root(Path::new("/mnt/c/Users/dev")));
869 assert!(!is_broad_or_unsafe_root(Path::new(
870 "/mnt/c/Users/dev/projects/my-app"
871 )));
872 }
873
874 #[test]
875 fn broad_root_rejects_filesystem_root() {
876 assert!(is_broad_or_unsafe_root(Path::new("/")));
877 }
878
879 #[test]
880 fn broad_root_rejects_dot() {
881 assert!(is_broad_or_unsafe_root(Path::new(".")));
882 }
883
884 #[test]
885 fn broad_root_rejects_agent_dirs() {
886 assert!(is_broad_or_unsafe_root(Path::new("/home/user/.claude")));
887 assert!(is_broad_or_unsafe_root(Path::new("/home/user/.codex")));
888 }
889
890 #[test]
891 fn broad_root_rejects_copilot_and_friends() {
892 assert!(is_broad_or_unsafe_root(Path::new("/home/user/.copilot")));
895 assert!(is_broad_or_unsafe_root(Path::new("/home/user/.cursor")));
896 assert!(is_broad_or_unsafe_root(Path::new("/home/user/.windsurf")));
897 assert!(is_broad_or_unsafe_root(Path::new("/home/user/.gemini")));
898 assert!(is_broad_or_unsafe_root(Path::new("/home/user/.lmstudio")));
899 }
900
901 #[test]
902 fn agent_config_dir_matches_every_known_client() {
903 for name in AGENT_CONFIG_DIRS {
904 let leaf = format!("/home/user/{name}");
905 assert!(is_agent_config_dir(Path::new(&leaf)), "{leaf}");
906 let nested = format!("/home/user/{name}/mcp");
907 assert!(is_agent_config_dir(Path::new(&nested)), "{nested}");
908 }
909 }
910
911 #[test]
912 fn claude_code_worktree_checkout_is_not_agent_config() {
913 for p in [
916 "/repo/.claude/worktrees/fix-x",
917 "/repo/.claude/worktrees/fix-x/rust/src",
918 r"C:\repo\.claude\worktrees\fix-x",
919 ] {
920 assert!(!is_agent_config_dir(Path::new(p)), "{p}");
921 assert!(!is_broad_or_unsafe_root(Path::new(p)), "{p}");
922 }
923 for p in [
924 "/repo/.claude/worktrees",
925 "/repo/.claude/worktrees/",
926 "/repo/.claude/settings",
927 "/repo/.claude/worktrees/fix-x/.claude",
928 "/repo/.claude/worktrees/fix-x/.codex/mcp",
929 "/home/user/.claude/worktreesx/a",
930 ] {
931 assert!(is_agent_config_dir(Path::new(p)), "{p}");
932 }
933 assert!(!is_agent_config_dir(Path::new("/repo/.claudex/a")));
934 }
935
936 #[test]
937 fn agent_config_dir_matches_windows_backslash() {
938 assert!(is_agent_config_dir(Path::new(r"C:\Users\me\.copilot")));
940 assert!(is_agent_config_dir(Path::new(r"C:\Users\me\.copilot\mcp")));
941 }
942
943 #[test]
944 fn agent_config_dir_ignores_real_projects() {
945 assert!(!is_agent_config_dir(Path::new("/home/user/code/lean-ctx")));
946 assert!(!is_agent_config_dir(Path::new(r"C:\src\app")));
947 }
948
949 #[test]
950 fn broad_root_allows_project_subdir() {
951 let tmp = tempfile::tempdir().unwrap();
952 let subdir = tmp.path().join("my-project");
953 std::fs::create_dir_all(&subdir).unwrap();
954 assert!(!is_broad_or_unsafe_root(&subdir));
955 }
956
957 #[test]
958 fn broad_root_allows_home_subdirs() {
959 if let Some(home) = dirs::home_dir() {
960 let subdir = home.join("projects").join("my-app");
961 assert!(!is_broad_or_unsafe_root(&subdir));
962 }
963 }
964
965 #[test]
966 fn data_dir_collision_rejects_home() {
967 if let Some(home) = dirs::home_dir() {
968 assert!(is_data_dir_collision(&home));
969 }
970 }
971
972 #[test]
973 fn data_dir_collision_allows_normal_project() {
974 let tmp = tempfile::tempdir().unwrap();
975 let project = tmp.path().join("my-project");
976 std::fs::create_dir_all(&project).unwrap();
977 assert!(!is_data_dir_collision(&project));
978 }
979
980 #[test]
981 fn has_project_marker_detects_git() {
982 let tmp = tempfile::tempdir().unwrap();
983 let root = tmp.path().join("repo");
984 std::fs::create_dir_all(&root).unwrap();
985 assert!(!has_project_marker(&root));
986 std::fs::create_dir(root.join(".git")).unwrap();
987 assert!(has_project_marker(&root));
988 }
989
990 #[test]
991 fn has_project_marker_detects_cargo_toml() {
992 let tmp = tempfile::tempdir().unwrap();
993 let root = tmp.path().join("rust-project");
994 std::fs::create_dir_all(&root).unwrap();
995 std::fs::write(root.join("Cargo.toml"), "[package]").unwrap();
996 assert!(has_project_marker(&root));
997 }
998
999 #[test]
1000 fn has_project_marker_detects_godot_project() {
1001 let tmp = tempfile::tempdir().unwrap();
1002 let root = tmp.path().join("godot-game");
1003 std::fs::create_dir_all(&root).unwrap();
1004 std::fs::write(root.join("project.godot"), "config_version=5\n").unwrap();
1005 assert!(has_project_marker(&root));
1006 }
1007
1008 #[test]
1009 fn multi_repo_children_needs_two() {
1010 let tmp = tempfile::tempdir().unwrap();
1011 let parent = tmp.path().join("code");
1012 std::fs::create_dir_all(&parent).unwrap();
1013
1014 assert!(!has_multi_repo_children(&parent));
1016
1017 let repo1 = parent.join("repo1");
1019 std::fs::create_dir_all(repo1.join(".git")).unwrap();
1020 assert!(!has_multi_repo_children(&parent));
1021
1022 let repo2 = parent.join("repo2");
1024 std::fs::create_dir_all(repo2.join(".git")).unwrap();
1025 assert!(has_multi_repo_children(&parent));
1026 }
1027
1028 #[test]
1029 fn multi_repo_children_ignores_files() {
1030 let tmp = tempfile::tempdir().unwrap();
1031 let parent = tmp.path().join("mixed");
1032 std::fs::create_dir_all(&parent).unwrap();
1033
1034 let repo1 = parent.join("repo1");
1036 std::fs::create_dir_all(repo1.join(".git")).unwrap();
1037 std::fs::write(parent.join("not-a-repo"), "file").unwrap();
1038 assert!(!has_multi_repo_children(&parent));
1039
1040 let repo2 = parent.join("repo2");
1042 std::fs::create_dir_all(&repo2).unwrap();
1043 std::fs::write(repo2.join("package.json"), "{}").unwrap();
1044 assert!(has_multi_repo_children(&parent));
1045 }
1046
1047 #[test]
1048 fn multi_repo_children_nonexistent_dir() {
1049 assert!(!has_multi_repo_children(Path::new("/nonexistent/path/xyz")));
1050 }
1051
1052 #[test]
1053 fn regular_file_is_not_symlink_or_reparse() {
1054 let tmp = tempfile::tempdir().unwrap();
1055 let file = tmp.path().join("plain.txt");
1056 std::fs::write(&file, "x").unwrap();
1057 let meta = std::fs::symlink_metadata(&file).unwrap();
1058 assert!(!is_symlink_or_reparse(&meta));
1059 }
1060
1061 #[cfg(unix)]
1062 #[test]
1063 fn unix_symlink_is_detected() {
1064 let tmp = tempfile::tempdir().unwrap();
1065 let target = tmp.path().join("target.txt");
1066 std::fs::write(&target, "x").unwrap();
1067 let link = tmp.path().join("link.txt");
1068 std::os::unix::fs::symlink(&target, &link).unwrap();
1069 let meta = std::fs::symlink_metadata(&link).unwrap();
1070 assert!(is_symlink_or_reparse(&meta));
1071 }
1072
1073 #[cfg(windows)]
1076 #[test]
1077 fn windows_symlink_is_detected() {
1078 let tmp = tempfile::tempdir().unwrap();
1079 let target = tmp.path().join("target.txt");
1080 std::fs::write(&target, "x").unwrap();
1081 let link = tmp.path().join("link.txt");
1082 if std::os::windows::fs::symlink_file(&target, &link).is_err() {
1083 eprintln!("skipping: symlink creation not permitted on this runner");
1084 return;
1085 }
1086 let meta = std::fs::symlink_metadata(&link).unwrap();
1087 assert!(is_symlink_or_reparse(&meta));
1088 }
1089}