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