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