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