1use std::path::Path;
2
3pub fn uri_to_path(uri: &str) -> Option<String> {
7 let raw = uri.strip_prefix("file://")?;
8 if raw.contains("%00") {
9 return None;
10 }
11 let decoded = percent_decode(raw);
12 if decoded.is_empty() || decoded.contains('\0') {
13 return None;
14 }
15 #[cfg(windows)]
23 let decoded = if has_leading_slash_drive(&decoded) {
24 decoded[1..].to_string()
25 } else {
26 decoded
27 };
28 let path = Path::new(&decoded);
29 if !path.is_absolute() {
30 return None;
31 }
32 let canonical = crate::core::pathutil::safe_canonicalize_or_self(path);
33 let s = canonical.to_string_lossy().to_string();
34 if s.is_empty() {
35 return None;
36 }
37 Some(s)
38}
39
40fn percent_decode(s: &str) -> String {
41 let mut out = String::with_capacity(s.len());
42 let mut chars = s.bytes();
43 while let Some(b) = chars.next() {
44 if b == b'%' {
45 let hi = chars.next().and_then(hex_val);
46 let lo = chars.next().and_then(hex_val);
47 if let (Some(h), Some(l)) = (hi, lo) {
48 let byte = h << 4 | l;
49 if byte == 0 {
50 continue;
51 }
52 out.push(byte as char);
53 } else {
54 out.push('%');
55 }
56 } else {
57 out.push(b as char);
58 }
59 }
60 out
61}
62
63fn hex_val(b: u8) -> Option<u8> {
64 match b {
65 b'0'..=b'9' => Some(b - b'0'),
66 b'a'..=b'f' => Some(b - b'a' + 10),
67 b'A'..=b'F' => Some(b - b'A' + 10),
68 _ => None,
69 }
70}
71
72#[cfg_attr(not(windows), allow(dead_code))]
79fn has_leading_slash_drive(p: &str) -> bool {
80 let b = p.as_bytes();
81 b.len() >= 3 && b[0] == b'/' && b[1].is_ascii_alphabetic() && b[2] == b':'
82}
83
84pub(super) fn has_project_marker(dir: &Path) -> bool {
85 crate::core::pathutil::has_project_marker(dir)
86}
87
88pub fn best_root_from_uris(uris: &[String]) -> Option<String> {
95 best_root_from_paths(uris.iter().filter_map(|u| uri_to_path(u)).collect())
96}
97
98fn best_root_from_paths(paths: Vec<String>) -> Option<String> {
106 let paths: Vec<String> = paths
107 .into_iter()
108 .filter(|p| Path::new(p).is_dir())
109 .collect();
110
111 if paths.is_empty() {
112 return None;
113 }
114
115 for p in &paths {
116 if has_project_marker(Path::new(p)) {
117 return Some(p.clone());
118 }
119 }
120
121 paths
122 .into_iter()
123 .find(|p| !crate::core::pathutil::is_broad_or_unsafe_root(Path::new(p)))
124}
125
126pub fn valid_dir_paths_from_uris(uris: &[String]) -> Vec<String> {
128 uris.iter()
129 .filter_map(|u| uri_to_path(u))
130 .filter(|p| Path::new(p).is_dir())
131 .collect()
132}
133
134pub fn root_from_env() -> Option<String> {
146 const VARS: &[&str] = &[
147 "LEAN_CTX_PROJECT_ROOT",
148 "CURSOR_PROJECT_DIR",
149 "CLAUDE_PROJECT_DIR",
150 "WINDSURF_PROJECT_DIR",
151 "TRAE_PROJECT_DIR",
152 "KIRO_PROJECT_DIR",
153 "CODEX_SANDBOX_DIR",
154 "GIT_WORK_TREE",
155 ];
156 for var in VARS {
157 if let Ok(val) = std::env::var(var) {
158 let trimmed = val.trim().to_string();
159 if !trimmed.is_empty()
160 && Path::new(&trimmed).is_dir()
161 && !crate::core::pathutil::is_broad_or_unsafe_root(Path::new(&trimmed))
162 {
163 return Some(trimmed);
164 }
165 }
166 }
167 None
168}
169
170pub fn session_root(env_root: Option<String>, cwd_root: Option<String>) -> Option<String> {
180 let pin = std::env::var("LEAN_CTX_PROJECT_ROOT")
181 .ok()
182 .map(|v| v.trim().to_string());
183 let env_is_pin = env_root.is_some() && env_root == pin;
184 reconcile_session_root(env_root, env_is_pin, cwd_root)
185}
186
187fn reconcile_session_root(
188 env_root: Option<String>,
189 env_is_pin: bool,
190 cwd_root: Option<String>,
191) -> Option<String> {
192 if let (true, Some(pin), Some(cwd)) = (env_is_pin, env_root.as_deref(), cwd_root.as_deref()) {
193 let pin_path = crate::core::pathutil::safe_canonicalize_or_self(Path::new(pin));
194 let cwd_path = crate::core::pathutil::safe_canonicalize_or_self(Path::new(cwd));
195 let unrelated = !cwd_path.starts_with(&pin_path) && !pin_path.starts_with(&cwd_path);
196 if unrelated && has_project_marker(&cwd_path) {
197 tracing::warn!(
198 "LEAN_CTX_PROJECT_ROOT pins {pin}, but this session started in project {cwd} — \
199 using {cwd}. Remove the pin from the agent's global MCP config \
200 (`lean-ctx doctor --fix`)."
201 );
202 return cwd_root;
203 }
204 }
205 env_root.or(cwd_root)
206}
207
208fn split_workspace_paths(raw: &str) -> Vec<String> {
214 let delims: &[char] = if cfg!(windows) {
215 &[',', ';']
216 } else {
217 &[',', ':']
218 };
219 raw.split(delims)
220 .map(str::trim)
221 .filter(|s| !s.is_empty())
222 .map(ToString::to_string)
223 .collect()
224}
225
226pub fn root_from_workspace_env() -> Option<String> {
235 for var in ["WORKSPACE_FOLDER_PATHS", "VSCODE_WORKSPACE_FOLDER"] {
236 if let Ok(raw) = std::env::var(var) {
237 if let Some(root) = best_root_from_paths(split_workspace_paths(&raw)) {
238 return Some(root);
239 }
240 }
241 }
242 None
243}
244
245pub fn workspace_roots_from_env() -> Vec<String> {
250 for var in ["WORKSPACE_FOLDER_PATHS", "VSCODE_WORKSPACE_FOLDER"] {
251 if let Ok(raw) = std::env::var(var) {
252 let paths: Vec<String> = split_workspace_paths(&raw)
253 .into_iter()
254 .filter(|p| Path::new(p).is_dir())
255 .filter(|p| !crate::core::pathutil::is_broad_or_unsafe_root(Path::new(p)))
256 .collect();
257 if !paths.is_empty() {
258 return paths;
259 }
260 }
261 }
262 Vec::new()
263}
264
265#[cfg(test)]
266mod tests {
267 use super::*;
268
269 #[cfg(unix)]
270 #[test]
271 fn parse_file_uri_unix() {
272 assert_eq!(
273 uri_to_path("file:///home/user/project"),
274 Some("/home/user/project".to_string())
275 );
276 }
277
278 #[cfg(unix)]
279 #[test]
280 fn parse_file_uri_windows() {
281 assert_eq!(
282 uri_to_path("file:///C:/Users/dev/project"),
283 Some("/C:/Users/dev/project".to_string())
284 );
285 }
286
287 #[cfg(unix)]
288 #[test]
289 fn parse_file_uri_with_spaces() {
290 assert_eq!(
291 uri_to_path("file:///home/user/my%20project"),
292 Some("/home/user/my project".to_string())
293 );
294 }
295
296 #[test]
297 fn parse_non_file_uri_returns_none() {
298 assert!(uri_to_path("https://example.com").is_none());
299 assert!(uri_to_path("").is_none());
300 }
301
302 #[test]
303 fn detects_leading_slash_windows_drive() {
304 assert!(has_leading_slash_drive("/C:/Users/dev"));
308 assert!(has_leading_slash_drive("/c:/proj"));
309 assert!(has_leading_slash_drive("/Z:"));
310 assert!(!has_leading_slash_drive("/home/user/proj"));
312 assert!(!has_leading_slash_drive("C:/already"));
313 assert!(!has_leading_slash_drive("//server/share"));
314 assert!(!has_leading_slash_drive("/"));
315 assert!(!has_leading_slash_drive("/1:/x"));
316 }
317
318 #[cfg(windows)]
319 #[test]
320 fn parse_file_uri_windows_drive_strips_leading_slash() {
321 let got = uri_to_path("file:///C:/Users/dev/project").expect("windows drive uri");
325 assert!(
326 !got.starts_with('/'),
327 "leading slash must be stripped: {got}"
328 );
329 assert!(
330 got.to_ascii_lowercase().starts_with("c:"),
331 "drive prefix must survive: {got}"
332 );
333 }
334
335 #[cfg(windows)]
336 #[test]
337 fn parse_file_uri_windows_percent_encoded_colon() {
338 let got = uri_to_path("file:///C%3A/Users/dev/project").expect("encoded colon uri");
340 assert!(
341 !got.starts_with('/'),
342 "leading slash must be stripped: {got}"
343 );
344 assert!(got.to_ascii_lowercase().starts_with("c:"), "got: {got}");
345 }
346
347 #[test]
348 fn rejects_null_bytes() {
349 assert!(uri_to_path("file:///tmp/evil%00path").is_none());
350 }
351
352 #[test]
353 fn rejects_relative_uri() {
354 assert!(uri_to_path("file://relative/path").is_none());
355 }
356
357 #[test]
358 fn canonicalizes_traversal() {
359 let tmp = tempfile::tempdir().unwrap();
360 let sub = tmp.path().join("a").join("b");
361 std::fs::create_dir_all(&sub).unwrap();
362 let traversal = format!("file://{}/a/b/../..", tmp.path().display());
363 let result = uri_to_path(&traversal);
364 assert!(result.is_some());
365 let resolved = result.unwrap();
366 assert!(
367 !resolved.contains(".."),
368 "should be canonicalized: {resolved}"
369 );
370 }
371
372 #[test]
373 fn best_root_prefers_marker() {
374 let tmp = tempfile::tempdir().unwrap();
375 let with_marker = tmp.path().join("has_git");
376 let without = tmp.path().join("plain");
377 std::fs::create_dir_all(&with_marker).unwrap();
378 std::fs::create_dir_all(&without).unwrap();
379 std::fs::create_dir(with_marker.join(".git")).unwrap();
380
381 let uris = vec![
382 format!("file://{}", without.display()),
383 format!("file://{}", with_marker.display()),
384 ];
385 let result = best_root_from_uris(&uris).unwrap();
386 assert!(result.contains("has_git"));
387 }
388
389 #[test]
390 fn best_root_falls_back_to_first_existing_dir() {
391 let tmp = tempfile::tempdir().unwrap();
392 let a = tmp.path().join("dir_a");
393 let b = tmp.path().join("dir_b");
394 std::fs::create_dir_all(&a).unwrap();
395 std::fs::create_dir_all(&b).unwrap();
396
397 let uris = vec![
398 format!("file://{}", a.display()),
399 format!("file://{}", b.display()),
400 ];
401 let result = best_root_from_uris(&uris).unwrap();
402 assert!(result.contains("dir_a"));
403 }
404
405 #[test]
406 fn best_root_skips_nonexistent() {
407 let uris = vec!["file:///nonexistent_abc_123".to_string()];
408 assert!(best_root_from_uris(&uris).is_none());
409 }
410
411 #[test]
412 fn best_root_empty_returns_none() {
413 assert!(best_root_from_uris(&[]).is_none());
414 }
415
416 #[test]
417 fn env_override_returns_none_when_unset() {
418 let _ = root_from_env();
419 }
420
421 #[test]
422 fn best_root_rejects_home_without_marker() {
423 if let Some(home) = dirs::home_dir() {
426 let uris = vec![format!("file://{}", home.display())];
427 assert_eq!(
428 best_root_from_uris(&uris),
429 None,
430 "HOME must never be accepted as a marker-less project root"
431 );
432 }
433 }
434
435 #[test]
436 fn best_root_prefers_safe_dir_over_home() {
437 if let Some(home) = dirs::home_dir() {
438 let tmp = tempfile::tempdir().unwrap();
439 let safe = tmp.path().join("real_project");
440 std::fs::create_dir_all(&safe).unwrap();
441 let uris = vec![
442 format!("file://{}", home.display()),
443 format!("file://{}", safe.display()),
444 ];
445 let result = best_root_from_uris(&uris).unwrap();
446 assert!(result.contains("real_project"));
447 }
448 }
449
450 #[test]
451 fn best_root_rejects_filesystem_root() {
452 let uris = vec!["file:///".to_string()];
453 assert!(best_root_from_uris(&uris).is_none());
454 }
455
456 #[test]
457 fn all_paths_from_uris() {
458 let tmp = tempfile::tempdir().unwrap();
459 let a = tmp.path().join("project_a");
460 let b = tmp.path().join("project_b");
461 std::fs::create_dir_all(&a).unwrap();
462 std::fs::create_dir_all(&b).unwrap();
463 std::fs::create_dir(a.join(".git")).unwrap();
464
465 let uris = vec![
466 format!("file://{}", a.display()),
467 format!("file://{}", b.display()),
468 ];
469
470 let paths: Vec<String> = uris.iter().filter_map(|u| uri_to_path(u)).collect();
471 assert_eq!(paths.len(), 2);
472 assert!(paths[0].contains("project_a"));
473 assert!(paths[1].contains("project_b"));
474
475 let best = best_root_from_uris(&uris).unwrap();
476 assert!(best.contains("project_a"));
477 }
478
479 #[test]
480 fn split_workspace_paths_comma_separated() {
481 assert_eq!(
482 split_workspace_paths("/home/u/proj-a,/home/u/proj-b"),
483 vec!["/home/u/proj-a".to_string(), "/home/u/proj-b".to_string()]
484 );
485 }
486
487 #[test]
488 fn split_workspace_paths_trims_and_drops_empty() {
489 assert_eq!(
490 split_workspace_paths(" /a , , /b ,"),
491 vec!["/a".to_string(), "/b".to_string()]
492 );
493 }
494
495 #[cfg(unix)]
496 #[test]
497 fn split_workspace_paths_unix_colon_delimiter() {
498 assert_eq!(
500 split_workspace_paths("/a:/b"),
501 vec!["/a".to_string(), "/b".to_string()]
502 );
503 }
504
505 #[test]
506 fn best_root_from_paths_prefers_marker_over_first() {
507 let tmp = tempfile::tempdir().unwrap();
508 let plain = tmp.path().join("plain");
509 let marked = tmp.path().join("marked");
510 std::fs::create_dir_all(&plain).unwrap();
511 std::fs::create_dir_all(&marked).unwrap();
512 std::fs::create_dir(marked.join(".git")).unwrap();
513 let got = best_root_from_paths(vec![
514 plain.to_string_lossy().to_string(),
515 marked.to_string_lossy().to_string(),
516 ])
517 .unwrap();
518 assert!(got.contains("marked"), "marker dir must win: {got}");
519 }
520
521 #[test]
522 fn best_root_from_paths_filters_nonexistent() {
523 let tmp = tempfile::tempdir().unwrap();
524 let safe = tmp.path().join("real_proj");
525 std::fs::create_dir_all(&safe).unwrap();
526 let got = best_root_from_paths(vec![
527 "/nonexistent_xyz_987".to_string(),
528 safe.to_string_lossy().to_string(),
529 ])
530 .unwrap();
531 assert!(got.contains("real_proj"));
532 }
533
534 #[test]
535 fn best_root_from_paths_empty_returns_none() {
536 assert!(best_root_from_paths(vec![]).is_none());
537 assert!(best_root_from_paths(vec!["/nonexistent_abc".to_string()]).is_none());
538 }
539
540 #[test]
541 fn workspace_env_value_picks_marker_root() {
542 let tmp = tempfile::tempdir().unwrap();
545 let a = tmp.path().join("ws_a");
546 let b = tmp.path().join("ws_b");
547 std::fs::create_dir_all(&a).unwrap();
548 std::fs::create_dir_all(&b).unwrap();
549 std::fs::write(b.join("Cargo.toml"), "[package]").unwrap();
550 let raw = format!("{},{}", a.display(), b.display());
551 let got = best_root_from_paths(split_workspace_paths(&raw)).unwrap();
552 assert!(got.contains("ws_b"), "marker workspace must win: {got}");
553 }
554
555 #[test]
556 fn stale_global_pin_yields_to_the_sessions_real_project() {
557 let tmp = tempfile::tempdir().unwrap();
558 let pinned = tmp.path().join("thinkery");
559 let actual = tmp.path().join("lean-ctx");
560 for dir in [&pinned, &actual] {
561 std::fs::create_dir_all(dir.join(".git")).unwrap();
562 }
563 let s = |p: &std::path::Path| p.to_string_lossy().to_string();
564
565 assert_eq!(
567 reconcile_session_root(Some(s(&pinned)), true, Some(s(&actual))),
568 Some(s(&actual))
569 );
570 assert_eq!(
572 reconcile_session_root(Some(s(&pinned)), false, Some(s(&actual))),
573 Some(s(&pinned))
574 );
575 let sub = pinned.join("crates/a");
577 std::fs::create_dir_all(sub.join(".git")).unwrap();
578 assert_eq!(
579 reconcile_session_root(Some(s(&pinned)), true, Some(s(&sub))),
580 Some(s(&pinned))
581 );
582 let bare = tmp.path().join("scratch");
584 std::fs::create_dir_all(&bare).unwrap();
585 assert_eq!(
586 reconcile_session_root(Some(s(&pinned)), true, Some(s(&bare))),
587 Some(s(&pinned))
588 );
589 assert_eq!(
590 reconcile_session_root(None, false, Some(s(&actual))),
591 Some(s(&actual))
592 );
593 }
594
595 #[test]
596 fn workspace_env_readers_do_not_panic() {
597 let _ = root_from_workspace_env();
599 let _ = workspace_roots_from_env();
600 }
601}