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 candidate_under_jail = resolved.starts_with(jail_root_path);
252                        let allow_reroot = if !candidate_under_jail {
253                            if let Some(ref trusted_root) = self.startup_project_root {
254                                std::path::Path::new(trusted_root) == new_root.as_path()
255                            } else {
256                                !has_project_marker(jail_root_path)
257                                    || is_suspicious_root(jail_root_path)
258                            }
259                        } else {
260                            false
261                        };
262
263                        if allow_reroot {
264                            let mut session = self.session.write().await;
265                            let new_root_str = new_root.to_string_lossy().to_string();
266                            session.project_root = Some(new_root_str.clone());
267                            session.shell_cwd = self
268                                .startup_shell_cwd
269                                .as_ref()
270                                .filter(|cwd| std::path::Path::new(cwd).starts_with(&new_root))
271                                .cloned()
272                                .or_else(|| Some(new_root_str.clone()));
273                            let _ = session.save();
274
275                            crate::core::pathjail::jail_path(&resolved, &new_root)?
276                        } else {
277                            return Err(e);
278                        }
279                    } else {
280                        return Err(e);
281                    }
282                } else {
283                    return Err(e);
284                }
285            }
286        };
287
288        Ok(crate::hooks::normalize_tool_path(
289            &jailed.to_string_lossy().replace('\\', "/"),
290        ))
291    }
292
293    pub async fn resolve_path_or_passthrough(&self, path: &str) -> String {
294        self.resolve_path(path)
295            .await
296            .unwrap_or_else(|_| path.to_string())
297    }
298
299    pub async fn check_idle_expiry(&self) {
300        if self.cache_ttl_secs == 0 {
301            return;
302        }
303        let last = *self.last_call.read().await;
304        if last.elapsed().as_secs() >= self.cache_ttl_secs {
305            {
306                let mut session = self.session.write().await;
307                let _ = session.save();
308            }
309            let mut cache = self.cache.write().await;
310            let count = cache.clear();
311            if count > 0 {
312                tracing::info!(
313                    "Cache auto-cleared after {}s idle ({count} file(s))",
314                    self.cache_ttl_secs
315                );
316            }
317        }
318        *self.last_call.write().await = Instant::now();
319    }
320
321    pub async fn record_call(
322        &self,
323        tool: &str,
324        original: usize,
325        saved: usize,
326        mode: Option<String>,
327    ) {
328        self.record_call_with_timing(tool, original, saved, mode, 0)
329            .await;
330    }
331
332    pub async fn record_call_with_timing(
333        &self,
334        tool: &str,
335        original: usize,
336        saved: usize,
337        mode: Option<String>,
338        duration_ms: u64,
339    ) {
340        let ts = chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string();
341        let mut calls = self.tool_calls.write().await;
342        calls.push(ToolCallRecord {
343            tool: tool.to_string(),
344            original_tokens: original,
345            saved_tokens: saved,
346            mode: mode.clone(),
347            duration_ms,
348            timestamp: ts.clone(),
349        });
350
351        if duration_ms > 0 {
352            Self::append_tool_call_log(tool, duration_ms, original, saved, mode.as_deref(), &ts);
353        }
354
355        crate::core::events::emit_tool_call(
356            tool,
357            original as u64,
358            saved as u64,
359            mode.clone(),
360            duration_ms,
361            None,
362        );
363
364        let output_tokens = original.saturating_sub(saved);
365        crate::core::stats::record(tool, original, output_tokens);
366
367        let mut session = self.session.write().await;
368        session.record_tool_call(saved as u64, original as u64);
369        if tool == "ctx_shell" {
370            session.record_command();
371        }
372        if session.should_save() {
373            let _ = session.save();
374        }
375        drop(calls);
376        drop(session);
377
378        self.write_mcp_live_stats().await;
379
380        // Ship this event to the cloud server via the in-process queue.
381        // enqueue() returns immediately; the drain task handles the HTTP POST.
382        let session_slug = {
383            let session = self.session.read().await;
384            session.project_root.clone().unwrap_or_default()
385        };
386        let project_context = std::env::current_dir()
387            .ok()
388            .map(|d| crate::git_context::discover_project_context(&d));
389        let request = crate::models::TelemetryIngestRequest {
390            tool_name: tool.to_string(),
391            tokens_original: original as i64,
392            tokens_saved: saved as i64,
393            duration_ms: duration_ms as i64,
394            mode,
395            repository_fingerprint: project_context.as_ref().map(|c| c.fingerprint.clone()),
396            checkout_binding: project_context.as_ref().map(|c| c.checkout_binding.clone()),
397            project_slug: project_context
398                .as_ref()
399                .map(|c| c.project_slug.clone())
400                .filter(|s| !s.is_empty())
401                .or_else(|| {
402                    let slug = std::path::Path::new(&session_slug)
403                        .file_name()
404                        .and_then(|n| n.to_str())
405                        .unwrap_or("unknown")
406                        .to_string();
407                    Some(slug)
408                }),
409        };
410        crate::core::telemetry_queue::enqueue(request);
411    }
412
413    pub async fn is_prompt_cache_stale(&self) -> bool {
414        let last = *self.last_call.read().await;
415        last.elapsed().as_secs() > 3600
416    }
417
418    pub fn upgrade_mode_if_stale(mode: &str, stale: bool) -> &str {
419        if !stale {
420            return mode;
421        }
422        match mode {
423            "full" => "full",
424            "map" => "signatures",
425            m => m,
426        }
427    }
428
429    pub fn increment_and_check(&self) -> bool {
430        let count = self.call_count.fetch_add(1, Ordering::Relaxed) + 1;
431        self.checkpoint_interval > 0 && count.is_multiple_of(self.checkpoint_interval)
432    }
433
434    pub async fn auto_checkpoint(&self) -> Option<String> {
435        let cache = self.cache.read().await;
436        if cache.get_all_entries().is_empty() {
437            return None;
438        }
439        let complexity = crate::core::adaptive::classify_from_context(&cache);
440        let checkpoint = ctx_compress::handle(&cache, true, self.crp_mode);
441        drop(cache);
442
443        let mut session = self.session.write().await;
444        let _ = session.save();
445        let session_summary = session.format_compact();
446        let has_insights = !session.findings.is_empty() || !session.decisions.is_empty();
447        let project_root = session.project_root.clone();
448        drop(session);
449
450        if has_insights {
451            if let Some(ref root) = project_root {
452                let root = root.clone();
453                std::thread::spawn(move || {
454                    auto_consolidate_knowledge(&root);
455                });
456            }
457        }
458
459        let multi_agent_block = self.auto_multi_agent_checkpoint(&project_root).await;
460
461        self.record_call("ctx_compress", 0, 0, Some("auto".to_string()))
462            .await;
463
464        self.record_cep_snapshot().await;
465
466        Some(format!(
467            "{checkpoint}\n\n--- SESSION STATE ---\n{session_summary}\n\n{}{multi_agent_block}",
468            complexity.instruction_suffix()
469        ))
470    }
471
472    async fn auto_multi_agent_checkpoint(&self, project_root: &Option<String>) -> String {
473        let root = match project_root {
474            Some(r) => r,
475            None => return String::new(),
476        };
477
478        let registry = crate::core::agents::AgentRegistry::load_or_create();
479        let active = registry.list_active(Some(root));
480        if active.len() <= 1 {
481            return String::new();
482        }
483
484        let agent_id = self.agent_id.read().await;
485        let my_id = match agent_id.as_deref() {
486            Some(id) => id.to_string(),
487            None => return String::new(),
488        };
489        drop(agent_id);
490
491        let cache = self.cache.read().await;
492        let entries = cache.get_all_entries();
493        if !entries.is_empty() {
494            let mut by_access: Vec<_> = entries.iter().collect();
495            by_access.sort_by_key(|x| std::cmp::Reverse(x.1.read_count));
496            let top_paths: Vec<&str> = by_access
497                .iter()
498                .take(5)
499                .map(|(key, _)| key.as_str())
500                .collect();
501            let paths_csv = top_paths.join(",");
502
503            let _ = ctx_share::handle("push", Some(&my_id), None, Some(&paths_csv), None, &cache);
504        }
505        drop(cache);
506
507        let pending_count = registry
508            .scratchpad
509            .iter()
510            .filter(|e| !e.read_by.contains(&my_id) && e.from_agent != my_id)
511            .count();
512
513        let shared_dir = crate::core::data_dir::nebu_ctx_data_dir()
514            .unwrap_or_default()
515            .join("agents")
516            .join("shared");
517        let shared_count = if shared_dir.exists() {
518            std::fs::read_dir(&shared_dir)
519                .map(|rd| rd.count())
520                .unwrap_or(0)
521        } else {
522            0
523        };
524
525        let agent_names: Vec<String> = active
526            .iter()
527            .map(|a| {
528                let role = a.role.as_deref().unwrap_or(&a.agent_type);
529                format!("{role}({})", &a.agent_id[..8.min(a.agent_id.len())])
530            })
531            .collect();
532
533        format!(
534            "\n\n--- MULTI-AGENT SYNC ---\nAgents: {} | Pending msgs: {} | Shared contexts: {}\nAuto-shared top-5 cached files.\n--- END SYNC ---",
535            agent_names.join(", "),
536            pending_count,
537            shared_count,
538        )
539    }
540
541    pub fn append_tool_call_log(
542        tool: &str,
543        duration_ms: u64,
544        original: usize,
545        saved: usize,
546        mode: Option<&str>,
547        timestamp: &str,
548    ) {
549        const MAX_LOG_LINES: usize = 50;
550        if let Ok(dir) = crate::core::data_dir::nebu_ctx_data_dir() {
551            let log_path = dir.join("tool-calls.log");
552            let mode_str = mode.unwrap_or("-");
553            let slow = if duration_ms > 5000 { " **SLOW**" } else { "" };
554            let line = format!(
555                "{timestamp}\t{tool}\t{duration_ms}ms\torig={original}\tsaved={saved}\tmode={mode_str}{slow}\n"
556            );
557
558            let mut lines: Vec<String> = std::fs::read_to_string(&log_path)
559                .unwrap_or_default()
560                .lines()
561                .map(|l| l.to_string())
562                .collect();
563
564            lines.push(line.trim_end().to_string());
565            if lines.len() > MAX_LOG_LINES {
566                lines.drain(0..lines.len() - MAX_LOG_LINES);
567            }
568
569            let _ = std::fs::write(&log_path, lines.join("\n") + "\n");
570        }
571    }
572
573    fn compute_cep_stats(
574        calls: &[ToolCallRecord],
575        stats: &crate::core::cache::CacheStats,
576        complexity: &crate::core::adaptive::TaskComplexity,
577    ) -> CepComputedStats {
578        let total_original: u64 = calls.iter().map(|c| c.original_tokens as u64).sum();
579        let total_saved: u64 = calls.iter().map(|c| c.saved_tokens as u64).sum();
580        let total_compressed = total_original.saturating_sub(total_saved);
581        let compression_rate = if total_original > 0 {
582            total_saved as f64 / total_original as f64
583        } else {
584            0.0
585        };
586
587        let modes_used: std::collections::HashSet<&str> =
588            calls.iter().filter_map(|c| c.mode.as_deref()).collect();
589        let mode_diversity = (modes_used.len() as f64 / 10.0).min(1.0);
590        let cache_util = stats.hit_rate() / 100.0;
591        let cep_score = cache_util * 0.3 + mode_diversity * 0.2 + compression_rate * 0.5;
592
593        let mut mode_counts: std::collections::HashMap<String, u64> =
594            std::collections::HashMap::new();
595        for call in calls {
596            if let Some(ref mode) = call.mode {
597                *mode_counts.entry(mode.clone()).or_insert(0) += 1;
598            }
599        }
600
601        CepComputedStats {
602            cep_score: (cep_score * 100.0).round() as u32,
603            cache_util: (cache_util * 100.0).round() as u32,
604            mode_diversity: (mode_diversity * 100.0).round() as u32,
605            compression_rate: (compression_rate * 100.0).round() as u32,
606            total_original,
607            total_compressed,
608            total_saved,
609            mode_counts,
610            complexity: format!("{:?}", complexity),
611            cache_hits: stats.cache_hits,
612            total_reads: stats.total_reads,
613            tool_call_count: calls.len() as u64,
614        }
615    }
616
617    async fn write_mcp_live_stats(&self) {
618        let cache = self.cache.read().await;
619        let calls = self.tool_calls.read().await;
620        let stats = cache.get_stats();
621        let complexity = crate::core::adaptive::classify_from_context(&cache);
622
623        let cs = Self::compute_cep_stats(&calls, stats, &complexity);
624        let started_at = calls
625            .first()
626            .map(|c| c.timestamp.clone())
627            .unwrap_or_default();
628
629        drop(cache);
630        drop(calls);
631        let live = serde_json::json!({
632            "cep_score": cs.cep_score,
633            "cache_utilization": cs.cache_util,
634            "mode_diversity": cs.mode_diversity,
635            "compression_rate": cs.compression_rate,
636            "task_complexity": cs.complexity,
637            "files_cached": cs.total_reads,
638            "total_reads": cs.total_reads,
639            "cache_hits": cs.cache_hits,
640            "tokens_saved": cs.total_saved,
641            "tokens_original": cs.total_original,
642            "tool_calls": cs.tool_call_count,
643            "started_at": started_at,
644            "updated_at": chrono::Local::now().to_rfc3339(),
645        });
646
647        if let Ok(dir) = crate::core::data_dir::nebu_ctx_data_dir() {
648            let _ = std::fs::write(dir.join("mcp-live.json"), live.to_string());
649        }
650    }
651
652    pub async fn record_cep_snapshot(&self) {
653        let cache = self.cache.read().await;
654        let calls = self.tool_calls.read().await;
655        let stats = cache.get_stats();
656        let complexity = crate::core::adaptive::classify_from_context(&cache);
657
658        let cs = Self::compute_cep_stats(&calls, stats, &complexity);
659
660        drop(cache);
661        drop(calls);
662
663        crate::core::stats::record_cep_session(
664            cs.cep_score,
665            cs.cache_hits,
666            cs.total_reads,
667            cs.total_original,
668            cs.total_compressed,
669            &cs.mode_counts,
670            cs.tool_call_count,
671            &cs.complexity,
672        );
673    }
674}
675
676#[derive(Clone, Debug, Default)]
677struct StartupContext {
678    project_root: Option<String>,
679    shell_cwd: Option<String>,
680}
681
682pub fn create_server() -> LeanCtxServer {
683    LeanCtxServer::new()
684}
685
686const PROJECT_ROOT_MARKERS: &[&str] = &[
687    ".git",
688    ".lean-ctx.toml",
689    "Cargo.toml",
690    "package.json",
691    "go.mod",
692    "pyproject.toml",
693    "pom.xml",
694    "build.gradle",
695    "Makefile",
696    ".planning",
697];
698
699fn has_project_marker(dir: &std::path::Path) -> bool {
700    PROJECT_ROOT_MARKERS.iter().any(|m| dir.join(m).exists())
701}
702
703fn is_suspicious_root(dir: &std::path::Path) -> bool {
704    let s = dir.to_string_lossy();
705    s.contains("/.claude")
706        || s.contains("/.codex")
707        || s.contains("\\.claude")
708        || s.contains("\\.codex")
709}
710
711fn canonicalize_path(path: &std::path::Path) -> String {
712    crate::core::pathutil::safe_canonicalize_or_self(path)
713        .to_string_lossy()
714        .to_string()
715}
716
717fn detect_startup_context(
718    explicit_project_root: Option<&str>,
719    startup_cwd: Option<&std::path::Path>,
720) -> StartupContext {
721    let shell_cwd = startup_cwd.map(canonicalize_path);
722    let project_root = explicit_project_root
723        .map(|root| canonicalize_path(std::path::Path::new(root)))
724        .or_else(|| {
725            startup_cwd
726                .and_then(maybe_derive_project_root_from_absolute)
727                .map(|p| canonicalize_path(&p))
728        });
729
730    let shell_cwd = match (shell_cwd, project_root.as_ref()) {
731        (Some(cwd), Some(root))
732            if std::path::Path::new(&cwd).starts_with(std::path::Path::new(root)) =>
733        {
734            Some(cwd)
735        }
736        (Some(_), Some(root)) => Some(root.clone()),
737        (Some(cwd), None) => Some(cwd),
738        (None, Some(root)) => Some(root.clone()),
739        (None, None) => None,
740    };
741
742    StartupContext {
743        project_root,
744        shell_cwd,
745    }
746}
747
748fn maybe_derive_project_root_from_absolute(abs: &std::path::Path) -> Option<std::path::PathBuf> {
749    let mut cur = if abs.is_dir() {
750        abs.to_path_buf()
751    } else {
752        abs.parent()?.to_path_buf()
753    };
754    loop {
755        if has_project_marker(&cur) {
756            return Some(crate::core::pathutil::safe_canonicalize_or_self(&cur));
757        }
758        if !cur.pop() {
759            break;
760        }
761    }
762    None
763}
764
765fn auto_consolidate_knowledge(project_root: &str) {
766    use crate::core::knowledge::ProjectKnowledge;
767    use crate::core::session::SessionState;
768
769    let session = match SessionState::load_latest() {
770        Some(s) => s,
771        None => return,
772    };
773
774    if session.findings.is_empty() && session.decisions.is_empty() {
775        return;
776    }
777
778    let mut knowledge = ProjectKnowledge::load_or_create(project_root);
779
780    for finding in &session.findings {
781        let key = if let Some(ref file) = finding.file {
782            if let Some(line) = finding.line {
783                format!("{file}:{line}")
784            } else {
785                file.clone()
786            }
787        } else {
788            "finding-auto".to_string()
789        };
790        knowledge.remember("finding", &key, &finding.summary, &session.id, 0.7);
791    }
792
793    for decision in &session.decisions {
794        let key = decision
795            .summary
796            .chars()
797            .take(50)
798            .collect::<String>()
799            .replace(' ', "-")
800            .to_lowercase();
801        knowledge.remember("decision", &key, &decision.summary, &session.id, 0.85);
802    }
803
804    let task_desc = session
805        .task
806        .as_ref()
807        .map(|t| t.description.clone())
808        .unwrap_or_default();
809
810    let summary = format!(
811        "Auto-consolidate session {}: {} — {} findings, {} decisions",
812        session.id,
813        task_desc,
814        session.findings.len(),
815        session.decisions.len()
816    );
817    knowledge.consolidate(&summary, vec![session.id.clone()]);
818    let _ = knowledge.save();
819}
820
821#[cfg(test)]
822mod resolve_path_tests {
823    use super::*;
824
825    fn create_git_root(path: &std::path::Path) -> String {
826        std::fs::create_dir_all(path.join(".git")).unwrap();
827        canonicalize_path(path)
828    }
829
830    #[tokio::test]
831    async fn resolve_path_can_reroot_to_trusted_startup_root_when_session_root_is_stale() {
832        let tmp = tempfile::tempdir().unwrap();
833        let stale = tmp.path().join("stale");
834        let real = tmp.path().join("real");
835        std::fs::create_dir_all(&stale).unwrap();
836        let real_root = create_git_root(&real);
837        std::fs::write(real.join("a.txt"), "ok").unwrap();
838
839        let server = LeanCtxServer::new_with_startup(None, Some(real.clone()));
840        {
841            let mut session = server.session.write().await;
842            session.project_root = Some(stale.to_string_lossy().to_string());
843            session.shell_cwd = Some(stale.to_string_lossy().to_string());
844        }
845
846        let out = server
847            .resolve_path(&real.join("a.txt").to_string_lossy())
848            .await
849            .unwrap();
850
851        assert!(out.ends_with("/a.txt"));
852
853        let session = server.session.read().await;
854        assert_eq!(session.project_root.as_deref(), Some(real_root.as_str()));
855        assert_eq!(session.shell_cwd.as_deref(), Some(real_root.as_str()));
856    }
857
858    #[tokio::test]
859    async fn resolve_path_rejects_absolute_path_outside_trusted_startup_root() {
860        let tmp = tempfile::tempdir().unwrap();
861        let stale = tmp.path().join("stale");
862        let root = tmp.path().join("root");
863        let other = tmp.path().join("other");
864        std::fs::create_dir_all(&stale).unwrap();
865        create_git_root(&root);
866        let _other_value = create_git_root(&other);
867        std::fs::write(other.join("b.txt"), "no").unwrap();
868
869        let server = LeanCtxServer::new_with_startup(None, Some(root.clone()));
870        {
871            let mut session = server.session.write().await;
872            session.project_root = Some(stale.to_string_lossy().to_string());
873            session.shell_cwd = Some(stale.to_string_lossy().to_string());
874        }
875
876        let err = server
877            .resolve_path(&other.join("b.txt").to_string_lossy())
878            .await
879            .unwrap_err();
880        assert!(err.contains("path escapes project root"));
881
882        let session = server.session.read().await;
883        assert_eq!(
884            session.project_root.as_deref(),
885            Some(stale.to_string_lossy().as_ref())
886        );
887    }
888
889    #[tokio::test]
890    async fn startup_prefers_workspace_scoped_session_over_global_latest() {
891        let _data = tempfile::tempdir().unwrap();
892        let _tmp = tempfile::tempdir().unwrap();
893
894        let (server, root_b) = {
895            let _lock = crate::core::data_dir::test_env_lock();
896            std::env::set_var("NEBU_CTX_DATA_DIR", _data.path());
897
898            let repo_a = _tmp.path().join("repo-a");
899            let repo_b = _tmp.path().join("repo-b");
900            let root_a = create_git_root(&repo_a);
901            let root_b = create_git_root(&repo_b);
902
903            let mut session_b = SessionState::new();
904            session_b.project_root = Some(root_b.clone());
905            session_b.shell_cwd = Some(root_b.clone());
906            session_b.set_task("repo-b task", None);
907            session_b.save().unwrap();
908
909            let mut session_a = SessionState::new();
910            session_a.project_root = Some(root_a.clone());
911            session_a.shell_cwd = Some(root_a.clone());
912            session_a.set_task("repo-a latest task", None);
913            session_a.save().unwrap();
914
915            let server = LeanCtxServer::new_with_startup(None, Some(repo_b.clone()));
916            std::env::remove_var("NEBU_CTX_DATA_DIR");
917            (server, root_b)
918        };
919
920        let session = server.session.read().await;
921        assert_eq!(session.project_root.as_deref(), Some(root_b.as_str()));
922        assert_eq!(session.shell_cwd.as_deref(), Some(root_b.as_str()));
923        assert_eq!(
924            session.task.as_ref().map(|t| t.description.as_str()),
925            Some("repo-b task")
926        );
927    }
928
929    #[tokio::test]
930    async fn startup_creates_fresh_session_for_new_workspace_and_preserves_subdir_cwd() {
931        let _data = tempfile::tempdir().unwrap();
932        let _tmp = tempfile::tempdir().unwrap();
933
934        let (server, root_b, repo_b_src_value, old_id) = {
935            let _lock = crate::core::data_dir::test_env_lock();
936            std::env::set_var("NEBU_CTX_DATA_DIR", _data.path());
937
938            let repo_a = _tmp.path().join("repo-a");
939            let repo_b = _tmp.path().join("repo-b");
940            let repo_b_src = repo_b.join("src");
941            let root_a = create_git_root(&repo_a);
942            let root_b = create_git_root(&repo_b);
943            std::fs::create_dir_all(&repo_b_src).unwrap();
944            let repo_b_src_value = canonicalize_path(&repo_b_src);
945
946            let mut session_a = SessionState::new();
947            session_a.project_root = Some(root_a.clone());
948            session_a.shell_cwd = Some(root_a.clone());
949            session_a.set_task("repo-a latest task", None);
950            let old_id = session_a.id.clone();
951            session_a.save().unwrap();
952
953            let server = LeanCtxServer::new_with_startup(None, Some(repo_b_src.clone()));
954            std::env::remove_var("NEBU_CTX_DATA_DIR");
955            (server, root_b, repo_b_src_value, old_id)
956        };
957
958        let session = server.session.read().await;
959        assert_eq!(session.project_root.as_deref(), Some(root_b.as_str()));
960        assert_eq!(
961            session.shell_cwd.as_deref(),
962            Some(repo_b_src_value.as_str())
963        );
964        assert!(session.task.is_none());
965        assert_ne!(session.id, old_id);
966    }
967
968    #[tokio::test]
969    async fn resolve_path_does_not_auto_update_when_current_root_is_real_project() {
970        let tmp = tempfile::tempdir().unwrap();
971        let root = tmp.path().join("root");
972        let other = tmp.path().join("other");
973        let root_value = create_git_root(&root);
974        create_git_root(&other);
975        std::fs::write(other.join("b.txt"), "no").unwrap();
976
977        let server = LeanCtxServer::new_with_project_root(Some(root.to_string_lossy().to_string()));
978
979        let err = server
980            .resolve_path(&other.join("b.txt").to_string_lossy())
981            .await
982            .unwrap_err();
983        assert!(err.contains("path escapes project root"));
984
985        let session = server.session.read().await;
986        assert_eq!(session.project_root.as_deref(), Some(root_value.as_str()));
987    }
988}