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