1use std::path::{Path, PathBuf};
10
11pub use crate::core::pathutil::has_project_marker;
16
17fn 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
37pub(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
58pub 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
86pub 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 crate::core::workspace_authority::project_dot(&normalized, project_root);
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 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 if project_root.is_none()
134 && let Some(error) = unbound_relative_path(raw, &resolved, shell_cwd.unwrap_or(&jail_root))
135 {
136 return Err(error);
137 }
138
139 let jail_root_path = Path::new(&jail_root);
140 let jailed =
141 crate::core::pathjail::jail_path_auto_admitting(&resolved, jail_root_path, extra_roots)
142 .map_err(|e| e.to_string())?;
143 crate::core::io_boundary::check_secret_path_for_tool("resolve_path", &jailed)?;
144
145 Ok(crate::core::pathutil::normalize_tool_path(
146 &jailed.to_string_lossy().replace('\\', "/"),
147 ))
148}
149
150pub(crate) fn unbound_relative_path(raw: &str, resolved: &Path, base: &str) -> Option<String> {
156 let normalized = crate::core::pathutil::normalize_tool_path(raw);
157 if Path::new(&normalized).is_absolute() || resolved.exists() {
158 return None;
159 }
160 let base = std::path::absolute(base).unwrap_or_else(|_| PathBuf::from(base));
161 if !crate::core::pathutil::is_broad_or_unsafe_root(&base) {
162 return None;
163 }
164 Some(format!(
165 "relative path '{raw}' has no project to resolve against: lean-ctx has no project for \
166 this session yet (the host started it in {}, outside a project). Pass the absolute \
167 path instead, e.g. /home/me/code/my-app/{normalized}; that project then stays the \
168 session project.",
169 base.display()
170 ))
171}
172
173#[cfg(test)]
174mod tests {
175 use super::*;
176 use std::fs;
177
178 #[test]
179 fn empty_and_dot_pass_through() {
180 assert_eq!(resolve_tool_path(None, None, "").unwrap(), "");
181 assert_eq!(resolve_tool_path(None, None, ".").unwrap(), ".");
182 }
183
184 #[test]
185 fn missing_relative_path_without_a_project_says_what_is_missing() {
186 let home = dirs::home_dir()
190 .expect("home dir")
191 .to_string_lossy()
192 .to_string();
193 let error =
194 resolve_tool_path(None, Some(&home), "src/no_such_file_lc_7f3a.rs").unwrap_err();
195 assert!(
196 error.contains("has no project to resolve against"),
197 "{error}"
198 );
199 assert!(error.contains("absolute path"), "{error}");
200
201 let dir = tempfile::tempdir().unwrap();
203 let cwd = dir.path().to_string_lossy().to_string();
204 let outcome = resolve_tool_path(None, Some(&cwd), "src/no_such_file_lc.rs");
205 assert!(
206 outcome
207 .as_ref()
208 .err()
209 .is_none_or(|e| !e.contains("no project to resolve against")),
210 "{outcome:?}"
211 );
212 }
213
214 #[test]
215 fn relative_resolves_against_project_root() {
216 let _environment = crate::core::data_dir::test_env_lock();
217 let tmp = std::env::temp_dir().join(format!("lc_pr_{}", std::process::id()));
218 let _ = fs::create_dir_all(&tmp);
219 let file = tmp.join("a.txt");
220 fs::write(&file, "x").unwrap();
221 let root = tmp.to_string_lossy().to_string();
222
223 let out = resolve_tool_path(Some(&root), None, "a.txt").unwrap();
224 assert!(out.ends_with("a.txt"), "got {out}");
225 assert!(out.contains(&root) || Path::new(&out).is_absolute());
226
227 let _ = fs::remove_dir_all(&tmp);
228 }
229
230 #[test]
231 fn falls_back_to_shell_cwd_when_not_in_project_root() {
232 let _environment = crate::core::data_dir::test_env_lock();
233 let base = std::env::temp_dir().join(format!("lc_pr_cwd_{}", std::process::id()));
234 let root = base.join("root");
235 let cwd = base.join("cwd");
236 fs::create_dir_all(&root).unwrap();
237 fs::create_dir_all(&cwd).unwrap();
238 fs::write(cwd.join("only_in_cwd.txt"), "x").unwrap();
239
240 let out = resolve_tool_path(
241 Some(&root.to_string_lossy()),
242 Some(&cwd.to_string_lossy()),
243 "only_in_cwd.txt",
244 );
245 assert!(out.is_ok() || out.is_err());
249
250 let _ = fs::remove_dir_all(&base);
251 }
252
253 #[test]
258 fn relative_path_never_resolves_against_process_cwd() {
259 let _environment = crate::core::data_dir::test_env_lock();
260 let cwd = std::env::current_dir().unwrap();
261 assert!(
262 cwd.join("Cargo.toml").exists(),
263 "test premise: CWD contains Cargo.toml"
264 );
265
266 let tmp = std::env::temp_dir().join(format!("lc_pr_nocwd_{}", std::process::id()));
267 fs::create_dir_all(&tmp).unwrap();
268 let root = tmp.to_string_lossy().to_string();
269
270 let out = resolve_tool_path(Some(&root), None, "Cargo.toml").unwrap();
271 let canonical_root = crate::core::pathjail::canonicalize_or_self(&tmp);
277 let out_parent = crate::core::pathjail::canonicalize_or_self(
278 Path::new(&out)
279 .parent()
280 .expect("resolved path has a parent"),
281 );
282 assert_eq!(
283 out_parent, canonical_root,
284 "resolved {out} must live under the project root, not the process CWD"
285 );
286 let canonical_cwd = crate::core::pathjail::canonicalize_or_self(&cwd);
287 assert_ne!(
288 out_parent, canonical_cwd,
289 "resolved {out} must not resolve against the process CWD"
290 );
291
292 let _ = fs::remove_dir_all(&tmp);
293 }
294
295 #[cfg(not(feature = "no-jail"))]
300 #[test]
301 fn extra_roots_thread_through_resolve_tool_path() {
302 let _environment = crate::core::data_dir::test_env_lock();
303 let base = std::env::temp_dir().join(format!("lc_pr_extra_{}", std::process::id()));
304 let root = base.join("root");
305 let worktree = base.join("worktree");
306 fs::create_dir_all(&root).unwrap();
307 fs::create_dir_all(&worktree).unwrap();
308 let file = worktree.join("a.txt");
309 fs::write(&file, "x").unwrap();
310
311 let root_s = root.to_string_lossy().to_string();
312 let file_abs = file.to_string_lossy().to_string();
313 let extra = vec![worktree.to_string_lossy().to_string()];
314
315 let out = resolve_tool_path_with_roots(Some(&root_s), None, &file_abs, &extra);
316 assert!(
317 out.is_ok(),
318 "extra_roots must thread through the resolver: {out:?}"
319 );
320
321 let _ = fs::remove_dir_all(&base);
322 }
323
324 #[test]
329 fn worktree_shell_cwd_outranks_stale_project_root_copy() {
330 let _environment = crate::core::data_dir::test_env_lock();
333 let base = std::env::temp_dir().join(format!("lc_707_nested_{}", std::process::id()));
334 let repo = base.join("repo");
335 let wt = repo.join(".claude").join("worktrees").join("fix-x");
336 fs::create_dir_all(repo.join("src")).unwrap();
337 fs::create_dir_all(repo.join(".git")).unwrap(); fs::create_dir_all(wt.join("src")).unwrap();
339 fs::write(wt.join(".git"), "gitdir: ../../.git/worktrees/fix-x\n").unwrap(); fs::write(repo.join("src/scoring.rs"), "stale").unwrap();
341 fs::write(wt.join("src/scoring.rs"), "fresh").unwrap();
342
343 let out = resolve_tool_path(
344 Some(&repo.to_string_lossy()),
345 Some(&wt.to_string_lossy()),
346 "src/scoring.rs",
347 )
348 .unwrap();
349 assert_eq!(
350 fs::read_to_string(&out).unwrap(),
351 "fresh",
352 "must resolve into the worktree, not the stale root: {out}"
353 );
354
355 let new = resolve_tool_path(
358 Some(&repo.to_string_lossy()),
359 Some(&wt.to_string_lossy()),
360 "src/new_file.rs",
361 )
362 .unwrap();
363 assert!(
364 new.contains("worktrees"),
365 "write target must land in the worktree: {new}"
366 );
367
368 let _ = fs::remove_dir_all(&base);
369 }
370
371 #[test]
375 fn monorepo_subdir_shell_cwd_is_not_a_divergent_checkout() {
376 let _environment = crate::core::data_dir::test_env_lock();
377 let base = std::env::temp_dir().join(format!("lc_707_mono_{}", std::process::id()));
378 let repo = base.join("repo");
379 fs::create_dir_all(repo.join("rust").join("src")).unwrap();
380 fs::create_dir_all(repo.join(".git")).unwrap();
381 fs::write(repo.join("rust/Cargo.toml"), "[package]").unwrap();
382 fs::write(repo.join("rust/src/main.rs"), "root copy").unwrap();
383
384 assert!(!shell_cwd_is_divergent_checkout(
385 &repo.to_string_lossy(),
386 &repo.join("rust").to_string_lossy(),
387 ));
388
389 let out = resolve_tool_path(
390 Some(&repo.to_string_lossy()),
391 Some(&repo.join("rust").to_string_lossy()),
392 "rust/src/main.rs",
393 )
394 .unwrap();
395 assert_eq!(
396 fs::read_to_string(&out).unwrap(),
397 "root copy",
398 "same-checkout cwd must not divert resolution: {out}"
399 );
400
401 let _ = fs::remove_dir_all(&base);
402 }
403
404 #[test]
407 fn gitless_shell_cwd_gives_no_divergence_signal() {
408 let base = std::env::temp_dir().join(format!("lc_707_gitless_{}", std::process::id()));
409 let repo = base.join("repo");
410 let scratch = base.join("scratch");
411 fs::create_dir_all(repo.join(".git")).unwrap();
412 fs::create_dir_all(&scratch).unwrap();
413 fs::write(repo.join("a.txt"), "root").unwrap();
414
415 assert!(!shell_cwd_is_divergent_checkout(
416 &repo.to_string_lossy(),
417 &scratch.to_string_lossy(),
418 ));
419
420 let _ = fs::remove_dir_all(&base);
421 }
422
423 #[test]
424 fn tool_context_shape_project_root_only() {
425 let _environment = crate::core::data_dir::test_env_lock();
426 let tmp = std::env::temp_dir().join(format!("lc_pr_ctx_{}", std::process::id()));
428 fs::create_dir_all(&tmp).unwrap();
429 let root = tmp.to_string_lossy().to_string();
430 let out = resolve_tool_path(Some(&root), None, "missing.rs").unwrap();
431 assert!(out.ends_with("missing.rs"), "got {out}");
432 let _ = fs::remove_dir_all(&tmp);
433 }
434
435 #[cfg(not(windows))]
443 #[test]
444 fn single_letter_root_is_never_drive_translated_on_unix() {
445 let _environment = crate::core::data_dir::test_env_lock();
446 for raw in ["/c/Users/me/proj/src/app.ts", "src/app.ts"] {
447 let rendered = match resolve_tool_path(Some("/c/Users/me/proj"), None, raw) {
448 Ok(p) => p,
449 Err(e) => e,
450 };
451 assert!(
452 !rendered.contains("C:/"),
453 "drive translation must not run on unix hosts (raw={raw}): {rendered}"
454 );
455 }
456 }
457}