Skip to main content

lean_ctx/tools/
mod.rs

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