lean-ctx-engine 3.12.2

LeanCTX | OSS library: the open-source runtime for the Context Gateway for AI agents behind the lean-ctx CLI, MCP server and proxy integrations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
// SPDX-License-Identifier: Apache-2.0
use std::path::Path;

mod derive;
pub use derive::{derive_project_root_from, derive_project_root_from_cwd};

/// Parse a `file://` URI to a validated local path string.
/// Rejects non-file URIs, null bytes, `..` traversal, and non-directory paths.
/// Returns a canonicalized absolute path.
pub fn uri_to_path(uri: &str) -> Option<String> {
    let raw = uri.strip_prefix("file://")?;
    if raw.contains("%00") {
        return None;
    }
    let decoded = percent_decode(raw);
    if decoded.is_empty() || decoded.contains('\0') {
        return None;
    }
    // Windows `file:///C:/path` URIs strip to `/C:/path`, which is NOT an
    // absolute Windows path (no drive prefix at the start) and would be rejected
    // below — so on Windows+Cursor every workspace root failed to parse and the
    // session fell back to the home dir as project root (GL discussion #273:
    // "MCP root misconfigured (resolves to C:/Users/<user>)"). Drop the single
    // leading slash before the drive letter so it parses as `C:/path`. POSIX
    // paths keep their leading slash (on Unix `/C:/x` is a legitimate path).
    #[cfg(windows)]
    let decoded = if has_leading_slash_drive(&decoded) {
        decoded[1..].to_string()
    } else {
        decoded
    };
    let path = Path::new(&decoded);
    if !path.is_absolute() {
        return None;
    }
    let canonical = crate::core::pathutil::safe_canonicalize_or_self(path);
    let s = canonical.to_string_lossy().to_string();
    if s.is_empty() {
        return None;
    }
    Some(s)
}

fn percent_decode(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut chars = s.bytes();
    while let Some(b) = chars.next() {
        if b == b'%' {
            let hi = chars.next().and_then(hex_val);
            let lo = chars.next().and_then(hex_val);
            if let (Some(h), Some(l)) = (hi, lo) {
                let byte = h << 4 | l;
                if byte == 0 {
                    continue;
                }
                out.push(byte as char);
            } else {
                out.push('%');
            }
        } else {
            out.push(b as char);
        }
    }
    out
}

fn hex_val(b: u8) -> Option<u8> {
    match b {
        b'0'..=b'9' => Some(b - b'0'),
        b'a'..=b'f' => Some(b - b'a' + 10),
        b'A'..=b'F' => Some(b - b'A' + 10),
        _ => None,
    }
}

/// True for a `file://` URI path of the form `/C:/…` — a leading slash, an ASCII
/// drive letter, then a colon. This shape comes from a Windows
/// `file:///C:/path` URI and is not an absolute Windows path until the leading
/// slash is removed. Pure predicate so the logic is unit-tested on every
/// platform, even though it is only wired into [`uri_to_path`] on Windows
/// (`allow(dead_code)` elsewhere keeps `-D warnings` clean).
#[cfg_attr(not(windows), allow(dead_code))]
fn has_leading_slash_drive(p: &str) -> bool {
    let b = p.as_bytes();
    b.len() >= 3 && b[0] == b'/' && b[1].is_ascii_alphabetic() && b[2] == b':'
}

pub(super) fn has_project_marker(dir: &Path) -> bool {
    crate::core::pathutil::has_project_marker(dir)
}

/// Select the best project root from MCP client roots.
/// Only considers paths that are existing directories.
/// Prefers roots with project markers (.git, Cargo.toml, etc.).
/// Falls back to the first valid directory if none have markers — but never
/// accepts a broad/unsafe root (HOME, filesystem root, agent sandbox dirs),
/// which would otherwise contaminate sessions across projects.
pub fn best_root_from_uris(uris: &[String]) -> Option<String> {
    root_selection_from_uris(uris).map(|selection| selection.chosen_root)
}

/// [`best_root_from_uris`] with the other candidates, so a choice among
/// several roots can be named (AP04-G7).
pub fn root_selection_from_uris(
    uris: &[String],
) -> Option<crate::core::root_selection::RootSelection> {
    crate::core::root_selection::select_with_preferences(
        uris.iter().filter_map(|u| uri_to_path(u)).collect(),
    )
}

/// Pick the best project root from a list of candidate directory paths.
///
/// Prefers a path with a project marker (`.git`, `Cargo.toml`, …); otherwise
/// falls back to the first *safe* directory. A caller that reports its workspace
/// root as HOME (some do) must not turn HOME into the project root — that is the
/// root cause of cross-project session contamination — so a broad/unsafe root is
/// never accepted as a marker-less fallback. A root the user chose with
/// `lean-ctx project use` wins when it is among the candidates
/// (`core::root_selection`).
#[cfg(test)]
fn best_root_from_paths(paths: Vec<String>) -> Option<String> {
    crate::core::root_selection::select_with_preferences(paths).map(|s| s.chosen_root)
}

/// Filter and validate URIs to existing directories only.
pub fn valid_dir_paths_from_uris(uris: &[String]) -> Vec<String> {
    uris.iter()
        .filter_map(|u| uri_to_path(u))
        .filter(|p| Path::new(p).is_dir())
        .collect()
}

/// Detect project root from IDE-specific environment variables.
///
/// Priority (first match wins):
///   LEAN_CTX_PROJECT_ROOT — explicit override (user/CI)
///   CURSOR_PROJECT_DIR    — Cursor ≥ 3.7
///   CLAUDE_PROJECT_DIR    — Claude Code
///   WINDSURF_PROJECT_DIR  — Windsurf (Codeium)
///   TRAE_PROJECT_DIR      — Trae (ByteDance)
///   KIRO_PROJECT_DIR      — AWS Kiro
///   CODEX_SANDBOX_DIR     — Codex desktop sandbox
///   GIT_WORK_TREE         — git worktree env
pub fn root_from_env() -> Option<String> {
    const VARS: &[&str] = &[
        "LEAN_CTX_PROJECT_ROOT",
        "CURSOR_PROJECT_DIR",
        "CLAUDE_PROJECT_DIR",
        "WINDSURF_PROJECT_DIR",
        "TRAE_PROJECT_DIR",
        "KIRO_PROJECT_DIR",
        "CODEX_SANDBOX_DIR",
        "GIT_WORK_TREE",
    ];
    for var in VARS {
        if let Ok(val) = std::env::var(var) {
            let trimmed = val.trim().to_string();
            if !trimmed.is_empty()
                && Path::new(&trimmed).is_dir()
                && !crate::core::pathutil::is_broad_or_unsafe_root(Path::new(&trimmed))
            {
                return Some(trimmed);
            }
        }
    }
    None
}

/// The session's project root from the host env and the server's working dir.
///
/// `LEAN_CTX_PROJECT_ROOT` is a pin. Placed in a user-global agent config (as
/// builds before the pin heal did) it names one project for *every* session,
/// so a Codex session started in repo B silently ran against repo A. When the
/// server was started inside a different real project, that working directory
/// is this session's project and outranks the pin. Host-specific signals
/// (`CLAUDE_PROJECT_DIR`, workspace folders, …) are session-scoped already and
/// keep precedence; a cwd inside the pinned tree keeps the pin.
pub fn session_root(env_root: Option<String>, cwd_root: Option<String>) -> Option<String> {
    let pin = std::env::var("LEAN_CTX_PROJECT_ROOT")
        .ok()
        .map(|v| v.trim().to_string());
    let env_is_pin = env_root.is_some() && env_root == pin;
    reconcile_session_root(env_root, env_is_pin, cwd_root)
}

/// The CLI's project under a `LEAN_CTX_PROJECT_ROOT` pin: the same rule as a
/// session's — a command run inside another real project acts for that
/// project, not for the pinned one (AP04-G10).
pub(crate) fn reconcile_pinned_root(pin: String, cwd_root: Option<String>) -> String {
    reconcile_session_root(Some(pin.clone()), true, cwd_root).unwrap_or(pin)
}

fn reconcile_session_root(
    env_root: Option<String>,
    env_is_pin: bool,
    cwd_root: Option<String>,
) -> Option<String> {
    let cwd_root =
        cwd_root.filter(|cwd| !crate::core::pathutil::is_broad_or_unsafe_root(Path::new(cwd)));
    if let (true, Some(pin), Some(cwd)) = (env_is_pin, env_root.as_deref(), cwd_root.as_deref()) {
        let pin_path = crate::core::pathutil::safe_canonicalize_or_self(Path::new(pin));
        let cwd_path = crate::core::pathutil::safe_canonicalize_or_self(Path::new(cwd));
        let unrelated = !cwd_path.starts_with(&pin_path) && !pin_path.starts_with(&cwd_path);
        if unrelated && has_project_marker(&cwd_path) {
            tracing::warn!(
                "LEAN_CTX_PROJECT_ROOT pins {pin}, but this session started in project {cwd} — \
                 using {cwd}. Remove the pin from the agent's global MCP config \
                 (`lean-ctx doctor --fix`)."
            );
            return cwd_root;
        }
    }
    env_root.or(cwd_root)
}

/// The project root the operator pinned with `LEAN_CTX_PROJECT_ROOT`.
///
/// The IDE variables in [`root_from_env`] are hints a host injects and may
/// name an agent or sandbox directory; this one is set on purpose and is a
/// boundary. `Some` only under the conditions `root_from_env` accepts it.
pub fn pinned_root() -> Option<String> {
    let pinned = std::env::var("LEAN_CTX_PROJECT_ROOT").ok()?;
    let pinned = pinned.trim();
    (!pinned.is_empty()
        && Path::new(pinned).is_dir()
        && !crate::core::pathutil::is_broad_or_unsafe_root(Path::new(pinned)))
    .then(|| pinned.to_string())
}

/// Split a `WORKSPACE_FOLDER_PATHS` value into individual paths.
///
/// Cursor separates entries with `,` (observed). We also tolerate the OS
/// path-list delimiter for robustness — `;` on Windows (never `:`, which is part
/// of `C:` drive specs) and `:` on Unix (never part of a POSIX path).
fn split_workspace_paths(raw: &str) -> Vec<String> {
    let delims: &[char] = if cfg!(windows) {
        &[',', ';']
    } else {
        &[',', ':']
    };
    raw.split(delims)
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(ToString::to_string)
        .collect()
}

/// Best project root from the IDE-injected `WORKSPACE_FOLDER_PATHS` env var.
///
/// Cursor declares the MCP `roots` capability but does NOT implement
/// `roots/list` (it answers `-32601 Method not found`) and launches stdio MCP
/// servers with `cwd = /`. Without this signal the project root falls back to an
/// unsafe directory and relative tool paths resolve against the wrong tree
/// (#699). This variable is the Cursor-sanctioned way to learn the active
/// workspace folder(s). The same broad/unsafe-root guards as MCP roots apply.
///
/// Returned as the selection, with the other candidates, so a choice among
/// several folders can be named (AP04-G7).
pub fn workspace_selection_from_env() -> Option<crate::core::root_selection::RootSelection> {
    for var in ["WORKSPACE_FOLDER_PATHS", "VSCODE_WORKSPACE_FOLDER"] {
        if let Ok(raw) = std::env::var(var)
            && let Some(selection) =
                crate::core::root_selection::select_with_preferences(split_workspace_paths(&raw))
        {
            return Some(selection);
        }
    }
    None
}

/// All valid, safe workspace directories from `WORKSPACE_FOLDER_PATHS`.
///
/// Used to register the sibling folders of a multi-root workspace as extra
/// trusted roots, so explicit paths into them are not rejected by the path jail.
pub fn workspace_roots_from_env() -> Vec<String> {
    for var in ["WORKSPACE_FOLDER_PATHS", "VSCODE_WORKSPACE_FOLDER"] {
        if let Ok(raw) = std::env::var(var) {
            let paths: Vec<String> = split_workspace_paths(&raw)
                .into_iter()
                .filter(|p| Path::new(p).is_dir())
                .filter(|p| !crate::core::pathutil::is_broad_or_unsafe_root(Path::new(p)))
                .collect();
            if !paths.is_empty() {
                return paths;
            }
        }
    }
    Vec::new()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(unix)]
    #[test]
    fn parse_file_uri_unix() {
        assert_eq!(
            uri_to_path("file:///home/user/project"),
            Some("/home/user/project".to_string())
        );
    }

    #[cfg(unix)]
    #[test]
    fn parse_file_uri_windows() {
        assert_eq!(
            uri_to_path("file:///C:/Users/dev/project"),
            Some("/C:/Users/dev/project".to_string())
        );
    }

    #[cfg(unix)]
    #[test]
    fn parse_file_uri_with_spaces() {
        assert_eq!(
            uri_to_path("file:///home/user/my%20project"),
            Some("/home/user/my project".to_string())
        );
    }

    #[test]
    fn parse_non_file_uri_returns_none() {
        assert!(uri_to_path("https://example.com").is_none());
        assert!(uri_to_path("").is_none());
    }

    #[test]
    fn detects_leading_slash_windows_drive() {
        // GL #273: the `/C:/…` shape (from a Windows `file:///C:/…` URI) must be
        // recognised so the leading slash can be stripped. Runs on every
        // platform so Linux CI guards the logic the Windows-only wiring uses.
        assert!(has_leading_slash_drive("/C:/Users/dev"));
        assert!(has_leading_slash_drive("/c:/proj"));
        assert!(has_leading_slash_drive("/Z:"));
        // POSIX paths, already-stripped drives, UNC shares and root stay intact.
        assert!(!has_leading_slash_drive("/home/user/proj"));
        assert!(!has_leading_slash_drive("C:/already"));
        assert!(!has_leading_slash_drive("//server/share"));
        assert!(!has_leading_slash_drive("/"));
        assert!(!has_leading_slash_drive("/1:/x"));
    }

    #[cfg(windows)]
    #[test]
    fn parse_file_uri_windows_drive_strips_leading_slash() {
        // GL #273: Cursor on Windows reports roots as `file:///C:/…`; these must
        // parse to an absolute `C:/` path instead of being rejected (which left
        // the session falling back to the home dir as project root).
        let got = uri_to_path("file:///C:/Users/dev/project").expect("windows drive uri");
        assert!(
            !got.starts_with('/'),
            "leading slash must be stripped: {got}"
        );
        assert!(
            got.to_ascii_lowercase().starts_with("c:"),
            "drive prefix must survive: {got}"
        );
    }

    #[cfg(windows)]
    #[test]
    fn parse_file_uri_windows_percent_encoded_colon() {
        // Some clients percent-encode the drive colon (`C%3A`).
        let got = uri_to_path("file:///C%3A/Users/dev/project").expect("encoded colon uri");
        assert!(
            !got.starts_with('/'),
            "leading slash must be stripped: {got}"
        );
        assert!(got.to_ascii_lowercase().starts_with("c:"), "got: {got}");
    }

    #[test]
    fn rejects_null_bytes() {
        assert!(uri_to_path("file:///tmp/evil%00path").is_none());
    }

    #[test]
    fn rejects_relative_uri() {
        assert!(uri_to_path("file://relative/path").is_none());
    }

    #[test]
    fn canonicalizes_traversal() {
        let tmp = tempfile::tempdir().unwrap();
        let sub = tmp.path().join("a").join("b");
        std::fs::create_dir_all(&sub).unwrap();
        let traversal = format!("file://{}/a/b/../..", tmp.path().display());
        let result = uri_to_path(&traversal);
        assert!(result.is_some());
        let resolved = result.unwrap();
        assert!(
            !resolved.contains(".."),
            "should be canonicalized: {resolved}"
        );
    }

    #[test]
    fn best_root_prefers_marker() {
        let tmp = tempfile::tempdir().unwrap();
        let with_marker = tmp.path().join("has_git");
        let without = tmp.path().join("plain");
        std::fs::create_dir_all(&with_marker).unwrap();
        std::fs::create_dir_all(&without).unwrap();
        std::fs::create_dir(with_marker.join(".git")).unwrap();

        let uris = vec![
            format!("file://{}", without.display()),
            format!("file://{}", with_marker.display()),
        ];
        let result = best_root_from_uris(&uris).unwrap();
        assert!(result.contains("has_git"));
    }

    #[test]
    fn best_root_falls_back_to_first_existing_dir() {
        let tmp = tempfile::tempdir().unwrap();
        let a = tmp.path().join("dir_a");
        let b = tmp.path().join("dir_b");
        std::fs::create_dir_all(&a).unwrap();
        std::fs::create_dir_all(&b).unwrap();

        let uris = vec![
            format!("file://{}", a.display()),
            format!("file://{}", b.display()),
        ];
        let result = best_root_from_uris(&uris).unwrap();
        assert!(result.contains("dir_a"));
    }

    #[test]
    fn best_root_skips_nonexistent() {
        let uris = vec!["file:///nonexistent_abc_123".to_string()];
        assert!(best_root_from_uris(&uris).is_none());
    }

    #[test]
    fn best_root_empty_returns_none() {
        assert!(best_root_from_uris(&[]).is_none());
    }

    #[test]
    fn env_override_returns_none_when_unset() {
        let _ = root_from_env();
    }

    #[test]
    fn best_root_rejects_home_without_marker() {
        let _home = crate::core::data_dir::test_env_lock();
        // A client reporting HOME as its workspace root must NOT turn HOME into
        // the project root (root cause of cross-project session contamination).
        if let Some(home) = dirs::home_dir() {
            let uris = vec![format!("file://{}", home.display())];
            assert_eq!(
                best_root_from_uris(&uris),
                None,
                "HOME must never be accepted as a marker-less project root"
            );
        }
    }

    #[test]
    fn best_root_prefers_safe_dir_over_home() {
        let _home = crate::core::data_dir::test_env_lock();
        if let Some(home) = dirs::home_dir() {
            let tmp = tempfile::tempdir().unwrap();
            let safe = tmp.path().join("real_project");
            std::fs::create_dir_all(&safe).unwrap();
            let uris = vec![
                format!("file://{}", home.display()),
                format!("file://{}", safe.display()),
            ];
            let result = best_root_from_uris(&uris).unwrap();
            assert!(result.contains("real_project"));
        }
    }

    #[test]
    fn best_root_rejects_filesystem_root() {
        let uris = vec!["file:///".to_string()];
        assert!(best_root_from_uris(&uris).is_none());
    }

    #[test]
    fn all_paths_from_uris() {
        let tmp = tempfile::tempdir().unwrap();
        let a = tmp.path().join("project_a");
        let b = tmp.path().join("project_b");
        std::fs::create_dir_all(&a).unwrap();
        std::fs::create_dir_all(&b).unwrap();
        std::fs::create_dir(a.join(".git")).unwrap();

        let uris = vec![
            format!("file://{}", a.display()),
            format!("file://{}", b.display()),
        ];

        let paths: Vec<String> = uris.iter().filter_map(|u| uri_to_path(u)).collect();
        assert_eq!(paths.len(), 2);
        assert!(paths[0].contains("project_a"));
        assert!(paths[1].contains("project_b"));

        let best = best_root_from_uris(&uris).unwrap();
        assert!(best.contains("project_a"));
    }

    #[test]
    fn split_workspace_paths_comma_separated() {
        assert_eq!(
            split_workspace_paths("/home/u/proj-a,/home/u/proj-b"),
            vec!["/home/u/proj-a".to_string(), "/home/u/proj-b".to_string()]
        );
    }

    #[test]
    fn split_workspace_paths_trims_and_drops_empty() {
        assert_eq!(
            split_workspace_paths(" /a , , /b ,"),
            vec!["/a".to_string(), "/b".to_string()]
        );
    }

    #[cfg(unix)]
    #[test]
    fn split_workspace_paths_unix_colon_delimiter() {
        // Unix path-list delimiter is ':'; POSIX paths never contain it.
        assert_eq!(
            split_workspace_paths("/a:/b"),
            vec!["/a".to_string(), "/b".to_string()]
        );
    }

    #[test]
    fn best_root_from_paths_prefers_marker_over_first() {
        let tmp = tempfile::tempdir().unwrap();
        let plain = tmp.path().join("plain");
        let marked = tmp.path().join("marked");
        std::fs::create_dir_all(&plain).unwrap();
        std::fs::create_dir_all(&marked).unwrap();
        std::fs::create_dir(marked.join(".git")).unwrap();
        let got = best_root_from_paths(vec![
            plain.to_string_lossy().to_string(),
            marked.to_string_lossy().to_string(),
        ])
        .unwrap();
        assert!(got.contains("marked"), "marker dir must win: {got}");
    }

    #[test]
    fn best_root_from_paths_filters_nonexistent() {
        let tmp = tempfile::tempdir().unwrap();
        let safe = tmp.path().join("real_proj");
        std::fs::create_dir_all(&safe).unwrap();
        let got = best_root_from_paths(vec![
            "/nonexistent_xyz_987".to_string(),
            safe.to_string_lossy().to_string(),
        ])
        .unwrap();
        assert!(got.contains("real_proj"));
    }

    #[test]
    fn best_root_from_paths_empty_returns_none() {
        assert!(best_root_from_paths(vec![]).is_none());
        assert!(best_root_from_paths(vec!["/nonexistent_abc".to_string()]).is_none());
    }

    #[test]
    fn workspace_env_value_picks_marker_root() {
        // Mirrors Cursor's `WORKSPACE_FOLDER_PATHS` (comma-separated multi-root):
        // the folder carrying a project marker must win over a sibling.
        let tmp = tempfile::tempdir().unwrap();
        let a = tmp.path().join("ws_a");
        let b = tmp.path().join("ws_b");
        std::fs::create_dir_all(&a).unwrap();
        std::fs::create_dir_all(&b).unwrap();
        std::fs::write(b.join("Cargo.toml"), "[package]").unwrap();
        let raw = format!("{},{}", a.display(), b.display());
        let got = best_root_from_paths(split_workspace_paths(&raw)).unwrap();
        assert!(got.contains("ws_b"), "marker workspace must win: {got}");
    }

    #[test]
    fn stale_global_pin_yields_to_the_sessions_real_project() {
        let tmp = tempfile::tempdir().unwrap();
        let pinned = tmp.path().join("thinkery");
        let actual = tmp.path().join("lean-ctx");
        for dir in [&pinned, &actual] {
            std::fs::create_dir_all(dir.join(".git")).unwrap();
        }
        let s = |p: &std::path::Path| p.to_string_lossy().to_string();

        // Pin from a global config + server started in another real project.
        assert_eq!(
            reconcile_session_root(Some(s(&pinned)), true, Some(s(&actual))),
            Some(s(&actual))
        );
        // A host-specific (session-scoped) env root is never overridden.
        assert_eq!(
            reconcile_session_root(Some(s(&pinned)), false, Some(s(&actual))),
            Some(s(&pinned))
        );
        // A cwd inside the pinned tree keeps the pin (monorepo subdir).
        let sub = pinned.join("crates/a");
        std::fs::create_dir_all(sub.join(".git")).unwrap();
        assert_eq!(
            reconcile_session_root(Some(s(&pinned)), true, Some(s(&sub))),
            Some(s(&pinned))
        );
        // A markerless cwd is no evidence against the pin.
        let bare = tmp.path().join("scratch");
        std::fs::create_dir_all(&bare).unwrap();
        assert_eq!(
            reconcile_session_root(Some(s(&pinned)), true, Some(s(&bare))),
            Some(s(&pinned))
        );
        assert_eq!(
            reconcile_session_root(None, false, Some(s(&actual))),
            Some(s(&actual))
        );
    }

    #[test]
    fn workspace_env_readers_do_not_panic() {
        // Smoke test: both env readers tolerate the variable being set or unset.
        let _ = workspace_selection_from_env();
        let _ = workspace_roots_from_env();
    }
}