Skip to main content

lean_ctx/tools/
mod.rs

1use std::path::Path;
2use std::sync::atomic::{AtomicUsize, Ordering};
3use std::sync::Arc;
4use std::time::Instant;
5use tokio::sync::RwLock;
6
7use crate::core::cache::SessionCache;
8use crate::core::session::SessionState;
9
10pub mod autonomy;
11pub mod ctx_agent;
12pub mod ctx_analyze;
13pub mod ctx_architecture;
14pub mod ctx_benchmark;
15pub mod ctx_callees;
16pub mod ctx_callers;
17pub mod ctx_compress;
18pub mod ctx_compress_memory;
19pub mod ctx_context;
20pub mod ctx_cost;
21pub mod ctx_dedup;
22pub mod ctx_delta;
23pub mod ctx_discover;
24pub mod ctx_edit;
25pub mod ctx_execute;
26pub mod ctx_expand;
27pub mod ctx_feedback;
28pub mod ctx_fill;
29pub mod ctx_gain;
30pub mod ctx_graph;
31pub mod ctx_graph_diagram;
32pub mod ctx_handoff;
33pub mod ctx_heatmap;
34pub mod ctx_impact;
35pub mod ctx_intent;
36pub mod ctx_knowledge;
37pub mod ctx_metrics;
38pub mod ctx_multi_read;
39pub mod ctx_outline;
40pub mod ctx_overview;
41pub mod ctx_prefetch;
42pub mod ctx_preload;
43pub mod ctx_read;
44pub mod ctx_response;
45pub mod ctx_review;
46pub mod ctx_routes;
47pub mod ctx_search;
48pub mod ctx_semantic_search;
49pub mod ctx_session;
50pub mod ctx_share;
51pub mod ctx_shell;
52pub mod ctx_smart_read;
53pub mod ctx_symbol;
54pub mod ctx_task;
55pub mod ctx_tree;
56pub mod ctx_workflow;
57pub mod ctx_wrapped;
58
59const DEFAULT_CACHE_TTL_SECS: u64 = 300;
60
61struct CepComputedStats {
62    cep_score: u32,
63    cache_util: u32,
64    mode_diversity: u32,
65    compression_rate: u32,
66    total_original: u64,
67    total_compressed: u64,
68    total_saved: u64,
69    mode_counts: std::collections::HashMap<String, u64>,
70    complexity: String,
71    cache_hits: u64,
72    total_reads: u64,
73    tool_call_count: u64,
74}
75
76/// Context Reduction Protocol mode controlling output verbosity.
77#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78pub enum CrpMode {
79    Off,
80    Compact,
81    Tdd,
82}
83
84impl CrpMode {
85    /// Reads the CRP mode from the `LEAN_CTX_CRP_MODE` environment variable.
86    pub fn from_env() -> Self {
87        match std::env::var("LEAN_CTX_CRP_MODE")
88            .unwrap_or_default()
89            .to_lowercase()
90            .as_str()
91        {
92            "off" => Self::Off,
93            "compact" => Self::Compact,
94            _ => Self::Tdd,
95        }
96    }
97
98    /// Returns true if the mode is TDD (maximum compression).
99    pub fn is_tdd(&self) -> bool {
100        *self == Self::Tdd
101    }
102}
103
104/// Thread-safe handle to the shared file content cache.
105pub type SharedCache = Arc<RwLock<SessionCache>>;
106
107/// Central MCP server state: cache, session, metrics, and autonomy runtime.
108#[derive(Clone)]
109pub struct LeanCtxServer {
110    pub cache: SharedCache,
111    pub session: Arc<RwLock<SessionState>>,
112    pub tool_calls: Arc<RwLock<Vec<ToolCallRecord>>>,
113    pub call_count: Arc<AtomicUsize>,
114    pub checkpoint_interval: usize,
115    pub cache_ttl_secs: u64,
116    pub last_call: Arc<RwLock<Instant>>,
117    pub crp_mode: CrpMode,
118    pub agent_id: Arc<RwLock<Option<String>>>,
119    pub client_name: Arc<RwLock<String>>,
120    pub autonomy: Arc<autonomy::AutonomyState>,
121    pub loop_detector: Arc<RwLock<crate::core::loop_detection::LoopDetector>>,
122    pub workflow: Arc<RwLock<Option<crate::core::workflow::WorkflowRun>>>,
123    pub ledger: Arc<RwLock<crate::core::context_ledger::ContextLedger>>,
124    pub pipeline_stats: Arc<RwLock<crate::core::pipeline::PipelineStats>>,
125    startup_project_root: Option<String>,
126    startup_shell_cwd: Option<String>,
127}
128
129/// Recorded metrics for a single MCP tool invocation.
130#[derive(Clone, Debug)]
131pub struct ToolCallRecord {
132    pub tool: String,
133    pub original_tokens: usize,
134    pub saved_tokens: usize,
135    pub mode: Option<String>,
136    pub duration_ms: u64,
137    pub timestamp: String,
138}
139
140impl Default for LeanCtxServer {
141    fn default() -> Self {
142        Self::new()
143    }
144}
145
146impl LeanCtxServer {
147    /// Creates a new server with default settings, auto-detecting the project root.
148    pub fn new() -> Self {
149        Self::new_with_project_root(None)
150    }
151
152    /// Creates a new server rooted at the given project directory.
153    pub fn new_with_project_root(project_root: Option<&str>) -> Self {
154        Self::new_with_startup(project_root, std::env::current_dir().ok().as_deref())
155    }
156
157    fn new_with_startup(project_root: Option<&str>, startup_cwd: Option<&Path>) -> Self {
158        let config = crate::core::config::Config::load();
159
160        let interval = std::env::var("LEAN_CTX_CHECKPOINT_INTERVAL")
161            .ok()
162            .and_then(|v| v.parse().ok())
163            .unwrap_or(config.checkpoint_interval as usize);
164
165        let ttl = std::env::var("LEAN_CTX_CACHE_TTL")
166            .ok()
167            .and_then(|v| v.parse().ok())
168            .unwrap_or(DEFAULT_CACHE_TTL_SECS);
169
170        let crp_mode = CrpMode::from_env();
171
172        let startup = detect_startup_context(project_root, startup_cwd);
173        let mut session = if let Some(ref root) = startup.project_root {
174            SessionState::load_latest_for_project_root(root).unwrap_or_default()
175        } else {
176            SessionState::load_latest().unwrap_or_default()
177        };
178
179        if let Some(ref root) = startup.project_root {
180            session.project_root = Some(root.clone());
181        }
182        if let Some(ref cwd) = startup.shell_cwd {
183            session.shell_cwd = Some(cwd.clone());
184        }
185
186        Self {
187            cache: Arc::new(RwLock::new(SessionCache::new())),
188            session: Arc::new(RwLock::new(session)),
189            tool_calls: Arc::new(RwLock::new(Vec::new())),
190            call_count: Arc::new(AtomicUsize::new(0)),
191            checkpoint_interval: interval,
192            cache_ttl_secs: ttl,
193            last_call: Arc::new(RwLock::new(Instant::now())),
194            crp_mode,
195            agent_id: Arc::new(RwLock::new(None)),
196            client_name: Arc::new(RwLock::new(String::new())),
197            autonomy: Arc::new(autonomy::AutonomyState::new()),
198            loop_detector: Arc::new(RwLock::new(
199                crate::core::loop_detection::LoopDetector::with_config(
200                    &crate::core::config::Config::load().loop_detection,
201                ),
202            )),
203            workflow: Arc::new(RwLock::new(
204                crate::core::workflow::load_active().ok().flatten(),
205            )),
206            ledger: Arc::new(RwLock::new(
207                crate::core::context_ledger::ContextLedger::new(),
208            )),
209            pipeline_stats: Arc::new(RwLock::new(crate::core::pipeline::PipelineStats::new())),
210            startup_project_root: startup.project_root,
211            startup_shell_cwd: startup.shell_cwd,
212        }
213    }
214
215    /// Resolves a (possibly relative) tool path against the session's project_root.
216    /// Absolute paths and "." are returned as-is. Relative paths like "src/main.rs"
217    /// are joined with project_root so tools work regardless of the server's cwd.
218    pub async fn resolve_path(&self, path: &str) -> Result<String, String> {
219        let normalized = crate::hooks::normalize_tool_path(path);
220        if normalized.is_empty() || normalized == "." {
221            return Ok(normalized);
222        }
223        let p = std::path::Path::new(&normalized);
224
225        let (resolved, jail_root) = {
226            let session = self.session.read().await;
227            let jail_root = session
228                .project_root
229                .as_deref()
230                .or(session.shell_cwd.as_deref())
231                .unwrap_or(".")
232                .to_string();
233
234            let resolved = if p.is_absolute() || p.exists() {
235                std::path::PathBuf::from(&normalized)
236            } else if let Some(ref root) = session.project_root {
237                let joined = std::path::Path::new(root).join(&normalized);
238                if joined.exists() {
239                    joined
240                } else if let Some(ref cwd) = session.shell_cwd {
241                    std::path::Path::new(cwd).join(&normalized)
242                } else {
243                    std::path::Path::new(&jail_root).join(&normalized)
244                }
245            } else if let Some(ref cwd) = session.shell_cwd {
246                std::path::Path::new(cwd).join(&normalized)
247            } else {
248                std::path::Path::new(&jail_root).join(&normalized)
249            };
250
251            (resolved, jail_root)
252        };
253
254        let jail_root_path = std::path::Path::new(&jail_root);
255        let jailed = match crate::core::pathjail::jail_path(&resolved, jail_root_path) {
256            Ok(p) => p,
257            Err(e) => {
258                if p.is_absolute() {
259                    if let Some(new_root) = maybe_derive_project_root_from_absolute(&resolved) {
260                        let candidate_under_jail = resolved.starts_with(jail_root_path);
261                        let allow_reroot = if candidate_under_jail {
262                            false
263                        } else if let Some(ref trusted_root) = self.startup_project_root {
264                            std::path::Path::new(trusted_root) == new_root.as_path()
265                        } else {
266                            !has_project_marker(jail_root_path)
267                                || is_suspicious_root(jail_root_path)
268                        };
269
270                        if allow_reroot {
271                            let mut session = self.session.write().await;
272                            let new_root_str = new_root.to_string_lossy().to_string();
273                            session.project_root = Some(new_root_str.clone());
274                            session.shell_cwd = self
275                                .startup_shell_cwd
276                                .as_ref()
277                                .filter(|cwd| std::path::Path::new(cwd).starts_with(&new_root))
278                                .cloned()
279                                .or_else(|| Some(new_root_str.clone()));
280                            let _ = session.save();
281
282                            crate::core::pathjail::jail_path(&resolved, &new_root)?
283                        } else {
284                            return Err(e);
285                        }
286                    } else {
287                        return Err(e);
288                    }
289                } else {
290                    return Err(e);
291                }
292            }
293        };
294
295        Ok(crate::hooks::normalize_tool_path(
296            &jailed.to_string_lossy().replace('\\', "/"),
297        ))
298    }
299
300    /// Like `resolve_path`, but returns the original path on failure instead of an error.
301    pub async fn resolve_path_or_passthrough(&self, path: &str) -> String {
302        self.resolve_path(path)
303            .await
304            .unwrap_or_else(|_| path.to_string())
305    }
306
307    /// Clears the cache and saves the session if the TTL idle threshold has been exceeded.
308    pub async fn check_idle_expiry(&self) {
309        if self.cache_ttl_secs == 0 {
310            return;
311        }
312        let last = *self.last_call.read().await;
313        if last.elapsed().as_secs() >= self.cache_ttl_secs {
314            {
315                let mut session = self.session.write().await;
316                let _ = session.save();
317            }
318            let mut cache = self.cache.write().await;
319            let count = cache.clear();
320            if count > 0 {
321                tracing::info!(
322                    "Cache auto-cleared after {}s idle ({count} file(s))",
323                    self.cache_ttl_secs
324                );
325            }
326        }
327        *self.last_call.write().await = Instant::now();
328    }
329
330    /// Records a tool call's token savings without timing information.
331    pub async fn record_call(
332        &self,
333        tool: &str,
334        original: usize,
335        saved: usize,
336        mode: Option<String>,
337    ) {
338        self.record_call_with_timing(tool, original, saved, mode, 0)
339            .await;
340    }
341
342    /// Records a tool call like `record_call`, but includes an optional file path for observability.
343    pub async fn record_call_with_path(
344        &self,
345        tool: &str,
346        original: usize,
347        saved: usize,
348        mode: Option<String>,
349        path: Option<&str>,
350    ) {
351        self.record_call_with_timing_inner(tool, original, saved, mode, 0, path)
352            .await;
353    }
354
355    /// Records a tool call's token savings, duration, and emits events and stats.
356    pub async fn record_call_with_timing(
357        &self,
358        tool: &str,
359        original: usize,
360        saved: usize,
361        mode: Option<String>,
362        duration_ms: u64,
363    ) {
364        self.record_call_with_timing_inner(tool, original, saved, mode, duration_ms, None)
365            .await;
366    }
367
368    async fn record_call_with_timing_inner(
369        &self,
370        tool: &str,
371        original: usize,
372        saved: usize,
373        mode: Option<String>,
374        duration_ms: u64,
375        path: Option<&str>,
376    ) {
377        let ts = chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
378        let mut calls = self.tool_calls.write().await;
379        calls.push(ToolCallRecord {
380            tool: tool.to_string(),
381            original_tokens: original,
382            saved_tokens: saved,
383            mode: mode.clone(),
384            duration_ms,
385            timestamp: ts.clone(),
386        });
387
388        if duration_ms > 0 {
389            Self::append_tool_call_log(tool, duration_ms, original, saved, mode.as_deref(), &ts);
390        }
391
392        crate::core::events::emit_tool_call(
393            tool,
394            original as u64,
395            saved as u64,
396            mode.clone(),
397            duration_ms,
398            path.map(ToString::to_string),
399        );
400
401        let output_tokens = original.saturating_sub(saved);
402        crate::core::stats::record(tool, original, output_tokens);
403
404        let mut session = self.session.write().await;
405        session.record_tool_call(saved as u64, original as u64);
406        if tool == "ctx_shell" {
407            session.record_command();
408        }
409        let pending_save = if session.should_save() {
410            session.prepare_save().ok()
411        } else {
412            None
413        };
414        drop(calls);
415        drop(session);
416
417        if let Some(prepared) = pending_save {
418            tokio::task::spawn_blocking(move || {
419                let _ = prepared.write_to_disk();
420            });
421        }
422
423        self.write_mcp_live_stats().await;
424    }
425
426    /// Returns true if over an hour has passed since the last tool call.
427    pub async fn is_prompt_cache_stale(&self) -> bool {
428        let last = *self.last_call.read().await;
429        last.elapsed().as_secs() > 3600
430    }
431
432    /// Promotes lightweight read modes to richer ones when the prompt cache is stale.
433    pub fn upgrade_mode_if_stale(mode: &str, stale: bool) -> &str {
434        if !stale {
435            return mode;
436        }
437        match mode {
438            "full" => "full",
439            "map" => "signatures",
440            m => m,
441        }
442    }
443
444    /// Increments the call counter and returns true if a checkpoint is due.
445    pub fn increment_and_check(&self) -> bool {
446        let count = self.call_count.fetch_add(1, Ordering::Relaxed) + 1;
447        self.checkpoint_interval > 0 && count.is_multiple_of(self.checkpoint_interval)
448    }
449
450    /// Generates a compressed context checkpoint with session state and multi-agent sync.
451    pub async fn auto_checkpoint(&self) -> Option<String> {
452        let cache = self.cache.read().await;
453        if cache.get_all_entries().is_empty() {
454            return None;
455        }
456        let complexity = crate::core::adaptive::classify_from_context(&cache);
457        let checkpoint = ctx_compress::handle(&cache, true, self.crp_mode);
458        drop(cache);
459
460        let mut session = self.session.write().await;
461        let _ = session.save();
462        let session_summary = session.format_compact();
463        let has_insights = !session.findings.is_empty() || !session.decisions.is_empty();
464        let project_root = session.project_root.clone();
465        drop(session);
466
467        if has_insights {
468            if let Some(ref root) = project_root {
469                let root = root.clone();
470                std::thread::spawn(move || {
471                    auto_consolidate_knowledge(&root);
472                });
473            }
474        }
475
476        let multi_agent_block = self
477            .auto_multi_agent_checkpoint(project_root.as_ref())
478            .await;
479
480        self.record_call("ctx_compress", 0, 0, Some("auto".to_string()))
481            .await;
482
483        self.record_cep_snapshot().await;
484
485        Some(format!(
486            "{checkpoint}\n\n--- SESSION STATE ---\n{session_summary}\n\n{}{multi_agent_block}",
487            complexity.instruction_suffix()
488        ))
489    }
490
491    async fn auto_multi_agent_checkpoint(&self, project_root: Option<&String>) -> String {
492        let Some(root) = project_root else {
493            return String::new();
494        };
495
496        let registry = crate::core::agents::AgentRegistry::load_or_create();
497        let active = registry.list_active(Some(root));
498        if active.len() <= 1 {
499            return String::new();
500        }
501
502        let agent_id = self.agent_id.read().await;
503        let my_id = match agent_id.as_deref() {
504            Some(id) => id.to_string(),
505            None => return String::new(),
506        };
507        drop(agent_id);
508
509        let cache = self.cache.read().await;
510        let entries = cache.get_all_entries();
511        if !entries.is_empty() {
512            let mut by_access: Vec<_> = entries.iter().collect();
513            by_access.sort_by_key(|x| std::cmp::Reverse(x.1.read_count));
514            let top_paths: Vec<&str> = by_access
515                .iter()
516                .take(5)
517                .map(|(key, _)| key.as_str())
518                .collect();
519            let paths_csv = top_paths.join(",");
520
521            let _ = ctx_share::handle("push", Some(&my_id), None, Some(&paths_csv), None, &cache);
522        }
523        drop(cache);
524
525        let pending_count = registry
526            .scratchpad
527            .iter()
528            .filter(|e| !e.read_by.contains(&my_id) && e.from_agent != my_id)
529            .count();
530
531        let shared_dir = crate::core::data_dir::lean_ctx_data_dir()
532            .unwrap_or_default()
533            .join("agents")
534            .join("shared");
535        let shared_count = if shared_dir.exists() {
536            std::fs::read_dir(&shared_dir).map_or(0, std::iter::Iterator::count)
537        } else {
538            0
539        };
540
541        let agent_names: Vec<String> = active
542            .iter()
543            .map(|a| {
544                let role = a.role.as_deref().unwrap_or(&a.agent_type);
545                format!("{role}({})", &a.agent_id[..8.min(a.agent_id.len())])
546            })
547            .collect();
548
549        format!(
550            "\n\n--- MULTI-AGENT SYNC ---\nAgents: {} | Pending msgs: {} | Shared contexts: {}\nAuto-shared top-5 cached files.\n--- END SYNC ---",
551            agent_names.join(", "),
552            pending_count,
553            shared_count,
554        )
555    }
556
557    /// Appends a tool call entry to the rotating `tool-calls.log` file.
558    pub fn append_tool_call_log(
559        tool: &str,
560        duration_ms: u64,
561        original: usize,
562        saved: usize,
563        mode: Option<&str>,
564        timestamp: &str,
565    ) {
566        const MAX_LOG_LINES: usize = 50;
567        if let Ok(dir) = crate::core::data_dir::lean_ctx_data_dir() {
568            let log_path = dir.join("tool-calls.log");
569            let mode_str = mode.unwrap_or("-");
570            let slow = if duration_ms > 5000 { " **SLOW**" } else { "" };
571            let line = format!(
572                "{timestamp}\t{tool}\t{duration_ms}ms\torig={original}\tsaved={saved}\tmode={mode_str}{slow}\n"
573            );
574
575            let mut lines: Vec<String> = std::fs::read_to_string(&log_path)
576                .unwrap_or_default()
577                .lines()
578                .map(std::string::ToString::to_string)
579                .collect();
580
581            lines.push(line.trim_end().to_string());
582            if lines.len() > MAX_LOG_LINES {
583                lines.drain(0..lines.len() - MAX_LOG_LINES);
584            }
585
586            let _ = std::fs::write(&log_path, lines.join("\n") + "\n");
587        }
588    }
589
590    fn compute_cep_stats(
591        calls: &[ToolCallRecord],
592        stats: &crate::core::cache::CacheStats,
593        complexity: &crate::core::adaptive::TaskComplexity,
594    ) -> CepComputedStats {
595        let total_original: u64 = calls.iter().map(|c| c.original_tokens as u64).sum();
596        let total_saved: u64 = calls.iter().map(|c| c.saved_tokens as u64).sum();
597        let total_compressed = total_original.saturating_sub(total_saved);
598        let compression_rate = if total_original > 0 {
599            total_saved as f64 / total_original as f64
600        } else {
601            0.0
602        };
603
604        let modes_used: std::collections::HashSet<&str> =
605            calls.iter().filter_map(|c| c.mode.as_deref()).collect();
606        let mode_diversity = (modes_used.len() as f64 / 10.0).min(1.0);
607        let cache_util = stats.hit_rate() / 100.0;
608        let cep_score = cache_util * 0.3 + mode_diversity * 0.2 + compression_rate * 0.5;
609
610        let mut mode_counts: std::collections::HashMap<String, u64> =
611            std::collections::HashMap::new();
612        for call in calls {
613            if let Some(ref mode) = call.mode {
614                *mode_counts.entry(mode.clone()).or_insert(0) += 1;
615            }
616        }
617
618        CepComputedStats {
619            cep_score: (cep_score * 100.0).round() as u32,
620            cache_util: (cache_util * 100.0).round() as u32,
621            mode_diversity: (mode_diversity * 100.0).round() as u32,
622            compression_rate: (compression_rate * 100.0).round() as u32,
623            total_original,
624            total_compressed,
625            total_saved,
626            mode_counts,
627            complexity: format!("{complexity:?}"),
628            cache_hits: stats.cache_hits,
629            total_reads: stats.total_reads,
630            tool_call_count: calls.len() as u64,
631        }
632    }
633
634    async fn write_mcp_live_stats(&self) {
635        let count = self.call_count.load(Ordering::Relaxed);
636        if count > 1 && !count.is_multiple_of(5) {
637            return;
638        }
639
640        let cache = self.cache.read().await;
641        let calls = self.tool_calls.read().await;
642        let stats = cache.get_stats();
643        let complexity = crate::core::adaptive::classify_from_context(&cache);
644
645        let cs = Self::compute_cep_stats(&calls, stats, &complexity);
646        let started_at = calls
647            .first()
648            .map(|c| c.timestamp.clone())
649            .unwrap_or_default();
650
651        drop(cache);
652        drop(calls);
653        let live = serde_json::json!({
654            "cep_score": cs.cep_score,
655            "cache_utilization": cs.cache_util,
656            "mode_diversity": cs.mode_diversity,
657            "compression_rate": cs.compression_rate,
658            "task_complexity": cs.complexity,
659            "files_cached": cs.total_reads,
660            "total_reads": cs.total_reads,
661            "cache_hits": cs.cache_hits,
662            "tokens_saved": cs.total_saved,
663            "tokens_original": cs.total_original,
664            "tool_calls": cs.tool_call_count,
665            "started_at": started_at,
666            "updated_at": chrono::Local::now().to_rfc3339(),
667        });
668
669        if let Ok(dir) = crate::core::data_dir::lean_ctx_data_dir() {
670            let _ = std::fs::write(dir.join("mcp-live.json"), live.to_string());
671        }
672    }
673
674    /// Persists a CEP (Context Efficiency Protocol) score snapshot for analytics.
675    pub async fn record_cep_snapshot(&self) {
676        let cache = self.cache.read().await;
677        let calls = self.tool_calls.read().await;
678        let stats = cache.get_stats();
679        let complexity = crate::core::adaptive::classify_from_context(&cache);
680
681        let cs = Self::compute_cep_stats(&calls, stats, &complexity);
682
683        drop(cache);
684        drop(calls);
685
686        crate::core::stats::record_cep_session(
687            cs.cep_score,
688            cs.cache_hits,
689            cs.total_reads,
690            cs.total_original,
691            cs.total_compressed,
692            &cs.mode_counts,
693            cs.tool_call_count,
694            &cs.complexity,
695        );
696    }
697}
698
699#[derive(Clone, Debug, Default)]
700struct StartupContext {
701    project_root: Option<String>,
702    shell_cwd: Option<String>,
703}
704
705/// Creates a new `LeanCtxServer` with default configuration.
706pub fn create_server() -> LeanCtxServer {
707    LeanCtxServer::new()
708}
709
710const PROJECT_ROOT_MARKERS: &[&str] = &[
711    ".git",
712    ".lean-ctx.toml",
713    "Cargo.toml",
714    "package.json",
715    "go.mod",
716    "pyproject.toml",
717    "pom.xml",
718    "build.gradle",
719    "Makefile",
720    ".planning",
721];
722
723fn has_project_marker(dir: &std::path::Path) -> bool {
724    PROJECT_ROOT_MARKERS.iter().any(|m| dir.join(m).exists())
725}
726
727fn is_suspicious_root(dir: &std::path::Path) -> bool {
728    let s = dir.to_string_lossy();
729    s.contains("/.claude")
730        || s.contains("/.codex")
731        || s.contains("\\.claude")
732        || s.contains("\\.codex")
733}
734
735fn canonicalize_path(path: &std::path::Path) -> String {
736    crate::core::pathutil::safe_canonicalize_or_self(path)
737        .to_string_lossy()
738        .to_string()
739}
740
741fn detect_startup_context(
742    explicit_project_root: Option<&str>,
743    startup_cwd: Option<&std::path::Path>,
744) -> StartupContext {
745    let shell_cwd = startup_cwd.map(canonicalize_path);
746    let project_root = explicit_project_root
747        .map(|root| canonicalize_path(std::path::Path::new(root)))
748        .or_else(|| {
749            startup_cwd
750                .and_then(maybe_derive_project_root_from_absolute)
751                .map(|p| canonicalize_path(&p))
752        });
753
754    let shell_cwd = match (shell_cwd, project_root.as_ref()) {
755        (Some(cwd), Some(root))
756            if std::path::Path::new(&cwd).starts_with(std::path::Path::new(root)) =>
757        {
758            Some(cwd)
759        }
760        (_, Some(root)) => Some(root.clone()),
761        (cwd, None) => cwd,
762    };
763
764    StartupContext {
765        project_root,
766        shell_cwd,
767    }
768}
769
770fn maybe_derive_project_root_from_absolute(abs: &std::path::Path) -> Option<std::path::PathBuf> {
771    let mut cur = if abs.is_dir() {
772        abs.to_path_buf()
773    } else {
774        abs.parent()?.to_path_buf()
775    };
776    loop {
777        if has_project_marker(&cur) {
778            return Some(crate::core::pathutil::safe_canonicalize_or_self(&cur));
779        }
780        if !cur.pop() {
781            break;
782        }
783    }
784    None
785}
786
787fn auto_consolidate_knowledge(project_root: &str) {
788    use crate::core::knowledge::ProjectKnowledge;
789    use crate::core::session::SessionState;
790
791    let Some(session) = SessionState::load_latest() else {
792        return;
793    };
794
795    if session.findings.is_empty() && session.decisions.is_empty() {
796        return;
797    }
798
799    let mut knowledge = ProjectKnowledge::load_or_create(project_root);
800
801    for finding in &session.findings {
802        let key = if let Some(ref file) = finding.file {
803            if let Some(line) = finding.line {
804                format!("{file}:{line}")
805            } else {
806                file.clone()
807            }
808        } else {
809            "finding-auto".to_string()
810        };
811        knowledge.remember("finding", &key, &finding.summary, &session.id, 0.7);
812    }
813
814    for decision in &session.decisions {
815        let key = decision
816            .summary
817            .chars()
818            .take(50)
819            .collect::<String>()
820            .replace(' ', "-")
821            .to_lowercase();
822        knowledge.remember("decision", &key, &decision.summary, &session.id, 0.85);
823    }
824
825    let task_desc = session
826        .task
827        .as_ref()
828        .map(|t| t.description.clone())
829        .unwrap_or_default();
830
831    let summary = format!(
832        "Auto-consolidate session {}: {} — {} findings, {} decisions",
833        session.id,
834        task_desc,
835        session.findings.len(),
836        session.decisions.len()
837    );
838    knowledge.consolidate(&summary, vec![session.id.clone()]);
839    let _ = knowledge.save();
840}
841
842#[cfg(test)]
843mod resolve_path_tests {
844    use super::*;
845
846    fn create_git_root(path: &std::path::Path) -> String {
847        std::fs::create_dir_all(path.join(".git")).unwrap();
848        canonicalize_path(path)
849    }
850
851    #[tokio::test]
852    async fn resolve_path_can_reroot_to_trusted_startup_root_when_session_root_is_stale() {
853        let tmp = tempfile::tempdir().unwrap();
854        let stale = tmp.path().join("stale");
855        let real = tmp.path().join("real");
856        std::fs::create_dir_all(&stale).unwrap();
857        let real_root = create_git_root(&real);
858        std::fs::write(real.join("a.txt"), "ok").unwrap();
859
860        let server = LeanCtxServer::new_with_startup(None, Some(real.as_path()));
861        {
862            let mut session = server.session.write().await;
863            session.project_root = Some(stale.to_string_lossy().to_string());
864            session.shell_cwd = Some(stale.to_string_lossy().to_string());
865        }
866
867        let out = server
868            .resolve_path(&real.join("a.txt").to_string_lossy())
869            .await
870            .unwrap();
871
872        assert!(out.ends_with("/a.txt"));
873
874        let session = server.session.read().await;
875        assert_eq!(session.project_root.as_deref(), Some(real_root.as_str()));
876        assert_eq!(session.shell_cwd.as_deref(), Some(real_root.as_str()));
877    }
878
879    #[tokio::test]
880    async fn resolve_path_rejects_absolute_path_outside_trusted_startup_root() {
881        let tmp = tempfile::tempdir().unwrap();
882        let stale = tmp.path().join("stale");
883        let root = tmp.path().join("root");
884        let other = tmp.path().join("other");
885        std::fs::create_dir_all(&stale).unwrap();
886        create_git_root(&root);
887        let _other_value = create_git_root(&other);
888        std::fs::write(other.join("b.txt"), "no").unwrap();
889
890        let server = LeanCtxServer::new_with_startup(None, Some(root.as_path()));
891        {
892            let mut session = server.session.write().await;
893            session.project_root = Some(stale.to_string_lossy().to_string());
894            session.shell_cwd = Some(stale.to_string_lossy().to_string());
895        }
896
897        let err = server
898            .resolve_path(&other.join("b.txt").to_string_lossy())
899            .await
900            .unwrap_err();
901        assert!(err.contains("path escapes project root"));
902
903        let session = server.session.read().await;
904        assert_eq!(
905            session.project_root.as_deref(),
906            Some(stale.to_string_lossy().as_ref())
907        );
908    }
909
910    #[tokio::test]
911    #[allow(clippy::await_holding_lock)]
912    async fn startup_prefers_workspace_scoped_session_over_global_latest() {
913        let _lock = crate::core::data_dir::test_env_lock();
914        let _data = tempfile::tempdir().unwrap();
915        let _tmp = tempfile::tempdir().unwrap();
916
917        std::env::set_var("LEAN_CTX_DATA_DIR", _data.path());
918
919        let repo_a = _tmp.path().join("repo-a");
920        let repo_b = _tmp.path().join("repo-b");
921        let root_a = create_git_root(&repo_a);
922        let root_b = create_git_root(&repo_b);
923
924        let mut session_b = SessionState::new();
925        session_b.project_root = Some(root_b.clone());
926        session_b.shell_cwd = Some(root_b.clone());
927        session_b.set_task("repo-b task", None);
928        session_b.save().unwrap();
929
930        std::thread::sleep(std::time::Duration::from_millis(50));
931
932        let mut session_a = SessionState::new();
933        session_a.project_root = Some(root_a.clone());
934        session_a.shell_cwd = Some(root_a.clone());
935        session_a.set_task("repo-a latest task", None);
936        session_a.save().unwrap();
937
938        let server = LeanCtxServer::new_with_startup(None, Some(repo_b.as_path()));
939        std::env::remove_var("LEAN_CTX_DATA_DIR");
940
941        let session = server.session.read().await;
942        assert_eq!(session.project_root.as_deref(), Some(root_b.as_str()));
943        assert_eq!(session.shell_cwd.as_deref(), Some(root_b.as_str()));
944        assert_eq!(
945            session.task.as_ref().map(|t| t.description.as_str()),
946            Some("repo-b task")
947        );
948    }
949
950    #[tokio::test]
951    #[allow(clippy::await_holding_lock)]
952    async fn startup_creates_fresh_session_for_new_workspace_and_preserves_subdir_cwd() {
953        let _lock = crate::core::data_dir::test_env_lock();
954        let _data = tempfile::tempdir().unwrap();
955        let _tmp = tempfile::tempdir().unwrap();
956
957        std::env::set_var("LEAN_CTX_DATA_DIR", _data.path());
958
959        let repo_a = _tmp.path().join("repo-a");
960        let repo_b = _tmp.path().join("repo-b");
961        let repo_b_src = repo_b.join("src");
962        let root_a = create_git_root(&repo_a);
963        let root_b = create_git_root(&repo_b);
964        std::fs::create_dir_all(&repo_b_src).unwrap();
965        let repo_b_src_value = canonicalize_path(&repo_b_src);
966
967        let mut session_a = SessionState::new();
968        session_a.project_root = Some(root_a.clone());
969        session_a.shell_cwd = Some(root_a.clone());
970        session_a.set_task("repo-a latest task", None);
971        let old_id = session_a.id.clone();
972        session_a.save().unwrap();
973
974        let server = LeanCtxServer::new_with_startup(None, Some(repo_b_src.as_path()));
975        std::env::remove_var("LEAN_CTX_DATA_DIR");
976
977        let session = server.session.read().await;
978        assert_eq!(session.project_root.as_deref(), Some(root_b.as_str()));
979        assert_eq!(
980            session.shell_cwd.as_deref(),
981            Some(repo_b_src_value.as_str())
982        );
983        assert!(session.task.is_none());
984        assert_ne!(session.id, old_id);
985    }
986
987    #[tokio::test]
988    async fn resolve_path_does_not_auto_update_when_current_root_is_real_project() {
989        let tmp = tempfile::tempdir().unwrap();
990        let root = tmp.path().join("root");
991        let other = tmp.path().join("other");
992        let root_value = create_git_root(&root);
993        create_git_root(&other);
994        std::fs::write(other.join("b.txt"), "no").unwrap();
995
996        let root_str = root.to_string_lossy().to_string();
997        let server = LeanCtxServer::new_with_project_root(Some(&root_str));
998
999        let err = server
1000            .resolve_path(&other.join("b.txt").to_string_lossy())
1001            .await
1002            .unwrap_err();
1003        assert!(err.contains("path escapes project root"));
1004
1005        let session = server.session.read().await;
1006        assert_eq!(session.project_root.as_deref(), Some(root_value.as_str()));
1007    }
1008}