Skip to main content

lean_ctx/tools/
mod.rs

1use std::sync::atomic::{AtomicUsize, Ordering};
2use std::sync::Arc;
3use std::time::Instant;
4use tokio::sync::RwLock;
5
6use crate::core::cache::SessionCache;
7use crate::core::session::SessionState;
8
9pub mod autonomy;
10pub mod ctx_agent;
11pub mod ctx_analyze;
12pub mod ctx_benchmark;
13pub mod ctx_compress;
14pub mod ctx_context;
15pub mod ctx_dedup;
16pub mod ctx_delta;
17pub mod ctx_discover;
18pub mod ctx_fill;
19pub mod ctx_graph;
20pub mod ctx_intent;
21pub mod ctx_knowledge;
22pub mod ctx_metrics;
23pub mod ctx_multi_read;
24pub mod ctx_overview;
25pub mod ctx_preload;
26pub mod ctx_read;
27pub mod ctx_response;
28pub mod ctx_search;
29pub mod ctx_semantic_search;
30pub mod ctx_session;
31pub mod ctx_shell;
32pub mod ctx_smart_read;
33pub mod ctx_tree;
34pub mod ctx_wrapped;
35
36const DEFAULT_CACHE_TTL_SECS: u64 = 300;
37
38struct CepComputedStats {
39    cep_score: u32,
40    cache_util: u32,
41    mode_diversity: u32,
42    compression_rate: u32,
43    total_original: u64,
44    total_compressed: u64,
45    total_saved: u64,
46    mode_counts: std::collections::HashMap<String, u64>,
47    complexity: String,
48    cache_hits: u64,
49    total_reads: u64,
50    tool_call_count: u64,
51}
52
53#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54pub enum CrpMode {
55    Off,
56    Compact,
57    Tdd,
58}
59
60impl CrpMode {
61    pub fn from_env() -> Self {
62        match std::env::var("LEAN_CTX_CRP_MODE")
63            .unwrap_or_default()
64            .to_lowercase()
65            .as_str()
66        {
67            "off" => Self::Off,
68            "compact" => Self::Compact,
69            _ => Self::Tdd,
70        }
71    }
72
73    pub fn is_tdd(&self) -> bool {
74        *self == Self::Tdd
75    }
76}
77
78pub type SharedCache = Arc<RwLock<SessionCache>>;
79
80#[derive(Clone)]
81pub struct LeanCtxServer {
82    pub cache: SharedCache,
83    pub session: Arc<RwLock<SessionState>>,
84    pub tool_calls: Arc<RwLock<Vec<ToolCallRecord>>>,
85    pub call_count: Arc<AtomicUsize>,
86    pub checkpoint_interval: usize,
87    pub cache_ttl_secs: u64,
88    pub last_call: Arc<RwLock<Instant>>,
89    pub crp_mode: CrpMode,
90    pub agent_id: Arc<RwLock<Option<String>>>,
91    pub client_name: Arc<RwLock<String>>,
92    pub autonomy: Arc<autonomy::AutonomyState>,
93}
94
95#[derive(Clone, Debug)]
96pub struct ToolCallRecord {
97    pub tool: String,
98    pub original_tokens: usize,
99    pub saved_tokens: usize,
100    pub mode: Option<String>,
101}
102
103impl Default for LeanCtxServer {
104    fn default() -> Self {
105        Self::new()
106    }
107}
108
109impl LeanCtxServer {
110    pub fn new() -> Self {
111        let config = crate::core::config::Config::load();
112
113        let interval = std::env::var("LEAN_CTX_CHECKPOINT_INTERVAL")
114            .ok()
115            .and_then(|v| v.parse().ok())
116            .unwrap_or(config.checkpoint_interval as usize);
117
118        let ttl = std::env::var("LEAN_CTX_CACHE_TTL")
119            .ok()
120            .and_then(|v| v.parse().ok())
121            .unwrap_or(DEFAULT_CACHE_TTL_SECS);
122
123        let crp_mode = CrpMode::from_env();
124
125        let session = SessionState::load_latest().unwrap_or_default();
126
127        Self {
128            cache: Arc::new(RwLock::new(SessionCache::new())),
129            session: Arc::new(RwLock::new(session)),
130            tool_calls: Arc::new(RwLock::new(Vec::new())),
131            call_count: Arc::new(AtomicUsize::new(0)),
132            checkpoint_interval: interval,
133            cache_ttl_secs: ttl,
134            last_call: Arc::new(RwLock::new(Instant::now())),
135            crp_mode,
136            agent_id: Arc::new(RwLock::new(None)),
137            client_name: Arc::new(RwLock::new(String::new())),
138            autonomy: Arc::new(autonomy::AutonomyState::new()),
139        }
140    }
141
142    pub async fn check_idle_expiry(&self) {
143        if self.cache_ttl_secs == 0 {
144            return;
145        }
146        let last = *self.last_call.read().await;
147        if last.elapsed().as_secs() >= self.cache_ttl_secs {
148            {
149                let mut session = self.session.write().await;
150                let _ = session.save();
151            }
152            let mut cache = self.cache.write().await;
153            let count = cache.clear();
154            if count > 0 {
155                tracing::info!(
156                    "Cache auto-cleared after {}s idle ({count} file(s))",
157                    self.cache_ttl_secs
158                );
159            }
160        }
161        *self.last_call.write().await = Instant::now();
162    }
163
164    pub async fn record_call(
165        &self,
166        tool: &str,
167        original: usize,
168        saved: usize,
169        mode: Option<String>,
170    ) {
171        let mut calls = self.tool_calls.write().await;
172        calls.push(ToolCallRecord {
173            tool: tool.to_string(),
174            original_tokens: original,
175            saved_tokens: saved,
176            mode,
177        });
178
179        let output_tokens = original.saturating_sub(saved);
180        crate::core::stats::record(tool, original, output_tokens);
181
182        let mut session = self.session.write().await;
183        session.record_tool_call(saved as u64, original as u64);
184        if tool == "ctx_shell" {
185            session.record_command();
186        }
187        if session.should_save() {
188            let _ = session.save();
189        }
190        drop(calls);
191        drop(session);
192
193        self.write_mcp_live_stats().await;
194    }
195
196    pub async fn is_prompt_cache_stale(&self) -> bool {
197        let last = *self.last_call.read().await;
198        last.elapsed().as_secs() > 3600
199    }
200
201    pub fn upgrade_mode_if_stale(mode: &str, stale: bool) -> &str {
202        if !stale {
203            return mode;
204        }
205        match mode {
206            "full" => "aggressive",
207            "map" => "signatures",
208            m => m,
209        }
210    }
211
212    pub fn increment_and_check(&self) -> bool {
213        let count = self.call_count.fetch_add(1, Ordering::Relaxed) + 1;
214        self.checkpoint_interval > 0 && count.is_multiple_of(self.checkpoint_interval)
215    }
216
217    pub async fn auto_checkpoint(&self) -> Option<String> {
218        let cache = self.cache.read().await;
219        if cache.get_all_entries().is_empty() {
220            return None;
221        }
222        let complexity = crate::core::adaptive::classify_from_context(&cache);
223        let checkpoint = ctx_compress::handle(&cache, true, self.crp_mode);
224        drop(cache);
225
226        let mut session = self.session.write().await;
227        let _ = session.save();
228        let session_summary = session.format_compact();
229        let has_insights = !session.findings.is_empty() || !session.decisions.is_empty();
230        let project_root = session.project_root.clone();
231        drop(session);
232
233        if has_insights {
234            if let Some(root) = project_root {
235                std::thread::spawn(move || {
236                    auto_consolidate_knowledge(&root);
237                });
238            }
239        }
240
241        self.record_call("ctx_compress", 0, 0, Some("auto".to_string()))
242            .await;
243
244        self.record_cep_snapshot().await;
245
246        Some(format!(
247            "{checkpoint}\n\n--- SESSION STATE ---\n{session_summary}\n\n{}",
248            complexity.instruction_suffix()
249        ))
250    }
251
252    fn compute_cep_stats(
253        calls: &[ToolCallRecord],
254        stats: &crate::core::cache::CacheStats,
255        complexity: &crate::core::adaptive::TaskComplexity,
256    ) -> CepComputedStats {
257        let total_original: u64 = calls.iter().map(|c| c.original_tokens as u64).sum();
258        let total_saved: u64 = calls.iter().map(|c| c.saved_tokens as u64).sum();
259        let total_compressed = total_original.saturating_sub(total_saved);
260        let compression_rate = if total_original > 0 {
261            total_saved as f64 / total_original as f64
262        } else {
263            0.0
264        };
265
266        let modes_used: std::collections::HashSet<&str> =
267            calls.iter().filter_map(|c| c.mode.as_deref()).collect();
268        let mode_diversity = (modes_used.len() as f64 / 6.0).min(1.0);
269        let cache_util = stats.hit_rate() / 100.0;
270        let cep_score = cache_util * 0.3 + mode_diversity * 0.2 + compression_rate * 0.5;
271
272        let mut mode_counts: std::collections::HashMap<String, u64> =
273            std::collections::HashMap::new();
274        for call in calls {
275            if let Some(ref mode) = call.mode {
276                *mode_counts.entry(mode.clone()).or_insert(0) += 1;
277            }
278        }
279
280        CepComputedStats {
281            cep_score: (cep_score * 100.0).round() as u32,
282            cache_util: (cache_util * 100.0).round() as u32,
283            mode_diversity: (mode_diversity * 100.0).round() as u32,
284            compression_rate: (compression_rate * 100.0).round() as u32,
285            total_original,
286            total_compressed,
287            total_saved,
288            mode_counts,
289            complexity: format!("{:?}", complexity),
290            cache_hits: stats.cache_hits,
291            total_reads: stats.total_reads,
292            tool_call_count: calls.len() as u64,
293        }
294    }
295
296    async fn write_mcp_live_stats(&self) {
297        let cache = self.cache.read().await;
298        let calls = self.tool_calls.read().await;
299        let stats = cache.get_stats();
300        let complexity = crate::core::adaptive::classify_from_context(&cache);
301
302        let cs = Self::compute_cep_stats(&calls, stats, &complexity);
303
304        drop(cache);
305        drop(calls);
306
307        let live = serde_json::json!({
308            "cep_score": cs.cep_score,
309            "cache_utilization": cs.cache_util,
310            "mode_diversity": cs.mode_diversity,
311            "compression_rate": cs.compression_rate,
312            "task_complexity": cs.complexity,
313            "files_cached": cs.total_reads,
314            "total_reads": cs.total_reads,
315            "cache_hits": cs.cache_hits,
316            "tokens_saved": cs.total_saved,
317            "tokens_original": cs.total_original,
318            "tool_calls": cs.tool_call_count,
319            "updated_at": chrono::Local::now().to_rfc3339(),
320        });
321
322        if let Some(dir) = dirs::home_dir().map(|h| h.join(".lean-ctx")) {
323            let _ = std::fs::write(dir.join("mcp-live.json"), live.to_string());
324        }
325    }
326
327    pub async fn record_cep_snapshot(&self) {
328        let cache = self.cache.read().await;
329        let calls = self.tool_calls.read().await;
330        let stats = cache.get_stats();
331        let complexity = crate::core::adaptive::classify_from_context(&cache);
332
333        let cs = Self::compute_cep_stats(&calls, stats, &complexity);
334
335        drop(cache);
336        drop(calls);
337
338        crate::core::stats::record_cep_session(
339            cs.cep_score,
340            cs.cache_hits,
341            cs.total_reads,
342            cs.total_original,
343            cs.total_compressed,
344            &cs.mode_counts,
345            cs.tool_call_count,
346            &cs.complexity,
347        );
348    }
349}
350
351pub fn create_server() -> LeanCtxServer {
352    LeanCtxServer::new()
353}
354
355fn auto_consolidate_knowledge(project_root: &str) {
356    use crate::core::knowledge::ProjectKnowledge;
357    use crate::core::session::SessionState;
358
359    let session = match SessionState::load_latest() {
360        Some(s) => s,
361        None => return,
362    };
363
364    if session.findings.is_empty() && session.decisions.is_empty() {
365        return;
366    }
367
368    let mut knowledge = ProjectKnowledge::load_or_create(project_root);
369
370    for finding in &session.findings {
371        let key = if let Some(ref file) = finding.file {
372            if let Some(line) = finding.line {
373                format!("{file}:{line}")
374            } else {
375                file.clone()
376            }
377        } else {
378            "finding-auto".to_string()
379        };
380        knowledge.remember("finding", &key, &finding.summary, &session.id, 0.7);
381    }
382
383    for decision in &session.decisions {
384        let key = decision
385            .summary
386            .chars()
387            .take(50)
388            .collect::<String>()
389            .replace(' ', "-")
390            .to_lowercase();
391        knowledge.remember("decision", &key, &decision.summary, &session.id, 0.85);
392    }
393
394    let task_desc = session
395        .task
396        .as_ref()
397        .map(|t| t.description.clone())
398        .unwrap_or_default();
399
400    let summary = format!(
401        "Auto-consolidate session {}: {} — {} findings, {} decisions",
402        session.id,
403        task_desc,
404        session.findings.len(),
405        session.decisions.len()
406    );
407    knowledge.consolidate(&summary, vec![session.id.clone()]);
408    let _ = knowledge.save();
409}