Skip to main content

lean_ctx/tools/
mod.rs

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