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