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