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