Skip to main content

lean_ctx/tools/
mod.rs

1pub(crate) mod admitted_sources;
2pub mod autonomy;
3pub mod ctx_agent;
4pub mod ctx_architecture;
5pub mod ctx_artifacts;
6pub mod ctx_callgraph;
7#[allow(dead_code, unreachable_pub)]
8pub mod ctx_compile;
9pub mod ctx_compose;
10pub mod ctx_compress;
11pub mod ctx_compress_memory;
12pub mod ctx_context;
13pub mod ctx_control;
14pub mod ctx_cost;
15pub mod ctx_dedup;
16pub mod ctx_delta;
17pub mod ctx_discover;
18pub mod ctx_edit;
19pub mod ctx_execute;
20pub mod ctx_expand;
21pub mod ctx_explore;
22pub mod ctx_feedback;
23pub mod ctx_gain;
24pub mod ctx_glob;
25pub mod ctx_graph;
26pub mod ctx_graph_diagram;
27pub mod ctx_graph_diff;
28pub mod ctx_graph_primitives;
29pub mod ctx_handoff;
30pub mod ctx_heatmap;
31pub mod ctx_impact;
32pub mod ctx_index;
33pub mod ctx_knowledge;
34pub mod ctx_knowledge_relations;
35pub mod ctx_metrics;
36pub mod ctx_multi_read;
37pub mod ctx_multi_repo;
38pub mod ctx_outline;
39pub mod ctx_overview;
40pub mod ctx_pack;
41pub mod ctx_package;
42pub mod ctx_patch;
43pub mod ctx_plan;
44pub mod ctx_prefetch;
45pub mod ctx_preload;
46pub mod ctx_proof;
47pub mod ctx_provider;
48pub mod ctx_read;
49pub mod ctx_refactor;
50pub mod ctx_response;
51pub mod ctx_search;
52pub mod ctx_semantic_search;
53pub mod ctx_session;
54pub mod ctx_share;
55pub mod ctx_shell;
56pub mod ctx_skillify;
57pub mod ctx_smart_read;
58pub mod ctx_smells;
59pub mod ctx_summary;
60pub mod ctx_symbol;
61pub(crate) mod ctx_tasks_swarm;
62pub mod ctx_tools;
63pub mod ctx_transcript_compact;
64pub mod ctx_tree;
65pub mod ctx_verify;
66pub mod ctx_work_graph;
67pub(crate) mod edit_io;
68pub(crate) mod edit_recovery;
69pub(crate) mod graph_meta;
70pub(crate) mod knowledge_shared;
71pub(crate) mod output_format;
72pub mod registered;
73pub mod search_hook;
74pub mod search_kernel;
75pub(crate) mod walk_guard;
76
77mod server;
78mod server_lifecycle;
79pub(crate) use server_lifecycle::shutdown_stage;
80mod server_metrics;
81mod server_paths;
82pub(crate) mod startup;
83
84pub use server::*;
85pub use startup::create_server;
86
87#[cfg(test)]
88mod resolve_path_tests {
89    use super::startup::canonicalize_path;
90    use super::*;
91
92    fn create_git_root(path: &std::path::Path) -> String {
93        std::fs::create_dir_all(path.join(".git")).unwrap();
94        canonicalize_path(path)
95    }
96
97    #[cfg(not(feature = "no-jail"))]
98    #[tokio::test]
99    #[allow(clippy::await_holding_lock)]
100    async fn resolve_path_can_reroot_to_trusted_startup_root_when_session_root_is_stale() {
101        // #991: serialize via `isolated_data_dir` (holds `test_env_lock`) so the
102        // reroot test running in parallel (e.g. the `remove_var` in
103        // `..._without_opt_in`) between set and `resolve_path` — which would
104        // silently disable rerooting and flake this assertion. Cleaned up at the
105        // end so the opt-in never leaks to other tests.
106        let _iso = crate::core::data_dir::isolated_data_dir();
107        let tmp = tempfile::tempdir().unwrap();
108        let stale = tmp.path().join("stale");
109        let real = tmp.path().join("real");
110        std::fs::create_dir_all(&stale).unwrap();
111        let real_root = create_git_root(&real);
112        std::fs::write(real.join("a.txt"), "ok").unwrap();
113
114        let server = LeanCtxServer::new_with_startup(
115            None,
116            Some(real.as_path()),
117            SessionMode::Personal,
118            "default",
119            "default",
120        );
121        {
122            let mut session = server.session.write().await;
123            session.project_root = Some(stale.to_string_lossy().to_string());
124            session.shell_cwd = Some(stale.to_string_lossy().to_string());
125        }
126
127        let out = server
128            .resolve_path(&real.join("a.txt").to_string_lossy())
129            .await
130            .unwrap();
131
132        assert!(out.ends_with("/a.txt"));
133
134        let session = server.session.read().await;
135        assert_eq!(session.project_root.as_deref(), Some(real_root.as_str()));
136        assert_eq!(session.shell_cwd.as_deref(), Some(real_root.as_str()));
137        drop(session);
138    }
139    #[tokio::test]
140    #[allow(clippy::await_holding_lock)]
141    async fn resolve_path_reroots_from_markerless_stale_root_to_real_project() {
142        // Universal auto-reroot: if session.project_root is markerless (stale),
143        // accessing a path in a real project triggers reroot instead of rejection.
144        let _iso = crate::core::data_dir::isolated_data_dir();
145        let tmp = tempfile::tempdir().unwrap();
146        let stale = tmp.path().join("stale");
147        let root = tmp.path().join("root");
148        let other = tmp.path().join("other");
149        std::fs::create_dir_all(&stale).unwrap();
150        create_git_root(&root);
151        let _other_value = create_git_root(&other);
152        std::fs::write(other.join("b.txt"), "no").unwrap();
153
154        let server = LeanCtxServer::new_with_startup(
155            None,
156            Some(root.as_path()),
157            SessionMode::Personal,
158            "default",
159            "default",
160        );
161        {
162            let mut session = server.session.write().await;
163            session.project_root = Some(stale.to_string_lossy().to_string());
164            session.shell_cwd = Some(stale.to_string_lossy().to_string());
165        }
166
167        let resolved = server
168            .resolve_path(&other.join("b.txt").to_string_lossy())
169            .await
170            .unwrap();
171        assert!(
172            resolved.contains("b.txt"),
173            "should resolve after reroot: {resolved}"
174        );
175
176        let session = server.session.read().await;
177        let actual = std::path::Path::new(session.project_root.as_deref().unwrap_or(""))
178            .canonicalize()
179            .unwrap_or_default();
180        let expected = other.canonicalize().unwrap_or(other.clone());
181        assert_eq!(actual, expected, "should have rerooted to real project");
182    }
183
184    /// AP04 review S4: a re-root goes through the session switch — the call
185    /// continues in the corrected project's own session with a request
186    /// project to match, and the stale session's data stays behind.
187    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
188    #[allow(clippy::await_holding_lock)]
189    async fn a_reroot_moves_the_call_and_leaves_the_stale_sessions_data_behind() {
190        let _iso = crate::core::data_dir::isolated_data_dir();
191        let tmp = tempfile::tempdir().unwrap();
192        let stale = tmp.path().join("stale");
193        std::fs::create_dir_all(&stale).unwrap();
194        let repo = tmp.path().join("repo");
195        let repo_root = create_git_root(&repo);
196        std::fs::write(repo.join("a.txt"), "a").unwrap();
197        let server = LeanCtxServer::new_with_startup(
198            None,
199            None,
200            SessionMode::Personal,
201            "default",
202            "default",
203        );
204        {
205            let mut session = server.session.write().await;
206            session.project_root = Some(stale.to_string_lossy().to_string());
207            session.shell_cwd = Some(stale.to_string_lossy().to_string());
208            session.record_manual_evidence("ap04:stale", None);
209        }
210
211        let call = async {
212            server.session.pin();
213            server
214                .resolve_path(&repo.join("a.txt").to_string_lossy())
215                .await
216                .unwrap();
217            let project = crate::core::policy::runtime::REQUEST_PROJECT
218                .with(|slot| slot.borrow().clone())
219                .map(|project| project.to_string_lossy().into_owned());
220            let bound = server.session.read().await;
221            assert_eq!(bound.project_root.as_deref(), Some(repo_root.as_str()));
222            assert_eq!(project, bound.project_root);
223            assert!(bound.evidence.iter().all(|e| e.key != "ap04:stale"));
224        };
225        server
226            .session
227            .scope(
228                crate::core::policy::runtime::REQUEST_PROJECT
229                    .scope(std::cell::RefCell::new(Some(stale.clone())), call),
230            )
231            .await;
232    }
233
234    /// AP04 review S3: a path one client of a shared session names never
235    /// re-roots that session, not even away from a markerless root.
236    #[tokio::test]
237    #[allow(clippy::await_holding_lock)]
238    async fn resolve_path_never_reroots_a_shared_session() {
239        let _iso = crate::core::data_dir::isolated_data_dir();
240        let tmp = tempfile::tempdir().unwrap();
241        let markerless = tmp.path().join("shared");
242        std::fs::create_dir_all(&markerless).unwrap();
243        let repo = tmp.path().join("repo");
244        create_git_root(&repo);
245        std::fs::write(repo.join("a.txt"), "a").unwrap();
246        let server =
247            LeanCtxServer::new_shared_with_context(&markerless.to_string_lossy(), "ap04-s3", "s3");
248        let root = server.session.read().await.project_root.clone();
249        assert!(root.is_some());
250
251        let _ = server
252            .resolve_path(&repo.join("a.txt").to_string_lossy())
253            .await;
254
255        assert_eq!(server.session.read().await.project_root, root);
256    }
257
258    /// AP04-G6: the outermost marker above a path can be `~` itself (a
259    /// dotfiles repository); a markerless session root is never rerooted to it.
260    #[tokio::test]
261    #[allow(clippy::await_holding_lock)]
262    async fn resolve_path_never_reroots_to_the_home_directory() {
263        let _iso = crate::core::data_dir::isolated_data_dir();
264        let tmp = tempfile::tempdir().unwrap();
265        let home = tmp.path().join("home");
266        create_git_root(&home);
267        let home = home.canonicalize().unwrap();
268        let stale = tmp.path().join("stale");
269        std::fs::create_dir_all(&stale).unwrap();
270        std::fs::create_dir_all(home.join("notes")).unwrap();
271        std::fs::write(home.join("notes/a.md"), "notes").unwrap();
272        let home_guard = crate::test_env::VarGuard::set("HOME", &home);
273
274        let server = LeanCtxServer::new_with_startup(
275            None,
276            None,
277            SessionMode::Personal,
278            "default",
279            "default",
280        );
281        let stale = stale.to_string_lossy().to_string();
282        {
283            let mut session = server.session.write().await;
284            session.project_root = Some(stale.clone());
285            session.shell_cwd = Some(stale.clone());
286        }
287        let _ = server
288            .resolve_path(&home.join("notes/a.md").to_string_lossy())
289            .await;
290        drop(home_guard);
291
292        let session = server.session.read().await;
293        assert_eq!(session.project_root.as_deref(), Some(stale.as_str()));
294    }
295
296    #[cfg(not(feature = "no-jail"))]
297    #[tokio::test]
298    #[allow(clippy::await_holding_lock)]
299    async fn resolve_path_auto_registers_language_cache_and_serves_the_same_call() {
300        // #899: reading dependency source in a language cache (here a Go module
301        // cache outside the project) registers the cache as a read-only root
302        // and resolves in the same call — no "retry", no config edit. Writes
303        // into the cache stay denied.
304        let _iso = crate::core::data_dir::isolated_data_dir();
305        let tmp = tempfile::tempdir().unwrap();
306        let root = tmp.path().join("project");
307        create_git_root(&root);
308        let dep = tmp.path().join("go/pkg/mod/example.com/lib@v1");
309        std::fs::create_dir_all(&dep).unwrap();
310        let file = dep.join("lib.go");
311        std::fs::write(&file, "package lib").unwrap();
312
313        let server = LeanCtxServer::new_with_startup(
314            None,
315            Some(root.as_path()),
316            SessionMode::Personal,
317            "default",
318            "default",
319        );
320        {
321            let mut session = server.session.write().await;
322            session.project_root = Some(root.to_string_lossy().to_string());
323            session.shell_cwd = Some(root.to_string_lossy().to_string());
324        }
325
326        let ok = server
327            .resolve_path(&file.to_string_lossy())
328            .await
329            .unwrap_or_else(|e| panic!("first read of a cache file must resolve, got: {e}"));
330        assert!(ok.ends_with("/lib.go"), "resolves the cache file: {ok}");
331        assert!(
332            crate::core::pathjail::is_read_only_path(&file),
333            "the auto-registered cache stays read-only"
334        );
335
336        // A second read takes the ordinary path through the read allow-list.
337        let again = server
338            .resolve_path(&file.to_string_lossy())
339            .await
340            .unwrap_or_else(|e| panic!("second read must resolve, got: {e}"));
341        assert_eq!(again, ok);
342    }
343
344    #[cfg(not(feature = "no-jail"))]
345    #[tokio::test]
346    #[allow(clippy::await_holding_lock)]
347    async fn resolve_path_auto_reroots_from_agent_config_dir_without_opt_in() {
348        // #580: the MCP server is launched from an agent/IDE config dir
349        // (~/.copilot-style) and wrongly adopts it as the root. With no
350        // `allow_auto_reroot` opt-in and no trusted startup root, the first
351        // absolute path into a real project must still correct the root — an
352        // agent config dir is never a real jail boundary.
353        let _iso = crate::core::data_dir::isolated_data_dir();
354        let tmp = tempfile::tempdir().unwrap();
355        let agent = tmp.path().join(".copilot");
356        let real = tmp.path().join("repo");
357        std::fs::create_dir_all(&agent).unwrap();
358        let real_root = create_git_root(&real);
359        std::fs::write(real.join("a.txt"), "ok").unwrap();
360
361        let server = LeanCtxServer::new_with_startup(
362            None,
363            None,
364            SessionMode::Personal,
365            "default",
366            "default",
367        );
368        {
369            let mut session = server.session.write().await;
370            session.project_root = Some(agent.to_string_lossy().to_string());
371            session.shell_cwd = Some(agent.to_string_lossy().to_string());
372        }
373
374        let out = server
375            .resolve_path(&real.join("a.txt").to_string_lossy())
376            .await
377            .unwrap();
378        assert!(
379            out.ends_with("/a.txt"),
380            "agent-dir jail must auto-correct: {out}"
381        );
382
383        let session = server.session.read().await;
384        assert_eq!(session.project_root.as_deref(), Some(real_root.as_str()));
385    }
386
387    #[cfg(not(feature = "no-jail"))]
388    #[tokio::test]
389    #[allow(clippy::await_holding_lock)]
390    async fn resolve_path_auto_reroots_from_markerless_client_cwd_without_opt_in() {
391        // VS Code/WSL can launch the MCP server from /mnt/c/Users while the
392        // workspace lives under /mnt/d. That markerless cwd must not become a
393        // permanent PathJail root when the request points at a real project.
394        let _iso = crate::core::data_dir::isolated_data_dir();
395        let tmp = tempfile::tempdir().unwrap();
396        let client_cwd = tmp.path().join("Users").join("user");
397        let real = tmp.path().join("workspaces").join("lean-ctx");
398        std::fs::create_dir_all(&client_cwd).unwrap();
399        let real_root = create_git_root(&real);
400        std::fs::write(real.join("rust.rs"), "ok").unwrap();
401
402        let server = LeanCtxServer::new_with_startup(
403            None,
404            None,
405            SessionMode::Personal,
406            "default",
407            "default",
408        );
409        {
410            let mut session = server.session.write().await;
411            session.project_root = Some(client_cwd.to_string_lossy().to_string());
412            session.shell_cwd = Some(client_cwd.to_string_lossy().to_string());
413        }
414
415        let out = server
416            .resolve_path(&real.join("rust.rs").to_string_lossy())
417            .await
418            .unwrap();
419        assert!(
420            out.ends_with("/rust.rs"),
421            "markerless client cwd must auto-correct: {out}"
422        );
423
424        let session = server.session.read().await;
425        assert_eq!(session.project_root.as_deref(), Some(real_root.as_str()));
426    }
427
428    #[cfg(not(feature = "no-jail"))]
429    #[tokio::test]
430    #[allow(clippy::await_holding_lock)]
431    async fn resolve_path_keeps_a_pinned_markerless_root_inside_a_checkout() {
432        // A directory pinned with LEAN_CTX_PROJECT_ROOT that carries no marker
433        // and lies inside a checkout stays the root: neither a path below it nor
434        // one in the surrounding checkout may widen the jail to that checkout.
435        let _iso = crate::core::data_dir::isolated_data_dir();
436        let tmp = tempfile::tempdir().unwrap();
437        let checkout = tmp.path().join("checkout");
438        create_git_root(&checkout);
439        let pinned = checkout.join("runs").join("one");
440        std::fs::create_dir_all(&pinned).unwrap();
441        std::fs::write(pinned.join("note.md"), "ok").unwrap();
442        std::fs::write(checkout.join("outside.md"), "no").unwrap();
443        let pinned_root = pinned.to_string_lossy().to_string();
444        crate::test_env::set_var("LEAN_CTX_PROJECT_ROOT", &pinned_root);
445
446        let server = LeanCtxServer::new_with_startup(
447            None,
448            None,
449            SessionMode::Personal,
450            "default",
451            "default",
452        );
453        {
454            let mut session = server.session.write().await;
455            session.project_root = Some(pinned_root.clone());
456            session.shell_cwd = Some(pinned_root.clone());
457        }
458
459        let inside = server
460            .resolve_path(&pinned.join("note.md").to_string_lossy())
461            .await;
462        let outside = server
463            .resolve_path(&checkout.join("outside.md").to_string_lossy())
464            .await;
465        let root = server.session.read().await.project_root.clone();
466        crate::test_env::remove_var("LEAN_CTX_PROJECT_ROOT");
467
468        assert!(inside.is_ok_and(|path| path.ends_with("/note.md")));
469        assert!(outside.is_err(), "a path above the pin is refused");
470        assert_eq!(root.as_deref(), Some(pinned_root.as_str()));
471    }
472
473    #[cfg(not(feature = "no-jail"))]
474    #[tokio::test]
475    #[allow(clippy::await_holding_lock)]
476    async fn resolve_path_auto_reroots_even_when_extra_root_allows_path() {
477        let _iso = crate::core::data_dir::isolated_data_dir();
478        let tmp = tempfile::tempdir().unwrap();
479        let client_cwd = tmp.path().join("Users").join("user");
480        let real = tmp.path().join("workspaces").join("lean-ctx");
481        std::fs::create_dir_all(&client_cwd).unwrap();
482        let real_root = create_git_root(&real);
483        std::fs::write(real.join("rust.rs"), "ok").unwrap();
484
485        let server = LeanCtxServer::new_with_startup(
486            None,
487            None,
488            SessionMode::Personal,
489            "default",
490            "default",
491        );
492        {
493            let mut session = server.session.write().await;
494            session.project_root = Some(client_cwd.to_string_lossy().to_string());
495            session.shell_cwd = Some(client_cwd.to_string_lossy().to_string());
496            session.extra_roots.push(real_root.clone());
497        }
498
499        let out = server
500            .resolve_path(&real.join("rust.rs").to_string_lossy())
501            .await
502            .unwrap();
503        assert!(
504            out.ends_with("/rust.rs"),
505            "extra root must not suppress markerless-cwd reroot: {out}"
506        );
507
508        let session = server.session.read().await;
509        assert_eq!(session.project_root.as_deref(), Some(real_root.as_str()));
510        assert_eq!(session.shell_cwd.as_deref(), Some(real_root.as_str()));
511    }
512
513    #[cfg(not(feature = "no-jail"))]
514    #[tokio::test]
515    #[allow(clippy::await_holding_lock)]
516    async fn resolve_path_markerless_root_still_blocks_markerless_escape() {
517        // #649 must not weaken PathJail: from a markerless client cwd, an absolute
518        // path that derives NO project marker stays blocked and the root is
519        // unchanged. Only rerooting *to a real project* is permitted.
520        let _iso = crate::core::data_dir::isolated_data_dir();
521        let tmp = tempfile::tempdir().unwrap();
522        let client_cwd = tmp.path().join("Users").join("user");
523        let loose = tmp.path().join("workspaces").join("loose");
524        std::fs::create_dir_all(&client_cwd).unwrap();
525        std::fs::create_dir_all(&loose).unwrap();
526        std::fs::write(loose.join("data.txt"), "no").unwrap();
527
528        let server = LeanCtxServer::new_with_startup(
529            None,
530            None,
531            SessionMode::Personal,
532            "default",
533            "default",
534        );
535        {
536            let mut session = server.session.write().await;
537            session.project_root = Some(client_cwd.to_string_lossy().to_string());
538            session.shell_cwd = Some(client_cwd.to_string_lossy().to_string());
539        }
540
541        let err = server
542            .resolve_path(&loose.join("data.txt").to_string_lossy())
543            .await
544            .unwrap_err();
545        assert!(err.contains("path escapes project root"), "got: {err}");
546
547        let session = server.session.read().await;
548        assert_eq!(
549            session.project_root.as_deref(),
550            Some(client_cwd.to_string_lossy().as_ref())
551        );
552    }
553
554    #[cfg(not(feature = "no-jail"))]
555    #[tokio::test]
556    #[allow(clippy::await_holding_lock)]
557    async fn resolve_path_agent_dir_still_blocks_markerless_escape() {
558        // The agent-dir bypass only reroots to a *real* project (one carrying a
559        // marker). A markerless absolute path outside the jail stays blocked —
560        // PathJail enforcement is unchanged, only the root *choice* is corrected.
561        let _iso = crate::core::data_dir::isolated_data_dir();
562        let tmp = tempfile::tempdir().unwrap();
563        let agent = tmp.path().join(".copilot");
564        let loose = tmp.path().join("loose");
565        std::fs::create_dir_all(&agent).unwrap();
566        std::fs::create_dir_all(&loose).unwrap();
567        std::fs::write(loose.join("data.txt"), "no").unwrap();
568
569        let server = LeanCtxServer::new_with_startup(
570            None,
571            None,
572            SessionMode::Personal,
573            "default",
574            "default",
575        );
576        {
577            let mut session = server.session.write().await;
578            session.project_root = Some(agent.to_string_lossy().to_string());
579            session.shell_cwd = Some(agent.to_string_lossy().to_string());
580        }
581
582        let err = server
583            .resolve_path(&loose.join("data.txt").to_string_lossy())
584            .await
585            .unwrap_err();
586        assert!(err.contains("path escapes project root"), "got: {err}");
587
588        let session = server.session.read().await;
589        assert_eq!(
590            session.project_root.as_deref(),
591            Some(agent.to_string_lossy().as_ref())
592        );
593    }
594
595    #[tokio::test]
596    #[allow(clippy::await_holding_lock)]
597    async fn startup_creates_fresh_session_scoped_to_workspace() {
598        let _lock = crate::core::data_dir::test_env_lock();
599        let _data = tempfile::tempdir().unwrap();
600        let _tmp = tempfile::tempdir().unwrap();
601
602        crate::test_env::set_var("LEAN_CTX_DATA_DIR", _data.path());
603
604        let repo_b = _tmp.path().join("repo-b");
605        let root_b = create_git_root(&repo_b);
606
607        let server = LeanCtxServer::new_with_startup(
608            None,
609            Some(repo_b.as_path()),
610            SessionMode::Personal,
611            "default",
612            "default",
613        );
614        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
615
616        let session = server.session.read().await;
617        // #1388: Personal mode creates a fresh PID-qualified session.
618        // The workspace root is detected from startup_cwd, but task
619        // starts empty (no cross-session state inheritance).
620        assert_eq!(session.project_root.as_deref(), Some(root_b.as_str()));
621        assert_eq!(session.shell_cwd.as_deref(), Some(root_b.as_str()));
622        assert!(session.task.is_none());
623    }
624
625    #[tokio::test]
626    #[allow(clippy::await_holding_lock)]
627    async fn startup_creates_fresh_session_for_new_workspace_and_preserves_subdir_cwd() {
628        let _lock = crate::core::data_dir::test_env_lock();
629        let _data = tempfile::tempdir().unwrap();
630        let _tmp = tempfile::tempdir().unwrap();
631
632        crate::test_env::set_var("LEAN_CTX_DATA_DIR", _data.path());
633
634        let repo_a = _tmp.path().join("repo-a");
635        let repo_b = _tmp.path().join("repo-b");
636        let repo_b_src = repo_b.join("src");
637        let root_a = create_git_root(&repo_a);
638        let root_b = create_git_root(&repo_b);
639        std::fs::create_dir_all(&repo_b_src).unwrap();
640        let repo_b_src_value = canonicalize_path(&repo_b_src);
641
642        let mut session_a = crate::core::session::SessionState::new();
643        session_a.project_root = Some(root_a.clone());
644        session_a.shell_cwd = Some(root_a.clone());
645        session_a.set_task("repo-a latest task", None);
646        let old_id = session_a.id.clone();
647        session_a.save().unwrap();
648
649        let server = LeanCtxServer::new_with_startup(
650            None,
651            Some(repo_b_src.as_path()),
652            SessionMode::Personal,
653            "default",
654            "default",
655        );
656        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
657
658        let session = server.session.read().await;
659        assert_eq!(session.project_root.as_deref(), Some(root_b.as_str()));
660        assert_eq!(
661            session.shell_cwd.as_deref(),
662            Some(repo_b_src_value.as_str())
663        );
664        assert!(session.task.is_none());
665        assert_ne!(session.id, old_id);
666    }
667
668    #[cfg(not(feature = "no-jail"))]
669    #[tokio::test]
670    #[allow(clippy::await_holding_lock)]
671    async fn resolve_path_does_not_auto_update_when_current_root_is_real_project() {
672        // Hermetic config + serialized via test_env_lock so a parallel test that
673        // flips `path_jail` cannot disable this jail-enforcement assertion (#406).
674        let _iso = crate::core::data_dir::isolated_data_dir();
675        let tmp = tempfile::tempdir().unwrap();
676        let root = tmp.path().join("root");
677        let other = tmp.path().join("other");
678        let root_value = create_git_root(&root);
679        create_git_root(&other);
680        std::fs::write(other.join("b.txt"), "no").unwrap();
681
682        let root_str = root.to_string_lossy().to_string();
683        let server = LeanCtxServer::new_with_project_root(Some(&root_str));
684
685        let err = server
686            .resolve_path(&other.join("b.txt").to_string_lossy())
687            .await
688            .unwrap_err();
689        assert!(err.contains("path escapes project root"));
690
691        let session = server.session.read().await;
692        assert_eq!(session.project_root.as_deref(), Some(root_value.as_str()));
693    }
694
695    // #707: a mid-session worktree switch moves shell_cwd into a nested linked
696    // worktree (own `.git` *file*) while project_root stays at initialize-time.
697    // The path `src/lib.rs` deliberately also exists relative to the test
698    // process CWD (`rust/`): the server's `p.exists()` probe used to
699    // short-circuit on exactly that and serve the stale root copy before the
700    // divergent-checkout precedence could apply.
701    #[tokio::test]
702    #[allow(clippy::await_holding_lock)]
703    async fn resolve_path_prefers_worktree_copy_after_mid_session_switch() {
704        let _iso = crate::core::data_dir::isolated_data_dir();
705        let tmp = tempfile::tempdir().unwrap();
706        let repo = tmp.path().join("repo");
707        let root_value = create_git_root(&repo);
708        let wt = repo.join(".claude/worktrees/wt");
709        std::fs::create_dir_all(wt.join("src")).unwrap();
710        std::fs::write(wt.join(".git"), "gitdir: ../../../.git/worktrees/wt\n").unwrap();
711        std::fs::create_dir_all(repo.join("src")).unwrap();
712        std::fs::write(repo.join("src/lib.rs"), "stale").unwrap();
713        std::fs::write(wt.join("src/lib.rs"), "fresh").unwrap();
714
715        let server = LeanCtxServer::new_with_project_root(Some(&root_value));
716        {
717            // The worktree switch as ctx_shell's cwd tracking records it.
718            let mut session = server.session.write().await;
719            session.shell_cwd = Some(wt.to_string_lossy().to_string());
720        }
721
722        let out = server.resolve_path("src/lib.rs").await.unwrap();
723        assert_eq!(
724            std::fs::read_to_string(&out).unwrap(),
725            "fresh",
726            "worktree copy must win over the stale project_root copy: {out}"
727        );
728
729        // Switching back restores the established precedence: without
730        // divergence the project_root fallback serves the root copy again.
731        // Probed via a path that does NOT exist relative to the test process
732        // CWD — `src/lib.rs` would hit the (intended) `p.exists()` fast path
733        // and resolve to the real checkout's file, making the assertion
734        // environment-dependent (that is exactly how CI diverged from local).
735        {
736            let mut session = server.session.write().await;
737            session.shell_cwd = Some(root_value.clone());
738        }
739        std::fs::write(repo.join("src/back_707.rs"), "stale").unwrap();
740        std::fs::write(wt.join("src/back_707.rs"), "fresh").unwrap();
741        let out = server.resolve_path("src/back_707.rs").await.unwrap();
742        assert_eq!(std::fs::read_to_string(&out).unwrap(), "stale");
743    }
744}