1use std::path::{Path, PathBuf};
10
11pub use crate::core::pathutil::has_project_marker;
16
17pub fn resolve_tool_path(
44 project_root: Option<&str>,
45 shell_cwd: Option<&str>,
46 raw: &str,
47) -> Result<String, String> {
48 resolve_tool_path_with_roots(project_root, shell_cwd, raw, &[])
49}
50
51pub fn resolve_tool_path_with_roots(
58 project_root: Option<&str>,
59 shell_cwd: Option<&str>,
60 raw: &str,
61 extra_roots: &[String],
62) -> Result<String, String> {
63 resolve_tool_path_refusing(project_root, shell_cwd, raw, extra_roots)
64 .map_err(|refusal| refusal.message)
65}
66
67#[derive(Debug)]
71pub struct PathRefusal {
72 pub message: String,
73 pub class: Option<crate::core::security_events::RefusalClass>,
74}
75
76impl From<String> for PathRefusal {
77 fn from(message: String) -> Self {
78 Self {
79 message,
80 class: None,
81 }
82 }
83}
84
85impl PathRefusal {
86 pub fn secret_path(message: String) -> Self {
88 Self {
89 message,
90 class: Some(crate::core::security_events::RefusalClass::SecretPath),
91 }
92 }
93
94 pub fn jail(error: &crate::core::error::PathJailError) -> Self {
97 Self {
98 message: error.to_string(),
99 class: crate::core::security_events::RefusalClass::of_jail_error(error),
100 }
101 }
102}
103
104pub fn resolve_tool_path_refusing(
106 project_root: Option<&str>,
107 shell_cwd: Option<&str>,
108 raw: &str,
109 extra_roots: &[String],
110) -> Result<String, PathRefusal> {
111 let normalized = crate::core::pathutil::normalize_tool_path(raw);
112 if normalized.is_empty() || normalized == "." {
113 return Ok(crate::core::workspace_authority::project_dot(
114 &normalized,
115 project_root,
116 )?);
117 }
118
119 let p = Path::new(&normalized);
120 let jail_root = project_root.or(shell_cwd).unwrap_or(".").to_string();
121
122 let resolved: PathBuf = if p.is_absolute() {
123 PathBuf::from(&normalized)
124 } else if let Some(root) = project_root {
125 Path::new(root).join(&normalized)
126 } else if let Some(cwd) = shell_cwd {
127 Path::new(cwd).join(&normalized)
128 } else {
129 Path::new(&jail_root).join(&normalized)
130 };
131
132 if project_root.is_none()
133 && let Some(error) = unbound_relative_path(raw, &resolved, shell_cwd.unwrap_or(&jail_root))
134 {
135 return Err(error.into());
136 }
137
138 let jail_root_path = Path::new(&jail_root);
139 let jailed =
140 crate::core::pathjail::jail_path_auto_admitting(&resolved, jail_root_path, extra_roots)
141 .map_err(|e| PathRefusal::jail(&e))?;
142 crate::core::io_boundary::check_secret_path_for_tool("resolve_path", &jailed)
143 .map_err(PathRefusal::secret_path)?;
144
145 Ok(crate::core::pathutil::normalize_tool_path(
146 &jailed.to_string_lossy().replace('\\', "/"),
147 ))
148}
149
150pub 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 = crate::core::data_dir::test_env_lock();
187 let home = dirs::home_dir()
191 .expect("home dir")
192 .to_string_lossy()
193 .to_string();
194 let error =
195 resolve_tool_path(None, Some(&home), "src/no_such_file_lc_7f3a.rs").unwrap_err();
196 assert!(
197 error.contains("has no project to resolve against"),
198 "{error}"
199 );
200 assert!(error.contains("absolute path"), "{error}");
201
202 let dir = tempfile::tempdir().unwrap();
204 let cwd = dir.path().to_string_lossy().to_string();
205 let outcome = resolve_tool_path(None, Some(&cwd), "src/no_such_file_lc.rs");
206 assert!(
207 outcome
208 .as_ref()
209 .err()
210 .is_none_or(|e| !e.contains("no project to resolve against")),
211 "{outcome:?}"
212 );
213 }
214
215 #[test]
216 fn relative_resolves_against_project_root() {
217 let _environment = crate::core::data_dir::test_env_lock();
218 let tmp = std::env::temp_dir().join(format!("lc_pr_{}", std::process::id()));
219 let _ = fs::create_dir_all(&tmp);
220 let file = tmp.join("a.txt");
221 fs::write(&file, "x").unwrap();
222 let root = tmp.to_string_lossy().to_string();
223
224 let out = resolve_tool_path(Some(&root), None, "a.txt").unwrap();
225 assert!(out.ends_with("a.txt"), "got {out}");
226 assert!(out.contains(&root) || Path::new(&out).is_absolute());
227
228 let _ = fs::remove_dir_all(&tmp);
229 }
230
231 #[test]
235 fn shell_cwd_is_no_second_base_when_a_project_root_is_set() {
236 let _environment = crate::core::data_dir::test_env_lock();
237 let base = tempfile::tempdir().unwrap();
238 let root = base.path().join("root");
239 let cwd = root.join("sub");
240 fs::create_dir_all(&cwd).unwrap();
241 fs::write(cwd.join("only_in_cwd.txt"), "x").unwrap();
242
243 let out = resolve_tool_path(
244 Some(&root.to_string_lossy()),
245 Some(&cwd.to_string_lossy()),
246 "only_in_cwd.txt",
247 )
248 .unwrap();
249 let parent = crate::core::pathjail::canonicalize_or_self(Path::new(&out).parent().unwrap());
250 assert_eq!(
251 parent,
252 crate::core::pathjail::canonicalize_or_self(&root),
253 "{out}"
254 );
255 }
256
257 #[test]
262 fn relative_path_never_resolves_against_process_cwd() {
263 let _environment = crate::core::data_dir::test_env_lock();
264 let cwd = std::env::current_dir().unwrap();
265 assert!(
266 cwd.join("Cargo.toml").exists(),
267 "test premise: CWD contains Cargo.toml"
268 );
269
270 let tmp = std::env::temp_dir().join(format!("lc_pr_nocwd_{}", std::process::id()));
271 fs::create_dir_all(&tmp).unwrap();
272 let root = tmp.to_string_lossy().to_string();
273
274 let out = resolve_tool_path(Some(&root), None, "Cargo.toml").unwrap();
275 let canonical_root = crate::core::pathjail::canonicalize_or_self(&tmp);
281 let out_parent = crate::core::pathjail::canonicalize_or_self(
282 Path::new(&out)
283 .parent()
284 .expect("resolved path has a parent"),
285 );
286 assert_eq!(
287 out_parent, canonical_root,
288 "resolved {out} must live under the project root, not the process CWD"
289 );
290 let canonical_cwd = crate::core::pathjail::canonicalize_or_self(&cwd);
291 assert_ne!(
292 out_parent, canonical_cwd,
293 "resolved {out} must not resolve against the process CWD"
294 );
295
296 let _ = fs::remove_dir_all(&tmp);
297 }
298
299 #[cfg(not(feature = "no-jail"))]
304 #[test]
305 fn extra_roots_thread_through_resolve_tool_path() {
306 let _environment = crate::core::data_dir::test_env_lock();
307 let base = std::env::temp_dir().join(format!("lc_pr_extra_{}", std::process::id()));
308 let root = base.join("root");
309 let worktree = base.join("worktree");
310 fs::create_dir_all(&root).unwrap();
311 fs::create_dir_all(&worktree).unwrap();
312 let file = worktree.join("a.txt");
313 fs::write(&file, "x").unwrap();
314
315 let root_s = root.to_string_lossy().to_string();
316 let file_abs = file.to_string_lossy().to_string();
317 let extra = vec![worktree.to_string_lossy().to_string()];
318
319 let out = resolve_tool_path_with_roots(Some(&root_s), None, &file_abs, &extra);
320 assert!(
321 out.is_ok(),
322 "extra_roots must thread through the resolver: {out:?}"
323 );
324
325 let _ = fs::remove_dir_all(&base);
326 }
327
328 #[test]
334 fn worktree_shell_cwd_does_not_move_the_relative_base() {
335 let _environment = crate::core::data_dir::test_env_lock();
338 let base = tempfile::tempdir().unwrap();
339 let repo = base.path().join("repo");
340 let wt = repo.join(".claude").join("worktrees").join("fix-x");
341 fs::create_dir_all(repo.join("src")).unwrap();
342 fs::create_dir_all(repo.join(".git")).unwrap(); fs::create_dir_all(wt.join("src")).unwrap();
344 fs::write(wt.join(".git"), "gitdir: ../../.git/worktrees/fix-x\n").unwrap(); fs::write(repo.join("src/scoring.rs"), "root").unwrap();
346 fs::write(wt.join("src/scoring.rs"), "worktree").unwrap();
347 let (repo_s, wt_s) = (repo.to_string_lossy(), wt.to_string_lossy());
348
349 let out = resolve_tool_path(Some(&repo_s), Some(&wt_s), "src/scoring.rs").unwrap();
350 assert_eq!(fs::read_to_string(&out).unwrap(), "root", "{out}");
351
352 let new = resolve_tool_path(Some(&repo_s), Some(&wt_s), "src/new_file.rs").unwrap();
353 assert!(
354 !new.contains("worktrees"),
355 "write target stays in the root: {new}"
356 );
357
358 let rel = resolve_tool_path(
360 Some(&repo_s),
361 Some(&wt_s),
362 ".claude/worktrees/fix-x/src/scoring.rs",
363 )
364 .unwrap();
365 assert_eq!(fs::read_to_string(&rel).unwrap(), "worktree", "{rel}");
366 assert_eq!(rel.matches("worktrees").count(), 1, "{rel}");
367
368 let abs = resolve_tool_path(
369 Some(&repo_s),
370 Some(&wt_s),
371 &wt.join("src/scoring.rs").to_string_lossy(),
372 )
373 .unwrap();
374 assert_eq!(fs::read_to_string(&abs).unwrap(), "worktree", "{abs}");
375 }
376
377 #[test]
378 fn tool_context_shape_project_root_only() {
379 let _environment = crate::core::data_dir::test_env_lock();
380 let tmp = std::env::temp_dir().join(format!("lc_pr_ctx_{}", std::process::id()));
382 fs::create_dir_all(&tmp).unwrap();
383 let root = tmp.to_string_lossy().to_string();
384 let out = resolve_tool_path(Some(&root), None, "missing.rs").unwrap();
385 assert!(out.ends_with("missing.rs"), "got {out}");
386 let _ = fs::remove_dir_all(&tmp);
387 }
388
389 #[cfg(not(windows))]
397 #[test]
398 fn single_letter_root_is_never_drive_translated_on_unix() {
399 let _environment = crate::core::data_dir::test_env_lock();
400 for raw in ["/c/Users/me/proj/src/app.ts", "src/app.ts"] {
401 let rendered = match resolve_tool_path(Some("/c/Users/me/proj"), None, raw) {
402 Ok(p) => p,
403 Err(e) => e,
404 };
405 assert!(
406 !rendered.contains("C:/"),
407 "drive translation must not run on unix hosts (raw={raw}): {rendered}"
408 );
409 }
410 }
411
412 #[test]
415 fn a_refusal_names_the_boundary_that_refused() {
416 use crate::core::security_events::RefusalClass;
417 let _environment = crate::core::data_dir::test_env_lock();
418 let tmp = tempfile::tempdir().unwrap();
419 let root = tmp.path().canonicalize().unwrap();
420 fs::write(root.join(".env"), "TOKEN=x").unwrap();
421 let root = root.to_string_lossy().into_owned();
422 let prev = std::env::var("LEAN_CTX_IO_BOUNDARY_MODE").ok();
423 crate::test_env::set_var("LEAN_CTX_IO_BOUNDARY_MODE", "enforce");
424 let secret = resolve_tool_path_refusing(Some(&root), None, ".env", &[]);
425 let outside =
426 resolve_tool_path_refusing(Some(&root), None, &format!("{root}/../outside.txt"), &[]);
427 match prev {
428 Some(v) => crate::test_env::set_var("LEAN_CTX_IO_BOUNDARY_MODE", v),
429 None => crate::test_env::remove_var("LEAN_CTX_IO_BOUNDARY_MODE"),
430 }
431 let secret = secret.expect_err("enforce mode refuses a secret path");
432 assert_eq!(secret.class, Some(RefusalClass::SecretPath));
433 assert!(
434 secret.message.contains("Secret-like path"),
435 "{}",
436 secret.message
437 );
438 if !cfg!(feature = "no-jail") {
439 let outside = outside.expect_err("the jail refuses a path outside the root");
440 assert_eq!(outside.class, Some(RefusalClass::OutsideRoot));
441 }
442 let unbound = resolve_tool_path_refusing(None, None, "src/no_such_file_lc_9c1.rs", &[]);
443 if let Err(refusal) = unbound {
444 assert_eq!(refusal.class, None, "{}", refusal.message);
445 }
446 }
447}