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/// A Windows absolute path (`C:\…`, `C:/…`) or UNC path (`\\server`, `//server`),
158/// recognised lexically on every platform.
159pub fn is_windows_absolute_path(path: &str) -> bool {
160    let bytes = path.as_bytes();
161    if bytes.len() >= 3
162        && bytes[0].is_ascii_alphabetic()
163        && bytes[1] == b':'
164        && matches!(bytes[2], b'\\' | b'/')
165    {
166        return true;
167    }
168
169    path.starts_with("\\\\") || path.starts_with("//")
170}
171
172/// Lexical (string-only) part of [`normalize_tool_path`]: MSYS2 drive prefix
173/// (Windows hosts only), separators, double slashes, trailing slash. Performs
174/// **no** filesystem access, so it is safe on persisted paths in
175/// TCC-standalone processes (launchd daemon, #356) and as a dedupe key where
176/// symlink resolution is not worth a `realpath` per entry.
177pub fn normalize_tool_path_lexical(path: &str) -> String {
178    let mut p = match strip_verbatim_str(path) {
179        Some(stripped) => stripped,
180        None => path.to_string(),
181    };
182
183    if cfg!(windows)
184        && let Some(translated) = translate_msys_drive_prefix(&p)
185    {
186        p = translated;
187    } else if !cfg!(windows) {
188        p = unescape_shell_path(&p);
189    }
190
191    p = p.replace('\\', "/");
192
193    // Collapse double slashes (preserve UNC paths starting with //)
194    while p.contains("//") && !p.starts_with("//") {
195        p = p.replace("//", "/");
196    }
197
198    // Remove trailing slash (unless root like "/" or "C:/")
199    if p.len() > 1 && p.ends_with('/') && !p.ends_with(":/") {
200        p.pop();
201    }
202
203    p
204}
205
206/// Undo shell quoting that agents copy into tool paths on Unix: one pair of
207/// surrounding quotes (`'/a b/c'`) and backslash escapes (`My\ Project`,
208/// `src/\(app\)`). Without this the separator rewrite below turned
209/// `My\ Project` into `My/ Project` — a directory that does not exist, so
210/// every path below a folder with a space failed. A backslash is never a
211/// separator on Unix and practically never part of a file name; a backslash
212/// before an ordinary character is kept for the rewrite as before.
213fn unescape_shell_path(path: &str) -> String {
214    let trimmed = path.trim();
215    let unquoted = [('\'', '\''), ('"', '"')]
216        .iter()
217        .find_map(|&(open, close)| {
218            trimmed
219                .strip_prefix(open)
220                .and_then(|rest| rest.strip_suffix(close))
221                .filter(|inner| !inner.is_empty())
222        })
223        .unwrap_or(path);
224    if !unquoted.contains('\\') {
225        return unquoted.to_string();
226    }
227    let mut out = String::with_capacity(unquoted.len());
228    let mut chars = unquoted.chars().peekable();
229    while let Some(c) = chars.next() {
230        if c == '\\'
231            && let Some(&next) = chars.peek()
232            && matches!(
233                next,
234                ' ' | '('
235                    | ')'
236                    | '['
237                    | ']'
238                    | '{'
239                    | '}'
240                    | '&'
241                    | '\''
242                    | '"'
243                    | '$'
244                    | '!'
245                    | '#'
246                    | ';'
247                    | '*'
248                    | '?'
249                    | '<'
250                    | '>'
251                    | '|'
252                    | '~'
253                    | '`'
254                    | '='
255            )
256        {
257            out.push(next);
258            chars.next();
259            continue;
260        }
261        out.push(c);
262    }
263    out
264}
265
266/// Normalize paths from any client format to a consistent OS-native form.
267/// Handles MSYS2/Git Bash drive prefixes on Windows hosts
268/// (`/c/Users/...` -> `C:/Users/...`), mixed separators, double slashes, and
269/// trailing slashes. Uses forward slashes for consistency. On non-Windows
270/// hosts `/c/...` is a literal directory and passes through unchanged (#397).
271/// Whether two recorded project roots name the same project: equal after
272/// separator and trailing-slash normalization, or after resolving symlinks.
273/// The one comparison for project-scoped records (agents, messages, shares):
274/// a raw string comparison split one project into several by spelling.
275pub fn same_project(a: &str, b: &str) -> bool {
276    let lexical = |path: &str| {
277        let path = path.trim().replace('\\', "/");
278        let trimmed = path.trim_end_matches('/');
279        if trimmed.is_empty() {
280            path
281        } else {
282            trimmed.to_string()
283        }
284    };
285    a == b || lexical(a) == lexical(b) || normalize_tool_path(a) == normalize_tool_path(b)
286}
287
288pub fn normalize_tool_path(path: &str) -> String {
289    let mut p = normalize_tool_path_lexical(path);
290
291    // Resolve symlinks for absolute paths to ensure cache key consistency.
292    // Skip relative paths (preserve "." / "../" as-is), root-only paths (/ or C:/),
293    // slow mounts (WSL DrvFS /mnt/) where canonicalize can hang, and paths a
294    // TCC-standalone process must not stat (launchd daemon + ~/Documents, #356).
295    // Uses safe_canonicalize to strip Windows \\?\ prefix.
296    let is_absolute = p.starts_with('/') || (p.len() >= 3 && p.as_bytes()[1] == b':');
297    let is_root_only = p == "/" || (p.len() <= 3 && p.ends_with('/') && is_absolute);
298    if is_absolute
299        && !is_root_only
300        && !crate::core::io_health::is_slow_mount(&p)
301        && may_probe_path(Path::new(&*p))
302        && let Ok(canonical) = safe_canonicalize(Path::new(&*p))
303    {
304        let canonical_str = canonical.to_string_lossy().replace('\\', "/");
305        if !canonical_str.is_empty() {
306            p = canonical_str;
307        }
308    }
309
310    p
311}
312
313/// Agent/IDE CLI config or sandbox directories some clients launch their MCP
314/// server from, but which are never a user's project root. Adopting one as the
315/// project root jails every real repository path out — the root cause of #580
316/// (GitHub Copilot CLI launches from `~/.copilot`; Cursor, Windsurf, Gemini CLI
317/// and LM Studio behave similarly). This is the canonical set: every "is this an
318/// agent dir?" check across the codebase delegates here so the list never drifts.
319pub const AGENT_CONFIG_DIRS: &[&str] = &[
320    ".claude",
321    ".codex",
322    ".codebuddy",
323    ".codewhale",
324    ".copilot",
325    ".cursor",
326    ".windsurf",
327    ".gemini",
328    ".lmstudio",
329];
330
331/// Returns `true` if `dir` is — or lies inside — a known agent/IDE config dir
332/// ([`AGENT_CONFIG_DIRS`]). Separator-agnostic so Windows backslash paths
333/// (`C:\Users\me\.copilot`) match too; #580 is a Windows Copilot report.
334///
335/// A checkout inside `<dir>/worktrees/<name>` (where Claude Code places its
336/// git worktrees, e.g. `<repo>/.claude/worktrees/fix-x`) is a real project,
337/// not agent config, and is exempt; `<dir>/worktrees` itself is not.
338pub fn is_agent_config_dir(dir: &Path) -> bool {
339    let s = dir.to_string_lossy().replace('\\', "/");
340    AGENT_CONFIG_DIRS.iter().any(|name| {
341        let segment = format!("/{name}");
342        s.match_indices(&segment).any(|(at, _)| {
343            let tail = &s[at + segment.len()..];
344            (tail.is_empty() || tail.starts_with('/')) && !is_worktree_checkout_tail(tail)
345        })
346    })
347}
348
349/// `tail` (the path after an agent dir) names `/worktrees/<name>[/...]`.
350fn is_worktree_checkout_tail(tail: &str) -> bool {
351    tail.strip_prefix("/worktrees/")
352        .and_then(|rest| rest.split('/').next())
353        .is_some_and(|name| !name.is_empty())
354}
355
356fn is_wsl_windows_user_profile(dir: &Path) -> bool {
357    let normalized = dir.to_string_lossy();
358    if !normalized.starts_with("/mnt/") {
359        return false;
360    }
361
362    let mut components = normalized
363        .split('/')
364        .filter(|component| !component.is_empty());
365    let (Some(mount), Some(drive), Some(users), Some(username)) = (
366        components.next(),
367        components.next(),
368        components.next(),
369        components.next(),
370    ) else {
371        return false;
372    };
373
374    mount.eq_ignore_ascii_case("mnt")
375        && drive.len() == 1
376        && drive.as_bytes()[0].is_ascii_alphabetic()
377        && users.eq_ignore_ascii_case("users")
378        && !username.is_empty()
379        && components.next().is_none()
380}
381
382/// Every spelling of the user's home directory a root guard must refuse: the
383/// profile folder (`dirs::home_dir`, which on Windows ignores the
384/// environment) and the override-friendly home (`HOME`/`USERPROFILE`,
385/// [`crate::core::home::resolve_home_dir`]). On Unix both are `$HOME` and
386/// one entry remains.
387pub fn home_dirs() -> Vec<PathBuf> {
388    let mut homes: Vec<PathBuf> = Vec::with_capacity(2);
389    for home in [dirs::home_dir(), crate::core::home::resolve_home_dir()]
390        .into_iter()
391        .flatten()
392    {
393        if !homes.contains(&home) {
394            homes.push(home);
395        }
396    }
397    homes
398}
399
400/// A startup root the server must not adopt as a jail root: too broad
401/// ([`is_broad_or_unsafe_root`]) or an agent/IDE config directory.
402pub fn is_suspicious_root(dir: &Path) -> bool {
403    is_broad_or_unsafe_root(dir) || is_agent_config_dir(dir)
404}
405
406/// Returns `true` if the directory is too broad to be a valid project root.
407/// Rejects home directories (including WSL-mounted Windows profiles), filesystem
408/// root, `.` (bare CWD), agent/IDE config directories ([`AGENT_CONFIG_DIRS`])
409/// and LeanCTX's own stores ([`is_lean_ctx_store_dir`]). Used to prevent
410/// adopting a bogus project root and writing project-scoped data into the
411/// global `~/.lean-ctx/` data directory.
412pub fn is_broad_or_unsafe_root(dir: &Path) -> bool {
413    // Compared without the Windows verbatim `\\?\` prefix, which
414    // `std::fs::canonicalize` adds there: `\\?\C:\Users\me` is the home
415    // directory as much as `C:\Users\me`.
416    let plain = strip_verbatim(dir.to_path_buf());
417    if home_dirs()
418        .into_iter()
419        .any(|home| plain == strip_verbatim(home))
420    {
421        return true;
422    }
423    if is_wsl_windows_user_profile(dir) {
424        return true;
425    }
426    let s = dir.to_string_lossy();
427    if s == "/" || s == "\\" || s == "." {
428        return true;
429    }
430    is_agent_config_dir(dir) || is_lean_ctx_store_dir(dir)
431}
432
433/// `dir` is LeanCTX's data, state, config or cache directory itself. A CLI
434/// started there without a project (the Cockpit's fallback working directory)
435/// must never adopt it as a project. Folders inside a store stay allowed:
436/// setups and fixtures with `LEAN_CTX_DATA_DIR` in a temp dir keep their
437/// projects there. Resolved read-only: nothing is created. Both sides are
438/// compared as given and canonical, so another spelling of the same folder
439/// (a symlink, macOS `/var` → `/private/var`) matches too.
440pub fn is_lean_ctx_store_dir(dir: &Path) -> bool {
441    let real_dir = dir.canonicalize().ok();
442    [
443        crate::core::data_dir::resolve_data_dir(),
444        crate::core::paths::state_dir_read_only(),
445        crate::core::paths::config_dir_read_only(),
446        crate::core::paths::cache_dir_read_only(),
447    ]
448    .into_iter()
449    .flatten()
450    .filter(|store| store.is_absolute())
451    .any(|store| {
452        let real_store = store.canonicalize().ok();
453        dir == store
454            || real_store.as_deref() == Some(dir)
455            || (real_dir.is_some() && real_dir == real_store)
456    })
457}
458
459/// Well-known project markers used to identify project roots.
460pub const PROJECT_MARKERS: &[&str] = &[
461    ".git",
462    "Cargo.toml",
463    "package.json",
464    "go.mod",
465    "pyproject.toml",
466    "setup.py",
467    "pom.xml",
468    "build.gradle",
469    "Makefile",
470    "project.godot",
471    "platformio.ini",
472    ".lean-ctx.toml",
473    ".planning",
474];
475
476/// Returns `true` if `dir` contains at least one known project marker.
477///
478/// TCC guard (#356): a launchd-owned process (daemon/proxy/auto-updater) must
479/// not stat marker files under `~/Documents` & co. — the probe itself pops the
480/// macOS privacy prompt. For those processes this conservatively reports
481/// "no marker" without touching the filesystem.
482pub fn has_project_marker(dir: &Path) -> bool {
483    if !may_probe_path(dir) {
484        return false;
485    }
486    PROJECT_MARKERS.iter().any(|m| dir.join(m).exists())
487}
488
489/// Returns `true` if the (lstat) metadata describes a symlink — or, on
490/// Windows, *any* reparse point (junctions, mount points, app-exec links).
491///
492/// Security boundaries must use this instead of `FileType::is_symlink`:
493/// Rust's `is_symlink()` reports `false` for NTFS junctions, which redirect
494/// exactly like directory symlinks and would otherwise bypass jail/TOCTOU
495/// checks on Windows (GL#442).
496pub fn is_symlink_or_reparse(meta: &std::fs::Metadata) -> bool {
497    meta.file_type().is_symlink() || is_reparse_point(meta)
498}
499
500/// An NTFS reparse point (junction, mount point, symlink) on Windows.
501#[cfg(windows)]
502fn is_reparse_point(meta: &std::fs::Metadata) -> bool {
503    use std::os::windows::fs::MetadataExt;
504    const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0400;
505    meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0
506}
507
508#[cfg(not(windows))]
509fn is_reparse_point(_meta: &std::fs::Metadata) -> bool {
510    false
511}
512
513/// Returns `true` if `dir` is the home directory or one of the macOS "magic"
514/// home subdirectories (`Documents`, `Desktop`, `Downloads`).
515///
516/// macOS guards these with TCC: the first time a process *enumerates or stats
517/// inside* one, the OS pops a privacy prompt ("lean-ctx would like to access
518/// files in your Documents folder", #356). They are also never valid project
519/// roots or multi-repo workspace parents, so scan heuristics should treat them
520/// as off-limits *without* calling `read_dir` (which is what trips the prompt).
521pub fn is_tcc_sensitive_home_dir(dir: &Path) -> bool {
522    let Some(home) = dirs::home_dir() else {
523        return false;
524    };
525    if dir == home {
526        return true;
527    }
528    if dir.parent() != Some(home.as_path()) {
529        return false;
530    }
531    matches!(
532        dir.file_name().and_then(|n| n.to_str()),
533        Some("Documents" | "Desktop" | "Downloads")
534    )
535}
536
537/// Returns `true` if `path` lies inside (or is) one of the macOS TCC-protected
538/// home folders (`~/Documents`, `~/Desktop`, `~/Downloads`). Pure string/path
539/// comparison — performs **no** filesystem access itself.
540///
541/// Unlike [`is_tcc_sensitive_home_dir`] (which only matches the magic dirs
542/// themselves), this also matches nested paths like `~/Documents/proj/src`,
543/// because *any* `stat` below the magic dir trips the TCC prompt (#356).
544pub fn is_under_tcc_protected_dir(path: &Path) -> bool {
545    if !cfg!(target_os = "macos") {
546        return false;
547    }
548    let Some(home) = dirs::home_dir() else {
549        return false;
550    };
551    ["Documents", "Desktop", "Downloads"]
552        .iter()
553        .any(|magic| path.starts_with(home.join(magic)))
554}
555
556/// Returns `true` when this process is its own TCC identity on macOS — i.e.
557/// it was started (or re-parented) by `launchd` rather than by a
558/// TCC-granted host like a terminal or an editor.
559///
560/// Context (#356): TCC permissions attach to the *responsible process*. The
561/// lean-ctx daemon/proxy LaunchAgents and the scheduled auto-updater run
562/// directly under `launchd` (ppid 1), so any `stat`/`read_dir` they perform
563/// under `~/Documents` pops the privacy prompt **in lean-ctx's own name** —
564/// and because every release replaces the ad-hoc-signed binary (new cdhash),
565/// a previously granted permission is invalidated on each update, re-prompting
566/// forever. Such processes must never probe TCC-protected paths on their own
567/// initiative. Child processes of a terminal or editor (MCP server, CLI)
568/// inherit their host's TCC grant and keep full functionality.
569pub fn process_is_tcc_standalone() -> bool {
570    #[cfg(target_os = "macos")]
571    {
572        // Deliberately uncached: getppid is a cheap syscall, the env override
573        // must stay testable within one process, and a daemonizing fork could
574        // change the answer after startup.
575        if let Ok(v) = std::env::var("LEAN_CTX_TCC_STANDALONE") {
576            match v.trim() {
577                "1" | "true" => return true,
578                "0" | "false" => return false,
579                _ => {}
580            }
581        }
582        // A process carrying the deny-~/Documents seatbelt sentinel is, by
583        // construction, a launchd-standalone descendant: the sentinel is set
584        // only by the LaunchAgent plist env and the self re-exec, and child
585        // processes inherit it. This catches a daemon the long-lived standalone
586        // proxy spawned via `start_daemon` (ppid = proxy, not 1), whose code-side
587        // path guards would otherwise stay off because `getppid()` is no longer
588        // 1. (#356)
589        if std::env::var_os(crate::core::tcc_guard_sandbox::SEATBELT_SENTINEL).is_some() {
590            return true;
591        }
592        // SAFETY: `getppid` takes no arguments and cannot fail.
593        (unsafe { libc::getppid() }) == 1
594    }
595    #[cfg(not(target_os = "macos"))]
596    {
597        false
598    }
599}
600
601/// Returns `true` when this process may `stat`/`read_dir`/`canonicalize`
602/// `path` without risking a macOS TCC privacy prompt in lean-ctx's name.
603///
604/// Heuristic call sites (project-marker probes, session/root matching) must
605/// consult this before touching paths from persisted state; security
606/// boundaries (PathJail) are exempt — they only ever canonicalize paths the
607/// client explicitly asked to access, in which case a prompt is legitimate.
608pub fn may_probe_path(path: &Path) -> bool {
609    !(process_is_tcc_standalone() && is_under_tcc_protected_dir(path))
610}
611
612/// Returns `true` if `dir` is a multi-repo workspace parent — i.e. it has at
613/// least 2 immediate child directories that each contain a project marker.
614pub fn has_multi_repo_children(dir: &Path) -> bool {
615    // Never enumerate the home dir or macOS TCC-protected dirs: read_dir there
616    // pops a macOS privacy prompt (#356) and they are never workspace parents.
617    // `is_tcc_sensitive_home_dir` only matches the magic dirs themselves;
618    // `!may_probe_path` additionally refuses *nested* paths like
619    // `~/Documents/proj` when this process is launchd-standalone.
620    if is_tcc_sensitive_home_dir(dir) || !may_probe_path(dir) {
621        return false;
622    }
623    let Ok(entries) = std::fs::read_dir(dir) else {
624        return false;
625    };
626    let count = entries
627        .filter_map(Result::ok)
628        .filter(|e| e.file_type().is_ok_and(|ft| ft.is_dir()))
629        .filter(|e| has_project_marker(&e.path()))
630        .take(2)
631        .count();
632    count >= 2
633}
634
635/// Returns `true` if `project_root` collides with the lean-ctx data directory.
636/// This prevents project-scoped files (overlays.json, policies.json) from being
637/// written into `~/.lean-ctx/` or `~/.config/lean-ctx/`.
638pub fn is_data_dir_collision(project_root: &Path) -> bool {
639    if is_broad_or_unsafe_root(project_root) {
640        return true;
641    }
642    if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
643        let project_lean_ctx = project_root.join(".lean-ctx");
644        if project_lean_ctx == data_dir || data_dir.starts_with(&project_lean_ctx) {
645            return true;
646        }
647    }
648    false
649}
650
651/// Returns the project-scoped `.lean-ctx/` directory if the project root is safe.
652/// Returns `Err` if the project root collides with the global data directory.
653pub fn safe_project_data_dir(project_root: &Path) -> Result<PathBuf, String> {
654    if is_data_dir_collision(project_root) {
655        return Err(format!(
656            "project root {} collides with global data directory; \
657             skipping project-scoped write",
658            project_root.display()
659        ));
660    }
661    Ok(project_root.join(".lean-ctx"))
662}
663
664/// First executable named `name` on `PATH`, resolved in-process.
665///
666/// Replaces spawning `where`/`which`: on Windows every spawn from the
667/// console-less daemon allocates a `conhost.exe`, and detection runs often.
668/// Windows tries each `PATHEXT` extension before the bare name, as `cmd`
669/// does when it runs a command, so an npm install yields `lean-ctx.cmd` rather
670/// than the extensionless shell shim beside it. Unix requires an execute bit,
671/// like `which`.
672pub fn find_on_path(name: &str) -> Option<PathBuf> {
673    find_all_on_path(name).into_iter().next()
674}
675
676/// Every executable named `name` on `PATH`, in lookup order: the one
677/// [`find_on_path`] returns first, then the ones it shadows.
678pub fn find_all_on_path(name: &str) -> Vec<PathBuf> {
679    if name.is_empty() {
680        return Vec::new();
681    }
682    let Some(path_var) = std::env::var_os("PATH") else {
683        return Vec::new();
684    };
685    let candidates = path_candidates(name);
686    std::env::split_paths(&path_var)
687        .filter(|dir| !dir.as_os_str().is_empty())
688        .flat_map(|dir| candidates.iter().map(move |c| dir.join(c)))
689        .filter(|p| is_executable_file(p))
690        .collect()
691}
692
693#[cfg(windows)]
694fn path_candidates(name: &str) -> Vec<String> {
695    let mut out = Vec::new();
696    if Path::new(name).extension().is_none() {
697        let exts = std::env::var("PATHEXT").unwrap_or_default();
698        let exts = if exts.trim().is_empty() {
699            ".COM;.EXE;.BAT;.CMD".to_string()
700        } else {
701            exts
702        };
703        out.extend(
704            exts.split(';')
705                .map(str::trim)
706                .filter(|e| !e.is_empty())
707                .map(|e| format!("{name}{e}")),
708        );
709    }
710    out.push(name.to_string());
711    out
712}
713
714#[cfg(not(windows))]
715fn path_candidates(name: &str) -> Vec<String> {
716    vec![name.to_string()]
717}
718
719#[cfg(unix)]
720fn is_executable_file(p: &Path) -> bool {
721    use std::os::unix::fs::PermissionsExt;
722    std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
723}
724
725#[cfg(not(unix))]
726fn is_executable_file(p: &Path) -> bool {
727    p.is_file()
728}
729
730#[cfg(test)]
731mod tests {
732    use super::*;
733
734    #[test]
735    fn find_on_path_resolves_extensionless_name_and_misses_unknown() {
736        let _env_lock = crate::core::data_dir::test_env_lock();
737        let tmp = tempfile::tempdir().unwrap();
738        #[cfg(windows)]
739        let file_name = "leanctx-fop-probe.cmd";
740        #[cfg(not(windows))]
741        let file_name = "leanctx-fop-probe";
742        let file = tmp.path().join(file_name);
743        std::fs::write(&file, "x").unwrap();
744        // An npm install puts an extensionless shell shim beside the `.cmd`;
745        // Windows must resolve to the runnable `.cmd`, not the shim.
746        #[cfg(windows)]
747        std::fs::write(tmp.path().join("leanctx-fop-probe"), "#!/bin/sh").unwrap();
748        #[cfg(unix)]
749        {
750            use std::os::unix::fs::PermissionsExt;
751            std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o755)).unwrap();
752        }
753
754        let old = std::env::var_os("PATH");
755        let mut dirs = vec![tmp.path().to_path_buf()];
756        dirs.extend(old.iter().flat_map(std::env::split_paths));
757        // SAFETY: serialized by test_env_lock; restored below.
758        unsafe { std::env::set_var("PATH", std::env::join_paths(dirs).unwrap()) };
759        let found = find_on_path("leanctx-fop-probe");
760        let missing = find_on_path("leanctx-fop-definitely-missing");
761        match old {
762            // SAFETY: still serialized by test_env_lock; restores the saved PATH.
763            Some(v) => unsafe { std::env::set_var("PATH", v) },
764            // SAFETY: still serialized by test_env_lock; PATH was unset before.
765            None => unsafe { std::env::remove_var("PATH") },
766        }
767
768        let found = found.expect("probe on PATH");
769        assert!(
770            found
771                .to_string_lossy()
772                .eq_ignore_ascii_case(&file.to_string_lossy()),
773            "{found:?} vs {file:?}"
774        );
775        assert!(missing.is_none());
776    }
777
778    /// AP04 review I1: project-scoped records compare roots by project, not
779    /// by spelling — a symlinked root, a trailing slash and Windows
780    /// separators name the same project; another directory does not.
781    #[cfg(unix)]
782    #[test]
783    fn same_project_ignores_spelling_but_not_identity() {
784        let tmp = tempfile::tempdir().unwrap();
785        let real = tmp.path().join("repo");
786        let other = tmp.path().join("other");
787        std::fs::create_dir_all(&real).unwrap();
788        std::fs::create_dir_all(&other).unwrap();
789        let link = tmp.path().join("link");
790        std::os::unix::fs::symlink(&real, &link).unwrap();
791        let (real, link, other) = (
792            real.to_string_lossy().to_string(),
793            link.to_string_lossy().to_string(),
794            other.to_string_lossy().to_string(),
795        );
796
797        assert!(same_project(&real, &link));
798        assert!(same_project(&real, &format!("{real}/")));
799        assert!(same_project(r"C:\work\repo", "C:/work/repo/"));
800        assert!(!same_project(&real, &other));
801    }
802
803    #[test]
804    fn lean_ctx_stores_are_never_a_project_root() {
805        let iso = crate::core::data_dir::isolated_data_dir();
806        let project = tempfile::tempdir().unwrap();
807        // The Cockpit's fallback working directory itself.
808        assert!(is_broad_or_unsafe_root(iso.path()));
809        // A fixture project inside a temp data dir stays a project.
810        assert!(!is_broad_or_unsafe_root(&iso.path().join("proj")));
811        assert!(!is_broad_or_unsafe_root(project.path()));
812    }
813
814    #[cfg(unix)]
815    #[test]
816    fn a_store_under_another_spelling_is_still_refused() {
817        let iso = crate::core::data_dir::isolated_data_dir();
818        let links = tempfile::tempdir().unwrap();
819        let alias = links.path().join("data-alias");
820        std::os::unix::fs::symlink(iso.path(), &alias).unwrap();
821        assert!(is_broad_or_unsafe_root(&alias));
822        // A folder that only links into the store is not the store.
823        let inner = iso.path().join("proj");
824        std::fs::create_dir_all(&inner).unwrap();
825        let inner_alias = links.path().join("proj-alias");
826        std::os::unix::fs::symlink(&inner, &inner_alias).unwrap();
827        assert!(!is_broad_or_unsafe_root(&inner_alias));
828    }
829
830    #[test]
831    fn strip_regular_verbatim() {
832        let p = PathBuf::from(r"\\?\C:\Users\dev\project");
833        let result = strip_verbatim(p);
834        assert_eq!(result, PathBuf::from("C:/Users/dev/project"));
835    }
836
837    #[test]
838    fn tcc_sensitive_home_dir_matches_home_and_magic_dirs() {
839        // HOME is read here and again inside the check; tests that set HOME
840        // hold the env lock, so holding it keeps both reads the same.
841        let _env_lock = crate::core::data_dir::test_env_lock();
842        let Some(home) = dirs::home_dir() else {
843            return;
844        };
845        // Home itself and the macOS magic dirs are off-limits (#356).
846        assert!(is_tcc_sensitive_home_dir(&home));
847        assert!(is_tcc_sensitive_home_dir(&home.join("Documents")));
848        assert!(is_tcc_sensitive_home_dir(&home.join("Desktop")));
849        assert!(is_tcc_sensitive_home_dir(&home.join("Downloads")));
850    }
851
852    #[test]
853    fn tcc_sensitive_home_dir_allows_real_projects() {
854        let _env_lock = crate::core::data_dir::test_env_lock();
855        let Some(home) = dirs::home_dir() else {
856            return;
857        };
858        // A real project (even nested under Documents) and non-magic home children
859        // are scannable — only the bare magic dirs / home are blocked.
860        assert!(!is_tcc_sensitive_home_dir(
861            &home.join("Documents").join("my-project")
862        ));
863        assert!(!is_tcc_sensitive_home_dir(&home.join("code")));
864        assert!(!is_tcc_sensitive_home_dir(&home.join("Projects")));
865    }
866
867    #[test]
868    #[cfg(target_os = "macos")]
869    fn under_tcc_protected_dir_matches_nested_paths() {
870        let _env_lock = crate::core::data_dir::test_env_lock();
871        let Some(home) = dirs::home_dir() else {
872            return;
873        };
874        // The magic dirs themselves and anything nested below them (#356).
875        assert!(is_under_tcc_protected_dir(&home.join("Documents")));
876        assert!(is_under_tcc_protected_dir(
877            &home.join("Documents/deep/nested/project")
878        ));
879        assert!(is_under_tcc_protected_dir(&home.join("Desktop/scratch")));
880        assert!(is_under_tcc_protected_dir(&home.join("Downloads/x.zip")));
881        // Home itself, siblings, and non-home paths are fine.
882        assert!(!is_under_tcc_protected_dir(&home));
883        assert!(!is_under_tcc_protected_dir(&home.join("code/project")));
884        assert!(!is_under_tcc_protected_dir(Path::new("/tmp/Documents")));
885    }
886
887    #[test]
888    #[cfg(target_os = "macos")]
889    #[serial_test::serial]
890    fn tcc_standalone_blocks_probes_under_protected_dirs() {
891        // `#[serial]` and `test_env_lock` are two different mutexes; the tests
892        // in this module need both. `LEAN_CTX_TCC_STANDALONE` is read by
893        // `is_tcc_standalone` (line ~376) on every path normalization, so
894        // setting it here reaches any test that resolves a path — most of which
895        // serialize on `test_env_lock`, not on `#[serial]`.
896        let _env_lock = crate::core::data_dir::test_env_lock();
897        let Some(home) = dirs::home_dir() else {
898            return;
899        };
900        let doc_proj = home.join("Documents/some-project");
901
902        crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "1");
903        assert!(process_is_tcc_standalone());
904        assert!(!may_probe_path(&doc_proj));
905        // Non-protected paths stay probeable even for standalone processes.
906        assert!(may_probe_path(Path::new("/tmp/some-project")));
907        // has_project_marker must refuse without touching the filesystem.
908        assert!(!has_project_marker(&doc_proj));
909
910        crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "0");
911        assert!(!process_is_tcc_standalone());
912        assert!(may_probe_path(&doc_proj));
913        crate::test_env::remove_var("LEAN_CTX_TCC_STANDALONE");
914    }
915
916    #[test]
917    #[cfg(target_os = "macos")]
918    #[serial_test::serial]
919    fn tcc_standalone_detected_via_seatbelt_sentinel() {
920        let _env_lock = crate::core::data_dir::test_env_lock();
921        let Some(home) = dirs::home_dir() else {
922            return;
923        };
924        let doc_proj = home.join("Documents/some-project");
925
926        // No explicit override: a process carrying the deny-~/Documents seatbelt
927        // sentinel (inherited from its sandboxed launchd parent) counts as
928        // standalone even when ppid != 1, so its heuristic probes stay
929        // suppressed — this is the proxy→daemon chain the ppid check missed. (#356)
930        crate::test_env::remove_var("LEAN_CTX_TCC_STANDALONE");
931        crate::test_env::set_var(crate::core::tcc_guard_sandbox::SEATBELT_SENTINEL, "1");
932        assert!(process_is_tcc_standalone());
933        assert!(!may_probe_path(&doc_proj));
934        crate::test_env::remove_var(crate::core::tcc_guard_sandbox::SEATBELT_SENTINEL);
935
936        // With neither override nor sentinel a normal test process (ppid != 1)
937        // is not standalone, so the sentinel is what flipped the result above.
938        assert!(!process_is_tcc_standalone());
939    }
940
941    #[test]
942    #[cfg(target_os = "macos")]
943    #[serial_test::serial]
944    fn tcc_standalone_skips_canonicalize_under_protected_dirs() {
945        let _env_lock = crate::core::data_dir::test_env_lock();
946        let Some(home) = dirs::home_dir() else {
947            return;
948        };
949        // A path that does NOT exist under ~/Documents. With the TCC choke-point
950        // guard active, `safe_canonicalize` returns Ok(input) *without* calling
951        // `std::fs::canonicalize` (which would Err on a missing path) — proving
952        // the filesystem is never touched (#356). This is the structural fix:
953        // every heuristic canonicalize funnels through here.
954        let missing = home.join("Documents/lean-ctx-tcc-test-does-not-exist-xyzzy");
955
956        crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "1");
957        let guarded = safe_canonicalize(&missing);
958        assert!(
959            guarded.is_ok(),
960            "standalone safe_canonicalize must short-circuit (no stat) under ~/Documents"
961        );
962        assert_eq!(guarded.unwrap(), missing);
963        assert_eq!(safe_canonicalize_or_self(&missing), missing);
964
965        // Outside the protected dirs the guard never engages, even when standalone.
966        let tmp_missing = Path::new("/tmp/lean-ctx-tcc-test-does-not-exist-xyzzy");
967        assert!(safe_canonicalize(tmp_missing).is_err());
968
969        // Without standalone the guard is inactive: a missing ~/Documents path
970        // Errs from the real `std::fs::canonicalize` as before.
971        crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "0");
972        assert!(safe_canonicalize(&missing).is_err());
973
974        crate::test_env::remove_var("LEAN_CTX_TCC_STANDALONE");
975    }
976
977    #[test]
978    #[cfg(target_os = "macos")]
979    #[serial_test::serial]
980    fn canonicalize_secure_bypasses_tcc_guard_for_pathjail() {
981        let _env_lock = crate::core::data_dir::test_env_lock();
982        // SECURITY counterpart to the test above (#356): PathJail must keep
983        // resolving symlinks even when standalone under ~/Documents, so the jail
984        // can detect escapes. `canonicalize_secure` therefore must NOT honour the
985        // guard — it always touches the filesystem. We prove that by feeding a
986        // missing ~/Documents path while standalone: the guarded path returns
987        // Ok(lexical) (no stat), while the secure path Errs (it did stat).
988        let Some(home) = dirs::home_dir() else {
989            return;
990        };
991        let missing = home.join("Documents/lean-ctx-secure-canon-does-not-exist-xyzzy");
992
993        crate::test_env::set_var("LEAN_CTX_TCC_STANDALONE", "1");
994        // Guarded sink short-circuits (no fs access).
995        assert_eq!(safe_canonicalize(&missing).unwrap(), missing);
996        // Security sink ignores the guard and actually stats -> Err on a missing
997        // path. If this ever returns Ok(lexical), the jail's symlink-escape
998        // detection has silently regressed under ~/Documents.
999        assert!(
1000            canonicalize_secure(&missing).is_err(),
1001            "canonicalize_secure must bypass the TCC guard and touch the filesystem"
1002        );
1003        assert_eq!(canonicalize_secure_or_self(&missing), missing);
1004        crate::test_env::remove_var("LEAN_CTX_TCC_STANDALONE");
1005    }
1006
1007    #[test]
1008    fn strip_unc_verbatim() {
1009        let p = PathBuf::from(r"\\?\UNC\server\share\dir");
1010        let result = strip_verbatim(p);
1011        assert_eq!(result, PathBuf::from("//server/share/dir"));
1012    }
1013
1014    #[test]
1015    fn no_prefix_unchanged() {
1016        let p = PathBuf::from("/home/user/project");
1017        let result = strip_verbatim(p.clone());
1018        assert_eq!(result, p);
1019    }
1020
1021    #[test]
1022    fn windows_drive_unchanged() {
1023        let p = PathBuf::from("C:/Users/dev");
1024        let result = strip_verbatim(p.clone());
1025        assert_eq!(result, p);
1026    }
1027
1028    #[test]
1029    fn strip_str_regular() {
1030        assert_eq!(
1031            strip_verbatim_str(r"\\?\E:\code\lean-ctx"),
1032            Some("E:/code/lean-ctx".to_string())
1033        );
1034    }
1035
1036    #[test]
1037    fn strip_str_unc() {
1038        assert_eq!(
1039            strip_verbatim_str(r"\\?\UNC\myserver\data"),
1040            Some("//myserver/data".to_string())
1041        );
1042    }
1043
1044    #[test]
1045    fn strip_str_forward_slash_variant() {
1046        assert_eq!(
1047            strip_verbatim_str("//?/C:/Users/dev"),
1048            Some("C:/Users/dev".to_string())
1049        );
1050    }
1051
1052    #[test]
1053    fn strip_str_no_prefix() {
1054        assert_eq!(strip_verbatim_str("/home/user"), None);
1055    }
1056
1057    #[test]
1058    fn safe_canonicalize_or_self_nonexistent() {
1059        let p = Path::new("/this/path/should/not/exist/xyzzy");
1060        let result = safe_canonicalize_or_self(p);
1061        assert_eq!(result, p.to_path_buf());
1062    }
1063
1064    // The drive translation itself is platform-independent and testable
1065    // everywhere; only its *application* is gated on Windows hosts (#397).
1066    #[test]
1067    fn msys_drive_prefix_translation() {
1068        assert_eq!(
1069            translate_msys_drive_prefix("/c/Users/ABC").as_deref(),
1070            Some("C:/Users/ABC")
1071        );
1072        assert_eq!(
1073            translate_msys_drive_prefix("/D/Program Files").as_deref(),
1074            Some("D:/Program Files")
1075        );
1076        assert_eq!(translate_msys_drive_prefix("/usr/local/bin"), None);
1077        assert_eq!(translate_msys_drive_prefix("/c"), None);
1078        assert_eq!(translate_msys_drive_prefix("c/Users"), None);
1079    }
1080
1081    #[cfg(windows)]
1082    #[test]
1083    fn normalize_msys_path_to_native() {
1084        assert_eq!(
1085            normalize_tool_path("/c/Users/ABC/AppData/lean-ctx"),
1086            "C:/Users/ABC/AppData/lean-ctx"
1087        );
1088        assert_eq!(
1089            normalize_tool_path("/D/Program Files/lean-ctx.exe"),
1090            "D:/Program Files/lean-ctx.exe"
1091        );
1092    }
1093
1094    // GH #397: on Linux/macOS, /c/… is a literal directory — a Linux project
1095    // rooted there must not be rewritten to a Windows drive path.
1096    #[cfg(not(windows))]
1097    #[test]
1098    fn normalize_single_letter_unix_path_untouched() {
1099        assert_eq!(
1100            normalize_tool_path_lexical("/c/Users/me/proj"),
1101            "/c/Users/me/proj"
1102        );
1103        assert_eq!(
1104            normalize_tool_path_lexical("/x/projects/app/src"),
1105            "/x/projects/app/src"
1106        );
1107    }
1108
1109    #[test]
1110    fn normalize_native_windows_path_unchanged() {
1111        assert_eq!(
1112            normalize_tool_path("C:/Users/ABC/lean-ctx.exe"),
1113            "C:/Users/ABC/lean-ctx.exe"
1114        );
1115    }
1116
1117    #[test]
1118    fn normalize_backslash_windows_path() {
1119        assert_eq!(
1120            normalize_tool_path(r"C:\Users\ABC\lean-ctx.exe"),
1121            "C:/Users/ABC/lean-ctx.exe"
1122        );
1123    }
1124
1125    #[test]
1126    fn normalize_unix_path_unchanged() {
1127        assert_eq!(
1128            normalize_tool_path("/usr/local/bin/lean-ctx"),
1129            "/usr/local/bin/lean-ctx"
1130        );
1131    }
1132
1133    #[cfg(not(windows))]
1134    #[test]
1135    fn normalize_unescapes_shell_quoting_on_unix() {
1136        assert_eq!(
1137            normalize_tool_path_lexical(r"/Users/me/Pfadi\ Scouting/app/main.ts"),
1138            "/Users/me/Pfadi Scouting/app/main.ts",
1139            "an escaped space must not become a separator"
1140        );
1141        assert_eq!(
1142            normalize_tool_path_lexical(r"/srv/\(group\)/a\&b.txt"),
1143            "/srv/(group)/a&b.txt"
1144        );
1145        assert_eq!(
1146            normalize_tool_path_lexical("'/Users/me/My Project/src'"),
1147            "/Users/me/My Project/src"
1148        );
1149        assert_eq!(normalize_tool_path_lexical("\"/tmp/a b\""), "/tmp/a b");
1150        assert_eq!(
1151            normalize_tool_path_lexical("'"),
1152            "'",
1153            "a lone quote is a name"
1154        );
1155    }
1156
1157    #[test]
1158    fn normalize_windows_path_with_spaces_and_backslashes() {
1159        // The exact "paths with spaces" scenario reported on Windows (#324):
1160        // backslashes are converted to forward slashes (so client render layers
1161        // never escape-mangle them) while spaces in directory names survive.
1162        assert_eq!(
1163            normalize_tool_path(r"C:\Users\My Name\My Project\src\main.rs"),
1164            "C:/Users/My Name/My Project/src/main.rs"
1165        );
1166        assert_eq!(
1167            normalize_tool_path(r"C:\Program Files\app\config.toml"),
1168            "C:/Program Files/app/config.toml"
1169        );
1170    }
1171
1172    #[test]
1173    fn normalize_double_slashes() {
1174        assert_eq!(
1175            normalize_tool_path("C:/Users//ABC//lean-ctx"),
1176            "C:/Users/ABC/lean-ctx"
1177        );
1178    }
1179
1180    #[test]
1181    fn normalize_trailing_slash_removed() {
1182        assert_eq!(normalize_tool_path("C:/Users/ABC/"), "C:/Users/ABC");
1183        assert_eq!(
1184            normalize_tool_path_lexical("/tmp/nonexistent-dir-xyzzy/"),
1185            "/tmp/nonexistent-dir-xyzzy"
1186        );
1187    }
1188
1189    #[test]
1190    fn normalize_root_slash_preserved() {
1191        assert_eq!(normalize_tool_path("/"), "/");
1192    }
1193
1194    #[test]
1195    fn normalize_drive_root_preserved() {
1196        assert_eq!(normalize_tool_path("C:/"), "C:/");
1197    }
1198
1199    #[test]
1200    fn normalize_verbatim_with_msys() {
1201        assert_eq!(normalize_tool_path(r"\\?\C:\Users\dev"), "C:/Users/dev");
1202    }
1203
1204    #[test]
1205    fn broad_root_rejects_home() {
1206        let _home = crate::core::data_dir::test_env_lock();
1207        if let Some(home) = dirs::home_dir() {
1208            assert!(is_broad_or_unsafe_root(&home));
1209        }
1210    }
1211
1212    #[test]
1213    fn broad_root_rejects_wsl_windows_user_profile() {
1214        assert!(is_broad_or_unsafe_root(Path::new("/mnt/c/Users/dev")));
1215        assert!(!is_broad_or_unsafe_root(Path::new(
1216            "/mnt/c/Users/dev/projects/my-app"
1217        )));
1218    }
1219
1220    #[test]
1221    fn broad_root_rejects_filesystem_root() {
1222        assert!(is_broad_or_unsafe_root(Path::new("/")));
1223    }
1224
1225    #[test]
1226    fn broad_root_rejects_dot() {
1227        assert!(is_broad_or_unsafe_root(Path::new(".")));
1228    }
1229
1230    #[test]
1231    fn broad_root_rejects_agent_dirs() {
1232        assert!(is_broad_or_unsafe_root(Path::new("/home/user/.claude")));
1233        assert!(is_broad_or_unsafe_root(Path::new("/home/user/.codex")));
1234    }
1235
1236    #[test]
1237    fn broad_root_rejects_copilot_and_friends() {
1238        // #580: the previously-missing agent/IDE dirs must now be rejected so
1239        // they are never adopted as the project root (the Copilot CLI case).
1240        assert!(is_broad_or_unsafe_root(Path::new("/home/user/.copilot")));
1241        assert!(is_broad_or_unsafe_root(Path::new("/home/user/.cursor")));
1242        assert!(is_broad_or_unsafe_root(Path::new("/home/user/.windsurf")));
1243        assert!(is_broad_or_unsafe_root(Path::new("/home/user/.gemini")));
1244        assert!(is_broad_or_unsafe_root(Path::new("/home/user/.lmstudio")));
1245    }
1246
1247    #[test]
1248    fn agent_config_dir_matches_every_known_client() {
1249        for name in AGENT_CONFIG_DIRS {
1250            let leaf = format!("/home/user/{name}");
1251            assert!(is_agent_config_dir(Path::new(&leaf)), "{leaf}");
1252            let nested = format!("/home/user/{name}/mcp");
1253            assert!(is_agent_config_dir(Path::new(&nested)), "{nested}");
1254        }
1255    }
1256
1257    #[test]
1258    fn claude_code_worktree_checkout_is_not_agent_config() {
1259        // Claude Code puts git worktrees at `<repo>/.claude/worktrees/<name>`;
1260        // those are the user's project, not agent config (#1903 regression).
1261        for p in [
1262            "/repo/.claude/worktrees/fix-x",
1263            "/repo/.claude/worktrees/fix-x/rust/src",
1264            r"C:\repo\.claude\worktrees\fix-x",
1265        ] {
1266            assert!(!is_agent_config_dir(Path::new(p)), "{p}");
1267            assert!(!is_broad_or_unsafe_root(Path::new(p)), "{p}");
1268        }
1269        for p in [
1270            "/repo/.claude/worktrees",
1271            "/repo/.claude/worktrees/",
1272            "/repo/.claude/settings",
1273            "/repo/.claude/worktrees/fix-x/.claude",
1274            "/repo/.claude/worktrees/fix-x/.codex/mcp",
1275            "/home/user/.claude/worktreesx/a",
1276        ] {
1277            assert!(is_agent_config_dir(Path::new(p)), "{p}");
1278        }
1279        assert!(!is_agent_config_dir(Path::new("/repo/.claudex/a")));
1280    }
1281
1282    #[test]
1283    fn agent_config_dir_matches_windows_backslash() {
1284        // #580 is a Windows Copilot report — backslash paths must match too.
1285        assert!(is_agent_config_dir(Path::new(r"C:\Users\me\.copilot")));
1286        assert!(is_agent_config_dir(Path::new(r"C:\Users\me\.copilot\mcp")));
1287    }
1288
1289    #[test]
1290    fn agent_config_dir_ignores_real_projects() {
1291        assert!(!is_agent_config_dir(Path::new("/home/user/code/lean-ctx")));
1292        assert!(!is_agent_config_dir(Path::new(r"C:\src\app")));
1293    }
1294
1295    #[test]
1296    fn broad_root_allows_project_subdir() {
1297        let tmp = tempfile::tempdir().unwrap();
1298        let subdir = tmp.path().join("my-project");
1299        std::fs::create_dir_all(&subdir).unwrap();
1300        assert!(!is_broad_or_unsafe_root(&subdir));
1301    }
1302
1303    #[test]
1304    fn broad_root_allows_home_subdirs() {
1305        let _home = crate::core::data_dir::test_env_lock();
1306        if let Some(home) = dirs::home_dir() {
1307            let subdir = home.join("projects").join("my-app");
1308            assert!(!is_broad_or_unsafe_root(&subdir));
1309        }
1310    }
1311
1312    #[test]
1313    fn data_dir_collision_rejects_home() {
1314        let _home = crate::core::data_dir::test_env_lock();
1315        if let Some(home) = dirs::home_dir() {
1316            assert!(is_data_dir_collision(&home));
1317        }
1318    }
1319
1320    #[test]
1321    fn data_dir_collision_allows_normal_project() {
1322        let tmp = tempfile::tempdir().unwrap();
1323        let project = tmp.path().join("my-project");
1324        std::fs::create_dir_all(&project).unwrap();
1325        assert!(!is_data_dir_collision(&project));
1326    }
1327
1328    #[test]
1329    fn has_project_marker_detects_git() {
1330        let tmp = tempfile::tempdir().unwrap();
1331        let root = tmp.path().join("repo");
1332        std::fs::create_dir_all(&root).unwrap();
1333        assert!(!has_project_marker(&root));
1334        std::fs::create_dir(root.join(".git")).unwrap();
1335        assert!(has_project_marker(&root));
1336    }
1337
1338    #[test]
1339    fn has_project_marker_detects_cargo_toml() {
1340        let tmp = tempfile::tempdir().unwrap();
1341        let root = tmp.path().join("rust-project");
1342        std::fs::create_dir_all(&root).unwrap();
1343        std::fs::write(root.join("Cargo.toml"), "[package]").unwrap();
1344        assert!(has_project_marker(&root));
1345    }
1346
1347    #[test]
1348    fn has_project_marker_detects_platformio_project() {
1349        let tmp = tempfile::tempdir().unwrap();
1350        let root = tmp.path().join("firmware");
1351        std::fs::create_dir_all(&root).unwrap();
1352        assert!(!has_project_marker(&root));
1353        std::fs::write(root.join("platformio.ini"), "[env:esp32]").unwrap();
1354        assert!(has_project_marker(&root));
1355    }
1356
1357    #[test]
1358    fn has_project_marker_detects_godot_project() {
1359        let tmp = tempfile::tempdir().unwrap();
1360        let root = tmp.path().join("godot-game");
1361        std::fs::create_dir_all(&root).unwrap();
1362        std::fs::write(root.join("project.godot"), "config_version=5\n").unwrap();
1363        assert!(has_project_marker(&root));
1364    }
1365
1366    #[test]
1367    fn multi_repo_children_needs_two() {
1368        let tmp = tempfile::tempdir().unwrap();
1369        let parent = tmp.path().join("code");
1370        std::fs::create_dir_all(&parent).unwrap();
1371
1372        // 0 repos → false
1373        assert!(!has_multi_repo_children(&parent));
1374
1375        // 1 repo → false
1376        let repo1 = parent.join("repo1");
1377        std::fs::create_dir_all(repo1.join(".git")).unwrap();
1378        assert!(!has_multi_repo_children(&parent));
1379
1380        // 2 repos → true
1381        let repo2 = parent.join("repo2");
1382        std::fs::create_dir_all(repo2.join(".git")).unwrap();
1383        assert!(has_multi_repo_children(&parent));
1384    }
1385
1386    #[test]
1387    fn multi_repo_children_ignores_files() {
1388        let tmp = tempfile::tempdir().unwrap();
1389        let parent = tmp.path().join("mixed");
1390        std::fs::create_dir_all(&parent).unwrap();
1391
1392        // One repo dir + one plain file with .git name (not a dir)
1393        let repo1 = parent.join("repo1");
1394        std::fs::create_dir_all(repo1.join(".git")).unwrap();
1395        std::fs::write(parent.join("not-a-repo"), "file").unwrap();
1396        assert!(!has_multi_repo_children(&parent));
1397
1398        // Add second actual repo
1399        let repo2 = parent.join("repo2");
1400        std::fs::create_dir_all(&repo2).unwrap();
1401        std::fs::write(repo2.join("package.json"), "{}").unwrap();
1402        assert!(has_multi_repo_children(&parent));
1403    }
1404
1405    #[test]
1406    fn multi_repo_children_nonexistent_dir() {
1407        assert!(!has_multi_repo_children(Path::new("/nonexistent/path/xyz")));
1408    }
1409
1410    #[test]
1411    fn regular_file_is_not_symlink_or_reparse() {
1412        let tmp = tempfile::tempdir().unwrap();
1413        let file = tmp.path().join("plain.txt");
1414        std::fs::write(&file, "x").unwrap();
1415        let meta = std::fs::symlink_metadata(&file).unwrap();
1416        assert!(!is_symlink_or_reparse(&meta));
1417    }
1418
1419    #[cfg(unix)]
1420    #[test]
1421    fn unix_symlink_is_detected() {
1422        let tmp = tempfile::tempdir().unwrap();
1423        let target = tmp.path().join("target.txt");
1424        std::fs::write(&target, "x").unwrap();
1425        let link = tmp.path().join("link.txt");
1426        std::os::unix::fs::symlink(&target, &link).unwrap();
1427        let meta = std::fs::symlink_metadata(&link).unwrap();
1428        assert!(is_symlink_or_reparse(&meta));
1429    }
1430
1431    /// Runs in the windows-latest CI lane (GL#442). Symlink creation needs
1432    /// either admin or Developer Mode — skip gracefully when unavailable.
1433    #[cfg(windows)]
1434    #[test]
1435    fn windows_symlink_is_detected() {
1436        let tmp = tempfile::tempdir().unwrap();
1437        let target = tmp.path().join("target.txt");
1438        std::fs::write(&target, "x").unwrap();
1439        let link = tmp.path().join("link.txt");
1440        if std::os::windows::fs::symlink_file(&target, &link).is_err() {
1441            eprintln!("skipping: symlink creation not permitted on this runner");
1442            return;
1443        }
1444        let meta = std::fs::symlink_metadata(&link).unwrap();
1445        assert!(is_symlink_or_reparse(&meta));
1446    }
1447}