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
395                .as_ref()
396                .and_then(|c| c.fingerprint.has_safe_identity().then(|| c.fingerprint.clone())),
397            checkout_binding: project_context.as_ref().map(|c| c.checkout_binding.clone()),
398            project_slug: project_context
399                .as_ref()
400                .map(|c| c.project_slug.clone())
401                .filter(|s| !s.is_empty())
402                .or_else(|| {
403                    let slug = std::path::Path::new(&session_slug)
404                        .file_name()
405                        .and_then(|n| n.to_str())
406                        .unwrap_or("unknown")
407                        .to_string();
408                    Some(slug)
409                }),
410        };
411        crate::core::telemetry_queue::enqueue(request);
412    }
413
414    pub async fn is_prompt_cache_stale(&self) -> bool {
415        let last = *self.last_call.read().await;
416        last.elapsed().as_secs() > 3600
417    }
418
419    pub fn upgrade_mode_if_stale(mode: &str, stale: bool) -> &str {
420        if !stale {
421            return mode;
422        }
423        match mode {
424            "full" => "full",
425            "map" => "signatures",
426            m => m,
427        }
428    }
429
430    pub fn increment_and_check(&self) -> bool {
431        let count = self.call_count.fetch_add(1, Ordering::Relaxed) + 1;
432        self.checkpoint_interval > 0 && count.is_multiple_of(self.checkpoint_interval)
433    }
434
435    pub async fn auto_checkpoint(&self) -> Option<String> {
436        let cache = self.cache.read().await;
437        if cache.get_all_entries().is_empty() {
438            return None;
439        }
440        let complexity = crate::core::adaptive::classify_from_context(&cache);
441        let checkpoint = ctx_compress::handle(&cache, true, self.crp_mode);
442        drop(cache);
443
444        let mut session = self.session.write().await;
445        let _ = session.save();
446        let session_summary = session.format_compact();
447        let has_insights = !session.findings.is_empty() || !session.decisions.is_empty();
448        let project_root = session.project_root.clone();
449        drop(session);
450
451        if has_insights {
452            if let Some(ref root) = project_root {
453                let root = root.clone();
454                std::thread::spawn(move || {
455                    auto_consolidate_knowledge(&root);
456                });
457            }
458        }
459
460        let multi_agent_block = self.auto_multi_agent_checkpoint(&project_root).await;
461
462        self.record_call("ctx_compress", 0, 0, Some("auto".to_string()))
463            .await;
464
465        self.record_cep_snapshot().await;
466
467        Some(format!(
468            "{checkpoint}\n\n--- SESSION STATE ---\n{session_summary}\n\n{}{multi_agent_block}",
469            complexity.instruction_suffix()
470        ))
471    }
472
473    async fn auto_multi_agent_checkpoint(&self, project_root: &Option<String>) -> String {
474        let root = match project_root {
475            Some(r) => r,
476            None => return String::new(),
477        };
478
479        let registry = crate::core::agents::AgentRegistry::load_or_create();
480        let active = registry.list_active(Some(root));
481        if active.len() <= 1 {
482            return String::new();
483        }
484
485        let agent_id = self.agent_id.read().await;
486        let my_id = match agent_id.as_deref() {
487            Some(id) => id.to_string(),
488            None => return String::new(),
489        };
490        drop(agent_id);
491
492        let cache = self.cache.read().await;
493        let entries = cache.get_all_entries();
494        if !entries.is_empty() {
495            let mut by_access: Vec<_> = entries.iter().collect();
496            by_access.sort_by_key(|x| std::cmp::Reverse(x.1.read_count));
497            let top_paths: Vec<&str> = by_access
498                .iter()
499                .take(5)
500                .map(|(key, _)| key.as_str())
501                .collect();
502            let paths_csv = top_paths.join(",");
503
504            let _ = ctx_share::handle("push", Some(&my_id), None, Some(&paths_csv), None, &cache);
505        }
506        drop(cache);
507
508        let pending_count = registry
509            .scratchpad
510            .iter()
511            .filter(|e| !e.read_by.contains(&my_id) && e.from_agent != my_id)
512            .count();
513
514        let shared_dir = crate::core::data_dir::nebu_ctx_data_dir()
515            .unwrap_or_default()
516            .join("agents")
517            .join("shared");
518        let shared_count = if shared_dir.exists() {
519            std::fs::read_dir(&shared_dir)
520                .map(|rd| rd.count())
521                .unwrap_or(0)
522        } else {
523            0
524        };
525
526        let agent_names: Vec<String> = active
527            .iter()
528            .map(|a| {
529                let role = a.role.as_deref().unwrap_or(&a.agent_type);
530                format!("{role}({})", &a.agent_id[..8.min(a.agent_id.len())])
531            })
532            .collect();
533
534        format!(
535            "\n\n--- MULTI-AGENT SYNC ---\nAgents: {} | Pending msgs: {} | Shared contexts: {}\nAuto-shared top-5 cached files.\n--- END SYNC ---",
536            agent_names.join(", "),
537            pending_count,
538            shared_count,
539        )
540    }
541
542    pub fn append_tool_call_log(
543        tool: &str,
544        duration_ms: u64,
545        original: usize,
546        saved: usize,
547        mode: Option<&str>,
548        timestamp: &str,
549    ) {
550        const MAX_LOG_LINES: usize = 50;
551        if let Ok(dir) = crate::core::data_dir::nebu_ctx_data_dir() {
552            let log_path = dir.join("tool-calls.log");
553            let mode_str = mode.unwrap_or("-");
554            let slow = if duration_ms > 5000 { " **SLOW**" } else { "" };
555            let line = format!(
556                "{timestamp}\t{tool}\t{duration_ms}ms\torig={original}\tsaved={saved}\tmode={mode_str}{slow}\n"
557            );
558
559            let mut lines: Vec<String> = std::fs::read_to_string(&log_path)
560                .unwrap_or_default()
561                .lines()
562                .map(|l| l.to_string())
563                .collect();
564
565            lines.push(line.trim_end().to_string());
566            if lines.len() > MAX_LOG_LINES {
567                lines.drain(0..lines.len() - MAX_LOG_LINES);
568            }
569
570            let _ = std::fs::write(&log_path, lines.join("\n") + "\n");
571        }
572    }
573
574    fn compute_cep_stats(
575        calls: &[ToolCallRecord],
576        stats: &crate::core::cache::CacheStats,
577        complexity: &crate::core::adaptive::TaskComplexity,
578    ) -> CepComputedStats {
579        let total_original: u64 = calls.iter().map(|c| c.original_tokens as u64).sum();
580        let total_saved: u64 = calls.iter().map(|c| c.saved_tokens as u64).sum();
581        let total_compressed = total_original.saturating_sub(total_saved);
582        let compression_rate = if total_original > 0 {
583            total_saved as f64 / total_original as f64
584        } else {
585            0.0
586        };
587
588        let modes_used: std::collections::HashSet<&str> =
589            calls.iter().filter_map(|c| c.mode.as_deref()).collect();
590        let mode_diversity = (modes_used.len() as f64 / 10.0).min(1.0);
591        let cache_util = stats.hit_rate() / 100.0;
592        let cep_score = cache_util * 0.3 + mode_diversity * 0.2 + compression_rate * 0.5;
593
594        let mut mode_counts: std::collections::HashMap<String, u64> =
595            std::collections::HashMap::new();
596        for call in calls {
597            if let Some(ref mode) = call.mode {
598                *mode_counts.entry(mode.clone()).or_insert(0) += 1;
599            }
600        }
601
602        CepComputedStats {
603            cep_score: (cep_score * 100.0).round() as u32,
604            cache_util: (cache_util * 100.0).round() as u32,
605            mode_diversity: (mode_diversity * 100.0).round() as u32,
606            compression_rate: (compression_rate * 100.0).round() as u32,
607            total_original,
608            total_compressed,
609            total_saved,
610            mode_counts,
611            complexity: format!("{:?}", complexity),
612            cache_hits: stats.cache_hits,
613            total_reads: stats.total_reads,
614            tool_call_count: calls.len() as u64,
615        }
616    }
617
618    async fn write_mcp_live_stats(&self) {
619        let cache = self.cache.read().await;
620        let calls = self.tool_calls.read().await;
621        let stats = cache.get_stats();
622        let complexity = crate::core::adaptive::classify_from_context(&cache);
623
624        let cs = Self::compute_cep_stats(&calls, stats, &complexity);
625        let started_at = calls
626            .first()
627            .map(|c| c.timestamp.clone())
628            .unwrap_or_default();
629
630        drop(cache);
631        drop(calls);
632        let live = serde_json::json!({
633            "cep_score": cs.cep_score,
634            "cache_utilization": cs.cache_util,
635            "mode_diversity": cs.mode_diversity,
636            "compression_rate": cs.compression_rate,
637            "task_complexity": cs.complexity,
638            "files_cached": cs.total_reads,
639            "total_reads": cs.total_reads,
640            "cache_hits": cs.cache_hits,
641            "tokens_saved": cs.total_saved,
642            "tokens_original": cs.total_original,
643            "tool_calls": cs.tool_call_count,
644            "started_at": started_at,
645            "updated_at": chrono::Local::now().to_rfc3339(),
646        });
647
648        if let Ok(dir) = crate::core::data_dir::nebu_ctx_data_dir() {
649            let _ = std::fs::write(dir.join("mcp-live.json"), live.to_string());
650        }
651    }
652
653    pub async fn record_cep_snapshot(&self) {
654        let cache = self.cache.read().await;
655        let calls = self.tool_calls.read().await;
656        let stats = cache.get_stats();
657        let complexity = crate::core::adaptive::classify_from_context(&cache);
658
659        let cs = Self::compute_cep_stats(&calls, stats, &complexity);
660
661        drop(cache);
662        drop(calls);
663
664        crate::core::stats::record_cep_session(
665            cs.cep_score,
666            cs.cache_hits,
667            cs.total_reads,
668            cs.total_original,
669            cs.total_compressed,
670            &cs.mode_counts,
671            cs.tool_call_count,
672            &cs.complexity,
673        );
674    }
675}
676
677#[derive(Clone, Debug, Default)]
678struct StartupContext {
679    project_root: Option<String>,
680    shell_cwd: Option<String>,
681}
682
683pub fn create_server() -> LeanCtxServer {
684    LeanCtxServer::new()
685}
686
687const PROJECT_ROOT_MARKERS: &[&str] = &[
688    ".git",
689    ".lean-ctx.toml",
690    "Cargo.toml",
691    "package.json",
692    "go.mod",
693    "pyproject.toml",
694    "pom.xml",
695    "build.gradle",
696    "Makefile",
697    ".planning",
698];
699
700fn has_project_marker(dir: &std::path::Path) -> bool {
701    PROJECT_ROOT_MARKERS.iter().any(|m| dir.join(m).exists())
702}
703
704fn is_suspicious_root(dir: &std::path::Path) -> bool {
705    let s = dir.to_string_lossy();
706    s.contains("/.claude")
707        || s.contains("/.codex")
708        || s.contains("\\.claude")
709        || s.contains("\\.codex")
710}
711
712fn canonicalize_path(path: &std::path::Path) -> String {
713    crate::core::pathutil::safe_canonicalize_or_self(path)
714        .to_string_lossy()
715        .to_string()
716}
717
718fn detect_startup_context(
719    explicit_project_root: Option<&str>,
720    startup_cwd: Option<&std::path::Path>,
721) -> StartupContext {
722    let shell_cwd = startup_cwd.map(canonicalize_path);
723    let project_root = explicit_project_root
724        .map(|root| canonicalize_path(std::path::Path::new(root)))
725        .or_else(|| {
726            startup_cwd
727                .and_then(maybe_derive_project_root_from_absolute)
728                .map(|p| canonicalize_path(&p))
729        });
730
731    let shell_cwd = match (shell_cwd, project_root.as_ref()) {
732        (Some(cwd), Some(root))
733            if std::path::Path::new(&cwd).starts_with(std::path::Path::new(root)) =>
734        {
735            Some(cwd)
736        }
737        (Some(_), Some(root)) => Some(root.clone()),
738        (Some(cwd), None) => Some(cwd),
739        (None, Some(root)) => Some(root.clone()),
740        (None, None) => None,
741    };
742
743    StartupContext {
744        project_root,
745        shell_cwd,
746    }
747}
748
749fn maybe_derive_project_root_from_absolute(abs: &std::path::Path) -> Option<std::path::PathBuf> {
750    let mut cur = if abs.is_dir() {
751        abs.to_path_buf()
752    } else {
753        abs.parent()?.to_path_buf()
754    };
755    loop {
756        if has_project_marker(&cur) {
757            return Some(crate::core::pathutil::safe_canonicalize_or_self(&cur));
758        }
759        if !cur.pop() {
760            break;
761        }
762    }
763    None
764}
765
766fn auto_consolidate_knowledge(project_root: &str) {
767    use crate::core::knowledge::ProjectKnowledge;
768    use crate::core::session::SessionState;
769
770    let session = match SessionState::load_latest() {
771        Some(s) => s,
772        None => return,
773    };
774
775    if session.findings.is_empty() && session.decisions.is_empty() {
776        return;
777    }
778
779    let mut knowledge = ProjectKnowledge::load_or_create(project_root);
780
781    for finding in &session.findings {
782        let key = if let Some(ref file) = finding.file {
783            if let Some(line) = finding.line {
784                format!("{file}:{line}")
785            } else {
786                file.clone()
787            }
788        } else {
789            "finding-auto".to_string()
790        };
791        knowledge.remember("finding", &key, &finding.summary, &session.id, 0.7);
792    }
793
794    for decision in &session.decisions {
795        let key = decision
796            .summary
797            .chars()
798            .take(50)
799            .collect::<String>()
800            .replace(' ', "-")
801            .to_lowercase();
802        knowledge.remember("decision", &key, &decision.summary, &session.id, 0.85);
803    }
804
805    let task_desc = session
806        .task
807        .as_ref()
808        .map(|t| t.description.clone())
809        .unwrap_or_default();
810
811    let summary = format!(
812        "Auto-consolidate session {}: {} — {} findings, {} decisions",
813        session.id,
814        task_desc,
815        session.findings.len(),
816        session.decisions.len()
817    );
818    knowledge.consolidate(&summary, vec![session.id.clone()]);
819    let _ = knowledge.save();
820}
821
822#[cfg(test)]
823mod resolve_path_tests {
824    use super::*;
825
826    fn create_git_root(path: &std::path::Path) -> String {
827        std::fs::create_dir_all(path.join(".git")).unwrap();
828        canonicalize_path(path)
829    }
830
831    #[tokio::test]
832    async fn resolve_path_can_reroot_to_trusted_startup_root_when_session_root_is_stale() {
833        let tmp = tempfile::tempdir().unwrap();
834        let stale = tmp.path().join("stale");
835        let real = tmp.path().join("real");
836        std::fs::create_dir_all(&stale).unwrap();
837        let real_root = create_git_root(&real);
838        std::fs::write(real.join("a.txt"), "ok").unwrap();
839
840        let server = LeanCtxServer::new_with_startup(None, Some(real.clone()));
841        {
842            let mut session = server.session.write().await;
843            session.project_root = Some(stale.to_string_lossy().to_string());
844            session.shell_cwd = Some(stale.to_string_lossy().to_string());
845        }
846
847        let out = server
848            .resolve_path(&real.join("a.txt").to_string_lossy())
849            .await
850            .unwrap();
851
852        assert!(out.ends_with("/a.txt"));
853
854        let session = server.session.read().await;
855        assert_eq!(session.project_root.as_deref(), Some(real_root.as_str()));
856        assert_eq!(session.shell_cwd.as_deref(), Some(real_root.as_str()));
857    }
858
859    #[tokio::test]
860    async fn resolve_path_rejects_absolute_path_outside_trusted_startup_root() {
861        let tmp = tempfile::tempdir().unwrap();
862        let stale = tmp.path().join("stale");
863        let root = tmp.path().join("root");
864        let other = tmp.path().join("other");
865        std::fs::create_dir_all(&stale).unwrap();
866        create_git_root(&root);
867        let _other_value = create_git_root(&other);
868        std::fs::write(other.join("b.txt"), "no").unwrap();
869
870        let server = LeanCtxServer::new_with_startup(None, Some(root.clone()));
871        {
872            let mut session = server.session.write().await;
873            session.project_root = Some(stale.to_string_lossy().to_string());
874            session.shell_cwd = Some(stale.to_string_lossy().to_string());
875        }
876
877        let err = server
878            .resolve_path(&other.join("b.txt").to_string_lossy())
879            .await
880            .unwrap_err();
881        assert!(err.contains("path escapes project root"));
882
883        let session = server.session.read().await;
884        assert_eq!(
885            session.project_root.as_deref(),
886            Some(stale.to_string_lossy().as_ref())
887        );
888    }
889
890    #[tokio::test]
891    async fn startup_prefers_workspace_scoped_session_over_global_latest() {
892        let _data = tempfile::tempdir().unwrap();
893        let _tmp = tempfile::tempdir().unwrap();
894
895        let (server, root_b) = {
896            let _lock = crate::core::data_dir::test_env_lock();
897            std::env::set_var("NEBU_CTX_DATA_DIR", _data.path());
898
899            let repo_a = _tmp.path().join("repo-a");
900            let repo_b = _tmp.path().join("repo-b");
901            let root_a = create_git_root(&repo_a);
902            let root_b = create_git_root(&repo_b);
903
904            let mut session_b = SessionState::new();
905            session_b.project_root = Some(root_b.clone());
906            session_b.shell_cwd = Some(root_b.clone());
907            session_b.set_task("repo-b task", None);
908            session_b.save().unwrap();
909
910            let mut session_a = SessionState::new();
911            session_a.project_root = Some(root_a.clone());
912            session_a.shell_cwd = Some(root_a.clone());
913            session_a.set_task("repo-a latest task", None);
914            session_a.save().unwrap();
915
916            let server = LeanCtxServer::new_with_startup(None, Some(repo_b.clone()));
917            std::env::remove_var("NEBU_CTX_DATA_DIR");
918            (server, root_b)
919        };
920
921        let session = server.session.read().await;
922        assert_eq!(session.project_root.as_deref(), Some(root_b.as_str()));
923        assert_eq!(session.shell_cwd.as_deref(), Some(root_b.as_str()));
924        assert_eq!(
925            session.task.as_ref().map(|t| t.description.as_str()),
926            Some("repo-b task")
927        );
928    }
929
930    #[tokio::test]
931    async fn startup_creates_fresh_session_for_new_workspace_and_preserves_subdir_cwd() {
932        let _data = tempfile::tempdir().unwrap();
933        let _tmp = tempfile::tempdir().unwrap();
934
935        let (server, root_b, repo_b_src_value, old_id) = {
936            let _lock = crate::core::data_dir::test_env_lock();
937            std::env::set_var("NEBU_CTX_DATA_DIR", _data.path());
938
939            let repo_a = _tmp.path().join("repo-a");
940            let repo_b = _tmp.path().join("repo-b");
941            let repo_b_src = repo_b.join("src");
942            let root_a = create_git_root(&repo_a);
943            let root_b = create_git_root(&repo_b);
944            std::fs::create_dir_all(&repo_b_src).unwrap();
945            let repo_b_src_value = canonicalize_path(&repo_b_src);
946
947            let mut session_a = SessionState::new();
948            session_a.project_root = Some(root_a.clone());
949            session_a.shell_cwd = Some(root_a.clone());
950            session_a.set_task("repo-a latest task", None);
951            let old_id = session_a.id.clone();
952            session_a.save().unwrap();
953
954            let server = LeanCtxServer::new_with_startup(None, Some(repo_b_src.clone()));
955            std::env::remove_var("NEBU_CTX_DATA_DIR");
956            (server, root_b, repo_b_src_value, old_id)
957        };
958
959        let session = server.session.read().await;
960        assert_eq!(session.project_root.as_deref(), Some(root_b.as_str()));
961        assert_eq!(
962            session.shell_cwd.as_deref(),
963            Some(repo_b_src_value.as_str())
964        );
965        assert!(session.task.is_none());
966        assert_ne!(session.id, old_id);
967    }
968
969    #[tokio::test]
970    async fn resolve_path_does_not_auto_update_when_current_root_is_real_project() {
971        let tmp = tempfile::tempdir().unwrap();
972        let root = tmp.path().join("root");
973        let other = tmp.path().join("other");
974        let root_value = create_git_root(&root);
975        create_git_root(&other);
976        std::fs::write(other.join("b.txt"), "no").unwrap();
977
978        let server = LeanCtxServer::new_with_project_root(Some(root.to_string_lossy().to_string()));
979
980        let err = server
981            .resolve_path(&other.join("b.txt").to_string_lossy())
982            .await
983            .unwrap_err();
984        assert!(err.contains("path escapes project root"));
985
986        let session = server.session.read().await;
987        assert_eq!(session.project_root.as_deref(), Some(root_value.as_str()));
988    }
989
990    #[cfg(unix)]
991    #[tokio::test]
992    async fn resolve_path_reroots_symlinked_workspace_path_when_shell_root_is_not_a_project() {
993        use std::os::unix::fs::symlink;
994
995        let data = tempfile::tempdir().unwrap();
996        let tmp = tempfile::tempdir().unwrap();
997        let home = tmp.path().join("home");
998        let mnt = tmp.path().join("mnt");
999        let real_repo = mnt.join("work").join("repo");
1000        let symlink_root = home.join("Work");
1001
1002        let _lock = crate::core::data_dir::test_env_lock();
1003        std::env::set_var("NEBU_CTX_DATA_DIR", data.path());
1004
1005        std::fs::create_dir_all(&home).unwrap();
1006        std::fs::create_dir_all(real_repo.join(".git")).unwrap();
1007        std::fs::write(real_repo.join("a.txt"), "ok").unwrap();
1008        symlink(real_repo.parent().unwrap(), &symlink_root).unwrap();
1009
1010        let aliased_file = symlink_root.join("repo").join("a.txt");
1011        let server = LeanCtxServer::new_with_startup(None, Some(home.clone()));
1012        std::env::remove_var("NEBU_CTX_DATA_DIR");
1013
1014        let out = server
1015            .resolve_path(&aliased_file.to_string_lossy())
1016            .await
1017            .unwrap();
1018
1019        assert_eq!(out, real_repo.join("a.txt").to_string_lossy());
1020
1021        let session = server.session.read().await;
1022        assert_eq!(session.project_root.as_deref(), Some(real_repo.to_string_lossy().as_ref()));
1023        assert_eq!(session.shell_cwd.as_deref(), Some(real_repo.to_string_lossy().as_ref()));
1024    }
1025}