Skip to main content

lean_ctx/core/
pathutil.rs

1use std::path::{Path, PathBuf};
2
3/// Canonicalize a path and strip the Windows verbatim/extended-length prefix (`\\?\`)
4/// that `std::fs::canonicalize` adds on Windows. This prefix breaks many tools and
5/// string-based path comparisons.
6///
7/// On non-Windows platforms this is equivalent to `std::fs::canonicalize`.
8pub fn safe_canonicalize(path: &Path) -> std::io::Result<PathBuf> {
9    // TCC choke-point (#356): a launchd-standalone process (daemon/proxy/auto-
10    // updater, ppid 1) must never realpath a path under ~/Documents, ~/Desktop
11    // or ~/Downloads — the `stat` trips the macOS privacy prompt in lean-ctx's
12    // own name, and every release re-invalidates the grant (new cdhash), so it
13    // re-prompts forever. Heuristic call sites (project-root detection, session
14    // matching, path normalization, scan-root checks) all funnel through here,
15    // so guarding the sink protects them centrally instead of one opt-in check
16    // per call site. Return the path unchanged (lexical) rather than touching
17    // the filesystem. Security boundaries (PathJail) deliberately bypass this
18    // guard via `canonicalize_secure` — they only resolve paths the client
19    // explicitly asked to access, where a prompt is legitimate, and must keep
20    // resolving symlinks to detect jail escapes.
21    if !may_probe_path(path) {
22        return Ok(path.to_path_buf());
23    }
24    canonicalize_raw(path)
25}
26
27/// Raw realpath + Windows-verbatim strip, with **no** TCC guard. Internal sink
28/// shared by [`safe_canonicalize`] (which gates it behind `may_probe_path`) and
29/// [`canonicalize_secure`] (which never gates it).
30pub(crate) fn canonicalize_raw(path: &Path) -> std::io::Result<PathBuf> {
31    let canon = std::fs::canonicalize(path)?;
32    Ok(strip_verbatim(canon))
33}
34
35/// Like `safe_canonicalize` but returns the original path on failure.
36pub fn safe_canonicalize_or_self(path: &Path) -> PathBuf {
37    safe_canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
38}
39
40/// SECURITY canonicalize: always resolves symlinks, even under ~/Documents in a
41/// launchd-standalone process. PathJail relies on this to detect symlink jail
42/// escapes (#356 must never weaken the security boundary). A standalone process
43/// only reaches here for a path the client *explicitly* asked to access, where a
44/// one-time TCC prompt is legitimate — unlike the self-initiated heuristic
45/// probes that [`safe_canonicalize`] suppresses.
46pub fn canonicalize_secure(path: &Path) -> std::io::Result<PathBuf> {
47    canonicalize_raw(path)
48}
49
50/// Like `canonicalize_secure` but returns the original path on failure.
51pub fn canonicalize_secure_or_self(path: &Path) -> PathBuf {
52    canonicalize_secure(path).unwrap_or_else(|_| path.to_path_buf())
53}
54
55/// Canonicalize with a timeout guard. Protects against hangs on WSL2 DrvFS,
56/// Windows reparse points, NFS, FUSE, sshfs, and other slow filesystems.
57/// Falls back to the original path if canonicalize doesn't complete within the timeout.
58/// Self-healing: after a timeout, subsequent calls to slow mounts skip the thread entirely.
59///
60/// Heuristic variant — honours the #356 TCC guard (see [`safe_canonicalize`]).
61pub fn safe_canonicalize_bounded(path: &Path, timeout_ms: u64) -> PathBuf {
62    canonicalize_bounded_with(path, timeout_ms, safe_canonicalize_or_self)
63}
64
65/// SECURITY variant of [`safe_canonicalize_bounded`] — bypasses the #356 TCC
66/// guard so PathJail keeps resolving symlinks to detect jail escapes. See
67/// [`canonicalize_secure`] for why a prompt here (explicit request) is legitimate.
68pub fn canonicalize_secure_bounded(path: &Path, timeout_ms: u64) -> PathBuf {
69    canonicalize_bounded_with(path, timeout_ms, canonicalize_secure_or_self)
70}
71
72/// Shared timeout machinery for the bounded canonicalizers. `resolve` selects
73/// the guarded (`safe_canonicalize_or_self`) or security (`canonicalize_secure_or_self`)
74/// sink so both variants get identical slow-mount/self-healing behaviour.
75fn 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
111/// Remove the `\\?\` / `//?/` verbatim prefix from a `PathBuf`.
112/// Handles both regular verbatim (`\\?\C:\...`) and UNC verbatim (`\\?\UNC\...`).
113pub 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
122/// Remove the `\\?\` / `//?/` verbatim prefix from a path string.
123/// Returns `Some(cleaned)` if a prefix was found, `None` otherwise.
124pub 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
136/// MSYS2/Git Bash drive mapping: `/c/Users/...` -> `C:/Users/...`.
137///
138/// Returns `None` when the path does not carry a single-letter drive prefix.
139/// Callers must apply this **only on Windows hosts**: clients running under
140/// MSYS2/Git Bash hand POSIX-style drive paths to a native Windows lean-ctx.
141/// On Linux/macOS `/c/...` is a literal directory and must pass through
142/// untouched (GH #397 — the unconditional rewrite broke every `ctx_*` tool
143/// for Linux projects rooted under `/c/...` and similar paths).
144fn 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
157/// Lexical (string-only) part of [`normalize_tool_path`]: MSYS2 drive prefix
158/// (Windows hosts only), separators, double slashes, trailing slash. Performs
159/// **no** filesystem access, so it is safe on persisted paths in
160/// TCC-standalone processes (launchd daemon, #356) and as a dedupe key where
161/// symlink resolution is not worth a `realpath` per entry.
162pub 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    // Collapse double slashes (preserve UNC paths starting with //)
177    while p.contains("//") && !p.starts_with("//") {
178        p = p.replace("//", "/");
179    }
180
181    // Remove trailing slash (unless root like "/" or "C:/")
182    if p.len() > 1 && p.ends_with('/') && !p.ends_with(":/") {
183        p.pop();
184    }
185
186    p
187}
188
189/// Normalize paths from any client format to a consistent OS-native form.
190/// Handles MSYS2/Git Bash drive prefixes on Windows hosts
191/// (`/c/Users/...` -> `C:/Users/...`), mixed separators, double slashes, and
192/// trailing slashes. Uses forward slashes for consistency. On non-Windows
193/// hosts `/c/...` is a literal directory and passes through unchanged (#397).
194pub fn normalize_tool_path(path: &str) -> String {
195    let mut p = normalize_tool_path_lexical(path);
196
197    // Resolve symlinks for absolute paths to ensure cache key consistency.
198    // Skip relative paths (preserve "." / "../" as-is), root-only paths (/ or C:/),
199    // slow mounts (WSL DrvFS /mnt/) where canonicalize can hang, and paths a
200    // TCC-standalone process must not stat (launchd daemon + ~/Documents, #356).
201    // Uses safe_canonicalize to strip Windows \\?\ prefix.
202    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
219/// Agent/IDE CLI config or sandbox directories some clients launch their MCP
220/// server from, but which are never a user's project root. Adopting one as the
221/// project root jails every real repository path out — the root cause of #580
222/// (GitHub Copilot CLI launches from `~/.copilot`; Cursor, Windsurf, Gemini CLI
223/// and LM Studio behave similarly). This is the canonical set: every "is this an
224/// agent dir?" check across the codebase delegates here so the list never drifts.
225pub 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
237/// Returns `true` if `dir` is — or lies inside — a known agent/IDE config dir
238/// ([`AGENT_CONFIG_DIRS`]). Separator-agnostic so Windows backslash paths
239/// (`C:\Users\me\.copilot`) match too; #580 is a Windows Copilot report.
240pub fn is_agent_config_dir(dir: &Path) -> bool {
241    let s = dir.to_string_lossy().replace('\\', "/");
242    AGENT_CONFIG_DIRS
243        .iter()
244        .any(|name| s.ends_with(&format!("/{name}")) || s.contains(&format!("/{name}/")))
245}
246
247fn is_wsl_windows_user_profile(dir: &Path) -> bool {
248    let normalized = dir.to_string_lossy();
249    if !normalized.starts_with("/mnt/") {
250        return false;
251    }
252
253    let mut components = normalized
254        .split('/')
255        .filter(|component| !component.is_empty());
256    let (Some(mount), Some(drive), Some(users), Some(username)) = (
257        components.next(),
258        components.next(),
259        components.next(),
260        components.next(),
261    ) else {
262        return false;
263    };
264
265    mount.eq_ignore_ascii_case("mnt")
266        && drive.len() == 1
267        && drive.as_bytes()[0].is_ascii_alphabetic()
268        && users.eq_ignore_ascii_case("users")
269        && !username.is_empty()
270        && components.next().is_none()
271}
272
273/// Returns `true` if the directory is too broad to be a valid project root.
274/// Rejects home directories (including WSL-mounted Windows profiles), filesystem
275/// root, `.` (bare CWD), and agent/IDE config directories
276/// ([`AGENT_CONFIG_DIRS`]). Used to prevent adopting a bogus project root and
277/// writing project-scoped data into the global `~/.lean-ctx/` data directory.
278pub fn is_broad_or_unsafe_root(dir: &Path) -> bool {
279    if let Some(home) = dirs::home_dir()
280        && dir == home
281    {
282        return true;
283    }
284    if is_wsl_windows_user_profile(dir) {
285        return true;
286    }
287    let s = dir.to_string_lossy();
288    if s == "/" || s == "\\" || s == "." {
289        return true;
290    }
291    is_agent_config_dir(dir)
292}
293
294/// Well-known project markers used to identify project roots.
295pub const PROJECT_MARKERS: &[&str] = &[
296    ".git",
297    "Cargo.toml",
298    "package.json",
299    "go.mod",
300    "pyproject.toml",
301    "setup.py",
302    "pom.xml",
303    "build.gradle",
304    "Makefile",
305    "project.godot",
306    ".lean-ctx.toml",
307    ".planning",
308];
309
310/// Returns `true` if `dir` contains at least one known project marker.
311///
312/// TCC guard (#356): a launchd-owned process (daemon/proxy/auto-updater) must
313/// not stat marker files under `~/Documents` & co. — the probe itself pops the
314/// macOS privacy prompt. For those processes this conservatively reports
315/// "no marker" without touching the filesystem.
316pub fn has_project_marker(dir: &Path) -> bool {
317    if !may_probe_path(dir) {
318        return false;
319    }
320    PROJECT_MARKERS.iter().any(|m| dir.join(m).exists())
321}
322
323/// Returns `true` if the (lstat) metadata describes a symlink — or, on
324/// Windows, *any* reparse point (junctions, mount points, app-exec links).
325///
326/// Security boundaries must use this instead of `FileType::is_symlink`:
327/// Rust's `is_symlink()` reports `false` for NTFS junctions, which redirect
328/// exactly like directory symlinks and would otherwise bypass jail/TOCTOU
329/// checks on Windows (GL#442).
330pub fn is_symlink_or_reparse(meta: &std::fs::Metadata) -> bool {
331    if meta.file_type().is_symlink() {
332        return true;
333    }
334    #[cfg(windows)]
335    {
336        use std::os::windows::fs::MetadataExt;
337        const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0400;
338        return meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0;
339    }
340    #[cfg(not(windows))]
341    false
342}
343
344/// Returns `true` if `dir` is the home directory or one of the macOS "magic"
345/// home subdirectories (`Documents`, `Desktop`, `Downloads`).
346///
347/// macOS guards these with TCC: the first time a process *enumerates or stats
348/// inside* one, the OS pops a privacy prompt ("lean-ctx would like to access
349/// files in your Documents folder", #356). They are also never valid project
350/// roots or multi-repo workspace parents, so scan heuristics should treat them
351/// as off-limits *without* calling `read_dir` (which is what trips the prompt).
352pub fn is_tcc_sensitive_home_dir(dir: &Path) -> bool {
353    let Some(home) = dirs::home_dir() else {
354        return false;
355    };
356    if dir == home {
357        return true;
358    }
359    if dir.parent() != Some(home.as_path()) {
360        return false;
361    }
362    matches!(
363        dir.file_name().and_then(|n| n.to_str()),
364        Some("Documents" | "Desktop" | "Downloads")
365    )
366}
367
368/// Returns `true` if `path` lies inside (or is) one of the macOS TCC-protected
369/// home folders (`~/Documents`, `~/Desktop`, `~/Downloads`). Pure string/path
370/// comparison — performs **no** filesystem access itself.
371///
372/// Unlike [`is_tcc_sensitive_home_dir`] (which only matches the magic dirs
373/// themselves), this also matches nested paths like `~/Documents/proj/src`,
374/// because *any* `stat` below the magic dir trips the TCC prompt (#356).
375pub fn is_under_tcc_protected_dir(path: &Path) -> bool {
376    if !cfg!(target_os = "macos") {
377        return false;
378    }
379    let Some(home) = dirs::home_dir() else {
380        return false;
381    };
382    ["Documents", "Desktop", "Downloads"]
383        .iter()
384        .any(|magic| path.starts_with(home.join(magic)))
385}
386
387/// Returns `true` when this process is its own TCC identity on macOS — i.e.
388/// it was started (or re-parented) by `launchd` rather than by a
389/// TCC-granted host like a terminal or an editor.
390///
391/// Context (#356): TCC permissions attach to the *responsible process*. The
392/// lean-ctx daemon/proxy LaunchAgents and the scheduled auto-updater run
393/// directly under `launchd` (ppid 1), so any `stat`/`read_dir` they perform
394/// under `~/Documents` pops the privacy prompt **in lean-ctx's own name** —
395/// and because every release replaces the ad-hoc-signed binary (new cdhash),
396/// a previously granted permission is invalidated on each update, re-prompting
397/// forever. Such processes must never probe TCC-protected paths on their own
398/// initiative. Child processes of a terminal or editor (MCP server, CLI)
399/// inherit their host's TCC grant and keep full functionality.
400pub fn process_is_tcc_standalone() -> bool {
401    #[cfg(target_os = "macos")]
402    {
403        // Deliberately uncached: getppid is a cheap syscall, the env override
404        // must stay testable within one process, and a daemonizing fork could
405        // change the answer after startup.
406        if let Ok(v) = std::env::var("LEAN_CTX_TCC_STANDALONE") {
407            match v.trim() {
408                "1" | "true" => return true,
409                "0" | "false" => return false,
410                _ => {}
411            }
412        }
413        // A process carrying the deny-~/Documents seatbelt sentinel is, by
414        // construction, a launchd-standalone descendant: the sentinel is set
415        // only by the LaunchAgent plist env and the self re-exec, and child
416        // processes inherit it. This catches a daemon the long-lived standalone
417        // proxy spawned via `start_daemon` (ppid = proxy, not 1), whose code-side
418        // path guards would otherwise stay off because `getppid()` is no longer
419        // 1. (#356)
420        if std::env::var_os(crate::core::tcc_guard_sandbox::SEATBELT_SENTINEL).is_some() {
421            return true;
422        }
423        // SAFETY: `getppid` takes no arguments and cannot fail.
424        (unsafe { libc::getppid() }) == 1
425    }
426    #[cfg(not(target_os = "macos"))]
427    {
428        false
429    }
430}
431
432/// Returns `true` when this process may `stat`/`read_dir`/`canonicalize`
433/// `path` without risking a macOS TCC privacy prompt in lean-ctx's name.
434///
435/// Heuristic call sites (project-marker probes, session/root matching) must
436/// consult this before touching paths from persisted state; security
437/// boundaries (PathJail) are exempt — they only ever canonicalize paths the
438/// client explicitly asked to access, in which case a prompt is legitimate.
439pub fn may_probe_path(path: &Path) -> bool {
440    !(process_is_tcc_standalone() && is_under_tcc_protected_dir(path))
441}
442
443/// Returns `true` if `dir` is a multi-repo workspace parent — i.e. it has at
444/// least 2 immediate child directories that each contain a project marker.
445pub fn has_multi_repo_children(dir: &Path) -> bool {
446    // Never enumerate the home dir or macOS TCC-protected dirs: read_dir there
447    // pops a macOS privacy prompt (#356) and they are never workspace parents.
448    // `is_tcc_sensitive_home_dir` only matches the magic dirs themselves;
449    // `!may_probe_path` additionally refuses *nested* paths like
450    // `~/Documents/proj` when this process is launchd-standalone.
451    if is_tcc_sensitive_home_dir(dir) || !may_probe_path(dir) {
452        return false;
453    }
454    let Ok(entries) = std::fs::read_dir(dir) else {
455        return false;
456    };
457    let count = entries
458        .filter_map(Result::ok)
459        .filter(|e| e.file_type().is_ok_and(|ft| ft.is_dir()))
460        .filter(|e| has_project_marker(&e.path()))
461        .take(2)
462        .count();
463    count >= 2
464}
465
466/// Returns `true` if `project_root` collides with the lean-ctx data directory.
467/// This prevents project-scoped files (overlays.json, policies.json) from being
468/// written into `~/.lean-ctx/` or `~/.config/lean-ctx/`.
469pub fn is_data_dir_collision(project_root: &Path) -> bool {
470    if is_broad_or_unsafe_root(project_root) {
471        return true;
472    }
473    if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
474        let project_lean_ctx = project_root.join(".lean-ctx");
475        if project_lean_ctx == data_dir || data_dir.starts_with(&project_lean_ctx) {
476            return true;
477        }
478    }
479    false
480}
481
482/// Returns the project-scoped `.lean-ctx/` directory if the project root is safe.
483/// Returns `Err` if the project root collides with the global data directory.
484pub fn safe_project_data_dir(project_root: &Path) -> Result<PathBuf, String> {
485    if is_data_dir_collision(project_root) {
486        return Err(format!(
487            "project root {} collides with global data directory; \
488             skipping project-scoped write",
489            project_root.display()
490        ));
491    }
492    Ok(project_root.join(".lean-ctx"))
493}
494
495#[cfg(test)]
496mod tests {
497    use super::*;
498
499    #[test]
500    fn strip_regular_verbatim() {
501        let p = PathBuf::from(r"\\?\C:\Users\dev\project");
502        let result = strip_verbatim(p);
503        assert_eq!(result, PathBuf::from("C:/Users/dev/project"));
504    }
505
506    #[test]
507    fn tcc_sensitive_home_dir_matches_home_and_magic_dirs() {
508        let Some(home) = dirs::home_dir() else {
509            return;
510        };
511        // Home itself and the macOS magic dirs are off-limits (#356).
512        assert!(is_tcc_sensitive_home_dir(&home));
513        assert!(is_tcc_sensitive_home_dir(&home.join("Documents")));
514        assert!(is_tcc_sensitive_home_dir(&home.join("Desktop")));
515        assert!(is_tcc_sensitive_home_dir(&home.join("Downloads")));
516    }
517
518    #[test]
519    fn tcc_sensitive_home_dir_allows_real_projects() {
520        let Some(home) = dirs::home_dir() else {
521            return;
522        };
523        // A real project (even nested under Documents) and non-magic home children
524        // are scannable — only the bare magic dirs / home are blocked.
525        assert!(!is_tcc_sensitive_home_dir(
526            &home.join("Documents").join("my-project")
527        ));
528        assert!(!is_tcc_sensitive_home_dir(&home.join("code")));
529        assert!(!is_tcc_sensitive_home_dir(&home.join("Projects")));
530    }
531
532    #[test]
533    #[cfg(target_os = "macos")]
534    fn under_tcc_protected_dir_matches_nested_paths() {
535        let Some(home) = dirs::home_dir() else {
536            return;
537        };
538        // The magic dirs themselves and anything nested below them (#356).
539        assert!(is_under_tcc_protected_dir(&home.join("Documents")));
540        assert!(is_under_tcc_protected_dir(
541            &home.join("Documents/deep/nested/project")
542        ));
543        assert!(is_under_tcc_protected_dir(&home.join("Desktop/scratch")));
544        assert!(is_under_tcc_protected_dir(&home.join("Downloads/x.zip")));
545        // Home itself, siblings, and non-home paths are fine.
546        assert!(!is_under_tcc_protected_dir(&home));
547        assert!(!is_under_tcc_protected_dir(&home.join("code/project")));
548        assert!(!is_under_tcc_protected_dir(Path::new("/tmp/Documents")));
549    }
550
551    #[test]
552    #[cfg(target_os = "macos")]
553    #[serial_test::serial]
554    fn tcc_standalone_blocks_probes_under_protected_dirs() {
555        // `#[serial]` and `test_env_lock` are two different mutexes; the tests
556        // in this module need both. `LEAN_CTX_TCC_STANDALONE` is read by
557        // `is_tcc_standalone` (line ~376) on every path normalization, so
558        // setting it here reaches any test that resolves a path — most of which
559        // serialize on `test_env_lock`, not on `#[serial]`.
560        let _env_lock = crate::core::data_dir::test_env_lock();
561        let Some(home) = dirs::home_dir() else {
562            return;
563        };
564        let doc_proj = home.join("Documents/some-project");
565
566        crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "1");
567        assert!(process_is_tcc_standalone());
568        assert!(!may_probe_path(&doc_proj));
569        // Non-protected paths stay probeable even for standalone processes.
570        assert!(may_probe_path(Path::new("/tmp/some-project")));
571        // has_project_marker must refuse without touching the filesystem.
572        assert!(!has_project_marker(&doc_proj));
573
574        crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "0");
575        assert!(!process_is_tcc_standalone());
576        assert!(may_probe_path(&doc_proj));
577        crate::test_env::remove_var("LEAN_CTX_TCC_STANDALONE");
578    }
579
580    #[test]
581    #[cfg(target_os = "macos")]
582    #[serial_test::serial]
583    fn tcc_standalone_detected_via_seatbelt_sentinel() {
584        let _env_lock = crate::core::data_dir::test_env_lock();
585        let Some(home) = dirs::home_dir() else {
586            return;
587        };
588        let doc_proj = home.join("Documents/some-project");
589
590        // No explicit override: a process carrying the deny-~/Documents seatbelt
591        // sentinel (inherited from its sandboxed launchd parent) counts as
592        // standalone even when ppid != 1, so its heuristic probes stay
593        // suppressed — this is the proxy→daemon chain the ppid check missed. (#356)
594        crate::test_env::remove_var("LEAN_CTX_TCC_STANDALONE");
595        crate::test_env::set_var(crate::core::tcc_guard_sandbox::SEATBELT_SENTINEL, "1");
596        assert!(process_is_tcc_standalone());
597        assert!(!may_probe_path(&doc_proj));
598        crate::test_env::remove_var(crate::core::tcc_guard_sandbox::SEATBELT_SENTINEL);
599
600        // With neither override nor sentinel a normal test process (ppid != 1)
601        // is not standalone, so the sentinel is what flipped the result above.
602        assert!(!process_is_tcc_standalone());
603    }
604
605    #[test]
606    #[cfg(target_os = "macos")]
607    #[serial_test::serial]
608    fn tcc_standalone_skips_canonicalize_under_protected_dirs() {
609        let _env_lock = crate::core::data_dir::test_env_lock();
610        let Some(home) = dirs::home_dir() else {
611            return;
612        };
613        // A path that does NOT exist under ~/Documents. With the TCC choke-point
614        // guard active, `safe_canonicalize` returns Ok(input) *without* calling
615        // `std::fs::canonicalize` (which would Err on a missing path) — proving
616        // the filesystem is never touched (#356). This is the structural fix:
617        // every heuristic canonicalize funnels through here.
618        let missing = home.join("Documents/lean-ctx-tcc-test-does-not-exist-xyzzy");
619
620        crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "1");
621        let guarded = safe_canonicalize(&missing);
622        assert!(
623            guarded.is_ok(),
624            "standalone safe_canonicalize must short-circuit (no stat) under ~/Documents"
625        );
626        assert_eq!(guarded.unwrap(), missing);
627        assert_eq!(safe_canonicalize_or_self(&missing), missing);
628
629        // Outside the protected dirs the guard never engages, even when standalone.
630        let tmp_missing = Path::new("/tmp/lean-ctx-tcc-test-does-not-exist-xyzzy");
631        assert!(safe_canonicalize(tmp_missing).is_err());
632
633        // Without standalone the guard is inactive: a missing ~/Documents path
634        // Errs from the real `std::fs::canonicalize` as before.
635        crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "0");
636        assert!(safe_canonicalize(&missing).is_err());
637
638        crate::test_env::remove_var("LEAN_CTX_TCC_STANDALONE");
639    }
640
641    #[test]
642    #[cfg(target_os = "macos")]
643    #[serial_test::serial]
644    fn canonicalize_secure_bypasses_tcc_guard_for_pathjail() {
645        let _env_lock = crate::core::data_dir::test_env_lock();
646        // SECURITY counterpart to the test above (#356): PathJail must keep
647        // resolving symlinks even when standalone under ~/Documents, so the jail
648        // can detect escapes. `canonicalize_secure` therefore must NOT honour the
649        // guard — it always touches the filesystem. We prove that by feeding a
650        // missing ~/Documents path while standalone: the guarded path returns
651        // Ok(lexical) (no stat), while the secure path Errs (it did stat).
652        let Some(home) = dirs::home_dir() else {
653            return;
654        };
655        let missing = home.join("Documents/lean-ctx-secure-canon-does-not-exist-xyzzy");
656
657        crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "1");
658        // Guarded sink short-circuits (no fs access).
659        assert_eq!(safe_canonicalize(&missing).unwrap(), missing);
660        // Security sink ignores the guard and actually stats -> Err on a missing
661        // path. If this ever returns Ok(lexical), the jail's symlink-escape
662        // detection has silently regressed under ~/Documents.
663        assert!(
664            canonicalize_secure(&missing).is_err(),
665            "canonicalize_secure must bypass the TCC guard and touch the filesystem"
666        );
667        assert_eq!(canonicalize_secure_or_self(&missing), missing);
668        crate::test_env::remove_var("LEAN_CTX_TCC_STANDALONE");
669    }
670
671    #[test]
672    fn strip_unc_verbatim() {
673        let p = PathBuf::from(r"\\?\UNC\server\share\dir");
674        let result = strip_verbatim(p);
675        assert_eq!(result, PathBuf::from("//server/share/dir"));
676    }
677
678    #[test]
679    fn no_prefix_unchanged() {
680        let p = PathBuf::from("/home/user/project");
681        let result = strip_verbatim(p.clone());
682        assert_eq!(result, p);
683    }
684
685    #[test]
686    fn windows_drive_unchanged() {
687        let p = PathBuf::from("C:/Users/dev");
688        let result = strip_verbatim(p.clone());
689        assert_eq!(result, p);
690    }
691
692    #[test]
693    fn strip_str_regular() {
694        assert_eq!(
695            strip_verbatim_str(r"\\?\E:\code\lean-ctx"),
696            Some("E:/code/lean-ctx".to_string())
697        );
698    }
699
700    #[test]
701    fn strip_str_unc() {
702        assert_eq!(
703            strip_verbatim_str(r"\\?\UNC\myserver\data"),
704            Some("//myserver/data".to_string())
705        );
706    }
707
708    #[test]
709    fn strip_str_forward_slash_variant() {
710        assert_eq!(
711            strip_verbatim_str("//?/C:/Users/dev"),
712            Some("C:/Users/dev".to_string())
713        );
714    }
715
716    #[test]
717    fn strip_str_no_prefix() {
718        assert_eq!(strip_verbatim_str("/home/user"), None);
719    }
720
721    #[test]
722    fn safe_canonicalize_or_self_nonexistent() {
723        let p = Path::new("/this/path/should/not/exist/xyzzy");
724        let result = safe_canonicalize_or_self(p);
725        assert_eq!(result, p.to_path_buf());
726    }
727
728    // The drive translation itself is platform-independent and testable
729    // everywhere; only its *application* is gated on Windows hosts (#397).
730    #[test]
731    fn msys_drive_prefix_translation() {
732        assert_eq!(
733            translate_msys_drive_prefix("/c/Users/ABC").as_deref(),
734            Some("C:/Users/ABC")
735        );
736        assert_eq!(
737            translate_msys_drive_prefix("/D/Program Files").as_deref(),
738            Some("D:/Program Files")
739        );
740        assert_eq!(translate_msys_drive_prefix("/usr/local/bin"), None);
741        assert_eq!(translate_msys_drive_prefix("/c"), None);
742        assert_eq!(translate_msys_drive_prefix("c/Users"), None);
743    }
744
745    #[cfg(windows)]
746    #[test]
747    fn normalize_msys_path_to_native() {
748        assert_eq!(
749            normalize_tool_path("/c/Users/ABC/AppData/lean-ctx"),
750            "C:/Users/ABC/AppData/lean-ctx"
751        );
752        assert_eq!(
753            normalize_tool_path("/D/Program Files/lean-ctx.exe"),
754            "D:/Program Files/lean-ctx.exe"
755        );
756    }
757
758    // GH #397: on Linux/macOS, /c/… is a literal directory — a Linux project
759    // rooted there must not be rewritten to a Windows drive path.
760    #[cfg(not(windows))]
761    #[test]
762    fn normalize_single_letter_unix_path_untouched() {
763        assert_eq!(
764            normalize_tool_path_lexical("/c/Users/me/proj"),
765            "/c/Users/me/proj"
766        );
767        assert_eq!(
768            normalize_tool_path_lexical("/x/projects/app/src"),
769            "/x/projects/app/src"
770        );
771    }
772
773    #[test]
774    fn normalize_native_windows_path_unchanged() {
775        assert_eq!(
776            normalize_tool_path("C:/Users/ABC/lean-ctx.exe"),
777            "C:/Users/ABC/lean-ctx.exe"
778        );
779    }
780
781    #[test]
782    fn normalize_backslash_windows_path() {
783        assert_eq!(
784            normalize_tool_path(r"C:\Users\ABC\lean-ctx.exe"),
785            "C:/Users/ABC/lean-ctx.exe"
786        );
787    }
788
789    #[test]
790    fn normalize_unix_path_unchanged() {
791        assert_eq!(
792            normalize_tool_path("/usr/local/bin/lean-ctx"),
793            "/usr/local/bin/lean-ctx"
794        );
795    }
796
797    #[test]
798    fn normalize_windows_path_with_spaces_and_backslashes() {
799        // The exact "paths with spaces" scenario reported on Windows (#324):
800        // backslashes are converted to forward slashes (so client render layers
801        // never escape-mangle them) while spaces in directory names survive.
802        assert_eq!(
803            normalize_tool_path(r"C:\Users\My Name\My Project\src\main.rs"),
804            "C:/Users/My Name/My Project/src/main.rs"
805        );
806        assert_eq!(
807            normalize_tool_path(r"C:\Program Files\app\config.toml"),
808            "C:/Program Files/app/config.toml"
809        );
810    }
811
812    #[test]
813    fn normalize_double_slashes() {
814        assert_eq!(
815            normalize_tool_path("C:/Users//ABC//lean-ctx"),
816            "C:/Users/ABC/lean-ctx"
817        );
818    }
819
820    #[test]
821    fn normalize_trailing_slash_removed() {
822        assert_eq!(normalize_tool_path("C:/Users/ABC/"), "C:/Users/ABC");
823        assert_eq!(
824            normalize_tool_path_lexical("/tmp/nonexistent-dir-xyzzy/"),
825            "/tmp/nonexistent-dir-xyzzy"
826        );
827    }
828
829    #[test]
830    fn normalize_root_slash_preserved() {
831        assert_eq!(normalize_tool_path("/"), "/");
832    }
833
834    #[test]
835    fn normalize_drive_root_preserved() {
836        assert_eq!(normalize_tool_path("C:/"), "C:/");
837    }
838
839    #[test]
840    fn normalize_verbatim_with_msys() {
841        assert_eq!(normalize_tool_path(r"\\?\C:\Users\dev"), "C:/Users/dev");
842    }
843
844    #[test]
845    fn broad_root_rejects_home() {
846        if let Some(home) = dirs::home_dir() {
847            assert!(is_broad_or_unsafe_root(&home));
848        }
849    }
850
851    #[test]
852    fn broad_root_rejects_wsl_windows_user_profile() {
853        assert!(is_broad_or_unsafe_root(Path::new("/mnt/c/Users/dev")));
854        assert!(!is_broad_or_unsafe_root(Path::new(
855            "/mnt/c/Users/dev/projects/my-app"
856        )));
857    }
858
859    #[test]
860    fn broad_root_rejects_filesystem_root() {
861        assert!(is_broad_or_unsafe_root(Path::new("/")));
862    }
863
864    #[test]
865    fn broad_root_rejects_dot() {
866        assert!(is_broad_or_unsafe_root(Path::new(".")));
867    }
868
869    #[test]
870    fn broad_root_rejects_agent_dirs() {
871        assert!(is_broad_or_unsafe_root(Path::new("/home/user/.claude")));
872        assert!(is_broad_or_unsafe_root(Path::new("/home/user/.codex")));
873    }
874
875    #[test]
876    fn broad_root_rejects_copilot_and_friends() {
877        // #580: the previously-missing agent/IDE dirs must now be rejected so
878        // they are never adopted as the project root (the Copilot CLI case).
879        assert!(is_broad_or_unsafe_root(Path::new("/home/user/.copilot")));
880        assert!(is_broad_or_unsafe_root(Path::new("/home/user/.cursor")));
881        assert!(is_broad_or_unsafe_root(Path::new("/home/user/.windsurf")));
882        assert!(is_broad_or_unsafe_root(Path::new("/home/user/.gemini")));
883        assert!(is_broad_or_unsafe_root(Path::new("/home/user/.lmstudio")));
884    }
885
886    #[test]
887    fn agent_config_dir_matches_every_known_client() {
888        for name in AGENT_CONFIG_DIRS {
889            let leaf = format!("/home/user/{name}");
890            assert!(is_agent_config_dir(Path::new(&leaf)), "{leaf}");
891            let nested = format!("/home/user/{name}/mcp");
892            assert!(is_agent_config_dir(Path::new(&nested)), "{nested}");
893        }
894    }
895
896    #[test]
897    fn agent_config_dir_matches_windows_backslash() {
898        // #580 is a Windows Copilot report — backslash paths must match too.
899        assert!(is_agent_config_dir(Path::new(r"C:\Users\me\.copilot")));
900        assert!(is_agent_config_dir(Path::new(r"C:\Users\me\.copilot\mcp")));
901    }
902
903    #[test]
904    fn agent_config_dir_ignores_real_projects() {
905        assert!(!is_agent_config_dir(Path::new("/home/user/code/lean-ctx")));
906        assert!(!is_agent_config_dir(Path::new(r"C:\src\app")));
907    }
908
909    #[test]
910    fn broad_root_allows_project_subdir() {
911        let tmp = tempfile::tempdir().unwrap();
912        let subdir = tmp.path().join("my-project");
913        std::fs::create_dir_all(&subdir).unwrap();
914        assert!(!is_broad_or_unsafe_root(&subdir));
915    }
916
917    #[test]
918    fn broad_root_allows_home_subdirs() {
919        if let Some(home) = dirs::home_dir() {
920            let subdir = home.join("projects").join("my-app");
921            assert!(!is_broad_or_unsafe_root(&subdir));
922        }
923    }
924
925    #[test]
926    fn data_dir_collision_rejects_home() {
927        if let Some(home) = dirs::home_dir() {
928            assert!(is_data_dir_collision(&home));
929        }
930    }
931
932    #[test]
933    fn data_dir_collision_allows_normal_project() {
934        let tmp = tempfile::tempdir().unwrap();
935        let project = tmp.path().join("my-project");
936        std::fs::create_dir_all(&project).unwrap();
937        assert!(!is_data_dir_collision(&project));
938    }
939
940    #[test]
941    fn has_project_marker_detects_git() {
942        let tmp = tempfile::tempdir().unwrap();
943        let root = tmp.path().join("repo");
944        std::fs::create_dir_all(&root).unwrap();
945        assert!(!has_project_marker(&root));
946        std::fs::create_dir(root.join(".git")).unwrap();
947        assert!(has_project_marker(&root));
948    }
949
950    #[test]
951    fn has_project_marker_detects_cargo_toml() {
952        let tmp = tempfile::tempdir().unwrap();
953        let root = tmp.path().join("rust-project");
954        std::fs::create_dir_all(&root).unwrap();
955        std::fs::write(root.join("Cargo.toml"), "[package]").unwrap();
956        assert!(has_project_marker(&root));
957    }
958
959    #[test]
960    fn has_project_marker_detects_godot_project() {
961        let tmp = tempfile::tempdir().unwrap();
962        let root = tmp.path().join("godot-game");
963        std::fs::create_dir_all(&root).unwrap();
964        std::fs::write(root.join("project.godot"), "config_version=5\n").unwrap();
965        assert!(has_project_marker(&root));
966    }
967
968    #[test]
969    fn multi_repo_children_needs_two() {
970        let tmp = tempfile::tempdir().unwrap();
971        let parent = tmp.path().join("code");
972        std::fs::create_dir_all(&parent).unwrap();
973
974        // 0 repos → false
975        assert!(!has_multi_repo_children(&parent));
976
977        // 1 repo → false
978        let repo1 = parent.join("repo1");
979        std::fs::create_dir_all(repo1.join(".git")).unwrap();
980        assert!(!has_multi_repo_children(&parent));
981
982        // 2 repos → true
983        let repo2 = parent.join("repo2");
984        std::fs::create_dir_all(repo2.join(".git")).unwrap();
985        assert!(has_multi_repo_children(&parent));
986    }
987
988    #[test]
989    fn multi_repo_children_ignores_files() {
990        let tmp = tempfile::tempdir().unwrap();
991        let parent = tmp.path().join("mixed");
992        std::fs::create_dir_all(&parent).unwrap();
993
994        // One repo dir + one plain file with .git name (not a dir)
995        let repo1 = parent.join("repo1");
996        std::fs::create_dir_all(repo1.join(".git")).unwrap();
997        std::fs::write(parent.join("not-a-repo"), "file").unwrap();
998        assert!(!has_multi_repo_children(&parent));
999
1000        // Add second actual repo
1001        let repo2 = parent.join("repo2");
1002        std::fs::create_dir_all(&repo2).unwrap();
1003        std::fs::write(repo2.join("package.json"), "{}").unwrap();
1004        assert!(has_multi_repo_children(&parent));
1005    }
1006
1007    #[test]
1008    fn multi_repo_children_nonexistent_dir() {
1009        assert!(!has_multi_repo_children(Path::new("/nonexistent/path/xyz")));
1010    }
1011
1012    #[test]
1013    fn regular_file_is_not_symlink_or_reparse() {
1014        let tmp = tempfile::tempdir().unwrap();
1015        let file = tmp.path().join("plain.txt");
1016        std::fs::write(&file, "x").unwrap();
1017        let meta = std::fs::symlink_metadata(&file).unwrap();
1018        assert!(!is_symlink_or_reparse(&meta));
1019    }
1020
1021    #[cfg(unix)]
1022    #[test]
1023    fn unix_symlink_is_detected() {
1024        let tmp = tempfile::tempdir().unwrap();
1025        let target = tmp.path().join("target.txt");
1026        std::fs::write(&target, "x").unwrap();
1027        let link = tmp.path().join("link.txt");
1028        std::os::unix::fs::symlink(&target, &link).unwrap();
1029        let meta = std::fs::symlink_metadata(&link).unwrap();
1030        assert!(is_symlink_or_reparse(&meta));
1031    }
1032
1033    /// Runs in the windows-latest CI lane (GL#442). Symlink creation needs
1034    /// either admin or Developer Mode — skip gracefully when unavailable.
1035    #[cfg(windows)]
1036    #[test]
1037    fn windows_symlink_is_detected() {
1038        let tmp = tempfile::tempdir().unwrap();
1039        let target = tmp.path().join("target.txt");
1040        std::fs::write(&target, "x").unwrap();
1041        let link = tmp.path().join("link.txt");
1042        if std::os::windows::fs::symlink_file(&target, &link).is_err() {
1043            eprintln!("skipping: symlink creation not permitted on this runner");
1044            return;
1045        }
1046        let meta = std::fs::symlink_metadata(&link).unwrap();
1047        assert!(is_symlink_or_reparse(&meta));
1048    }
1049}