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