Skip to main content

lean_ctx/tools/
mod.rs

1use std::sync::atomic::{AtomicUsize, Ordering};
2use std::sync::Arc;
3use std::time::Instant;
4use tokio::sync::RwLock;
5
6use crate::core::cache::SessionCache;
7use crate::core::session::SessionState;
8
9pub mod autonomy;
10pub mod ctx_agent;
11pub mod ctx_analyze;
12pub mod ctx_architecture;
13pub mod ctx_benchmark;
14pub mod ctx_callees;
15pub mod ctx_callers;
16pub mod ctx_compress;
17pub mod ctx_compress_memory;
18pub mod ctx_context;
19pub mod ctx_cost;
20pub mod ctx_dedup;
21pub mod ctx_delta;
22pub mod ctx_discover;
23pub mod ctx_edit;
24pub mod ctx_execute;
25pub mod ctx_feedback;
26pub mod ctx_fill;
27pub mod ctx_gain;
28pub mod ctx_graph;
29pub mod ctx_graph_diagram;
30pub mod ctx_handoff;
31pub mod ctx_heatmap;
32pub mod ctx_impact;
33pub mod ctx_intent;
34pub mod ctx_knowledge;
35pub mod ctx_metrics;
36pub mod ctx_multi_read;
37pub mod ctx_outline;
38pub mod ctx_overview;
39pub mod ctx_prefetch;
40pub mod ctx_preload;
41pub mod ctx_read;
42pub mod ctx_response;
43pub mod ctx_routes;
44pub mod ctx_search;
45pub mod ctx_semantic_search;
46pub mod ctx_session;
47pub mod ctx_share;
48pub mod ctx_shell;
49pub mod ctx_smart_read;
50pub mod ctx_symbol;
51pub mod ctx_task;
52pub mod ctx_tree;
53pub mod ctx_workflow;
54pub mod ctx_wrapped;
55
56const DEFAULT_CACHE_TTL_SECS: u64 = 300;
57
58struct CepComputedStats {
59    cep_score: u32,
60    cache_util: u32,
61    mode_diversity: u32,
62    compression_rate: u32,
63    total_original: u64,
64    total_compressed: u64,
65    total_saved: u64,
66    mode_counts: std::collections::HashMap<String, u64>,
67    complexity: String,
68    cache_hits: u64,
69    total_reads: u64,
70    tool_call_count: u64,
71}
72
73#[derive(Clone, Copy, Debug, PartialEq, Eq)]
74pub enum CrpMode {
75    Off,
76    Compact,
77    Tdd,
78}
79
80impl CrpMode {
81    pub fn from_env() -> Self {
82        match std::env::var("LEAN_CTX_CRP_MODE")
83            .unwrap_or_default()
84            .to_lowercase()
85            .as_str()
86        {
87            "off" => Self::Off,
88            "compact" => Self::Compact,
89            _ => Self::Tdd,
90        }
91    }
92
93    pub fn is_tdd(&self) -> bool {
94        *self == Self::Tdd
95    }
96}
97
98pub type SharedCache = Arc<RwLock<SessionCache>>;
99
100#[derive(Clone)]
101pub struct LeanCtxServer {
102    pub cache: SharedCache,
103    pub session: Arc<RwLock<SessionState>>,
104    pub tool_calls: Arc<RwLock<Vec<ToolCallRecord>>>,
105    pub call_count: Arc<AtomicUsize>,
106    pub checkpoint_interval: usize,
107    pub cache_ttl_secs: u64,
108    pub last_call: Arc<RwLock<Instant>>,
109    pub crp_mode: CrpMode,
110    pub agent_id: Arc<RwLock<Option<String>>>,
111    pub client_name: Arc<RwLock<String>>,
112    pub autonomy: Arc<autonomy::AutonomyState>,
113    pub loop_detector: Arc<RwLock<crate::core::loop_detection::LoopDetector>>,
114    pub workflow: Arc<RwLock<Option<crate::core::workflow::WorkflowRun>>>,
115}
116
117#[derive(Clone, Debug)]
118pub struct ToolCallRecord {
119    pub tool: String,
120    pub original_tokens: usize,
121    pub saved_tokens: usize,
122    pub mode: Option<String>,
123    pub duration_ms: u64,
124    pub timestamp: String,
125}
126
127impl Default for LeanCtxServer {
128    fn default() -> Self {
129        Self::new()
130    }
131}
132
133impl LeanCtxServer {
134    pub fn new() -> Self {
135        Self::new_with_project_root(None)
136    }
137
138    pub fn new_with_project_root(project_root: Option<String>) -> Self {
139        let config = crate::core::config::Config::load();
140
141        let interval = std::env::var("LEAN_CTX_CHECKPOINT_INTERVAL")
142            .ok()
143            .and_then(|v| v.parse().ok())
144            .unwrap_or(config.checkpoint_interval as usize);
145
146        let ttl = std::env::var("LEAN_CTX_CACHE_TTL")
147            .ok()
148            .and_then(|v| v.parse().ok())
149            .unwrap_or(DEFAULT_CACHE_TTL_SECS);
150
151        let crp_mode = CrpMode::from_env();
152
153        let mut session = SessionState::load_latest().unwrap_or_default();
154        if project_root.is_some() {
155            session.project_root = project_root;
156        }
157        Self {
158            cache: Arc::new(RwLock::new(SessionCache::new())),
159            session: Arc::new(RwLock::new(session)),
160            tool_calls: Arc::new(RwLock::new(Vec::new())),
161            call_count: Arc::new(AtomicUsize::new(0)),
162            checkpoint_interval: interval,
163            cache_ttl_secs: ttl,
164            last_call: Arc::new(RwLock::new(Instant::now())),
165            crp_mode,
166            agent_id: Arc::new(RwLock::new(None)),
167            client_name: Arc::new(RwLock::new(String::new())),
168            autonomy: Arc::new(autonomy::AutonomyState::new()),
169            loop_detector: Arc::new(RwLock::new(
170                crate::core::loop_detection::LoopDetector::with_config(
171                    &crate::core::config::Config::load().loop_detection,
172                ),
173            )),
174            workflow: Arc::new(RwLock::new(
175                crate::core::workflow::load_active().ok().flatten(),
176            )),
177        }
178    }
179
180    /// Resolves a (possibly relative) tool path against the session's project_root.
181    /// Absolute paths and "." are returned as-is. Relative paths like "src/main.rs"
182    /// are joined with project_root so tools work regardless of the server's cwd.
183    pub async fn resolve_path(&self, path: &str) -> Result<String, String> {
184        let normalized = crate::hooks::normalize_tool_path(path);
185        if normalized.is_empty() || normalized == "." {
186            return Ok(normalized);
187        }
188        let p = std::path::Path::new(&normalized);
189
190        let (resolved, jail_root) = {
191            let session = self.session.read().await;
192            let jail_root = session
193                .project_root
194                .as_deref()
195                .or(session.shell_cwd.as_deref())
196                .unwrap_or(".")
197                .to_string();
198
199            let resolved = if p.is_absolute() || p.exists() {
200                std::path::PathBuf::from(&normalized)
201            } else if let Some(ref root) = session.project_root {
202                let joined = std::path::Path::new(root).join(&normalized);
203                if joined.exists() {
204                    joined
205                } else if let Some(ref cwd) = session.shell_cwd {
206                    std::path::Path::new(cwd).join(&normalized)
207                } else {
208                    std::path::Path::new(&jail_root).join(&normalized)
209                }
210            } else if let Some(ref cwd) = session.shell_cwd {
211                std::path::Path::new(cwd).join(&normalized)
212            } else {
213                std::path::Path::new(&jail_root).join(&normalized)
214            };
215
216            (resolved, jail_root)
217        };
218
219        let jail_root_path = std::path::Path::new(&jail_root);
220        let jailed = match crate::core::pathjail::jail_path(&resolved, jail_root_path) {
221            Ok(p) => p,
222            Err(e) => {
223                if p.is_absolute() {
224                    if let Some(new_root) = maybe_derive_project_root_from_absolute(&resolved) {
225                        let jail_has_marker = has_project_marker(jail_root_path);
226                        let candidate_under_jail = resolved.starts_with(jail_root_path);
227
228                        if !candidate_under_jail
229                            && (!jail_has_marker || is_suspicious_root(jail_root_path))
230                        {
231                            let mut session = self.session.write().await;
232                            session.project_root = Some(new_root.to_string_lossy().to_string());
233                            if session.shell_cwd.is_none() {
234                                session.shell_cwd = Some(new_root.to_string_lossy().to_string());
235                            }
236                            let _ = session.save();
237
238                            crate::core::pathjail::jail_path(&resolved, &new_root)?
239                        } else {
240                            return Err(e);
241                        }
242                    } else {
243                        return Err(e);
244                    }
245                } else {
246                    return Err(e);
247                }
248            }
249        };
250
251        Ok(crate::hooks::normalize_tool_path(
252            &jailed.to_string_lossy().replace('\\', "/"),
253        ))
254    }
255
256    pub async fn resolve_path_or_passthrough(&self, path: &str) -> String {
257        self.resolve_path(path)
258            .await
259            .unwrap_or_else(|_| path.to_string())
260    }
261
262    pub async fn check_idle_expiry(&self) {
263        if self.cache_ttl_secs == 0 {
264            return;
265        }
266        let last = *self.last_call.read().await;
267        if last.elapsed().as_secs() >= self.cache_ttl_secs {
268            {
269                let mut session = self.session.write().await;
270                let _ = session.save();
271            }
272            let mut cache = self.cache.write().await;
273            let count = cache.clear();
274            if count > 0 {
275                tracing::info!(
276                    "Cache auto-cleared after {}s idle ({count} file(s))",
277                    self.cache_ttl_secs
278                );
279            }
280        }
281        *self.last_call.write().await = Instant::now();
282    }
283
284    pub async fn record_call(
285        &self,
286        tool: &str,
287        original: usize,
288        saved: usize,
289        mode: Option<String>,
290    ) {
291        self.record_call_with_timing(tool, original, saved, mode, 0)
292            .await;
293    }
294
295    pub async fn record_call_with_timing(
296        &self,
297        tool: &str,
298        original: usize,
299        saved: usize,
300        mode: Option<String>,
301        duration_ms: u64,
302    ) {
303        let ts = chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
304        let mut calls = self.tool_calls.write().await;
305        calls.push(ToolCallRecord {
306            tool: tool.to_string(),
307            original_tokens: original,
308            saved_tokens: saved,
309            mode: mode.clone(),
310            duration_ms,
311            timestamp: ts.clone(),
312        });
313
314        if duration_ms > 0 {
315            Self::append_tool_call_log(tool, duration_ms, original, saved, mode.as_deref(), &ts);
316        }
317
318        crate::core::events::emit_tool_call(
319            tool,
320            original as u64,
321            saved as u64,
322            mode.clone(),
323            duration_ms,
324            None,
325        );
326
327        let output_tokens = original.saturating_sub(saved);
328        crate::core::stats::record(tool, original, output_tokens);
329
330        let mut session = self.session.write().await;
331        session.record_tool_call(saved as u64, original as u64);
332        if tool == "ctx_shell" {
333            session.record_command();
334        }
335        if session.should_save() {
336            let _ = session.save();
337        }
338        drop(calls);
339        drop(session);
340
341        self.write_mcp_live_stats().await;
342    }
343
344    pub async fn is_prompt_cache_stale(&self) -> bool {
345        let last = *self.last_call.read().await;
346        last.elapsed().as_secs() > 3600
347    }
348
349    pub fn upgrade_mode_if_stale(mode: &str, stale: bool) -> &str {
350        if !stale {
351            return mode;
352        }
353        match mode {
354            "full" => "full",
355            "map" => "signatures",
356            m => m,
357        }
358    }
359
360    pub fn increment_and_check(&self) -> bool {
361        let count = self.call_count.fetch_add(1, Ordering::Relaxed) + 1;
362        self.checkpoint_interval > 0 && count.is_multiple_of(self.checkpoint_interval)
363    }
364
365    pub async fn auto_checkpoint(&self) -> Option<String> {
366        let cache = self.cache.read().await;
367        if cache.get_all_entries().is_empty() {
368            return None;
369        }
370        let complexity = crate::core::adaptive::classify_from_context(&cache);
371        let checkpoint = ctx_compress::handle(&cache, true, self.crp_mode);
372        drop(cache);
373
374        let mut session = self.session.write().await;
375        let _ = session.save();
376        let session_summary = session.format_compact();
377        let has_insights = !session.findings.is_empty() || !session.decisions.is_empty();
378        let project_root = session.project_root.clone();
379        drop(session);
380
381        if has_insights {
382            if let Some(ref root) = project_root {
383                let root = root.clone();
384                std::thread::spawn(move || {
385                    auto_consolidate_knowledge(&root);
386                });
387            }
388        }
389
390        let multi_agent_block = self.auto_multi_agent_checkpoint(&project_root).await;
391
392        self.record_call("ctx_compress", 0, 0, Some("auto".to_string()))
393            .await;
394
395        self.record_cep_snapshot().await;
396
397        Some(format!(
398            "{checkpoint}\n\n--- SESSION STATE ---\n{session_summary}\n\n{}{multi_agent_block}",
399            complexity.instruction_suffix()
400        ))
401    }
402
403    async fn auto_multi_agent_checkpoint(&self, project_root: &Option<String>) -> String {
404        let root = match project_root {
405            Some(r) => r,
406            None => return String::new(),
407        };
408
409        let registry = crate::core::agents::AgentRegistry::load_or_create();
410        let active = registry.list_active(Some(root));
411        if active.len() <= 1 {
412            return String::new();
413        }
414
415        let agent_id = self.agent_id.read().await;
416        let my_id = match agent_id.as_deref() {
417            Some(id) => id.to_string(),
418            None => return String::new(),
419        };
420        drop(agent_id);
421
422        let cache = self.cache.read().await;
423        let entries = cache.get_all_entries();
424        if !entries.is_empty() {
425            let mut by_access: Vec<_> = entries.iter().collect();
426            by_access.sort_by_key(|x| std::cmp::Reverse(x.1.read_count));
427            let top_paths: Vec<&str> = by_access
428                .iter()
429                .take(5)
430                .map(|(key, _)| key.as_str())
431                .collect();
432            let paths_csv = top_paths.join(",");
433
434            let _ = ctx_share::handle("push", Some(&my_id), None, Some(&paths_csv), None, &cache);
435        }
436        drop(cache);
437
438        let pending_count = registry
439            .scratchpad
440            .iter()
441            .filter(|e| !e.read_by.contains(&my_id) && e.from_agent != my_id)
442            .count();
443
444        let shared_dir = crate::core::data_dir::lean_ctx_data_dir()
445            .unwrap_or_default()
446            .join("agents")
447            .join("shared");
448        let shared_count = if shared_dir.exists() {
449            std::fs::read_dir(&shared_dir)
450                .map(|rd| rd.count())
451                .unwrap_or(0)
452        } else {
453            0
454        };
455
456        let agent_names: Vec<String> = active
457            .iter()
458            .map(|a| {
459                let role = a.role.as_deref().unwrap_or(&a.agent_type);
460                format!("{role}({})", &a.agent_id[..8.min(a.agent_id.len())])
461            })
462            .collect();
463
464        format!(
465            "\n\n--- MULTI-AGENT SYNC ---\nAgents: {} | Pending msgs: {} | Shared contexts: {}\nAuto-shared top-5 cached files.\n--- END SYNC ---",
466            agent_names.join(", "),
467            pending_count,
468            shared_count,
469        )
470    }
471
472    pub fn append_tool_call_log(
473        tool: &str,
474        duration_ms: u64,
475        original: usize,
476        saved: usize,
477        mode: Option<&str>,
478        timestamp: &str,
479    ) {
480        const MAX_LOG_LINES: usize = 50;
481        if let Ok(dir) = crate::core::data_dir::lean_ctx_data_dir() {
482            let log_path = dir.join("tool-calls.log");
483            let mode_str = mode.unwrap_or("-");
484            let slow = if duration_ms > 5000 { " **SLOW**" } else { "" };
485            let line = format!(
486                "{timestamp}\t{tool}\t{duration_ms}ms\torig={original}\tsaved={saved}\tmode={mode_str}{slow}\n"
487            );
488
489            let mut lines: Vec<String> = std::fs::read_to_string(&log_path)
490                .unwrap_or_default()
491                .lines()
492                .map(|l| l.to_string())
493                .collect();
494
495            lines.push(line.trim_end().to_string());
496            if lines.len() > MAX_LOG_LINES {
497                lines.drain(0..lines.len() - MAX_LOG_LINES);
498            }
499
500            let _ = std::fs::write(&log_path, lines.join("\n") + "\n");
501        }
502    }
503
504    fn compute_cep_stats(
505        calls: &[ToolCallRecord],
506        stats: &crate::core::cache::CacheStats,
507        complexity: &crate::core::adaptive::TaskComplexity,
508    ) -> CepComputedStats {
509        let total_original: u64 = calls.iter().map(|c| c.original_tokens as u64).sum();
510        let total_saved: u64 = calls.iter().map(|c| c.saved_tokens as u64).sum();
511        let total_compressed = total_original.saturating_sub(total_saved);
512        let compression_rate = if total_original > 0 {
513            total_saved as f64 / total_original as f64
514        } else {
515            0.0
516        };
517
518        let modes_used: std::collections::HashSet<&str> =
519            calls.iter().filter_map(|c| c.mode.as_deref()).collect();
520        let mode_diversity = (modes_used.len() as f64 / 10.0).min(1.0);
521        let cache_util = stats.hit_rate() / 100.0;
522        let cep_score = cache_util * 0.3 + mode_diversity * 0.2 + compression_rate * 0.5;
523
524        let mut mode_counts: std::collections::HashMap<String, u64> =
525            std::collections::HashMap::new();
526        for call in calls {
527            if let Some(ref mode) = call.mode {
528                *mode_counts.entry(mode.clone()).or_insert(0) += 1;
529            }
530        }
531
532        CepComputedStats {
533            cep_score: (cep_score * 100.0).round() as u32,
534            cache_util: (cache_util * 100.0).round() as u32,
535            mode_diversity: (mode_diversity * 100.0).round() as u32,
536            compression_rate: (compression_rate * 100.0).round() as u32,
537            total_original,
538            total_compressed,
539            total_saved,
540            mode_counts,
541            complexity: format!("{:?}", complexity),
542            cache_hits: stats.cache_hits,
543            total_reads: stats.total_reads,
544            tool_call_count: calls.len() as u64,
545        }
546    }
547
548    async fn write_mcp_live_stats(&self) {
549        let cache = self.cache.read().await;
550        let calls = self.tool_calls.read().await;
551        let stats = cache.get_stats();
552        let complexity = crate::core::adaptive::classify_from_context(&cache);
553
554        let cs = Self::compute_cep_stats(&calls, stats, &complexity);
555        let started_at = calls
556            .first()
557            .map(|c| c.timestamp.clone())
558            .unwrap_or_default();
559
560        drop(cache);
561        drop(calls);
562        let live = serde_json::json!({
563            "cep_score": cs.cep_score,
564            "cache_utilization": cs.cache_util,
565            "mode_diversity": cs.mode_diversity,
566            "compression_rate": cs.compression_rate,
567            "task_complexity": cs.complexity,
568            "files_cached": cs.total_reads,
569            "total_reads": cs.total_reads,
570            "cache_hits": cs.cache_hits,
571            "tokens_saved": cs.total_saved,
572            "tokens_original": cs.total_original,
573            "tool_calls": cs.tool_call_count,
574            "started_at": started_at,
575            "updated_at": chrono::Local::now().to_rfc3339(),
576        });
577
578        if let Ok(dir) = crate::core::data_dir::lean_ctx_data_dir() {
579            let _ = std::fs::write(dir.join("mcp-live.json"), live.to_string());
580        }
581    }
582
583    pub async fn record_cep_snapshot(&self) {
584        let cache = self.cache.read().await;
585        let calls = self.tool_calls.read().await;
586        let stats = cache.get_stats();
587        let complexity = crate::core::adaptive::classify_from_context(&cache);
588
589        let cs = Self::compute_cep_stats(&calls, stats, &complexity);
590
591        drop(cache);
592        drop(calls);
593
594        crate::core::stats::record_cep_session(
595            cs.cep_score,
596            cs.cache_hits,
597            cs.total_reads,
598            cs.total_original,
599            cs.total_compressed,
600            &cs.mode_counts,
601            cs.tool_call_count,
602            &cs.complexity,
603        );
604    }
605}
606
607pub fn create_server() -> LeanCtxServer {
608    LeanCtxServer::new()
609}
610
611const PROJECT_ROOT_MARKERS: &[&str] = &[
612    ".git",
613    ".lean-ctx.toml",
614    "Cargo.toml",
615    "package.json",
616    "go.mod",
617    "pyproject.toml",
618    "pom.xml",
619    "build.gradle",
620    "Makefile",
621    ".planning",
622];
623
624fn has_project_marker(dir: &std::path::Path) -> bool {
625    PROJECT_ROOT_MARKERS.iter().any(|m| dir.join(m).exists())
626}
627
628fn is_suspicious_root(dir: &std::path::Path) -> bool {
629    let s = dir.to_string_lossy();
630    s.contains("/.claude")
631        || s.contains("/.codex")
632        || s.contains("\\.claude")
633        || s.contains("\\.codex")
634}
635
636fn maybe_derive_project_root_from_absolute(abs: &std::path::Path) -> Option<std::path::PathBuf> {
637    let mut cur = if abs.is_dir() {
638        abs.to_path_buf()
639    } else {
640        abs.parent()?.to_path_buf()
641    };
642    loop {
643        if has_project_marker(&cur) {
644            return Some(crate::core::pathutil::safe_canonicalize_or_self(&cur));
645        }
646        if !cur.pop() {
647            break;
648        }
649    }
650    None
651}
652
653fn auto_consolidate_knowledge(project_root: &str) {
654    use crate::core::knowledge::ProjectKnowledge;
655    use crate::core::session::SessionState;
656
657    let session = match SessionState::load_latest() {
658        Some(s) => s,
659        None => return,
660    };
661
662    if session.findings.is_empty() && session.decisions.is_empty() {
663        return;
664    }
665
666    let mut knowledge = ProjectKnowledge::load_or_create(project_root);
667
668    for finding in &session.findings {
669        let key = if let Some(ref file) = finding.file {
670            if let Some(line) = finding.line {
671                format!("{file}:{line}")
672            } else {
673                file.clone()
674            }
675        } else {
676            "finding-auto".to_string()
677        };
678        knowledge.remember("finding", &key, &finding.summary, &session.id, 0.7);
679    }
680
681    for decision in &session.decisions {
682        let key = decision
683            .summary
684            .chars()
685            .take(50)
686            .collect::<String>()
687            .replace(' ', "-")
688            .to_lowercase();
689        knowledge.remember("decision", &key, &decision.summary, &session.id, 0.85);
690    }
691
692    let task_desc = session
693        .task
694        .as_ref()
695        .map(|t| t.description.clone())
696        .unwrap_or_default();
697
698    let summary = format!(
699        "Auto-consolidate session {}: {} — {} findings, {} decisions",
700        session.id,
701        task_desc,
702        session.findings.len(),
703        session.decisions.len()
704    );
705    knowledge.consolidate(&summary, vec![session.id.clone()]);
706    let _ = knowledge.save();
707}
708
709#[cfg(test)]
710mod resolve_path_tests {
711    use super::*;
712
713    #[tokio::test]
714    async fn resolve_path_can_auto_update_stale_root_from_absolute_project_path() {
715        let tmp = tempfile::tempdir().unwrap();
716        let stale = tmp.path().join("stale");
717        let real = tmp.path().join("real");
718        std::fs::create_dir_all(&stale).unwrap();
719        std::fs::create_dir_all(&real).unwrap();
720        std::fs::create_dir_all(real.join(".git")).unwrap();
721        std::fs::write(real.join("a.txt"), "ok").unwrap();
722
723        let server =
724            LeanCtxServer::new_with_project_root(Some(stale.to_string_lossy().to_string()));
725
726        let out = server
727            .resolve_path(&real.join("a.txt").to_string_lossy())
728            .await
729            .unwrap();
730
731        assert!(out.ends_with("/a.txt"));
732
733        let session = server.session.read().await;
734        let expected = crate::core::pathutil::safe_canonicalize_or_self(&real)
735            .to_string_lossy()
736            .to_string();
737        assert_eq!(session.project_root.as_deref(), Some(expected.as_str()));
738    }
739
740    #[tokio::test]
741    async fn resolve_path_does_not_auto_update_when_current_root_is_real_project() {
742        let tmp = tempfile::tempdir().unwrap();
743        let root = tmp.path().join("root");
744        let other = tmp.path().join("other");
745        std::fs::create_dir_all(&root).unwrap();
746        std::fs::create_dir_all(&other).unwrap();
747        std::fs::create_dir_all(root.join(".git")).unwrap();
748        std::fs::create_dir_all(other.join(".git")).unwrap();
749        std::fs::write(other.join("b.txt"), "no").unwrap();
750
751        let server = LeanCtxServer::new_with_project_root(Some(root.to_string_lossy().to_string()));
752
753        let err = server
754            .resolve_path(&other.join("b.txt").to_string_lossy())
755            .await
756            .unwrap_err();
757        assert!(err.contains("path escapes project root"));
758    }
759}