Skip to main content

lean_ctx/core/
path_resolve.rs

1//! Shared path-resolution for tool handlers.
2//!
3//! Previously two near-identical `resolve_path_sync` implementations lived in
4//! `tools/registered/mod.rs` (SessionState-based) and `server/tool_trait.rs`
5//! (ToolContext-based), plus several copies of the project-marker test. This
6//! module is the single source of truth: [`resolve_tool_path`] for jailed path
7//! resolution and a re-export of [`has_project_marker`] for marker detection.
8
9use std::path::{Path, PathBuf};
10
11/// Single canonical project-marker test (`.git`, `Cargo.toml`, …).
12///
13/// Re-exported from [`crate::core::pathutil`] so callers that think in terms of
14/// path resolution have a local, discoverable handle.
15pub use crate::core::pathutil::has_project_marker;
16
17/// Nearest ancestor (including `start` itself) containing a `.git` entry —
18/// directory (normal checkout) **or file** (linked worktree: `gitdir: …`),
19/// canonicalized for comparison. `None` when no git boundary exists upward.
20///
21/// Deliberately `.git`-only, NOT [`has_project_marker`]: markers like
22/// `Cargo.toml` exist in nested monorepo subdirectories (`rust/Cargo.toml`
23/// in this very repo), so using them here would make a plain `cd rust/` look
24/// like a checkout switch (#707).
25fn nearest_git_boundary(start: &Path) -> Option<PathBuf> {
26    let start = crate::core::pathutil::safe_canonicalize_or_self(start);
27    let mut cur: Option<&Path> = Some(start.as_path());
28    while let Some(dir) = cur {
29        if dir.join(".git").exists() {
30            return Some(dir.to_path_buf());
31        }
32        cur = dir.parent();
33    }
34    None
35}
36
37/// True when `shell_cwd` lives in a DIFFERENT git checkout than
38/// `project_root` (#707): both sides resolve to a `.git` boundary and the
39/// boundaries differ. This is the worktree signal — Claude Code's
40/// `EnterWorktree` nests a full checkout (own `.git` *file*) under
41/// `<repo>/.claude/worktrees/<name>/`, so a same-named relative path exists
42/// in both trees and a bare `exists()` probe silently picks the stale one.
43/// A monorepo subdirectory (`cd rust/`) shares the boundary → not diverged;
44/// either side without any `.git` upward → no signal → not diverged.
45pub(crate) fn shell_cwd_is_divergent_checkout(project_root: &str, shell_cwd: &str) -> bool {
46    if shell_cwd == project_root {
47        return false;
48    }
49    match (
50        nearest_git_boundary(Path::new(shell_cwd)),
51        nearest_git_boundary(Path::new(project_root)),
52    ) {
53        (Some(cwd_git), Some(root_git)) => cwd_git != root_git,
54        _ => false,
55    }
56}
57
58/// Resolve a (possibly relative) tool path to a normalized, jail-checked,
59/// secret-screened absolute path.
60///
61/// Resolution order for relative inputs:
62/// 1. absolute path → used as-is
63/// 2. `<project_root>/<path>` if it exists
64/// 3. `<shell_cwd>/<path>` if a shell cwd is known
65/// 4. `<jail_root>/<path>` as a last resort
66///
67/// Relative inputs are NEVER resolved against the process CWD: the daemon's
68/// CWD is not the project, so a CWD `exists()` probe made resolution
69/// nondeterministic across MCP/daemon/CLI contexts (and could pick a
70/// same-named file outside the project).
71///
72/// `jail_root` is `project_root`, else `shell_cwd`, else `"."`. The result is
73/// confined to the jail root via [`crate::core::pathjail::jail_path`] and
74/// screened by the secret-path I/O boundary.
75///
76/// Performs blocking filesystem `exists()` checks; callers on async runtimes
77/// must wrap this in `tokio::task::block_in_place`.
78pub fn resolve_tool_path(
79    project_root: Option<&str>,
80    shell_cwd: Option<&str>,
81    raw: &str,
82) -> Result<String, String> {
83    resolve_tool_path_with_roots(project_root, shell_cwd, raw, &[])
84}
85
86/// Like [`resolve_tool_path`], but also permits paths under any of
87/// `extra_roots` (session-scoped trusted roots from `session.extra_roots`).
88///
89/// An empty `extra_roots` is identical to [`resolve_tool_path`]; this is how
90/// sync tool handlers honor MCP `roots/list` / config `extra_roots` for an
91/// explicit path without widening the global jail (#403).
92pub fn resolve_tool_path_with_roots(
93    project_root: Option<&str>,
94    shell_cwd: Option<&str>,
95    raw: &str,
96    extra_roots: &[String],
97) -> Result<String, String> {
98    let normalized = crate::core::pathutil::normalize_tool_path(raw);
99    if normalized.is_empty() || normalized == "." {
100        return Ok(normalized);
101    }
102
103    let p = Path::new(&normalized);
104    let jail_root = project_root.or(shell_cwd).unwrap_or(".").to_string();
105
106    let resolved: PathBuf = if p.is_absolute() {
107        PathBuf::from(&normalized)
108    } else if let Some(root) = project_root {
109        // #707: a live shell_cwd inside a DIFFERENT git checkout (a worktree
110        // switched into mid-session) outranks the stale project_root — even
111        // when `<project_root>/<path>` exists, because in a worktree it
112        // almost always does (full checkout, same layout, stale content).
113        if let Some(cwd) = shell_cwd
114            && shell_cwd_is_divergent_checkout(root, cwd)
115        {
116            Path::new(cwd).join(&normalized)
117        } else {
118            let joined = Path::new(root).join(&normalized);
119            if joined.exists() {
120                joined
121            } else if let Some(cwd) = shell_cwd {
122                Path::new(cwd).join(&normalized)
123            } else {
124                joined
125            }
126        }
127    } else if let Some(cwd) = shell_cwd {
128        Path::new(cwd).join(&normalized)
129    } else {
130        Path::new(&jail_root).join(&normalized)
131    };
132
133    let jail_root_path = Path::new(&jail_root);
134    let jailed =
135        crate::core::pathjail::jail_path_with_roots(&resolved, jail_root_path, extra_roots)
136            .map_err(|e| e.to_string())?;
137    crate::core::io_boundary::check_secret_path_for_tool("resolve_path", &jailed)?;
138
139    Ok(crate::core::pathutil::normalize_tool_path(
140        &jailed.to_string_lossy().replace('\\', "/"),
141    ))
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147    use std::fs;
148
149    #[test]
150    fn empty_and_dot_pass_through() {
151        assert_eq!(resolve_tool_path(None, None, "").unwrap(), "");
152        assert_eq!(resolve_tool_path(None, None, ".").unwrap(), ".");
153    }
154
155    #[test]
156    fn relative_resolves_against_project_root() {
157        let _environment = crate::core::data_dir::test_env_lock();
158        let tmp = std::env::temp_dir().join(format!("lc_pr_{}", std::process::id()));
159        let _ = fs::create_dir_all(&tmp);
160        let file = tmp.join("a.txt");
161        fs::write(&file, "x").unwrap();
162        let root = tmp.to_string_lossy().to_string();
163
164        let out = resolve_tool_path(Some(&root), None, "a.txt").unwrap();
165        assert!(out.ends_with("a.txt"), "got {out}");
166        assert!(out.contains(&root) || Path::new(&out).is_absolute());
167
168        let _ = fs::remove_dir_all(&tmp);
169    }
170
171    #[test]
172    fn falls_back_to_shell_cwd_when_not_in_project_root() {
173        let _environment = crate::core::data_dir::test_env_lock();
174        let base = std::env::temp_dir().join(format!("lc_pr_cwd_{}", std::process::id()));
175        let root = base.join("root");
176        let cwd = base.join("cwd");
177        fs::create_dir_all(&root).unwrap();
178        fs::create_dir_all(&cwd).unwrap();
179        fs::write(cwd.join("only_in_cwd.txt"), "x").unwrap();
180
181        let out = resolve_tool_path(
182            Some(&root.to_string_lossy()),
183            Some(&cwd.to_string_lossy()),
184            "only_in_cwd.txt",
185        );
186        // jail_root is project_root; a file only under shell_cwd resolves to a
187        // cwd-joined path which may be rejected by the jail — either way it must
188        // not panic and must yield a deterministic Result.
189        assert!(out.is_ok() || out.is_err());
190
191        let _ = fs::remove_dir_all(&base);
192    }
193
194    // P0-3 (#415): a relative path that happens to exist in the *process CWD*
195    // must NOT short-circuit resolution. `Cargo.toml` exists in the package
196    // root (cargo test's CWD) but not in this empty project root — before the
197    // fix the CWD probe returned it as-is, now it must resolve into the root.
198    #[test]
199    fn relative_path_never_resolves_against_process_cwd() {
200        let _environment = crate::core::data_dir::test_env_lock();
201        let cwd = std::env::current_dir().unwrap();
202        assert!(
203            cwd.join("Cargo.toml").exists(),
204            "test premise: CWD contains Cargo.toml"
205        );
206
207        let tmp = std::env::temp_dir().join(format!("lc_pr_nocwd_{}", std::process::id()));
208        fs::create_dir_all(&tmp).unwrap();
209        let root = tmp.to_string_lossy().to_string();
210
211        let out = resolve_tool_path(Some(&root), None, "Cargo.toml").unwrap();
212        // Canonicalize BOTH sides before comparing: on macOS temp_dir() is a
213        // symlink (/var → /private/var) and on Windows it may carry 8.3 short
214        // names (RUNNER~1), so comparing raw strings is platform-flaky. The
215        // resolved file itself does not exist, but its parent does — compare
216        // the canonicalized parents.
217        let canonical_root = crate::core::pathjail::canonicalize_or_self(&tmp);
218        let out_parent = crate::core::pathjail::canonicalize_or_self(
219            Path::new(&out)
220                .parent()
221                .expect("resolved path has a parent"),
222        );
223        assert_eq!(
224            out_parent, canonical_root,
225            "resolved {out} must live under the project root, not the process CWD"
226        );
227        let canonical_cwd = crate::core::pathjail::canonicalize_or_self(&cwd);
228        assert_ne!(
229            out_parent, canonical_cwd,
230            "resolved {out} must not resolve against the process CWD"
231        );
232
233        let _ = fs::remove_dir_all(&tmp);
234    }
235
236    // #403: session-scoped extra_roots must thread through to the jail so an
237    // explicit path under a worktree resolves where the bare resolver rejects
238    // it. Asserts only the Ok case (robust against parallel env mutation): with
239    // the jail on, success here is only possible because extra_roots were honored.
240    #[cfg(not(feature = "no-jail"))]
241    #[test]
242    fn extra_roots_thread_through_resolve_tool_path() {
243        let _environment = crate::core::data_dir::test_env_lock();
244        let base = std::env::temp_dir().join(format!("lc_pr_extra_{}", std::process::id()));
245        let root = base.join("root");
246        let worktree = base.join("worktree");
247        fs::create_dir_all(&root).unwrap();
248        fs::create_dir_all(&worktree).unwrap();
249        let file = worktree.join("a.txt");
250        fs::write(&file, "x").unwrap();
251
252        let root_s = root.to_string_lossy().to_string();
253        let file_abs = file.to_string_lossy().to_string();
254        let extra = vec![worktree.to_string_lossy().to_string()];
255
256        let out = resolve_tool_path_with_roots(Some(&root_s), None, &file_abs, &extra);
257        assert!(
258            out.is_ok(),
259            "extra_roots must thread through the resolver: {out:?}"
260        );
261
262        let _ = fs::remove_dir_all(&base);
263    }
264
265    /// #707: the exact Claude Code `EnterWorktree` topology — a full checkout
266    /// with its own `.git` FILE nested under `<repo>/.claude/worktrees/<n>/`.
267    /// The same relative path exists in both trees; the live shell_cwd
268    /// (worktree) must win over the stale project_root copy.
269    #[test]
270    fn worktree_shell_cwd_outranks_stale_project_root_copy() {
271        // Path authorization reads the process-wide protected-runtime profile.
272        // Serialize with tests that temporarily change that profile.
273        let _environment = crate::core::data_dir::test_env_lock();
274        let base = std::env::temp_dir().join(format!("lc_707_nested_{}", std::process::id()));
275        let repo = base.join("repo");
276        let wt = repo.join(".claude").join("worktrees").join("fix-x");
277        fs::create_dir_all(repo.join("src")).unwrap();
278        fs::create_dir_all(repo.join(".git")).unwrap(); // main checkout: .git dir
279        fs::create_dir_all(wt.join("src")).unwrap();
280        fs::write(wt.join(".git"), "gitdir: ../../.git/worktrees/fix-x\n").unwrap(); // worktree: .git FILE
281        fs::write(repo.join("src/scoring.rs"), "stale").unwrap();
282        fs::write(wt.join("src/scoring.rs"), "fresh").unwrap();
283
284        let out = resolve_tool_path(
285            Some(&repo.to_string_lossy()),
286            Some(&wt.to_string_lossy()),
287            "src/scoring.rs",
288        )
289        .unwrap();
290        assert_eq!(
291            fs::read_to_string(&out).unwrap(),
292            "fresh",
293            "must resolve into the worktree, not the stale root: {out}"
294        );
295
296        // A path that does not exist yet (a write target) also lands in the
297        // worktree — writes after the switch must not touch the stale tree.
298        let new = resolve_tool_path(
299            Some(&repo.to_string_lossy()),
300            Some(&wt.to_string_lossy()),
301            "src/new_file.rs",
302        )
303        .unwrap();
304        assert!(
305            new.contains("worktrees"),
306            "write target must land in the worktree: {new}"
307        );
308
309        let _ = fs::remove_dir_all(&base);
310    }
311
312    /// #707 regression guard from the report: `cd rust/` inside the SAME
313    /// checkout (nested `Cargo.toml`, no own `.git`) must NOT count as a
314    /// divergent checkout — project_root resolution stays authoritative.
315    #[test]
316    fn monorepo_subdir_shell_cwd_is_not_a_divergent_checkout() {
317        let _environment = crate::core::data_dir::test_env_lock();
318        let base = std::env::temp_dir().join(format!("lc_707_mono_{}", std::process::id()));
319        let repo = base.join("repo");
320        fs::create_dir_all(repo.join("rust").join("src")).unwrap();
321        fs::create_dir_all(repo.join(".git")).unwrap();
322        fs::write(repo.join("rust/Cargo.toml"), "[package]").unwrap();
323        fs::write(repo.join("rust/src/main.rs"), "root copy").unwrap();
324
325        assert!(!shell_cwd_is_divergent_checkout(
326            &repo.to_string_lossy(),
327            &repo.join("rust").to_string_lossy(),
328        ));
329
330        let out = resolve_tool_path(
331            Some(&repo.to_string_lossy()),
332            Some(&repo.join("rust").to_string_lossy()),
333            "rust/src/main.rs",
334        )
335        .unwrap();
336        assert_eq!(
337            fs::read_to_string(&out).unwrap(),
338            "root copy",
339            "same-checkout cwd must not divert resolution: {out}"
340        );
341
342        let _ = fs::remove_dir_all(&base);
343    }
344
345    /// #707: divergence needs a `.git` boundary on BOTH sides — a cwd with no
346    /// git upward (scratch dir) gives no signal and must not divert.
347    #[test]
348    fn gitless_shell_cwd_gives_no_divergence_signal() {
349        let base = std::env::temp_dir().join(format!("lc_707_gitless_{}", std::process::id()));
350        let repo = base.join("repo");
351        let scratch = base.join("scratch");
352        fs::create_dir_all(repo.join(".git")).unwrap();
353        fs::create_dir_all(&scratch).unwrap();
354        fs::write(repo.join("a.txt"), "root").unwrap();
355
356        assert!(!shell_cwd_is_divergent_checkout(
357            &repo.to_string_lossy(),
358            &scratch.to_string_lossy(),
359        ));
360
361        let _ = fs::remove_dir_all(&base);
362    }
363
364    #[test]
365    fn tool_context_shape_project_root_only() {
366        let _environment = crate::core::data_dir::test_env_lock();
367        // Mirrors ToolContext::resolve_path_sync (shell_cwd = None).
368        let tmp = std::env::temp_dir().join(format!("lc_pr_ctx_{}", std::process::id()));
369        fs::create_dir_all(&tmp).unwrap();
370        let root = tmp.to_string_lossy().to_string();
371        let out = resolve_tool_path(Some(&root), None, "missing.rs").unwrap();
372        assert!(out.ends_with("missing.rs"), "got {out}");
373        let _ = fs::remove_dir_all(&tmp);
374    }
375
376    // GH #397: on Unix an absolute path under a single-letter root (`/c/…`)
377    // was rewritten to `C:/…`, which `Path::is_absolute()` rejects on Unix —
378    // the path was then re-joined under the (also-translated) project root,
379    // producing the doubled `C:/root/C:/root/file` form from the report.
380    // `/c` cannot be created in this test environment, so the jail may still
381    // reject the path as nonexistent — the regression assertion is that no
382    // `C:/` drive form appears anywhere in the outcome (Ok or Err).
383    #[cfg(not(windows))]
384    #[test]
385    fn single_letter_root_is_never_drive_translated_on_unix() {
386        let _environment = crate::core::data_dir::test_env_lock();
387        for raw in ["/c/Users/me/proj/src/app.ts", "src/app.ts"] {
388            let rendered = match resolve_tool_path(Some("/c/Users/me/proj"), None, raw) {
389                Ok(p) => p,
390                Err(e) => e,
391            };
392            assert!(
393                !rendered.contains("C:/"),
394                "drive translation must not run on unix hosts (raw={raw}): {rendered}"
395            );
396        }
397    }
398}