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