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