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