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 same_project(a: &str, b: &str) -> bool {
261 let lexical = |path: &str| {
262 let path = path.trim().replace('\\', "/");
263 let trimmed = path.trim_end_matches('/');
264 if trimmed.is_empty() {
265 path
266 } else {
267 trimmed.to_string()
268 }
269 };
270 a == b || lexical(a) == lexical(b) || normalize_tool_path(a) == normalize_tool_path(b)
271}
272
273pub fn normalize_tool_path(path: &str) -> String {
274 let mut p = normalize_tool_path_lexical(path);
275
276 let is_absolute = p.starts_with('/') || (p.len() >= 3 && p.as_bytes()[1] == b':');
282 let is_root_only = p == "/" || (p.len() <= 3 && p.ends_with('/') && is_absolute);
283 if is_absolute
284 && !is_root_only
285 && !crate::core::io_health::is_slow_mount(&p)
286 && may_probe_path(Path::new(&*p))
287 && let Ok(canonical) = safe_canonicalize(Path::new(&*p))
288 {
289 let canonical_str = canonical.to_string_lossy().replace('\\', "/");
290 if !canonical_str.is_empty() {
291 p = canonical_str;
292 }
293 }
294
295 p
296}
297
298pub const AGENT_CONFIG_DIRS: &[&str] = &[
305 ".claude",
306 ".codex",
307 ".codebuddy",
308 ".codewhale",
309 ".copilot",
310 ".cursor",
311 ".windsurf",
312 ".gemini",
313 ".lmstudio",
314];
315
316pub fn is_agent_config_dir(dir: &Path) -> bool {
324 let s = dir.to_string_lossy().replace('\\', "/");
325 AGENT_CONFIG_DIRS.iter().any(|name| {
326 let segment = format!("/{name}");
327 s.match_indices(&segment).any(|(at, _)| {
328 let tail = &s[at + segment.len()..];
329 (tail.is_empty() || tail.starts_with('/')) && !is_worktree_checkout_tail(tail)
330 })
331 })
332}
333
334fn is_worktree_checkout_tail(tail: &str) -> bool {
336 tail.strip_prefix("/worktrees/")
337 .and_then(|rest| rest.split('/').next())
338 .is_some_and(|name| !name.is_empty())
339}
340
341fn is_wsl_windows_user_profile(dir: &Path) -> bool {
342 let normalized = dir.to_string_lossy();
343 if !normalized.starts_with("/mnt/") {
344 return false;
345 }
346
347 let mut components = normalized
348 .split('/')
349 .filter(|component| !component.is_empty());
350 let (Some(mount), Some(drive), Some(users), Some(username)) = (
351 components.next(),
352 components.next(),
353 components.next(),
354 components.next(),
355 ) else {
356 return false;
357 };
358
359 mount.eq_ignore_ascii_case("mnt")
360 && drive.len() == 1
361 && drive.as_bytes()[0].is_ascii_alphabetic()
362 && users.eq_ignore_ascii_case("users")
363 && !username.is_empty()
364 && components.next().is_none()
365}
366
367pub fn home_dirs() -> Vec<PathBuf> {
373 let mut homes: Vec<PathBuf> = Vec::with_capacity(2);
374 for home in [dirs::home_dir(), crate::core::home::resolve_home_dir()]
375 .into_iter()
376 .flatten()
377 {
378 if !homes.contains(&home) {
379 homes.push(home);
380 }
381 }
382 homes
383}
384
385pub fn is_broad_or_unsafe_root(dir: &Path) -> bool {
392 let plain = strip_verbatim(dir.to_path_buf());
396 if home_dirs()
397 .into_iter()
398 .any(|home| plain == strip_verbatim(home))
399 {
400 return true;
401 }
402 if is_wsl_windows_user_profile(dir) {
403 return true;
404 }
405 let s = dir.to_string_lossy();
406 if s == "/" || s == "\\" || s == "." {
407 return true;
408 }
409 is_agent_config_dir(dir) || is_lean_ctx_store_dir(dir)
410}
411
412pub fn is_lean_ctx_store_dir(dir: &Path) -> bool {
420 let real_dir = dir.canonicalize().ok();
421 [
422 crate::core::data_dir::resolve_data_dir(),
423 crate::core::paths::state_dir_read_only(),
424 crate::core::paths::config_dir_read_only(),
425 crate::core::paths::cache_dir_read_only(),
426 ]
427 .into_iter()
428 .flatten()
429 .filter(|store| store.is_absolute())
430 .any(|store| {
431 let real_store = store.canonicalize().ok();
432 dir == store
433 || real_store.as_deref() == Some(dir)
434 || (real_dir.is_some() && real_dir == real_store)
435 })
436}
437
438pub const PROJECT_MARKERS: &[&str] = &[
440 ".git",
441 "Cargo.toml",
442 "package.json",
443 "go.mod",
444 "pyproject.toml",
445 "setup.py",
446 "pom.xml",
447 "build.gradle",
448 "Makefile",
449 "project.godot",
450 ".lean-ctx.toml",
451 ".planning",
452];
453
454pub fn has_project_marker(dir: &Path) -> bool {
461 if !may_probe_path(dir) {
462 return false;
463 }
464 PROJECT_MARKERS.iter().any(|m| dir.join(m).exists())
465}
466
467pub fn is_symlink_or_reparse(meta: &std::fs::Metadata) -> bool {
475 if meta.file_type().is_symlink() {
476 return true;
477 }
478 #[cfg(windows)]
479 {
480 use std::os::windows::fs::MetadataExt;
481 const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0400;
482 meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0
483 }
484 #[cfg(not(windows))]
485 false
486}
487
488pub fn is_tcc_sensitive_home_dir(dir: &Path) -> bool {
497 let Some(home) = dirs::home_dir() else {
498 return false;
499 };
500 if dir == home {
501 return true;
502 }
503 if dir.parent() != Some(home.as_path()) {
504 return false;
505 }
506 matches!(
507 dir.file_name().and_then(|n| n.to_str()),
508 Some("Documents" | "Desktop" | "Downloads")
509 )
510}
511
512pub fn is_under_tcc_protected_dir(path: &Path) -> bool {
520 if !cfg!(target_os = "macos") {
521 return false;
522 }
523 let Some(home) = dirs::home_dir() else {
524 return false;
525 };
526 ["Documents", "Desktop", "Downloads"]
527 .iter()
528 .any(|magic| path.starts_with(home.join(magic)))
529}
530
531pub fn process_is_tcc_standalone() -> bool {
545 #[cfg(target_os = "macos")]
546 {
547 if let Ok(v) = std::env::var("LEAN_CTX_TCC_STANDALONE") {
551 match v.trim() {
552 "1" | "true" => return true,
553 "0" | "false" => return false,
554 _ => {}
555 }
556 }
557 if std::env::var_os(crate::core::tcc_guard_sandbox::SEATBELT_SENTINEL).is_some() {
565 return true;
566 }
567 (unsafe { libc::getppid() }) == 1
569 }
570 #[cfg(not(target_os = "macos"))]
571 {
572 false
573 }
574}
575
576pub fn may_probe_path(path: &Path) -> bool {
584 !(process_is_tcc_standalone() && is_under_tcc_protected_dir(path))
585}
586
587pub fn has_multi_repo_children(dir: &Path) -> bool {
590 if is_tcc_sensitive_home_dir(dir) || !may_probe_path(dir) {
596 return false;
597 }
598 let Ok(entries) = std::fs::read_dir(dir) else {
599 return false;
600 };
601 let count = entries
602 .filter_map(Result::ok)
603 .filter(|e| e.file_type().is_ok_and(|ft| ft.is_dir()))
604 .filter(|e| has_project_marker(&e.path()))
605 .take(2)
606 .count();
607 count >= 2
608}
609
610pub fn is_data_dir_collision(project_root: &Path) -> bool {
614 if is_broad_or_unsafe_root(project_root) {
615 return true;
616 }
617 if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
618 let project_lean_ctx = project_root.join(".lean-ctx");
619 if project_lean_ctx == data_dir || data_dir.starts_with(&project_lean_ctx) {
620 return true;
621 }
622 }
623 false
624}
625
626pub fn safe_project_data_dir(project_root: &Path) -> Result<PathBuf, String> {
629 if is_data_dir_collision(project_root) {
630 return Err(format!(
631 "project root {} collides with global data directory; \
632 skipping project-scoped write",
633 project_root.display()
634 ));
635 }
636 Ok(project_root.join(".lean-ctx"))
637}
638
639#[cfg(test)]
640mod tests {
641 use super::*;
642
643 #[cfg(unix)]
647 #[test]
648 fn same_project_ignores_spelling_but_not_identity() {
649 let tmp = tempfile::tempdir().unwrap();
650 let real = tmp.path().join("repo");
651 let other = tmp.path().join("other");
652 std::fs::create_dir_all(&real).unwrap();
653 std::fs::create_dir_all(&other).unwrap();
654 let link = tmp.path().join("link");
655 std::os::unix::fs::symlink(&real, &link).unwrap();
656 let (real, link, other) = (
657 real.to_string_lossy().to_string(),
658 link.to_string_lossy().to_string(),
659 other.to_string_lossy().to_string(),
660 );
661
662 assert!(same_project(&real, &link));
663 assert!(same_project(&real, &format!("{real}/")));
664 assert!(same_project(r"C:\work\repo", "C:/work/repo/"));
665 assert!(!same_project(&real, &other));
666 }
667
668 #[test]
669 fn lean_ctx_stores_are_never_a_project_root() {
670 let iso = crate::core::data_dir::isolated_data_dir();
671 let project = tempfile::tempdir().unwrap();
672 assert!(is_broad_or_unsafe_root(iso.path()));
674 assert!(!is_broad_or_unsafe_root(&iso.path().join("proj")));
676 assert!(!is_broad_or_unsafe_root(project.path()));
677 }
678
679 #[cfg(unix)]
680 #[test]
681 fn a_store_under_another_spelling_is_still_refused() {
682 let iso = crate::core::data_dir::isolated_data_dir();
683 let links = tempfile::tempdir().unwrap();
684 let alias = links.path().join("data-alias");
685 std::os::unix::fs::symlink(iso.path(), &alias).unwrap();
686 assert!(is_broad_or_unsafe_root(&alias));
687 let inner = iso.path().join("proj");
689 std::fs::create_dir_all(&inner).unwrap();
690 let inner_alias = links.path().join("proj-alias");
691 std::os::unix::fs::symlink(&inner, &inner_alias).unwrap();
692 assert!(!is_broad_or_unsafe_root(&inner_alias));
693 }
694
695 #[test]
696 fn strip_regular_verbatim() {
697 let p = PathBuf::from(r"\\?\C:\Users\dev\project");
698 let result = strip_verbatim(p);
699 assert_eq!(result, PathBuf::from("C:/Users/dev/project"));
700 }
701
702 #[test]
703 fn tcc_sensitive_home_dir_matches_home_and_magic_dirs() {
704 let _env_lock = crate::core::data_dir::test_env_lock();
707 let Some(home) = dirs::home_dir() else {
708 return;
709 };
710 assert!(is_tcc_sensitive_home_dir(&home));
712 assert!(is_tcc_sensitive_home_dir(&home.join("Documents")));
713 assert!(is_tcc_sensitive_home_dir(&home.join("Desktop")));
714 assert!(is_tcc_sensitive_home_dir(&home.join("Downloads")));
715 }
716
717 #[test]
718 fn tcc_sensitive_home_dir_allows_real_projects() {
719 let _env_lock = crate::core::data_dir::test_env_lock();
720 let Some(home) = dirs::home_dir() else {
721 return;
722 };
723 assert!(!is_tcc_sensitive_home_dir(
726 &home.join("Documents").join("my-project")
727 ));
728 assert!(!is_tcc_sensitive_home_dir(&home.join("code")));
729 assert!(!is_tcc_sensitive_home_dir(&home.join("Projects")));
730 }
731
732 #[test]
733 #[cfg(target_os = "macos")]
734 fn under_tcc_protected_dir_matches_nested_paths() {
735 let _env_lock = crate::core::data_dir::test_env_lock();
736 let Some(home) = dirs::home_dir() else {
737 return;
738 };
739 assert!(is_under_tcc_protected_dir(&home.join("Documents")));
741 assert!(is_under_tcc_protected_dir(
742 &home.join("Documents/deep/nested/project")
743 ));
744 assert!(is_under_tcc_protected_dir(&home.join("Desktop/scratch")));
745 assert!(is_under_tcc_protected_dir(&home.join("Downloads/x.zip")));
746 assert!(!is_under_tcc_protected_dir(&home));
748 assert!(!is_under_tcc_protected_dir(&home.join("code/project")));
749 assert!(!is_under_tcc_protected_dir(Path::new("/tmp/Documents")));
750 }
751
752 #[test]
753 #[cfg(target_os = "macos")]
754 #[serial_test::serial]
755 fn tcc_standalone_blocks_probes_under_protected_dirs() {
756 let _env_lock = crate::core::data_dir::test_env_lock();
762 let Some(home) = dirs::home_dir() else {
763 return;
764 };
765 let doc_proj = home.join("Documents/some-project");
766
767 crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "1");
768 assert!(process_is_tcc_standalone());
769 assert!(!may_probe_path(&doc_proj));
770 assert!(may_probe_path(Path::new("/tmp/some-project")));
772 assert!(!has_project_marker(&doc_proj));
774
775 crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "0");
776 assert!(!process_is_tcc_standalone());
777 assert!(may_probe_path(&doc_proj));
778 crate::test_env::remove_var("LEAN_CTX_TCC_STANDALONE");
779 }
780
781 #[test]
782 #[cfg(target_os = "macos")]
783 #[serial_test::serial]
784 fn tcc_standalone_detected_via_seatbelt_sentinel() {
785 let _env_lock = crate::core::data_dir::test_env_lock();
786 let Some(home) = dirs::home_dir() else {
787 return;
788 };
789 let doc_proj = home.join("Documents/some-project");
790
791 crate::test_env::remove_var("LEAN_CTX_TCC_STANDALONE");
796 crate::test_env::set_var(crate::core::tcc_guard_sandbox::SEATBELT_SENTINEL, "1");
797 assert!(process_is_tcc_standalone());
798 assert!(!may_probe_path(&doc_proj));
799 crate::test_env::remove_var(crate::core::tcc_guard_sandbox::SEATBELT_SENTINEL);
800
801 assert!(!process_is_tcc_standalone());
804 }
805
806 #[test]
807 #[cfg(target_os = "macos")]
808 #[serial_test::serial]
809 fn tcc_standalone_skips_canonicalize_under_protected_dirs() {
810 let _env_lock = crate::core::data_dir::test_env_lock();
811 let Some(home) = dirs::home_dir() else {
812 return;
813 };
814 let missing = home.join("Documents/lean-ctx-tcc-test-does-not-exist-xyzzy");
820
821 crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "1");
822 let guarded = safe_canonicalize(&missing);
823 assert!(
824 guarded.is_ok(),
825 "standalone safe_canonicalize must short-circuit (no stat) under ~/Documents"
826 );
827 assert_eq!(guarded.unwrap(), missing);
828 assert_eq!(safe_canonicalize_or_self(&missing), missing);
829
830 let tmp_missing = Path::new("/tmp/lean-ctx-tcc-test-does-not-exist-xyzzy");
832 assert!(safe_canonicalize(tmp_missing).is_err());
833
834 crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "0");
837 assert!(safe_canonicalize(&missing).is_err());
838
839 crate::test_env::remove_var("LEAN_CTX_TCC_STANDALONE");
840 }
841
842 #[test]
843 #[cfg(target_os = "macos")]
844 #[serial_test::serial]
845 fn canonicalize_secure_bypasses_tcc_guard_for_pathjail() {
846 let _env_lock = crate::core::data_dir::test_env_lock();
847 let Some(home) = dirs::home_dir() else {
854 return;
855 };
856 let missing = home.join("Documents/lean-ctx-secure-canon-does-not-exist-xyzzy");
857
858 crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "1");
859 assert_eq!(safe_canonicalize(&missing).unwrap(), missing);
861 assert!(
865 canonicalize_secure(&missing).is_err(),
866 "canonicalize_secure must bypass the TCC guard and touch the filesystem"
867 );
868 assert_eq!(canonicalize_secure_or_self(&missing), missing);
869 crate::test_env::remove_var("LEAN_CTX_TCC_STANDALONE");
870 }
871
872 #[test]
873 fn strip_unc_verbatim() {
874 let p = PathBuf::from(r"\\?\UNC\server\share\dir");
875 let result = strip_verbatim(p);
876 assert_eq!(result, PathBuf::from("//server/share/dir"));
877 }
878
879 #[test]
880 fn no_prefix_unchanged() {
881 let p = PathBuf::from("/home/user/project");
882 let result = strip_verbatim(p.clone());
883 assert_eq!(result, p);
884 }
885
886 #[test]
887 fn windows_drive_unchanged() {
888 let p = PathBuf::from("C:/Users/dev");
889 let result = strip_verbatim(p.clone());
890 assert_eq!(result, p);
891 }
892
893 #[test]
894 fn strip_str_regular() {
895 assert_eq!(
896 strip_verbatim_str(r"\\?\E:\code\lean-ctx"),
897 Some("E:/code/lean-ctx".to_string())
898 );
899 }
900
901 #[test]
902 fn strip_str_unc() {
903 assert_eq!(
904 strip_verbatim_str(r"\\?\UNC\myserver\data"),
905 Some("//myserver/data".to_string())
906 );
907 }
908
909 #[test]
910 fn strip_str_forward_slash_variant() {
911 assert_eq!(
912 strip_verbatim_str("//?/C:/Users/dev"),
913 Some("C:/Users/dev".to_string())
914 );
915 }
916
917 #[test]
918 fn strip_str_no_prefix() {
919 assert_eq!(strip_verbatim_str("/home/user"), None);
920 }
921
922 #[test]
923 fn safe_canonicalize_or_self_nonexistent() {
924 let p = Path::new("/this/path/should/not/exist/xyzzy");
925 let result = safe_canonicalize_or_self(p);
926 assert_eq!(result, p.to_path_buf());
927 }
928
929 #[test]
932 fn msys_drive_prefix_translation() {
933 assert_eq!(
934 translate_msys_drive_prefix("/c/Users/ABC").as_deref(),
935 Some("C:/Users/ABC")
936 );
937 assert_eq!(
938 translate_msys_drive_prefix("/D/Program Files").as_deref(),
939 Some("D:/Program Files")
940 );
941 assert_eq!(translate_msys_drive_prefix("/usr/local/bin"), None);
942 assert_eq!(translate_msys_drive_prefix("/c"), None);
943 assert_eq!(translate_msys_drive_prefix("c/Users"), None);
944 }
945
946 #[cfg(windows)]
947 #[test]
948 fn normalize_msys_path_to_native() {
949 assert_eq!(
950 normalize_tool_path("/c/Users/ABC/AppData/lean-ctx"),
951 "C:/Users/ABC/AppData/lean-ctx"
952 );
953 assert_eq!(
954 normalize_tool_path("/D/Program Files/lean-ctx.exe"),
955 "D:/Program Files/lean-ctx.exe"
956 );
957 }
958
959 #[cfg(not(windows))]
962 #[test]
963 fn normalize_single_letter_unix_path_untouched() {
964 assert_eq!(
965 normalize_tool_path_lexical("/c/Users/me/proj"),
966 "/c/Users/me/proj"
967 );
968 assert_eq!(
969 normalize_tool_path_lexical("/x/projects/app/src"),
970 "/x/projects/app/src"
971 );
972 }
973
974 #[test]
975 fn normalize_native_windows_path_unchanged() {
976 assert_eq!(
977 normalize_tool_path("C:/Users/ABC/lean-ctx.exe"),
978 "C:/Users/ABC/lean-ctx.exe"
979 );
980 }
981
982 #[test]
983 fn normalize_backslash_windows_path() {
984 assert_eq!(
985 normalize_tool_path(r"C:\Users\ABC\lean-ctx.exe"),
986 "C:/Users/ABC/lean-ctx.exe"
987 );
988 }
989
990 #[test]
991 fn normalize_unix_path_unchanged() {
992 assert_eq!(
993 normalize_tool_path("/usr/local/bin/lean-ctx"),
994 "/usr/local/bin/lean-ctx"
995 );
996 }
997
998 #[cfg(not(windows))]
999 #[test]
1000 fn normalize_unescapes_shell_quoting_on_unix() {
1001 assert_eq!(
1002 normalize_tool_path_lexical(r"/Users/me/Pfadi\ Scouting/app/main.ts"),
1003 "/Users/me/Pfadi Scouting/app/main.ts",
1004 "an escaped space must not become a separator"
1005 );
1006 assert_eq!(
1007 normalize_tool_path_lexical(r"/srv/\(group\)/a\&b.txt"),
1008 "/srv/(group)/a&b.txt"
1009 );
1010 assert_eq!(
1011 normalize_tool_path_lexical("'/Users/me/My Project/src'"),
1012 "/Users/me/My Project/src"
1013 );
1014 assert_eq!(normalize_tool_path_lexical("\"/tmp/a b\""), "/tmp/a b");
1015 assert_eq!(
1016 normalize_tool_path_lexical("'"),
1017 "'",
1018 "a lone quote is a name"
1019 );
1020 }
1021
1022 #[test]
1023 fn normalize_windows_path_with_spaces_and_backslashes() {
1024 assert_eq!(
1028 normalize_tool_path(r"C:\Users\My Name\My Project\src\main.rs"),
1029 "C:/Users/My Name/My Project/src/main.rs"
1030 );
1031 assert_eq!(
1032 normalize_tool_path(r"C:\Program Files\app\config.toml"),
1033 "C:/Program Files/app/config.toml"
1034 );
1035 }
1036
1037 #[test]
1038 fn normalize_double_slashes() {
1039 assert_eq!(
1040 normalize_tool_path("C:/Users//ABC//lean-ctx"),
1041 "C:/Users/ABC/lean-ctx"
1042 );
1043 }
1044
1045 #[test]
1046 fn normalize_trailing_slash_removed() {
1047 assert_eq!(normalize_tool_path("C:/Users/ABC/"), "C:/Users/ABC");
1048 assert_eq!(
1049 normalize_tool_path_lexical("/tmp/nonexistent-dir-xyzzy/"),
1050 "/tmp/nonexistent-dir-xyzzy"
1051 );
1052 }
1053
1054 #[test]
1055 fn normalize_root_slash_preserved() {
1056 assert_eq!(normalize_tool_path("/"), "/");
1057 }
1058
1059 #[test]
1060 fn normalize_drive_root_preserved() {
1061 assert_eq!(normalize_tool_path("C:/"), "C:/");
1062 }
1063
1064 #[test]
1065 fn normalize_verbatim_with_msys() {
1066 assert_eq!(normalize_tool_path(r"\\?\C:\Users\dev"), "C:/Users/dev");
1067 }
1068
1069 #[test]
1070 fn broad_root_rejects_home() {
1071 if let Some(home) = dirs::home_dir() {
1072 assert!(is_broad_or_unsafe_root(&home));
1073 }
1074 }
1075
1076 #[test]
1077 fn broad_root_rejects_wsl_windows_user_profile() {
1078 assert!(is_broad_or_unsafe_root(Path::new("/mnt/c/Users/dev")));
1079 assert!(!is_broad_or_unsafe_root(Path::new(
1080 "/mnt/c/Users/dev/projects/my-app"
1081 )));
1082 }
1083
1084 #[test]
1085 fn broad_root_rejects_filesystem_root() {
1086 assert!(is_broad_or_unsafe_root(Path::new("/")));
1087 }
1088
1089 #[test]
1090 fn broad_root_rejects_dot() {
1091 assert!(is_broad_or_unsafe_root(Path::new(".")));
1092 }
1093
1094 #[test]
1095 fn broad_root_rejects_agent_dirs() {
1096 assert!(is_broad_or_unsafe_root(Path::new("/home/user/.claude")));
1097 assert!(is_broad_or_unsafe_root(Path::new("/home/user/.codex")));
1098 }
1099
1100 #[test]
1101 fn broad_root_rejects_copilot_and_friends() {
1102 assert!(is_broad_or_unsafe_root(Path::new("/home/user/.copilot")));
1105 assert!(is_broad_or_unsafe_root(Path::new("/home/user/.cursor")));
1106 assert!(is_broad_or_unsafe_root(Path::new("/home/user/.windsurf")));
1107 assert!(is_broad_or_unsafe_root(Path::new("/home/user/.gemini")));
1108 assert!(is_broad_or_unsafe_root(Path::new("/home/user/.lmstudio")));
1109 }
1110
1111 #[test]
1112 fn agent_config_dir_matches_every_known_client() {
1113 for name in AGENT_CONFIG_DIRS {
1114 let leaf = format!("/home/user/{name}");
1115 assert!(is_agent_config_dir(Path::new(&leaf)), "{leaf}");
1116 let nested = format!("/home/user/{name}/mcp");
1117 assert!(is_agent_config_dir(Path::new(&nested)), "{nested}");
1118 }
1119 }
1120
1121 #[test]
1122 fn claude_code_worktree_checkout_is_not_agent_config() {
1123 for p in [
1126 "/repo/.claude/worktrees/fix-x",
1127 "/repo/.claude/worktrees/fix-x/rust/src",
1128 r"C:\repo\.claude\worktrees\fix-x",
1129 ] {
1130 assert!(!is_agent_config_dir(Path::new(p)), "{p}");
1131 assert!(!is_broad_or_unsafe_root(Path::new(p)), "{p}");
1132 }
1133 for p in [
1134 "/repo/.claude/worktrees",
1135 "/repo/.claude/worktrees/",
1136 "/repo/.claude/settings",
1137 "/repo/.claude/worktrees/fix-x/.claude",
1138 "/repo/.claude/worktrees/fix-x/.codex/mcp",
1139 "/home/user/.claude/worktreesx/a",
1140 ] {
1141 assert!(is_agent_config_dir(Path::new(p)), "{p}");
1142 }
1143 assert!(!is_agent_config_dir(Path::new("/repo/.claudex/a")));
1144 }
1145
1146 #[test]
1147 fn agent_config_dir_matches_windows_backslash() {
1148 assert!(is_agent_config_dir(Path::new(r"C:\Users\me\.copilot")));
1150 assert!(is_agent_config_dir(Path::new(r"C:\Users\me\.copilot\mcp")));
1151 }
1152
1153 #[test]
1154 fn agent_config_dir_ignores_real_projects() {
1155 assert!(!is_agent_config_dir(Path::new("/home/user/code/lean-ctx")));
1156 assert!(!is_agent_config_dir(Path::new(r"C:\src\app")));
1157 }
1158
1159 #[test]
1160 fn broad_root_allows_project_subdir() {
1161 let tmp = tempfile::tempdir().unwrap();
1162 let subdir = tmp.path().join("my-project");
1163 std::fs::create_dir_all(&subdir).unwrap();
1164 assert!(!is_broad_or_unsafe_root(&subdir));
1165 }
1166
1167 #[test]
1168 fn broad_root_allows_home_subdirs() {
1169 if let Some(home) = dirs::home_dir() {
1170 let subdir = home.join("projects").join("my-app");
1171 assert!(!is_broad_or_unsafe_root(&subdir));
1172 }
1173 }
1174
1175 #[test]
1176 fn data_dir_collision_rejects_home() {
1177 if let Some(home) = dirs::home_dir() {
1178 assert!(is_data_dir_collision(&home));
1179 }
1180 }
1181
1182 #[test]
1183 fn data_dir_collision_allows_normal_project() {
1184 let tmp = tempfile::tempdir().unwrap();
1185 let project = tmp.path().join("my-project");
1186 std::fs::create_dir_all(&project).unwrap();
1187 assert!(!is_data_dir_collision(&project));
1188 }
1189
1190 #[test]
1191 fn has_project_marker_detects_git() {
1192 let tmp = tempfile::tempdir().unwrap();
1193 let root = tmp.path().join("repo");
1194 std::fs::create_dir_all(&root).unwrap();
1195 assert!(!has_project_marker(&root));
1196 std::fs::create_dir(root.join(".git")).unwrap();
1197 assert!(has_project_marker(&root));
1198 }
1199
1200 #[test]
1201 fn has_project_marker_detects_cargo_toml() {
1202 let tmp = tempfile::tempdir().unwrap();
1203 let root = tmp.path().join("rust-project");
1204 std::fs::create_dir_all(&root).unwrap();
1205 std::fs::write(root.join("Cargo.toml"), "[package]").unwrap();
1206 assert!(has_project_marker(&root));
1207 }
1208
1209 #[test]
1210 fn has_project_marker_detects_godot_project() {
1211 let tmp = tempfile::tempdir().unwrap();
1212 let root = tmp.path().join("godot-game");
1213 std::fs::create_dir_all(&root).unwrap();
1214 std::fs::write(root.join("project.godot"), "config_version=5\n").unwrap();
1215 assert!(has_project_marker(&root));
1216 }
1217
1218 #[test]
1219 fn multi_repo_children_needs_two() {
1220 let tmp = tempfile::tempdir().unwrap();
1221 let parent = tmp.path().join("code");
1222 std::fs::create_dir_all(&parent).unwrap();
1223
1224 assert!(!has_multi_repo_children(&parent));
1226
1227 let repo1 = parent.join("repo1");
1229 std::fs::create_dir_all(repo1.join(".git")).unwrap();
1230 assert!(!has_multi_repo_children(&parent));
1231
1232 let repo2 = parent.join("repo2");
1234 std::fs::create_dir_all(repo2.join(".git")).unwrap();
1235 assert!(has_multi_repo_children(&parent));
1236 }
1237
1238 #[test]
1239 fn multi_repo_children_ignores_files() {
1240 let tmp = tempfile::tempdir().unwrap();
1241 let parent = tmp.path().join("mixed");
1242 std::fs::create_dir_all(&parent).unwrap();
1243
1244 let repo1 = parent.join("repo1");
1246 std::fs::create_dir_all(repo1.join(".git")).unwrap();
1247 std::fs::write(parent.join("not-a-repo"), "file").unwrap();
1248 assert!(!has_multi_repo_children(&parent));
1249
1250 let repo2 = parent.join("repo2");
1252 std::fs::create_dir_all(&repo2).unwrap();
1253 std::fs::write(repo2.join("package.json"), "{}").unwrap();
1254 assert!(has_multi_repo_children(&parent));
1255 }
1256
1257 #[test]
1258 fn multi_repo_children_nonexistent_dir() {
1259 assert!(!has_multi_repo_children(Path::new("/nonexistent/path/xyz")));
1260 }
1261
1262 #[test]
1263 fn regular_file_is_not_symlink_or_reparse() {
1264 let tmp = tempfile::tempdir().unwrap();
1265 let file = tmp.path().join("plain.txt");
1266 std::fs::write(&file, "x").unwrap();
1267 let meta = std::fs::symlink_metadata(&file).unwrap();
1268 assert!(!is_symlink_or_reparse(&meta));
1269 }
1270
1271 #[cfg(unix)]
1272 #[test]
1273 fn unix_symlink_is_detected() {
1274 let tmp = tempfile::tempdir().unwrap();
1275 let target = tmp.path().join("target.txt");
1276 std::fs::write(&target, "x").unwrap();
1277 let link = tmp.path().join("link.txt");
1278 std::os::unix::fs::symlink(&target, &link).unwrap();
1279 let meta = std::fs::symlink_metadata(&link).unwrap();
1280 assert!(is_symlink_or_reparse(&meta));
1281 }
1282
1283 #[cfg(windows)]
1286 #[test]
1287 fn windows_symlink_is_detected() {
1288 let tmp = tempfile::tempdir().unwrap();
1289 let target = tmp.path().join("target.txt");
1290 std::fs::write(&target, "x").unwrap();
1291 let link = tmp.path().join("link.txt");
1292 if std::os::windows::fs::symlink_file(&target, &link).is_err() {
1293 eprintln!("skipping: symlink creation not permitted on this runner");
1294 return;
1295 }
1296 let meta = std::fs::symlink_metadata(&link).unwrap();
1297 assert!(is_symlink_or_reparse(&meta));
1298 }
1299}