Skip to main content

lean_ctx/core/
pathjail.rs

1use std::path::{Path, PathBuf};
2
3use crate::core::error::PathJailError;
4
5pub use crate::core::pathjail_write::{rebuild_below, write_below};
6
7/// `allow_paths` / `extra_roots` come from `config.toml`, where no shell ever
8/// runs — users writing `"$HOME/code"` or `"~/code"` got a literal,
9/// never-matching prefix and concluded the whole option was broken (GH #392).
10/// Unset variables are left verbatim (and warned about) so the entry fails
11/// loudly in `lean-ctx doctor` instead of silently matching something else.
12/// `HOME` falls back to the platform home directory when the environment
13/// variable is absent, as is common in native Windows shells.
14pub fn expand_user_path(raw: &str) -> PathBuf {
15    let mut s = raw.to_string();
16
17    if (s == "~" || s.starts_with("~/"))
18        && let Some(home) = dirs::home_dir()
19    {
20        s = format!("{}{}", home.to_string_lossy(), &s[1..]);
21    }
22
23    while let Some(start) = s.find('$') {
24        let rest = &s[start + 1..];
25        let (name, token_len) = if let Some(stripped) = rest.strip_prefix('{') {
26            match stripped.find('}') {
27                Some(end) => (stripped[..end].to_string(), end + 3),
28                None => break,
29            }
30        } else {
31            let end = rest
32                .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
33                .unwrap_or(rest.len());
34            (rest[..end].to_string(), end + 1)
35        };
36        if name.is_empty() {
37            break;
38        }
39        if let Ok(val) = std::env::var(&name) {
40            s.replace_range(start..start + token_len, &val);
41        } else if name == "HOME"
42            && let Some(home) = dirs::home_dir()
43        {
44            let home = home.to_string_lossy();
45            s.replace_range(start..start + token_len, home.as_ref());
46        } else {
47            tracing::warn!(
48                "allow_paths/extra_roots entry '{raw}' references unset variable ${name} — entry will never match"
49            );
50            break;
51        }
52    }
53
54    PathBuf::from(s)
55}
56
57pub fn allow_paths_from_env_and_config() -> Vec<PathBuf> {
58    let mut out = Vec::new();
59    let cfg = crate::core::config::Config::load();
60
61    // The allow-list defines the jail boundary, so it must be canonicalized the
62    // same (security, symlink-resolving) way as the candidate it is compared
63    // against — otherwise a guarded (lexical) root vs a resolved candidate would
64    // break `is_under_prefix`. These entries are data_dir / IDE-config dirs /
65    // user-configured paths, virtually never under ~/Documents.
66    //
67    // This is also lean-ctx's own state dir (sessions, knowledge, …) — always
68    // readable even while foreign editor dirs stay jailed. On a legacy install
69    // the resolver returns `~/.lean-ctx`; on a split install it returns the XDG
70    // data dir. Going through the resolver (not a hardcoded `~/.lean-ctx` join)
71    // is what keeps `home_allow_dirs` free of the legacy-path firewall trip.
72    if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
73        out.push(canonicalize_secure(&data_dir));
74    }
75
76    if let Some(home) = dirs::home_dir() {
77        let ide_dirs_allowed = cfg.allow_ide_config_dirs.unwrap_or(false)
78            || std::env::var("LEAN_CTX_ALLOW_IDE_DIRS").is_ok_and(|v| v == "1");
79        out.extend(home_allow_dirs(&home, ide_dirs_allowed));
80    }
81
82    for p in &cfg.allow_paths {
83        out.push(canonicalize_secure(&expand_user_path(p)));
84    }
85    for p in &cfg.extra_roots {
86        out.push(canonicalize_secure(&expand_user_path(p)));
87    }
88
89    for path in crate::core::runtime_flags::allow_paths() {
90        out.push(canonicalize_secure(&path));
91    }
92    // Env entries are expanded too: MCP host configs pass env blocks verbatim
93    // (no shell), so "$HOME/code" arrives literally there as well.
94    let v = std::env::var("LCTX_ALLOW_PATH")
95        .or_else(|_| std::env::var("LEAN_CTX_ALLOW_PATH"))
96        .unwrap_or_default();
97    if !v.trim().is_empty() {
98        for p in std::env::split_paths(&v) {
99            out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
100        }
101    }
102
103    let extra = std::env::var("LEAN_CTX_EXTRA_ROOTS").unwrap_or_default();
104    if !extra.trim().is_empty() {
105        for p in std::env::split_paths(&extra) {
106            out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
107        }
108    }
109
110    // Read-only roots are *readable* (the whole point is read access to sibling
111    // repos); writes into them are denied separately by `enforce_writable`
112    // (#475). Add them to the read allow-list so reads resolve, exactly like
113    // `extra_roots`, without granting write access.
114    out.extend(canonicalized_roots(
115        &cfg.read_only_roots,
116        "LEAN_CTX_READ_ONLY_ROOTS",
117    ));
118
119    out
120}
121
122/// Canonicalize a set of config-supplied root entries plus an env override
123/// (path-list separated), expanding `~`/`$VAR` first. Shared by the read
124/// allow-list and the read-only-roots collector so both tiers parse roots
125/// identically.
126fn canonicalized_roots(config_entries: &[String], env_var: &str) -> Vec<PathBuf> {
127    let mut out = Vec::new();
128    for p in config_entries {
129        out.push(canonicalize_secure(&expand_user_path(p)));
130    }
131    let v = std::env::var(env_var).unwrap_or_default();
132    if !v.trim().is_empty() {
133        for p in std::env::split_paths(&v) {
134            out.push(canonicalize_secure(&expand_user_path(&p.to_string_lossy())));
135        }
136    }
137    out
138}
139
140/// A read-only root is a sibling subtree the agent may **read** but never
141/// **write** — e.g. a reference repo mounted next to the project. Empty by
142/// default, so [`is_read_only_path`]/[`enforce_writable`] are zero-cost no-ops
143/// for everyone who hasn't opted in (#475).
144pub fn read_only_roots_from_env_and_config() -> Vec<PathBuf> {
145    let cfg = crate::core::config::Config::load();
146    let mut roots = canonicalized_roots(&cfg.read_only_roots, "LEAN_CTX_READ_ONLY_ROOTS");
147    // #899: session-scoped roots auto-detected from language caches. Consulted
148    // by both the read allow-list (jail) and `is_read_only_path` (write-deny),
149    // so a cache root is readable but never writable — exactly like a configured
150    // read-only root, minus the config-file edit.
151    roots.extend(session_read_only_roots());
152    roots
153}
154
155static SESSION_READ_ONLY_ROOTS: std::sync::OnceLock<std::sync::Mutex<Vec<PathBuf>>> =
156    std::sync::OnceLock::new();
157
158fn session_read_only_roots_cell() -> &'static std::sync::Mutex<Vec<PathBuf>> {
159    SESSION_READ_ONLY_ROOTS.get_or_init(|| std::sync::Mutex::new(Vec::new()))
160}
161
162/// The session-scoped read-only roots auto-registered this process (#899).
163pub fn session_read_only_roots() -> Vec<PathBuf> {
164    session_read_only_roots_cell()
165        .lock()
166        .map(|g| g.clone())
167        .unwrap_or_default()
168}
169
170/// Register a session-scoped read-only root (an auto-detected language cache).
171/// Returns `true` when newly added. Idempotent on the canonicalized path.
172///
173/// ponytail: process-global set, not per-session — language caches
174/// (`~/go/pkg/mod`, `~/.cargo/registry`, …) are machine-global read-only dirs,
175/// so sharing read access across sessions grants nothing a session couldn't
176/// already get by reading them; per-session isolation would be plumbing for no
177/// security gain. Upgrade to a session-keyed map only if writable roots ever go
178/// down this path.
179pub fn register_session_read_only_root(root: &Path) -> bool {
180    let canon = canonicalize_secure(root);
181    let mut guard = match session_read_only_roots_cell().lock() {
182        Ok(g) => g,
183        Err(poisoned) => poisoned.into_inner(),
184    };
185    if guard.iter().any(|r| r == &canon) {
186        return false;
187    }
188    guard.push(canon);
189    true
190}
191
192/// A single active relaxation of the path jail. Each one widens or disables what
193/// tools can reach beyond the project root, so it is surfaced loudly (GH security
194/// audit, finding 3): the MCP/HTTP server inherits its process env from the
195/// IDE/launchd, so a globally-set `LEAN_CTX_ALLOW_PATH` / `LEAN_CTX_EXTRA_ROOTS`
196/// / `LEAN_CTX_ALLOW_IDE_DIRS` (or `path_jail = false`) silently loosens the
197/// boundary with no in-band signal otherwise.
198#[derive(Debug, Clone, Copy, PartialEq, Eq)]
199pub struct JailRelaxation {
200    /// The knob that activated it (env var name, config key, or build feature).
201    pub source: &'static str,
202    /// Human-readable effect of the relaxation.
203    pub detail: &'static str,
204}
205
206fn env_is_set(var: &str) -> bool {
207    std::env::var(var).is_ok_and(|v| !v.trim().is_empty())
208}
209
210/// Collect every currently-active path-jail relaxation. An empty result means
211/// the jail is fully in force. This is the single source of truth shared by the
212/// startup warning ([`warn_if_relaxed`]) and `lean-ctx doctor`.
213#[must_use]
214pub fn active_relaxations() -> Vec<JailRelaxation> {
215    let mut out = Vec::new();
216
217    if cfg!(feature = "no-jail") {
218        out.push(JailRelaxation {
219            source: "no-jail (build feature)",
220            detail: "path jail compiled out — every tool path is allowed",
221        });
222    }
223
224    if crate::core::config::Config::load().path_jail == Some(false) {
225        out.push(JailRelaxation {
226            source: "path_jail = false (config.toml)",
227            detail: "path jail disabled — every tool path is allowed",
228        });
229    }
230
231    if crate::core::runtime_flags::allow_path_enabled() {
232        out.push(JailRelaxation {
233            source: "LEAN_CTX_ALLOW_PATH",
234            detail: "widens the read/write allow-list beyond the project root",
235        });
236    }
237
238    if env_is_set("LEAN_CTX_EXTRA_ROOTS") {
239        out.push(JailRelaxation {
240            source: "LEAN_CTX_EXTRA_ROOTS",
241            detail: "adds extra accessible roots beyond the project root",
242        });
243    }
244
245    let ide_env = std::env::var("LEAN_CTX_ALLOW_IDE_DIRS").is_ok_and(|v| v == "1");
246    if ide_env
247        || crate::core::config::Config::load()
248            .allow_ide_config_dirs
249            .unwrap_or(false)
250    {
251        out.push(JailRelaxation {
252            source: if ide_env {
253                "LEAN_CTX_ALLOW_IDE_DIRS=1"
254            } else {
255                "allow_ide_config_dirs = true (config.toml)"
256            },
257            detail: "exposes ~/.cursor, ~/.claude, … (other agents' sessions/credentials) to tools",
258        });
259    }
260
261    // `home` admits writes wherever it admits reads (every project below ~);
262    // the default `projects` keeps writes in the session's project.
263    if super::pathjail_scope::PathJailScope::resolve() == super::pathjail_scope::PathJailScope::Home
264    {
265        out.push(JailRelaxation {
266            source: if std::env::var("LEAN_CTX_PATH_JAIL_SCOPE")
267                .ok()
268                .and_then(|v| super::pathjail_scope::PathJailScope::parse(&v))
269                .is_some()
270            {
271                "LEAN_CTX_PATH_JAIL_SCOPE=home"
272            } else {
273                "path_jail_scope = home (config.toml)"
274            },
275            detail: "reads and writes anywhere below ~ outside protected zones, not only in the active project",
276        });
277    }
278
279    out
280}
281
282/// Emit a loud `tracing::warn!` for every active path-jail relaxation. Called
283/// once at MCP/HTTP server startup so a trusted-but-loosening env/config leaves
284/// an in-band audit signal instead of silently defeating the jail (finding 3).
285pub fn warn_if_relaxed() {
286    for relaxation in active_relaxations() {
287        tracing::warn!(
288            "[SECURITY] path jail relaxed via {}: {} — intended for trusted local use only",
289            relaxation.source,
290            relaxation.detail
291        );
292    }
293}
294
295/// True when `candidate` resolves to a location inside a configured read-only
296/// root. The candidate's nearest existing ancestor is canonicalized (so a
297/// not-yet-existing file inherits the read-only status of the directory it
298/// would be created in — closing the "create a new file in a read-only repo"
299/// hole) and matched against the (symlink-resolved) read-only roots.
300///
301/// A `false` return is only authoritative when the roots list is empty or the
302/// path provably sits outside every root; an unresolvable candidate (no
303/// existing ancestor) is treated as *not* read-only here and is rejected later
304/// by the ordinary write/jail error, never silently written.
305pub fn is_read_only_path(candidate: &Path) -> bool {
306    let roots = read_only_roots_from_env_and_config();
307    if roots.is_empty() {
308        return false;
309    }
310    let base = canonical_target(candidate);
311    roots.iter().any(|r| is_under_prefix(&base, r))
312}
313
314/// The canonicalized nearest-existing-ancestor of `candidate` with the
315/// not-yet-existing remainder re-appended. Resolves symlinks so a symlink
316/// *into* a guarded root cannot launder a write past a prefix check.
317pub(crate) fn canonical_target(candidate: &Path) -> PathBuf {
318    match canonicalize_existing_ancestor(candidate) {
319        Some((mut p, remainder)) => {
320            for part in remainder.iter().rev() {
321                p.push(part);
322            }
323            p
324        }
325        None => canonicalize_or_self(candidate),
326    }
327}
328
329/// Default-deny write guard for the read-only tier (#475): returns an error if
330/// `candidate` is inside a configured read-only root, `Ok(())` otherwise.
331///
332/// This is the single read-only-aware choke point. Every filesystem write that
333/// can target a caller-supplied path routes through it (the atomic writers in
334/// `ctx_edit`/`edit_apply`, the handoff/session export bundle writers, the
335/// in-place memory-compaction writer, and the refactor IDE pre-write gate), so
336/// a "read-only" root cannot be written through any tool. Reads are unaffected.
337pub fn enforce_writable(candidate: &Path) -> Result<(), String> {
338    // This boundary covers caller-selected edit/backup/export destinations.
339    // Engine-owned knowledge persistence uses its own authorized store writer.
340    crate::core::protected_store::enforce_protected_store_path(candidate)?;
341    // Cloud policies and limits are never changed by an agent (Release B).
342    if crate::core::policy::cloud_floor::is_policy_path(&canonical_target(candidate)) {
343        return Err(format!(
344            "LeanCTX policy files are written by the instance only; agents cannot change them: {}",
345            candidate.display()
346        ));
347    }
348    // The session's own rights profile (process-v1 §9) narrows every write,
349    // under a Workspace too: own worktree only, never a locked path.
350    crate::core::session_rights::check_write(candidate)?;
351    // A project adopted from a first path keeps its VCS metadata and
352    // execution hooks closed until the user declares it (activation #3).
353    if let Some(denial) =
354        super::pathjail_autobind::adopted_write_denial(&canonical_target(candidate))
355    {
356        return Err(denial);
357    }
358    // Under a Workspace a write needs a read-write root (#2120).
359    match crate::core::workspace_authority::current() {
360        crate::core::workspace_authority::Authority::Legacy => {}
361        crate::core::workspace_authority::Authority::Unavailable(reason) => {
362            return Err(crate::core::workspace_authority::unavailable_reason(
363                &reason,
364            ));
365        }
366        crate::core::workspace_authority::Authority::Workspace(snapshot) => {
367            let target = canonical_target(candidate);
368            if snapshot.admits_write(&target) {
369                return Ok(());
370            }
371            return Err(format!(
372                "writes are denied outside the read-write roots of Workspace '{}' (rev {}): {}",
373                snapshot.id,
374                snapshot.revision,
375                candidate.display()
376            ));
377        }
378    }
379    if is_read_only_path(candidate) {
380        return Err(format!(
381            "path is inside a read-only root — writes are denied (read_only_roots): {}",
382            candidate.display()
383        ));
384    }
385    match super::pathjail_scope::home_scope_write_denial(&canonical_target(candidate)) {
386        Some(denial) => Err(denial),
387        None => Ok(()),
388    }
389}
390
391/// Foreign editor config dirs for the jail (~/.cursor, ~/.claude, VS Code, …).
392///
393/// These expose other projects' sessions, MCP configs and credentials to any
394/// agent, so they are opt-in only (config `allow_ide_config_dirs = true` or
395/// `LEAN_CTX_ALLOW_IDE_DIRS=1`). lean-ctx's *own* state dir is intentionally NOT
396/// handled here: the caller already adds it via the sanctioned `data_dir`
397/// resolver (the legacy `~/.lean-ctx` is just one resolution of it). Keeping this
398/// a pure foreign-editor list means no legacy `~/.lean-ctx` literal is built in
399/// this module, so the legacy-path firewall (tests/legacy_path_firewall) has
400/// nothing to flag.
401fn home_allow_dirs(home: &Path, ide_dirs_allowed: bool) -> Vec<PathBuf> {
402    let mut out = Vec::new();
403    if ide_dirs_allowed {
404        // Cached per home and config generation (#2195); see `ide_dirs`.
405        let targets = ide_dirs::editor_targets(home);
406        collect_ide_allow_dirs(home, &targets, &mut out);
407    }
408    out
409}
410
411/// Collect the in-home config/detect directories of every supported editor.
412///
413/// Derived from the editor registry (the single source of truth) so it covers
414/// non-dotfile layouts too — VS Code's `Library/Application Support/Code/User`,
415/// Cline/Roo globalStorage, JetBrains — and never drifts as editors are added.
416/// A config file that sits directly in `$HOME` (`~/.claude.json`,
417/// `~/.jb-mcp.json`) resolves its parent to `$HOME`; those entries are skipped
418/// so the jail is never widened to the entire home directory.
419fn collect_ide_allow_dirs(
420    home: &Path,
421    targets: &[crate::core::editor_registry::EditorTarget],
422    out: &mut Vec<PathBuf>,
423) {
424    let mut seen: std::collections::HashSet<PathBuf> = out.iter().cloned().collect();
425    for target in targets {
426        let candidates = [
427            target.config_path.parent().map(Path::to_path_buf),
428            Some(target.detect_path.clone()),
429        ];
430        for cand in candidates.into_iter().flatten() {
431            if cand.as_path() == home || !cand.starts_with(home) || !cand.is_dir() {
432                continue;
433            }
434            let resolved = canonicalize_secure(&cand);
435            if seen.insert(resolved.clone()) {
436                out.push(resolved);
437            }
438        }
439    }
440}
441
442fn is_under_prefix(path: &Path, prefix: &Path) -> bool {
443    path.starts_with(prefix)
444}
445
446/// True for Claude Code / CodeBuddy auto-memory files under
447/// `~/.claude/projects/<slug>/memory/` (and the CodeBuddy twin).
448///
449/// Anchored to the harness home — the current user's `~/.claude` /
450/// `~/.codebuddy`, or `$CLAUDE_CONFIG_DIR` — so a look-alike
451/// `…/.claude/projects/<slug>/memory` elsewhere on disk (a cloned repo, `/tmp`)
452/// is not admitted. `..` components never match.
453///
454/// Auto memory uses the host's native Read/Edit/Write on these paths
455/// (code.claude.com/docs/en/memory). Replace-mode PathJail must not force
456/// agents to shell out or hit MCP `resources/read` with file URIs (GH #1228).
457/// Scoped to the `memory/` subdirectory only — session transcripts and
458/// credentials under `projects/<slug>/` stay jailed.
459pub fn is_harness_auto_memory_path(path: &Path) -> bool {
460    use std::path::Component;
461    harness_project_dirs().iter().any(|projects| {
462        let Ok(rest) = path.strip_prefix(projects) else {
463            return false;
464        };
465        if rest
466            .components()
467            .any(|c| !matches!(c, Component::Normal(_)))
468        {
469            return false;
470        }
471        let mut parts = rest.components();
472        parts.next().is_some()
473            && parts
474                .next()
475                .is_some_and(|c| c.as_os_str().eq_ignore_ascii_case("memory"))
476    })
477}
478
479/// The harness `projects/` directories auto memory lives in, as configured and
480/// canonical (hook payloads carry the spelled path, the jail the canonical one).
481fn harness_project_dirs() -> Vec<PathBuf> {
482    let mut configs = Vec::new();
483    if let Some(home) = dirs::home_dir() {
484        configs.push(home.join(".claude"));
485        configs.push(home.join(".codebuddy"));
486    }
487    if let Some(dir) = std::env::var_os("CLAUDE_CONFIG_DIR").filter(|v| !v.is_empty()) {
488        configs.push(PathBuf::from(dir));
489    }
490    let mut out = Vec::new();
491    for config in configs.into_iter().filter(|c| c.is_absolute()) {
492        let projects = config.join("projects");
493        let canonical = canonicalize_secure(&projects);
494        if canonical != projects {
495            out.push(canonical);
496        }
497        out.push(projects);
498    }
499    out
500}
501
502fn path_allowed_by_jail(base: &Path, root: &Path, allow: &[PathBuf]) -> bool {
503    if is_harness_auto_memory_path(base) {
504        return true;
505    }
506    let allowed = is_under_prefix(base, root)
507        || allow.iter().any(|p| is_under_prefix(base, p))
508        || super::pathjail_scope::home_scope_admits(base);
509    #[cfg(windows)]
510    let allowed = allowed || is_under_prefix_windows(base, root);
511    allowed && super::pathjail_scope::protected_zone_permits(base, root, allow)
512}
513
514/// Heuristic canonicalize — honours the #356 TCC guard. Used by the
515/// jail-disabled bypass and by external callers (session/startup/server roots)
516/// that must not pop a privacy prompt on their own initiative.
517pub fn canonicalize_or_self(path: &Path) -> PathBuf {
518    super::pathutil::safe_canonicalize_bounded(path, 2000)
519}
520
521/// SECURITY canonicalize for the jail boundary itself (roots + candidate +
522/// escape re-check). Deliberately bypasses the #356 TCC guard: the jail must
523/// keep resolving symlinks to detect escapes, and it only ever runs on a path
524/// the client explicitly asked to access, where a one-time prompt is legitimate.
525pub(crate) fn canonicalize_secure(path: &Path) -> PathBuf {
526    super::pathutil::canonicalize_secure_bounded(path, 2000)
527}
528
529fn canonicalize_existing_ancestor(path: &Path) -> Option<(PathBuf, Vec<std::ffi::OsString>)> {
530    let mut cur = path.to_path_buf();
531    let mut remainder: Vec<std::ffi::OsString> = Vec::new();
532    loop {
533        if cur.exists() {
534            return Some((canonicalize_secure(&cur), remainder));
535        }
536        let name = cur.file_name()?.to_os_string();
537        remainder.push(name);
538        if !cur.pop() {
539            return None;
540        }
541    }
542}
543
544pub fn jail_path(candidate: &Path, jail_root: &Path) -> Result<PathBuf, PathJailError> {
545    jail_path_with_roots(candidate, jail_root, &[])
546}
547
548/// Jail `candidate` to the request's Workspace snapshot (#2120). A relative
549/// path resolves against `jail_root` when the Workspace contains it, else
550/// against the primary root. Only the snapshot's roots admit — lean-ctx's own
551/// data and state directories hold every project's indexes, sessions and
552/// archives, and reach them through engine APIs (`ctx_expand`, recall), not
553/// through a model-chosen path. `..` below a missing ancestor is refused, and an
554/// existing target is re-resolved and re-checked.
555fn jail_in_workspace(
556    candidate: &Path,
557    jail_root: &Path,
558    snapshot: &crate::core::workspace_authority::Snapshot,
559) -> Result<PathBuf, PathJailError> {
560    let canonical = |path: &Path| crate::core::pathutil::canonicalize_secure(path).ok();
561    let base_root = canonical(jail_root)
562        .filter(|root| snapshot.admits(root))
563        .unwrap_or_else(|| snapshot.primary.clone());
564    let candidate = if candidate.is_absolute() {
565        candidate.to_path_buf()
566    } else {
567        base_root.join(candidate)
568    };
569    let admitted = |path: &Path| snapshot.admits(path);
570    let outside = |path: &Path| PathJailError::OutsideWorkspace {
571        path: path.to_path_buf(),
572        workspace: snapshot.id.clone(),
573        revision: snapshot.revision,
574        roots: snapshot
575            .granting_roots()
576            .map(|(root, access)| format!("{} ({})", root.display(), access.as_str()))
577            .collect::<Vec<_>>()
578            .join(", "),
579    };
580
581    let mut existing = candidate.clone();
582    let mut remainder: Vec<std::ffi::OsString> = Vec::new();
583    while !existing.exists() {
584        let Some(name) = existing.file_name() else {
585            return Err(PathJailError::NoExistingAncestor { path: candidate });
586        };
587        remainder.push(name.to_os_string());
588        if !existing.pop() {
589            return Err(PathJailError::NoExistingAncestor { path: candidate });
590        }
591    }
592    if remainder
593        .iter()
594        .any(|part| part == std::ffi::OsStr::new("..") || part == std::ffi::OsStr::new("."))
595    {
596        return Err(outside(&candidate));
597    }
598    // Unbounded on purpose: a timed-out canonicalization would leave a lexical
599    // path whose symlinks were never resolved.
600    let base = canonical(&existing).ok_or_else(|| outside(&candidate))?;
601    if !admitted(&base) {
602        return Err(outside(&candidate));
603    }
604
605    #[cfg(windows)]
606    reject_symlink_on_windows(&candidate)?;
607
608    let mut out = base;
609    for part in remainder.iter().rev() {
610        out.push(part);
611    }
612    if out.exists() {
613        let resolved = canonical(&out).ok_or_else(|| outside(&candidate))?;
614        if !admitted(&resolved) {
615            return Err(PathJailError::PostCanonicalizeEscape {
616                path: candidate,
617                resolved,
618            });
619        }
620    }
621    crate::core::protected_store::enforce_protected_store_path(&out)
622        .map_err(|reason| PathJailError::ProtectedContext { reason })?;
623    Ok(out)
624}
625
626/// Known language-cache markers (#899): (path substring, human label, config
627/// example). Single source of truth shared by [`detected_cache_hint`] (the
628/// jail-error suggestion) and [`detect_language_cache_root`] (session
629/// auto-registration), so the two never drift.
630const LANGUAGE_CACHE_PATTERNS: &[(&str, &str, &str)] = &[
631    ("/go/pkg/mod/", "Go module cache", "~/go/pkg/mod"),
632    (
633        "/.cargo/registry/",
634        "Rust crate registry",
635        "~/.cargo/registry",
636    ),
637    (
638        "/site-packages/",
639        "Python site-packages",
640        "<venv>/lib/pythonX.Y/site-packages",
641    ),
642    ("/node_modules/", "Node modules", "<project>/node_modules"),
643    (
644        "/.m2/repository/",
645        "Maven local repository",
646        "~/.m2/repository",
647    ),
648    ("/.gradle/caches/", "Gradle cache", "~/.gradle/caches"),
649    (
650        "/.nuget/packages/",
651        "NuGet package cache",
652        "~/.nuget/packages",
653    ),
654    // Dependency source agents look up as often as the registry: the Rust
655    // standard library and git dependencies, and the Bun, Dart and Ruby
656    // package stores. Package source only — no credentials live here.
657    (
658        "/.rustup/toolchains/",
659        "Rust toolchain source",
660        "~/.rustup/toolchains",
661    ),
662    (
663        "/.cargo/git/checkouts/",
664        "Cargo git dependencies",
665        "~/.cargo/git/checkouts",
666    ),
667    (
668        "/.bun/install/cache/",
669        "Bun package cache",
670        "~/.bun/install/cache",
671    ),
672    (
673        "/.pub-cache/hosted/",
674        "Dart pub cache",
675        "~/.pub-cache/hosted",
676    ),
677    ("/.gem/ruby/", "Ruby gems", "~/.gem/ruby"),
678    // Interpreter installs whose stdlib agents look up like site-packages
679    // (which is already admitted inside them). Source and binaries only.
680    (
681        "/.pyenv/versions/",
682        "pyenv Python installations",
683        "~/.pyenv/versions",
684    ),
685    // Embedded frameworks, toolchains and libraries PlatformIO installs for
686    // every project; agents read their headers and sources like a registry.
687    (
688        "/.platformio/packages/",
689        "PlatformIO packages",
690        "~/.platformio/packages",
691    ),
692];
693
694/// Agent-owned instruction locations below `~` that the agents themselves are
695/// told to read: skills, slash commands, sub-agent definitions, rules, plans
696/// and the global instruction files. They live inside protected dot folders,
697/// so every such read failed although nothing in them is a credential (auth
698/// tokens sit next to them — `~/.codex/auth.json`, `~/.claude/.credentials.json`
699/// — and stay jailed because only these exact subtrees are opened). Opened
700/// read-only, like a language cache; writes stay denied. (Per-project auto
701/// memory is admitted separately by [`is_harness_auto_memory_path`].)
702///
703/// The agents' own settings and MCP configs are opened the same way, file by
704/// file: agents read them to debug their setup, and "protected location" was
705/// still the refusal seen on the most installations in 3.11.4. A token in them
706/// is masked by the context gateway like in any other read. `~/.claude.json`
707/// (may hold an API key), credential files, sessions and transcripts stay
708/// jailed.
709const AGENT_INSTRUCTION_ROOTS: &[(&str, &str)] = &[
710    (".claude/skills", "Claude Code skills"),
711    (".claude/commands", "Claude Code commands"),
712    (".claude/agents", "Claude Code agents"),
713    (".claude/plans", "Claude Code plans"),
714    (".claude/rules", "Claude Code rules"),
715    (".claude/plugins/marketplaces", "Claude Code plugins"),
716    (".claude/plugins/cache", "Claude Code plugins"),
717    (".claude/CLAUDE.md", "Claude Code instructions"),
718    (".claude/settings.json", "Claude Code settings"),
719    (".claude/settings.local.json", "Claude Code settings"),
720    (".claude/keybindings.json", "Claude Code settings"),
721    (".codex/skills", "Codex skills"),
722    (".codex/prompts", "Codex prompts"),
723    (".codex/AGENTS.md", "Codex instructions"),
724    (".codex/config.toml", "Codex config"),
725    (".codex/hooks.json", "Codex config"),
726    (".agents/skills", "agent skills"),
727    (".cursor/rules", "Cursor rules"),
728    (".cursor/skills", "Cursor skills"),
729    (".cursor/commands", "Cursor commands"),
730    (".cursor/mcp.json", "Cursor config"),
731    (".cursor/hooks.json", "Cursor config"),
732    (".gemini/GEMINI.md", "Gemini instructions"),
733    (".gemini/commands", "Gemini commands"),
734    (".gemini/settings.json", "Gemini config"),
735    (".codebuddy/settings.json", "CodeBuddy settings"),
736    (".config/opencode/agent", "OpenCode agents"),
737    (".config/opencode/command", "OpenCode commands"),
738    (".config/opencode/AGENTS.md", "OpenCode instructions"),
739    (".config/opencode/opencode.json", "OpenCode config"),
740    (".config/opencode/opencode.jsonc", "OpenCode config"),
741    (".codeium/windsurf/mcp_config.json", "Windsurf config"),
742];
743
744/// Folders below `~/.cursor/projects/<workspace>/` where Cursor's agent writes
745/// long tool output and terminal logs, then greps and reads them back. With
746/// lean-ctx in place those reads go through the jail, which refused every one
747/// as a protected location — Cursor sessions hit that refusal on `ctx_search`
748/// about three times as often per installation as other clients in 3.11.4.
749/// Opened read-only, and only for the session's own workspace
750/// ([`cursor_workspace_matches`]); other projects' logs, the workspace's
751/// `mcp-auth.json`, transcripts and the rest of `~/.cursor` stay jailed.
752const CURSOR_AGENT_OUTPUT_DIRS: &[&str] = &["agent-tools", "terminals"];
753const CURSOR_AGENT_OUTPUT_LABEL: &str = "Cursor agent output";
754
755/// Cursor names a workspace's folder after the path it opened: every
756/// character other than an ASCII letter or digit becomes `-`, leading ones
757/// dropped (`/Users/me/my_app` → `Users-me-my-app`).
758fn cursor_workspace_slug(root: &Path) -> String {
759    let slug: String = root
760        .to_string_lossy()
761        .chars()
762        .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
763        .collect();
764    slug.trim_start_matches('-').to_string()
765}
766
767/// `…/.cursor/projects/<workspace>/<dir>` with `<dir>` in
768/// [`CURSOR_AGENT_OUTPUT_DIRS`]; path components only, no filesystem access
769/// (runs for every registered root on every jail call).
770fn is_cursor_agent_output_root(path: &Path) -> bool {
771    let mut back = path.components().rev().map(std::path::Component::as_os_str);
772    let (Some(dir), Some(_workspace), Some(projects), Some(cursor)) =
773        (back.next(), back.next(), back.next(), back.next())
774    else {
775        return false;
776    };
777    cursor == ".cursor"
778        && projects == "projects"
779        && CURSOR_AGENT_OUTPUT_DIRS.iter().any(|d| dir == *d)
780}
781
782/// True when the Cursor output folder `admitted_root`
783/// (`~/.cursor/projects/<workspace>/<dir>`) belongs to the session's project
784/// or one of its declared roots, raw or canonical (`/var` vs `/private/var`).
785/// Exact match only: a prefix would let `lean-ctx` read `lean-ctx-enterprise`.
786/// Numbered and `empty-window` workspaces belong to no project and stay jailed.
787fn cursor_workspace_matches(
788    admitted_root: &Path,
789    jail_root: &Path,
790    extra_roots: &[String],
791) -> bool {
792    let Some(workspace) = admitted_root.parent().and_then(Path::file_name) else {
793        return false;
794    };
795    std::iter::once(jail_root.to_path_buf())
796        .chain(extra_roots.iter().map(PathBuf::from))
797        .flat_map(|root| [canonicalize_secure(&root), root])
798        .any(|root| workspace == cursor_workspace_slug(&root).as_str())
799}
800
801/// `rel` (relative to `~`, only normal components) inside one of
802/// [`CURSOR_AGENT_OUTPUT_DIRS`] → that folder, relative to `~`.
803fn cursor_agent_output_root(rel: &Path) -> Option<PathBuf> {
804    let mut parts = rel.components().map(std::path::Component::as_os_str);
805    if parts.next()? != ".cursor" || parts.next()? != "projects" {
806        return None;
807    }
808    let workspace = parts.next()?;
809    let dir = parts.next()?;
810    CURSOR_AGENT_OUTPUT_DIRS
811        .iter()
812        .any(|d| dir == *d)
813        .then(|| Path::new(".cursor/projects").join(workspace).join(dir))
814}
815
816/// If `candidate` lies in one of [`AGENT_INSTRUCTION_ROOTS`] or
817/// [`CURSOR_AGENT_OUTPUT_DIRS`] below the home directory, return
818/// `(label, root)`. Anchored at `~` so a same-named folder elsewhere on disk
819/// is not opened.
820fn detect_agent_instruction_root(candidate: &Path) -> Option<(&'static str, PathBuf)> {
821    let home = dirs::home_dir()?;
822    let canon_home = canonicalize_secure(&home);
823    let rel = candidate
824        .strip_prefix(&home)
825        .or_else(|_| candidate.strip_prefix(&canon_home))
826        .ok()?;
827    // A `..` would let `~/.claude/skills/../.credentials.json` match by prefix.
828    if rel
829        .components()
830        .any(|c| !matches!(c, std::path::Component::Normal(_)))
831    {
832        return None;
833    }
834    AGENT_INSTRUCTION_ROOTS
835        .iter()
836        .find(|(root, _)| rel.starts_with(root))
837        .map(|&(root, label)| (label, canon_home.join(root)))
838        .or_else(|| detect_host_session_output_root(rel, &canon_home))
839        .or_else(|| {
840            cursor_agent_output_root(rel)
841                .map(|root| canon_home.join(root))
842                // The agent can write here, so a symlinked folder (or workspace)
843                // would open its target — `agent-tools -> ~/.ssh`. Admit only a
844                // root that resolves to itself.
845                .filter(|root| canonicalize_secure(root) == *root)
846                .map(|root| (CURSOR_AGENT_OUTPUT_LABEL, root))
847        })
848}
849
850/// Output the host wrote for the agent's *own* session and then pointed the
851/// agent at: Claude Code persists large tool results under
852/// `~/.claude/projects/<slug>/<session>/tool-results` (and subagent logs next
853/// to it). Cursor's `agent-tools`/`terminals` take the stricter path of
854/// [`cursor_agent_output_root`] (own workspace only, no symlinked folder).
855/// They sit in protected dot folders, so every follow-up read was refused —
856/// ~1'900 refusals in 30 days on 3.11.3+ (focus analysis 2026-10-15). Only
857/// these exact per-session subtrees open, read-only; credentials beside them
858/// (`~/.claude/.credentials.json`, `~/.cursor/projects/<id>/mcp-auth.json`)
859/// and other conversations' transcripts stay jailed. `rel` is relative to
860/// `~` and contains normal components only.
861fn detect_host_session_output_root(
862    rel: &Path,
863    canon_home: &Path,
864) -> Option<(&'static str, PathBuf)> {
865    let parts: Vec<&str> = rel
866        .components()
867        .map(|c| c.as_os_str().to_str())
868        .collect::<Option<_>>()?;
869    let (depth, label) = match parts.as_slice() {
870        [
871            ".claude",
872            "projects",
873            _,
874            _,
875            "tool-results" | "subagents",
876            ..,
877        ] => (5, "Claude Code session output"),
878        _ => return None,
879    };
880    Some((
881        label,
882        canon_home.join(parts[..depth].iter().collect::<PathBuf>()),
883    ))
884}
885
886/// The host's own per-user scratch directory outside `~`: Claude Code keeps
887/// the session scratchpad below `<tmp>/claude-<uid>/` and tells the agent to
888/// put intermediate files there. Admitted read-only only when that directory
889/// belongs to this user and nobody else can write into it, so another local
890/// account cannot pre-create it in the shared `/tmp`.
891#[cfg(unix)]
892fn detect_host_scratch_root(candidate: &Path) -> Option<(&'static str, PathBuf)> {
893    use std::os::unix::fs::MetadataExt;
894    // SAFETY: geteuid has no arguments or failure state.
895    let uid = unsafe { libc::geteuid() };
896    let name = format!("claude-{uid}");
897    // Canonical through the nearest existing ancestor (`/var` vs
898    // `/private/var` on macOS); a `..` in the missing tail yields `None`.
899    let (base, rest) = canonicalize_existing_ancestor(candidate)?;
900    let candidate = rest.iter().rev().fold(base, |path, part| path.join(part));
901    [std::env::temp_dir(), PathBuf::from("/tmp")]
902        .into_iter()
903        .map(|tmp| tmp.join(&name))
904        .find_map(|dir| {
905            let meta = std::fs::symlink_metadata(&dir).ok()?;
906            let root = canonicalize_secure(&dir);
907            (meta.is_dir()
908                && meta.uid() == uid
909                && meta.mode() & 0o022 == 0
910                && candidate.starts_with(&root))
911            .then_some(("Claude Code scratchpad", root))
912        })
913}
914
915#[cfg(not(unix))]
916fn detect_host_scratch_root(_candidate: &Path) -> Option<(&'static str, PathBuf)> {
917    None
918}
919
920/// When `candidate` reaches its target through a symlink inside an agent
921/// instruction `root` (a skill directory linked in from a checkout or from
922/// `~/.agents/skills`), register the target's directory read-only too.
923///
924/// Only agent instruction roots qualify: lean-ctx's tools cannot write there
925/// (protected zone, read-only root), so a link inside was put there by the
926/// user. A language cache such as `node_modules` sits in a writable project,
927/// where an agent could plant a link to anything — those are never followed.
928/// Targets must stay below `~` and outside protected zones, so a link cannot
929/// smuggle `~/.ssh` or a system directory in. Cursor's agent output folders
930/// are excluded: the agent writes them itself. Returns `true` when a target
931/// directory was newly registered.
932pub fn register_symlink_target_read_only(candidate: &Path, root: &Path) -> bool {
933    if detect_agent_instruction_root(root)
934        .is_none_or(|(label, _)| label == CURSOR_AGENT_OUTPUT_LABEL)
935        || (!candidate.starts_with(root) && !candidate.starts_with(canonicalize_secure(root)))
936    {
937        return false;
938    }
939    let Ok(target) = std::fs::canonicalize(candidate) else {
940        return false;
941    };
942    let root = canonicalize_secure(root);
943    if target.starts_with(&root) {
944        return false;
945    }
946    // Skill managers link `~/.claude/skills/x` to `~/.agents/skills/x`: a
947    // target in another agent instruction root opens that root, not more.
948    if let Some((_, agent_root)) = detect_agent_instruction_root(&target) {
949        return register_session_read_only_root(&agent_root);
950    }
951    let dir = if target.is_dir() {
952        target
953    } else {
954        match target.parent() {
955            Some(parent) => parent.to_path_buf(),
956            None => return false,
957        }
958    };
959    let below_home =
960        dirs::home_dir().is_some_and(|home| dir.starts_with(canonicalize_secure(&home)));
961    if !below_home
962        || crate::core::pathutil::is_broad_or_unsafe_root(&dir)
963        || super::pathjail_scope::in_protected_zone(&dir)
964    {
965        return false;
966    }
967    register_session_read_only_root(&dir)
968}
969
970/// [`jail_path_with_roots`] plus the read-only auto-admission of #899: a path
971/// the jail refuses inside a language cache or an agent instruction folder
972/// registers that root read-only for the session and resolves again, so the
973/// call is served instead of failing with "retry". A symlinked skill whose
974/// target is still refused gets its target opened read-only
975/// ([`register_symlink_target_read_only`]). Writes stay denied either way.
976/// One implementation for the MCP server and the one-shot CLI.
977pub fn jail_path_auto_admitting(
978    candidate: &Path,
979    jail_root: &Path,
980    extra_roots: &[String],
981) -> Result<PathBuf, PathJailError> {
982    let first = jail_path_with_roots(candidate, jail_root, extra_roots);
983    let Err(refused) = first else {
984        return first;
985    };
986    // Under a Workspace nothing is admitted on the fly (#2120): a cache or
987    // instruction folder is reachable only as an attached root.
988    if crate::core::workspace_authority::is_configured() {
989        return Err(refused);
990    }
991    let Some((label, root)) = detect_language_cache_root(candidate) else {
992        return Err(refused);
993    };
994    // One output folder per Cursor workspace: another project's terminal logs
995    // stay jailed.
996    if label == CURSOR_AGENT_OUTPUT_LABEL
997        && !cursor_workspace_matches(&root, jail_root, extra_roots)
998    {
999        return Err(refused);
1000    }
1001    if register_session_read_only_root(&root) {
1002        tracing::info!(
1003            "auto-registered {label} at {} as a read-only root",
1004            root.display()
1005        );
1006    }
1007    let retry = jail_path_with_roots(candidate, jail_root, extra_roots);
1008    // Only when the jail still refuses the target is it opened — never when it
1009    // is already readable, which would make it read-only for a project the
1010    // agent may be editing.
1011    if retry.is_err() && register_symlink_target_read_only(candidate, &root) {
1012        return jail_path_with_roots(candidate, jail_root, extra_roots);
1013    }
1014    retry
1015}
1016
1017/// Detect well-known language cache paths and return a targeted hint. Used for
1018/// jail callers that don't auto-register (e.g. batch reads); the single-path
1019/// ctx_read flow instead auto-registers via [`detect_language_cache_root`].
1020fn detected_cache_hint(candidate: &std::path::Path) -> Option<String> {
1021    let s = candidate.to_string_lossy();
1022    for &(pattern, name, example) in LANGUAGE_CACHE_PATTERNS {
1023        if s.contains(pattern) {
1024            return Some(format!(
1025                ". Detected {name} — add read_only_roots = [\"{example}\"] to \
1026                 ~/.config/lean-ctx/config.toml for cached, compressed reads without write access"
1027            ));
1028        }
1029    }
1030    None
1031}
1032
1033/// If `candidate` sits inside a known language cache, return `(label, root)`
1034/// where `root` is the path truncated at the end of the marker directory (no
1035/// trailing slash). resolve_path uses this to auto-register a session read-only
1036/// root so the retry resolves without a config edit or a subprocess (#899).
1037pub fn detect_language_cache_root(candidate: &Path) -> Option<(&'static str, PathBuf)> {
1038    if let Some(found) = detect_agent_instruction_root(candidate) {
1039        return Some(found);
1040    }
1041    if let Some(found) = detect_host_scratch_root(candidate) {
1042        return Some(found);
1043    }
1044    let s = candidate.to_string_lossy().replace('\\', "/");
1045    for &(marker, label, _) in LANGUAGE_CACHE_PATTERNS {
1046        if let Some(idx) = s.find(marker) {
1047            let end = idx + marker.len() - 1; // keep the marker dir, drop trailing '/'
1048            return Some((label, PathBuf::from(&s[..end])));
1049        }
1050    }
1051    None
1052}
1053
1054/// Like [`jail_path`], but also accepts paths under any of `extra_roots`.
1055///
1056/// `extra_roots` are session-scoped trusted roots (MCP `roots/list` and config
1057/// `extra_roots`, surfaced via `session.extra_roots`) — e.g. sibling git
1058/// worktrees the agent legitimately spans. They widen the allow-list for *this
1059/// call only*, so an explicit `path` under a worktree resolves instead of
1060/// failing with "path escapes project root", without loosening the global jail
1061/// (#403). `path_jail = false` still bypasses entirely and an empty slice is
1062/// byte-for-byte identical to the old single-root behaviour.
1063pub fn jail_path_with_roots(
1064    candidate: &Path,
1065    jail_root: &Path,
1066    extra_roots: &[String],
1067) -> Result<PathBuf, PathJailError> {
1068    jail_path_checked(candidate, jail_root, extra_roots, true)
1069}
1070
1071/// [`jail_path`] with the off-switches ignored: the root + allow-list check
1072/// runs even in a `no-jail` build and under `path_jail = false`.
1073///
1074/// For destinations whose containment is a property of the operation rather
1075/// than of the general tool jail — an unredacted canonical session export is
1076/// bound to its session's project root (plus the configured allow-list), and a
1077/// build or config that opens tool paths must not also open where that export
1078/// may land. With the jail in force this is identical to [`jail_path`].
1079pub fn jail_path_enforced(candidate: &Path, jail_root: &Path) -> Result<PathBuf, PathJailError> {
1080    jail_path_checked(candidate, jail_root, &[], false)
1081}
1082
1083fn jail_path_checked(
1084    candidate: &Path,
1085    jail_root: &Path,
1086    extra_roots: &[String],
1087    honor_off_switch: bool,
1088) -> Result<PathBuf, PathJailError> {
1089    if candidate.to_string_lossy().as_bytes().contains(&0) {
1090        return Err(PathJailError::NullByte);
1091    }
1092
1093    // Runtime context is reached through authorized knowledge/recovery APIs,
1094    // never by widening a model-directed file read to the Engine's own store.
1095    // Apply this before no-jail/config/implicit runtime allow-list shortcuts.
1096    let absolute = if candidate.is_absolute() {
1097        candidate.to_path_buf()
1098    } else {
1099        jail_root.join(candidate)
1100    };
1101    crate::core::protected_store::enforce_protected_store_path(&absolute)
1102        .map_err(|reason| PathJailError::ProtectedContext { reason })?;
1103
1104    // A launcher-bound Workspace is the only authority (#2120): it is checked
1105    // before the off-switches, the configured widening and the home scope,
1106    // none of which apply while it is bound.
1107    match crate::core::workspace_authority::current() {
1108        crate::core::workspace_authority::Authority::Legacy => {}
1109        crate::core::workspace_authority::Authority::Unavailable(reason) => {
1110            return Err(PathJailError::WorkspaceUnavailable {
1111                reason: crate::core::workspace_authority::unavailable_reason(&reason),
1112            });
1113        }
1114        crate::core::workspace_authority::Authority::Workspace(snapshot) => {
1115            return jail_in_workspace(candidate, jail_root, &snapshot);
1116        }
1117    }
1118
1119    // With the jail off a relative path still means "in the project": the
1120    // process CWD (the daemon's) is not the project, so resolve it against
1121    // the root here as well.
1122    #[cfg(feature = "no-jail")]
1123    {
1124        if honor_off_switch {
1125            return Ok(canonicalize_or_self(&absolute));
1126        }
1127    }
1128
1129    {
1130        let cfg = crate::core::config::Config::load();
1131        if honor_off_switch && cfg.path_jail == Some(false) {
1132            return Ok(canonicalize_or_self(&absolute));
1133        }
1134
1135        let root = canonicalize_secure(jail_root);
1136
1137        // Resolve relative candidates against the (absolute) jail root — never the process
1138        // CWD. The daemon's CWD is not the project, so CWD-relative resolution made
1139        // graph-relative paths (e.g. auto-preload candidates like `rust/src/core/foo.rs`)
1140        // spuriously fail with "no existing ancestor". Absolute candidates are unchanged.
1141        let resolved: PathBuf;
1142        let candidate: &Path = if candidate.is_absolute() {
1143            candidate
1144        } else {
1145            resolved = root.join(candidate);
1146            resolved.as_path()
1147        };
1148
1149        let mut allow = allow_paths_from_env_and_config();
1150        // Session-scoped roots widen the allow-list for this call only.
1151        allow.extend(
1152            extra_roots
1153                .iter()
1154                .filter(|r| !r.is_empty())
1155                .map(|r| canonicalize_secure(Path::new(r))),
1156        );
1157
1158        // #820: lean-ctx's own state dir (tee files, artifacts, tool-results)
1159        // must be readable even when outside the project root. ctx_shell
1160        // tells agents to read tee-file paths, so the jail must allow them.
1161        if let Ok(state) = crate::core::paths::state_dir() {
1162            allow.push(canonicalize_secure(&state));
1163        }
1164        // Read-only roots are also allowed for reads (they only block writes
1165        // via enforce_writable, not reads via the jail). The registry is
1166        // process-global; a Cursor output folder is per workspace, so one
1167        // registered by another project's session stays jailed here.
1168        allow.extend(
1169            read_only_roots_from_env_and_config()
1170                .into_iter()
1171                .map(|p| canonicalize_secure(&p))
1172                .filter(|p| {
1173                    !is_cursor_agent_output_root(p)
1174                        || cursor_workspace_matches(p, jail_root, extra_roots)
1175                }),
1176        );
1177
1178        let (base, remainder) = canonicalize_existing_ancestor(candidate).ok_or_else(|| {
1179            PathJailError::NoExistingAncestor {
1180                path: candidate.to_path_buf(),
1181            }
1182        })?;
1183
1184        let allowed = path_allowed_by_jail(&base, &root, &allow);
1185
1186        if !allowed {
1187            let is_suspicious = crate::core::pathutil::is_suspicious_root(&root);
1188            let mut hint = if is_suspicious || root == std::path::Path::new("/") {
1189                format!(
1190                    ". {}. lean-ctx has not bound this session to a project yet (the host \
1191                     reported no project directory). Relative paths cannot bind it: one \
1192                     absolute path inside the project, e.g. /home/me/code/my-app/README.md, \
1193                     binds it and it stays the session project; if it persists, the user \
1194                     runs: lean-ctx doctor --fix",
1195                    super::pathjail_scope::AGENT_BIND_ACTION
1196                )
1197            } else {
1198                super::pathjail_scope::escape_hint(candidate, &base, &root)
1199            };
1200            // An untrusted workspace's project-local `allow_paths` is silently
1201            // withheld; always surface that reason (the stderr warning is
1202            // invisible over MCP, and the hint above is meta-gated off) (#540).
1203            if let Some(notice) = crate::core::workspace_trust::untrusted_override_notice() {
1204                hint.push_str(". ");
1205                hint.push_str(&notice);
1206            }
1207            // The global config the runtime reads doesn't exist → on defaults, so
1208            // an `allow_paths` edit made to a config.toml elsewhere (XDG vs legacy
1209            // dir, or a sandboxed/container HOME) is never seen (#540).
1210            if let Some(missing) = crate::core::config::Config::missing_config_path() {
1211                hint.push_str(&format!(
1212                    ". ⚠ lean-ctx reads no config file at {} (running on defaults) — an \
1213                     allow_paths edit in a config.toml elsewhere is not read; \
1214                     `lean-ctx doctor` shows the path in effect",
1215                    missing.display()
1216                ));
1217            }
1218            if let Some(cache_hint) = detected_cache_hint(candidate) {
1219                hint.push_str(&cache_hint);
1220            }
1221            return Err(PathJailError::EscapesRoot {
1222                path: candidate.to_path_buf(),
1223                root,
1224                hint,
1225            });
1226        }
1227
1228        #[cfg(windows)]
1229        reject_symlink_on_windows(candidate)?;
1230
1231        let mut out = base;
1232        for part in remainder.iter().rev() {
1233            out.push(part);
1234        }
1235
1236        // Re-validate after reconstruction: if the final path exists, canonicalize
1237        // and re-check to close TOCTOU window (symlink created between check and use).
1238        if out.exists() {
1239            let final_canon = canonicalize_secure(&out);
1240            let final_ok = path_allowed_by_jail(&final_canon, &root, &allow);
1241            if !final_ok {
1242                return Err(PathJailError::PostCanonicalizeEscape {
1243                    path: candidate.to_path_buf(),
1244                    resolved: final_canon,
1245                });
1246            }
1247        }
1248
1249        crate::core::protected_store::enforce_protected_store_path(&out)
1250            .map_err(|reason| PathJailError::ProtectedContext { reason })?;
1251        Ok(out)
1252    }
1253}
1254
1255#[cfg(all(test, target_os = "macos"))]
1256mod protected_store_tests {
1257    use super::*;
1258
1259    #[test]
1260    fn runtime_store_is_not_reopened_by_implicit_or_explicit_roots() {
1261        let isolated = crate::core::data_dir::isolated_data_dir();
1262        let project = tempfile::tempdir().unwrap();
1263        let store = isolated.path().join("knowledge");
1264        std::fs::create_dir_all(&store).unwrap();
1265        let fact = store.join("facts.json");
1266        std::fs::write(&fact, "private stored context").unwrap();
1267        let code = project.path().join("main.rs");
1268        std::fs::write(&code, "fn main() {}\n").unwrap();
1269        assert!(
1270            jail_path(&fact, project.path()).is_ok(),
1271            "Community keeps its existing runtime access"
1272        );
1273        let _protected =
1274            crate::core::protected_store::pin_synthetic_session(isolated.path()).unwrap();
1275        let roots = vec![isolated.path().to_string_lossy().into_owned()];
1276        for candidate in [&fact, &store, &isolated.path().to_path_buf()] {
1277            assert!(
1278                matches!(
1279                    jail_path_with_roots(candidate, project.path(), &roots),
1280                    Err(PathJailError::ProtectedContext { .. })
1281                ),
1282                "{candidate:?}"
1283            );
1284        }
1285        assert!(jail_path(&code, project.path()).is_ok());
1286        assert!(jail_path_with_roots(Path::new("facts.json"), &store, &roots).is_err());
1287        // Raw backup paths enter the shared atomic writer without the dispatch
1288        // resolver; its write guard must refuse a hidden record or a sibling.
1289        // (The writer itself is exercised end to end in `tools::edit_io`.)
1290        for target in [&fact, &store.join("new/backup.json")] {
1291            assert!(enforce_writable(target).is_err(), "{target:?}");
1292        }
1293        assert_eq!(
1294            std::fs::read_to_string(&fact).unwrap(),
1295            "private stored context"
1296        );
1297        assert!(!store.join("new").exists());
1298        enforce_writable(&code).unwrap();
1299        // Internal storage is unaffected by the model-directed path resolver.
1300        std::fs::write(&fact, "retained internal update").unwrap();
1301        assert_eq!(
1302            std::fs::read_to_string(&fact).unwrap(),
1303            "retained internal update"
1304        );
1305    }
1306
1307    #[test]
1308    fn missing_child_profile_never_falls_back_to_the_normal_jail() {
1309        let isolated = crate::core::data_dir::isolated_data_dir();
1310        let project = tempfile::tempdir().unwrap();
1311        let code = project.path().join("main.rs");
1312        std::fs::write(&code, "fn main() {}\n").unwrap();
1313        let _protected =
1314            crate::core::protected_store::pin_synthetic_session(isolated.path()).unwrap();
1315        crate::test_env::remove_var(crate::core::protected_store::CHILD_PROFILE_ENV);
1316        assert!(matches!(
1317            jail_path(&code, project.path()),
1318            Err(PathJailError::ProtectedContext { .. })
1319        ));
1320    }
1321}
1322
1323#[cfg(windows)]
1324fn is_under_prefix_windows(path: &Path, prefix: &Path) -> bool {
1325    let path_str = normalize_windows_path(&path.to_string_lossy());
1326    let prefix_str = normalize_windows_path(&prefix.to_string_lossy());
1327    let prefix_str = prefix_str.trim_end_matches('\\');
1328    // Component boundary: `c:\proj` must not admit `c:\proj-evil\x`.
1329    path_str == prefix_str
1330        || path_str
1331            .strip_prefix(prefix_str)
1332            .is_some_and(|rest| rest.starts_with('\\'))
1333}
1334
1335#[cfg(windows)]
1336fn normalize_windows_path(s: &str) -> String {
1337    let stripped = super::pathutil::strip_verbatim_str(s).unwrap_or_else(|| s.to_string());
1338    stripped.to_lowercase().replace('/', "\\")
1339}
1340
1341#[cfg(windows)]
1342fn reject_symlink_on_windows(path: &Path) -> Result<(), PathJailError> {
1343    if let Ok(meta) = std::fs::symlink_metadata(path) {
1344        // Junctions and other reparse points redirect like symlinks but are
1345        // invisible to `is_symlink()` — reject them too (GL#442).
1346        if super::pathutil::is_symlink_or_reparse(&meta) {
1347            return Err(PathJailError::Symlink {
1348                path: path.to_path_buf(),
1349            });
1350        }
1351    }
1352    Ok(())
1353}
1354
1355#[path = "pathjail_ide_dirs.rs"]
1356mod ide_dirs;
1357
1358#[cfg(all(test, windows))]
1359#[path = "pathjail_windows_tests.rs"]
1360mod windows_prefix_tests;
1361
1362#[cfg(test)]
1363#[path = "pathjail_tests.rs"]
1364mod tests;