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