lean-ctx-server 3.12.1

The LeanCTX MCP server and its tools on top of LeanCTX | OSS.
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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
// SPDX-License-Identifier: Apache-2.0
pub mod admitted_sources;
pub mod autonomy;
pub mod ctx_agent;
pub mod ctx_architecture;
pub mod ctx_artifacts;
pub mod ctx_callgraph;
#[allow(dead_code, unreachable_pub)]
pub mod ctx_compile;
pub mod ctx_compose;
pub mod ctx_compress;
pub mod ctx_compress_memory;
pub mod ctx_context;
pub mod ctx_control;
pub mod ctx_cost;
pub mod ctx_dedup;
pub mod ctx_delta;
pub mod ctx_discover;
pub mod ctx_doc;
pub mod ctx_edit;
pub mod ctx_execute;
pub mod ctx_expand;
pub mod ctx_explore;
pub mod ctx_feedback;
pub mod ctx_gain;
pub mod ctx_glob;
pub mod ctx_graph;
pub mod ctx_graph_diagram;
pub mod ctx_graph_diff;
pub mod ctx_graph_primitives;
pub mod ctx_handoff;
pub mod ctx_heatmap;
pub mod ctx_impact;
pub mod ctx_index;
pub mod ctx_knowledge;
pub mod ctx_knowledge_relations;
pub mod ctx_metrics;
pub mod ctx_multi_read;
pub mod ctx_multi_repo;
pub mod ctx_outline;
pub mod ctx_overview;
pub mod ctx_pack;
pub mod ctx_package;
pub mod ctx_patch;
pub mod ctx_plan;
pub mod ctx_prefetch;
pub mod ctx_preload;
pub mod ctx_proof;
pub mod ctx_provider;
pub mod ctx_read;
pub mod ctx_refactor;
pub mod ctx_response;
pub mod ctx_search;
pub mod ctx_semantic_search;
pub mod ctx_session;
pub mod ctx_share;
pub mod ctx_shell;
pub mod ctx_skillify;
pub mod ctx_smart_read;
pub mod ctx_smells;
pub mod ctx_summary;
pub mod ctx_symbol;
pub mod ctx_tools;
pub mod ctx_transcript_compact;
pub mod ctx_tree;
pub mod ctx_verify;
pub mod ctx_work_graph;
pub(crate) mod edit_io;
pub(crate) mod edit_recovery;
pub(crate) mod graph_meta;
pub mod knowledge_shared;
pub(crate) mod output_format;
pub mod registered;
pub use lean_ctx::core::search_hook;
pub use lean_ctx::core::search_kernel;
#[cfg(test)]
mod store_admission_tests;
pub mod walk_guard;

mod server;
mod server_lifecycle;
pub use server_lifecycle::shutdown_stage;
mod server_metrics;
mod server_paths;
pub(crate) mod startup;

pub use server::*;
pub use startup::create_server;

#[cfg(test)]
mod resolve_path_tests {
    use super::startup::canonicalize_path;
    use super::*;

    fn create_git_root(path: &std::path::Path) -> String {
        std::fs::create_dir_all(path.join(".git")).unwrap();
        canonicalize_path(path)
    }

    #[cfg(not(feature = "no-jail"))]
    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn resolve_path_can_reroot_to_trusted_startup_root_when_session_root_is_stale() {
        // #991: serialize via `isolated_data_dir` (holds `test_env_lock`) so the
        // reroot test running in parallel (e.g. the `remove_var` in
        // `..._without_opt_in`) between set and `resolve_path` — which would
        // silently disable rerooting and flake this assertion. Cleaned up at the
        // end so the opt-in never leaks to other tests.
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let tmp = tempfile::tempdir().unwrap();
        let stale = tmp.path().join("stale");
        let real = tmp.path().join("real");
        std::fs::create_dir_all(&stale).unwrap();
        let real_root = create_git_root(&real);
        std::fs::write(real.join("a.txt"), "ok").unwrap();

        let server = LeanCtxServer::new_with_startup(
            None,
            Some(real.as_path()),
            SessionMode::Personal,
            "default",
            "default",
        );
        {
            let mut session = server.session.write().await;
            session.project_root = Some(stale.to_string_lossy().to_string());
            session.shell_cwd = Some(stale.to_string_lossy().to_string());
        }

        let out = server
            .resolve_path(&real.join("a.txt").to_string_lossy())
            .await
            .unwrap();

        assert!(out.ends_with("/a.txt"));

        let session = server.session.read().await;
        assert_eq!(session.project_root.as_deref(), Some(real_root.as_str()));
        assert_eq!(session.shell_cwd.as_deref(), Some(real_root.as_str()));
        drop(session);
    }
    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn resolve_path_reroots_from_markerless_stale_root_to_real_project() {
        // Universal auto-reroot: if session.project_root is markerless (stale),
        // accessing a path in a real project triggers reroot instead of rejection.
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let tmp = tempfile::tempdir().unwrap();
        let stale = tmp.path().join("stale");
        let root = tmp.path().join("root");
        let other = tmp.path().join("other");
        std::fs::create_dir_all(&stale).unwrap();
        create_git_root(&root);
        let _other_value = create_git_root(&other);
        std::fs::write(other.join("b.txt"), "no").unwrap();

        let server = LeanCtxServer::new_with_startup(
            None,
            Some(root.as_path()),
            SessionMode::Personal,
            "default",
            "default",
        );
        {
            let mut session = server.session.write().await;
            session.project_root = Some(stale.to_string_lossy().to_string());
            session.shell_cwd = Some(stale.to_string_lossy().to_string());
        }

        let resolved = server
            .resolve_path(&other.join("b.txt").to_string_lossy())
            .await
            .unwrap();
        assert!(
            resolved.contains("b.txt"),
            "should resolve after reroot: {resolved}"
        );

        let session = server.session.read().await;
        let actual = std::path::Path::new(session.project_root.as_deref().unwrap_or(""))
            .canonicalize()
            .unwrap_or_default();
        let expected = other.canonicalize().unwrap_or(other.clone());
        assert_eq!(actual, expected, "should have rerooted to real project");
    }

    /// AP04 review S4: a re-root goes through the session switch — the call
    /// continues in the corrected project's own session with a request
    /// project to match, and the stale session's data stays behind.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    #[allow(clippy::await_holding_lock)]
    async fn a_reroot_moves_the_call_and_leaves_the_stale_sessions_data_behind() {
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let tmp = tempfile::tempdir().unwrap();
        let stale = tmp.path().join("stale");
        std::fs::create_dir_all(&stale).unwrap();
        let repo = tmp.path().join("repo");
        let repo_root = create_git_root(&repo);
        std::fs::write(repo.join("a.txt"), "a").unwrap();
        let server = LeanCtxServer::new_with_startup(
            None,
            None,
            SessionMode::Personal,
            "default",
            "default",
        );
        {
            let mut session = server.session.write().await;
            session.project_root = Some(stale.to_string_lossy().to_string());
            session.shell_cwd = Some(stale.to_string_lossy().to_string());
            session.record_manual_evidence("ap04:stale", None);
        }

        let call = async {
            server.session.pin();
            server
                .resolve_path(&repo.join("a.txt").to_string_lossy())
                .await
                .unwrap();
            let project = lean_ctx::core::policy::runtime::REQUEST_PROJECT
                .with(|slot| slot.borrow().clone())
                .map(|project| project.to_string_lossy().into_owned());
            let bound = server.session.read().await;
            assert_eq!(bound.project_root.as_deref(), Some(repo_root.as_str()));
            assert_eq!(project, bound.project_root);
            assert!(bound.evidence.iter().all(|e| e.key != "ap04:stale"));
        };
        server
            .session
            .scope(
                lean_ctx::core::policy::runtime::REQUEST_PROJECT
                    .scope(std::cell::RefCell::new(Some(stale.clone())), call),
            )
            .await;
    }

    /// AP04 review S3: a path one client of a shared session names never
    /// re-roots that session, not even away from a markerless root.
    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn resolve_path_never_reroots_a_shared_session() {
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let tmp = tempfile::tempdir().unwrap();
        let markerless = tmp.path().join("shared");
        std::fs::create_dir_all(&markerless).unwrap();
        let repo = tmp.path().join("repo");
        create_git_root(&repo);
        std::fs::write(repo.join("a.txt"), "a").unwrap();
        let server =
            LeanCtxServer::new_shared_with_context(&markerless.to_string_lossy(), "ap04-s3", "s3");
        let root = server.session.read().await.project_root.clone();
        assert!(root.is_some());

        let _ = server
            .resolve_path(&repo.join("a.txt").to_string_lossy())
            .await;

        assert_eq!(server.session.read().await.project_root, root);
    }

    /// AP04-G6: the outermost marker above a path can be `~` itself (a
    /// dotfiles repository); a markerless session root is never rerooted to it.
    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn resolve_path_never_reroots_to_the_home_directory() {
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().join("home");
        create_git_root(&home);
        let home = home.canonicalize().unwrap();
        let stale = tmp.path().join("stale");
        std::fs::create_dir_all(&stale).unwrap();
        std::fs::create_dir_all(home.join("notes")).unwrap();
        std::fs::write(home.join("notes/a.md"), "notes").unwrap();
        let home_guard = lean_ctx::test_env::VarGuard::set("HOME", &home);

        let server = LeanCtxServer::new_with_startup(
            None,
            None,
            SessionMode::Personal,
            "default",
            "default",
        );
        let stale = stale.to_string_lossy().to_string();
        {
            let mut session = server.session.write().await;
            session.project_root = Some(stale.clone());
            session.shell_cwd = Some(stale.clone());
        }
        let _ = server
            .resolve_path(&home.join("notes/a.md").to_string_lossy())
            .await;
        drop(home_guard);

        let session = server.session.read().await;
        assert_eq!(session.project_root.as_deref(), Some(stale.as_str()));
    }

    #[cfg(not(feature = "no-jail"))]
    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn resolve_path_auto_registers_language_cache_and_serves_the_same_call() {
        // #899: reading dependency source in a language cache (here a Go module
        // cache outside the project) registers the cache as a read-only root
        // and resolves in the same call — no "retry", no config edit. Writes
        // into the cache stay denied.
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("project");
        create_git_root(&root);
        let dep = tmp.path().join("go/pkg/mod/example.com/lib@v1");
        std::fs::create_dir_all(&dep).unwrap();
        let file = dep.join("lib.go");
        std::fs::write(&file, "package lib").unwrap();

        let server = LeanCtxServer::new_with_startup(
            None,
            Some(root.as_path()),
            SessionMode::Personal,
            "default",
            "default",
        );
        {
            let mut session = server.session.write().await;
            session.project_root = Some(root.to_string_lossy().to_string());
            session.shell_cwd = Some(root.to_string_lossy().to_string());
        }

        let ok = server
            .resolve_path(&file.to_string_lossy())
            .await
            .unwrap_or_else(|e| panic!("first read of a cache file must resolve, got: {e}"));
        assert!(ok.ends_with("/lib.go"), "resolves the cache file: {ok}");
        assert!(
            lean_ctx::core::pathjail::is_read_only_path(&file),
            "the auto-registered cache stays read-only"
        );

        // A second read takes the ordinary path through the read allow-list.
        let again = server
            .resolve_path(&file.to_string_lossy())
            .await
            .unwrap_or_else(|e| panic!("second read must resolve, got: {e}"));
        assert_eq!(again, ok);
    }

    #[cfg(not(feature = "no-jail"))]
    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn resolve_path_auto_reroots_from_agent_config_dir_without_opt_in() {
        // #580: the MCP server is launched from an agent/IDE config dir
        // (~/.copilot-style) and wrongly adopts it as the root. With no
        // `allow_auto_reroot` opt-in and no trusted startup root, the first
        // absolute path into a real project must still correct the root — an
        // agent config dir is never a real jail boundary.
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let tmp = tempfile::tempdir().unwrap();
        let agent = tmp.path().join(".copilot");
        let real = tmp.path().join("repo");
        std::fs::create_dir_all(&agent).unwrap();
        let real_root = create_git_root(&real);
        std::fs::write(real.join("a.txt"), "ok").unwrap();

        let server = LeanCtxServer::new_with_startup(
            None,
            None,
            SessionMode::Personal,
            "default",
            "default",
        );
        {
            let mut session = server.session.write().await;
            session.project_root = Some(agent.to_string_lossy().to_string());
            session.shell_cwd = Some(agent.to_string_lossy().to_string());
        }

        let out = server
            .resolve_path(&real.join("a.txt").to_string_lossy())
            .await
            .unwrap();
        assert!(
            out.ends_with("/a.txt"),
            "agent-dir jail must auto-correct: {out}"
        );

        let session = server.session.read().await;
        assert_eq!(session.project_root.as_deref(), Some(real_root.as_str()));
    }

    #[cfg(not(feature = "no-jail"))]
    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn resolve_path_auto_reroots_from_markerless_client_cwd_without_opt_in() {
        // VS Code/WSL can launch the MCP server from /mnt/c/Users while the
        // workspace lives under /mnt/d. That markerless cwd must not become a
        // permanent PathJail root when the request points at a real project.
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let tmp = tempfile::tempdir().unwrap();
        let client_cwd = tmp.path().join("Users").join("user");
        let real = tmp.path().join("workspaces").join("lean-ctx");
        std::fs::create_dir_all(&client_cwd).unwrap();
        let real_root = create_git_root(&real);
        std::fs::write(real.join("rust.rs"), "ok").unwrap();

        let server = LeanCtxServer::new_with_startup(
            None,
            None,
            SessionMode::Personal,
            "default",
            "default",
        );
        {
            let mut session = server.session.write().await;
            session.project_root = Some(client_cwd.to_string_lossy().to_string());
            session.shell_cwd = Some(client_cwd.to_string_lossy().to_string());
        }

        let out = server
            .resolve_path(&real.join("rust.rs").to_string_lossy())
            .await
            .unwrap();
        assert!(
            out.ends_with("/rust.rs"),
            "markerless client cwd must auto-correct: {out}"
        );

        let session = server.session.read().await;
        assert_eq!(session.project_root.as_deref(), Some(real_root.as_str()));
    }

    #[cfg(not(feature = "no-jail"))]
    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn resolve_path_keeps_a_pinned_markerless_root_inside_a_checkout() {
        // A directory pinned with LEAN_CTX_PROJECT_ROOT that carries no marker
        // and lies inside a checkout stays the root: neither a path below it nor
        // one in the surrounding checkout may widen the jail to that checkout.
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let tmp = tempfile::tempdir().unwrap();
        let checkout = tmp.path().join("checkout");
        create_git_root(&checkout);
        let pinned = checkout.join("runs").join("one");
        std::fs::create_dir_all(&pinned).unwrap();
        std::fs::write(pinned.join("note.md"), "ok").unwrap();
        std::fs::write(checkout.join("outside.md"), "no").unwrap();
        let pinned_root = pinned.to_string_lossy().to_string();
        lean_ctx::test_env::set_var("LEAN_CTX_PROJECT_ROOT", &pinned_root);

        let server = LeanCtxServer::new_with_startup(
            None,
            None,
            SessionMode::Personal,
            "default",
            "default",
        );
        {
            let mut session = server.session.write().await;
            session.project_root = Some(pinned_root.clone());
            session.shell_cwd = Some(pinned_root.clone());
        }

        let inside = server
            .resolve_path(&pinned.join("note.md").to_string_lossy())
            .await;
        let outside = server
            .resolve_path(&checkout.join("outside.md").to_string_lossy())
            .await;
        let root = server.session.read().await.project_root.clone();
        lean_ctx::test_env::remove_var("LEAN_CTX_PROJECT_ROOT");

        assert!(inside.is_ok_and(|path| path.ends_with("/note.md")));
        assert!(outside.is_err(), "a path above the pin is refused");
        assert_eq!(root.as_deref(), Some(pinned_root.as_str()));
    }

    #[cfg(not(feature = "no-jail"))]
    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn resolve_path_auto_reroots_even_when_extra_root_allows_path() {
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let tmp = tempfile::tempdir().unwrap();
        let client_cwd = tmp.path().join("Users").join("user");
        let real = tmp.path().join("workspaces").join("lean-ctx");
        std::fs::create_dir_all(&client_cwd).unwrap();
        let real_root = create_git_root(&real);
        std::fs::write(real.join("rust.rs"), "ok").unwrap();

        let server = LeanCtxServer::new_with_startup(
            None,
            None,
            SessionMode::Personal,
            "default",
            "default",
        );
        {
            let mut session = server.session.write().await;
            session.project_root = Some(client_cwd.to_string_lossy().to_string());
            session.shell_cwd = Some(client_cwd.to_string_lossy().to_string());
            session.extra_roots.push(real_root.clone());
        }

        let out = server
            .resolve_path(&real.join("rust.rs").to_string_lossy())
            .await
            .unwrap();
        assert!(
            out.ends_with("/rust.rs"),
            "extra root must not suppress markerless-cwd reroot: {out}"
        );

        let session = server.session.read().await;
        assert_eq!(session.project_root.as_deref(), Some(real_root.as_str()));
        assert_eq!(session.shell_cwd.as_deref(), Some(real_root.as_str()));
    }

    #[cfg(not(feature = "no-jail"))]
    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn resolve_path_markerless_root_still_blocks_markerless_escape() {
        // #649 must not weaken PathJail: from a markerless client cwd, an absolute
        // path that derives NO project marker stays blocked and the root is
        // unchanged. Only rerooting *to a real project* is permitted.
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let tmp = tempfile::tempdir().unwrap();
        let client_cwd = tmp.path().join("Users").join("user");
        let loose = tmp.path().join("workspaces").join("loose");
        std::fs::create_dir_all(&client_cwd).unwrap();
        std::fs::create_dir_all(&loose).unwrap();
        std::fs::write(loose.join("data.txt"), "no").unwrap();

        let server = LeanCtxServer::new_with_startup(
            None,
            None,
            SessionMode::Personal,
            "default",
            "default",
        );
        {
            let mut session = server.session.write().await;
            session.project_root = Some(client_cwd.to_string_lossy().to_string());
            session.shell_cwd = Some(client_cwd.to_string_lossy().to_string());
        }

        let err = server
            .resolve_path(&loose.join("data.txt").to_string_lossy())
            .await
            .unwrap_err();
        assert!(err.contains("path escapes project root"), "got: {err}");

        let session = server.session.read().await;
        assert_eq!(
            session.project_root.as_deref(),
            Some(client_cwd.to_string_lossy().as_ref())
        );
    }

    #[cfg(not(feature = "no-jail"))]
    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn resolve_path_agent_dir_still_blocks_markerless_escape() {
        // The agent-dir bypass only reroots to a *real* project (one carrying a
        // marker). A markerless absolute path outside the jail stays blocked —
        // PathJail enforcement is unchanged, only the root *choice* is corrected.
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let tmp = tempfile::tempdir().unwrap();
        let agent = tmp.path().join(".copilot");
        let loose = tmp.path().join("loose");
        std::fs::create_dir_all(&agent).unwrap();
        std::fs::create_dir_all(&loose).unwrap();
        std::fs::write(loose.join("data.txt"), "no").unwrap();

        let server = LeanCtxServer::new_with_startup(
            None,
            None,
            SessionMode::Personal,
            "default",
            "default",
        );
        {
            let mut session = server.session.write().await;
            session.project_root = Some(agent.to_string_lossy().to_string());
            session.shell_cwd = Some(agent.to_string_lossy().to_string());
        }

        let err = server
            .resolve_path(&loose.join("data.txt").to_string_lossy())
            .await
            .unwrap_err();
        assert!(err.contains("path escapes project root"), "got: {err}");

        let session = server.session.read().await;
        assert_eq!(
            session.project_root.as_deref(),
            Some(agent.to_string_lossy().as_ref())
        );
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn startup_creates_fresh_session_scoped_to_workspace() {
        let _lock = lean_ctx::core::data_dir::test_env_lock();
        let _data = tempfile::tempdir().unwrap();
        let _tmp = tempfile::tempdir().unwrap();

        lean_ctx::test_env::set_var("LEAN_CTX_DATA_DIR", _data.path());

        let repo_b = _tmp.path().join("repo-b");
        let root_b = create_git_root(&repo_b);

        let server = LeanCtxServer::new_with_startup(
            None,
            Some(repo_b.as_path()),
            SessionMode::Personal,
            "default",
            "default",
        );
        lean_ctx::test_env::remove_var("LEAN_CTX_DATA_DIR");

        let session = server.session.read().await;
        // #1388: Personal mode creates a fresh PID-qualified session.
        // The workspace root is detected from startup_cwd, but task
        // starts empty (no cross-session state inheritance).
        assert_eq!(session.project_root.as_deref(), Some(root_b.as_str()));
        assert_eq!(session.shell_cwd.as_deref(), Some(root_b.as_str()));
        assert!(session.task.is_none());
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn startup_creates_fresh_session_for_new_workspace_and_preserves_subdir_cwd() {
        let _lock = lean_ctx::core::data_dir::test_env_lock();
        let _data = tempfile::tempdir().unwrap();
        let _tmp = tempfile::tempdir().unwrap();

        lean_ctx::test_env::set_var("LEAN_CTX_DATA_DIR", _data.path());

        let repo_a = _tmp.path().join("repo-a");
        let repo_b = _tmp.path().join("repo-b");
        let repo_b_src = repo_b.join("src");
        let root_a = create_git_root(&repo_a);
        let root_b = create_git_root(&repo_b);
        std::fs::create_dir_all(&repo_b_src).unwrap();
        let repo_b_src_value = canonicalize_path(&repo_b_src);

        let mut session_a = lean_ctx::core::session::SessionState::new();
        session_a.project_root = Some(root_a.clone());
        session_a.shell_cwd = Some(root_a.clone());
        session_a.set_task("repo-a latest task", None);
        let old_id = session_a.id.clone();
        session_a.save().unwrap();

        let server = LeanCtxServer::new_with_startup(
            None,
            Some(repo_b_src.as_path()),
            SessionMode::Personal,
            "default",
            "default",
        );
        lean_ctx::test_env::remove_var("LEAN_CTX_DATA_DIR");

        let session = server.session.read().await;
        assert_eq!(session.project_root.as_deref(), Some(root_b.as_str()));
        assert_eq!(
            session.shell_cwd.as_deref(),
            Some(repo_b_src_value.as_str())
        );
        assert!(session.task.is_none());
        assert_ne!(session.id, old_id);
    }

    #[cfg(not(feature = "no-jail"))]
    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn resolve_path_does_not_auto_update_when_current_root_is_real_project() {
        // Hermetic config + serialized via test_env_lock so a parallel test that
        // flips `path_jail` cannot disable this jail-enforcement assertion (#406).
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("root");
        let other = tmp.path().join("other");
        let root_value = create_git_root(&root);
        create_git_root(&other);
        std::fs::write(other.join("b.txt"), "no").unwrap();

        let root_str = root.to_string_lossy().to_string();
        let server = LeanCtxServer::new_with_project_root(Some(&root_str));

        let err = server
            .resolve_path(&other.join("b.txt").to_string_lossy())
            .await
            .unwrap_err();
        assert!(err.contains("path escapes project root"));

        let session = server.session.read().await;
        assert_eq!(session.project_root.as_deref(), Some(root_value.as_str()));
    }

    // #707: a mid-session worktree switch moves shell_cwd into a nested linked
    // worktree (own `.git` *file*) while project_root stays at initialize-time.
    // The path `src/lib.rs` deliberately also exists relative to the test
    // process CWD (`rust/`): the server's `p.exists()` probe used to
    // short-circuit on exactly that and serve the stale root copy before the
    // divergent-checkout precedence could apply.
    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn resolve_path_prefers_worktree_copy_after_mid_session_switch() {
        let _iso = lean_ctx::core::data_dir::isolated_data_dir();
        let tmp = tempfile::tempdir().unwrap();
        let repo = tmp.path().join("repo");
        let root_value = create_git_root(&repo);
        let wt = repo.join(".claude/worktrees/wt");
        std::fs::create_dir_all(wt.join("src")).unwrap();
        std::fs::write(wt.join(".git"), "gitdir: ../../../.git/worktrees/wt\n").unwrap();
        std::fs::create_dir_all(repo.join("src")).unwrap();
        std::fs::write(repo.join("src/lib.rs"), "stale").unwrap();
        std::fs::write(wt.join("src/lib.rs"), "fresh").unwrap();

        let server = LeanCtxServer::new_with_project_root(Some(&root_value));
        {
            // The worktree switch as ctx_shell's cwd tracking records it.
            let mut session = server.session.write().await;
            session.shell_cwd = Some(wt.to_string_lossy().to_string());
        }

        let out = server.resolve_path("src/lib.rs").await.unwrap();
        assert_eq!(
            std::fs::read_to_string(&out).unwrap(),
            "fresh",
            "worktree copy must win over the stale project_root copy: {out}"
        );

        // Switching back restores the established precedence: without
        // divergence the project_root fallback serves the root copy again.
        // Probed via a path that does NOT exist relative to the test process
        // CWD — `src/lib.rs` would hit the (intended) `p.exists()` fast path
        // and resolve to the real checkout's file, making the assertion
        // environment-dependent (that is exactly how CI diverged from local).
        {
            let mut session = server.session.write().await;
            session.shell_cwd = Some(root_value.clone());
        }
        std::fs::write(repo.join("src/back_707.rs"), "stale").unwrap();
        std::fs::write(wt.join("src/back_707.rs"), "fresh").unwrap();
        let out = server.resolve_path("src/back_707.rs").await.unwrap();
        assert_eq!(std::fs::read_to_string(&out).unwrap(), "stale");
    }
}