Skip to main content

lean_ctx/server/
roots.rs

1use std::path::Path;
2
3/// Parse a `file://` URI to a validated local path string.
4/// Rejects non-file URIs, null bytes, `..` traversal, and non-directory paths.
5/// Returns a canonicalized absolute path.
6pub 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    // Windows `file:///C:/path` URIs strip to `/C:/path`, which is NOT an
16    // absolute Windows path (no drive prefix at the start) and would be rejected
17    // below — so on Windows+Cursor every workspace root failed to parse and the
18    // session fell back to the home dir as project root (GL discussion #273:
19    // "MCP root misconfigured (resolves to C:/Users/<user>)"). Drop the single
20    // leading slash before the drive letter so it parses as `C:/path`. POSIX
21    // paths keep their leading slash (on Unix `/C:/x` is a legitimate path).
22    #[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/// True for a `file://` URI path of the form `/C:/…` — a leading slash, an ASCII
73/// drive letter, then a colon. This shape comes from a Windows
74/// `file:///C:/path` URI and is not an absolute Windows path until the leading
75/// slash is removed. Pure predicate so the logic is unit-tested on every
76/// platform, even though it is only wired into [`uri_to_path`] on Windows
77/// (`allow(dead_code)` elsewhere keeps `-D warnings` clean).
78#[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
88/// Select the best project root from MCP client roots.
89/// Only considers paths that are existing directories.
90/// Prefers roots with project markers (.git, Cargo.toml, etc.).
91/// Falls back to the first valid directory if none have markers — but never
92/// accepts a broad/unsafe root (HOME, filesystem root, agent sandbox dirs),
93/// which would otherwise contaminate sessions across projects.
94pub 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
98/// Pick the best project root from a list of candidate directory paths.
99///
100/// Prefers a path with a project marker (`.git`, `Cargo.toml`, …); otherwise
101/// falls back to the first *safe* directory. A caller that reports its workspace
102/// root as HOME (some do) must not turn HOME into the project root — that is the
103/// root cause of cross-project session contamination — so a broad/unsafe root is
104/// never accepted as a marker-less fallback.
105fn 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
126/// Filter and validate URIs to existing directories only.
127pub 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
134/// Detect project root from IDE-specific environment variables.
135///
136/// Priority (first match wins):
137///   LEAN_CTX_PROJECT_ROOT — explicit override (user/CI)
138///   CURSOR_PROJECT_DIR    — Cursor ≥ 3.7
139///   CLAUDE_PROJECT_DIR    — Claude Code
140///   WINDSURF_PROJECT_DIR  — Windsurf (Codeium)
141///   TRAE_PROJECT_DIR      — Trae (ByteDance)
142///   KIRO_PROJECT_DIR      — AWS Kiro
143///   CODEX_SANDBOX_DIR     — Codex desktop sandbox
144///   GIT_WORK_TREE         — git worktree env
145pub 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
170/// The session's project root from the host env and the server's working dir.
171///
172/// `LEAN_CTX_PROJECT_ROOT` is a pin. Placed in a user-global agent config (as
173/// builds before the pin heal did) it names one project for *every* session,
174/// so a Codex session started in repo B silently ran against repo A. When the
175/// server was started inside a different real project, that working directory
176/// is this session's project and outranks the pin. Host-specific signals
177/// (`CLAUDE_PROJECT_DIR`, workspace folders, …) are session-scoped already and
178/// keep precedence; a cwd inside the pinned tree keeps the pin.
179pub 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
208/// Split a `WORKSPACE_FOLDER_PATHS` value into individual paths.
209///
210/// Cursor separates entries with `,` (observed). We also tolerate the OS
211/// path-list delimiter for robustness — `;` on Windows (never `:`, which is part
212/// of `C:` drive specs) and `:` on Unix (never part of a POSIX path).
213fn 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
226/// Best project root from the IDE-injected `WORKSPACE_FOLDER_PATHS` env var.
227///
228/// Cursor declares the MCP `roots` capability but does NOT implement
229/// `roots/list` (it answers `-32601 Method not found`) and launches stdio MCP
230/// servers with `cwd = /`. Without this signal the project root falls back to an
231/// unsafe directory and relative tool paths resolve against the wrong tree
232/// (#699). This variable is the Cursor-sanctioned way to learn the active
233/// workspace folder(s). The same broad/unsafe-root guards as MCP roots apply.
234pub 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
245/// All valid, safe workspace directories from `WORKSPACE_FOLDER_PATHS`.
246///
247/// Used to register the sibling folders of a multi-root workspace as extra
248/// trusted roots, so explicit paths into them are not rejected by the path jail.
249pub 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        // GL #273: the `/C:/…` shape (from a Windows `file:///C:/…` URI) must be
305        // recognised so the leading slash can be stripped. Runs on every
306        // platform so Linux CI guards the logic the Windows-only wiring uses.
307        assert!(has_leading_slash_drive("/C:/Users/dev"));
308        assert!(has_leading_slash_drive("/c:/proj"));
309        assert!(has_leading_slash_drive("/Z:"));
310        // POSIX paths, already-stripped drives, UNC shares and root stay intact.
311        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        // GL #273: Cursor on Windows reports roots as `file:///C:/…`; these must
322        // parse to an absolute `C:/` path instead of being rejected (which left
323        // the session falling back to the home dir as project root).
324        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        // Some clients percent-encode the drive colon (`C%3A`).
339        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        // A client reporting HOME as its workspace root must NOT turn HOME into
424        // the project root (root cause of cross-project session contamination).
425        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        // Unix path-list delimiter is ':'; POSIX paths never contain it.
499        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        // Mirrors Cursor's `WORKSPACE_FOLDER_PATHS` (comma-separated multi-root):
543        // the folder carrying a project marker must win over a sibling.
544        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        // Pin from a global config + server started in another real project.
566        assert_eq!(
567            reconcile_session_root(Some(s(&pinned)), true, Some(s(&actual))),
568            Some(s(&actual))
569        );
570        // A host-specific (session-scoped) env root is never overridden.
571        assert_eq!(
572            reconcile_session_root(Some(s(&pinned)), false, Some(s(&actual))),
573            Some(s(&pinned))
574        );
575        // A cwd inside the pinned tree keeps the pin (monorepo subdir).
576        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        // A markerless cwd is no evidence against the pin.
583        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        // Smoke test: both env readers tolerate the variable being set or unset.
598        let _ = root_from_workspace_env();
599        let _ = workspace_roots_from_env();
600    }
601}