Skip to main content

lean_ctx/doctor/
mod.rs

1//! Environment diagnostics for lean-ctx installation and integration.
2
3mod checks;
4mod common;
5mod fix;
6mod integrations;
7mod workspace_scope;
8
9#[allow(clippy::wildcard_imports)]
10use checks::*;
11#[allow(clippy::wildcard_imports)]
12use common::*;
13
14pub(super) const GREEN: &str = "\x1b[32m";
15
16pub(super) const RED: &str = "\x1b[31m";
17
18pub(super) const BOLD: &str = "\x1b[1m";
19
20pub(super) const RST: &str = "\x1b[0m";
21
22pub(super) const DIM: &str = "\x1b[2m";
23
24pub(super) const WHITE: &str = "\x1b[97m";
25
26pub(super) const YELLOW: &str = "\x1b[33m";
27
28pub(super) struct Outcome {
29    pub ok: bool,
30    pub line: String,
31}
32
33/// Run diagnostic checks and print colored results to stdout.
34pub fn run() {
35    let mut passed = 0u32;
36    let total = 10u32;
37
38    println!("{BOLD}{WHITE}lean-ctx doctor{RST}  {DIM}diagnostics{RST}\n");
39
40    // 1) Binary on PATH
41    let path_bin = resolve_lean_ctx_binary();
42    let also_in_path_dirs = path_in_path_env();
43    let bin_ok = path_bin.is_some() || also_in_path_dirs;
44    if bin_ok {
45        passed += 1;
46    }
47    let bin_line = if let Some(p) = path_bin {
48        format!("{BOLD}lean-ctx in PATH{RST}  {WHITE}{}{RST}", p.display())
49    } else if also_in_path_dirs {
50        format!(
51            "{BOLD}lean-ctx in PATH{RST}  {YELLOW}found via PATH walk (not resolved by `command -v`){RST}"
52        )
53    } else {
54        format!("{BOLD}lean-ctx in PATH{RST}  {RED}not found{RST}")
55    };
56    print_check(&Outcome {
57        ok: bin_ok,
58        line: bin_line,
59    });
60
61    // 2) Version from PATH binary
62    let ver = if bin_ok {
63        lean_ctx_version_from_path()
64    } else {
65        Outcome {
66            ok: false,
67            line: format!("{BOLD}lean-ctx version{RST}  {RED}skipped (binary not in PATH){RST}"),
68        }
69    };
70    if ver.ok {
71        passed += 1;
72    }
73    print_check(&ver);
74
75    // 3) data directory (respects LEAN_CTX_DATA_DIR)
76    let lean_dir = crate::core::data_dir::lean_ctx_data_dir().ok();
77    let dir_outcome = match &lean_dir {
78        Some(p) if p.is_dir() => {
79            passed += 1;
80            Outcome {
81                ok: true,
82                line: format!(
83                    "{BOLD}data dir{RST}  {GREEN}exists{RST}  {DIM}{}{RST}",
84                    p.display()
85                ),
86            }
87        }
88        Some(p) => Outcome {
89            ok: false,
90            line: format!(
91                "{BOLD}data dir{RST}  {RED}missing or not a directory{RST}  {DIM}{}{RST}",
92                p.display()
93            ),
94        },
95        None => Outcome {
96            ok: false,
97            line: format!("{BOLD}data dir{RST}  {RED}could not resolve data directory{RST}"),
98        },
99    };
100    print_check(&dir_outcome);
101
102    // 4) stats.json + size
103    let stats_path = lean_dir.as_ref().map(|d| d.join("stats.json"));
104    let stats_outcome = match stats_path.as_ref().and_then(|p| std::fs::metadata(p).ok()) {
105        Some(m) if m.is_file() => {
106            passed += 1;
107            let size = m.len();
108            let path_display = if let Some(p) = stats_path.as_ref() {
109                p.display().to_string()
110            } else {
111                String::new()
112            };
113            Outcome {
114                ok: true,
115                line: format!(
116                    "{BOLD}stats.json{RST}  {GREEN}exists{RST}  {WHITE}{size} bytes{RST}  {DIM}{path_display}{RST}",
117                ),
118            }
119        }
120        Some(_m) => {
121            let path_display = if let Some(p) = stats_path.as_ref() {
122                p.display().to_string()
123            } else {
124                String::new()
125            };
126            Outcome {
127                ok: false,
128                line: format!(
129                    "{BOLD}stats.json{RST}  {RED}not a file{RST}  {DIM}{path_display}{RST}",
130                ),
131            }
132        }
133        None => {
134            passed += 1;
135            Outcome {
136                ok: true,
137                line: match &stats_path {
138                    Some(p) => format!(
139                        "{BOLD}stats.json{RST}  {YELLOW}not yet created{RST}  {DIM}(will appear after first use) {}{RST}",
140                        p.display()
141                    ),
142                    None => format!("{BOLD}stats.json{RST}  {RED}could not resolve path{RST}"),
143                },
144            }
145        }
146    };
147    print_check(&stats_outcome);
148
149    let split_dirs = crate::core::data_dir::all_data_dirs_with_stats();
150    if split_dirs.len() >= 2 {
151        let dirs_str = split_dirs
152            .iter()
153            .map(|d| d.display().to_string())
154            .collect::<Vec<_>>()
155            .join(", ");
156        print_check(&Outcome {
157            ok: false,
158            line: format!(
159                "{BOLD}data dir split{RST}  {RED}stats.json found in {count} locations{RST}: {dirs_str}  {DIM}(run: lean-ctx setup to auto-merge){RST}",
160                count = split_dirs.len(),
161            ),
162        });
163    }
164
165    // 5) config.toml (missing is OK)
166    let config_path = lean_dir.as_ref().map(|d| d.join("config.toml"));
167    let config_outcome = match &config_path {
168        Some(p) => match std::fs::metadata(p) {
169            Ok(m) if m.is_file() => {
170                passed += 1;
171                Outcome {
172                    ok: true,
173                    line: format!(
174                        "{BOLD}config.toml{RST}  {GREEN}exists{RST}  {DIM}{}{RST}",
175                        p.display()
176                    ),
177                }
178            }
179            Ok(_) => Outcome {
180                ok: false,
181                line: format!(
182                    "{BOLD}config.toml{RST}  {RED}exists but is not a regular file{RST}  {DIM}{}{RST}",
183                    p.display()
184                ),
185            },
186            Err(_) => {
187                passed += 1;
188                Outcome {
189                    ok: true,
190                    line: format!(
191                        "{BOLD}config.toml{RST}  {YELLOW}not found, using defaults{RST}  {DIM}(expected at {}){RST}",
192                        p.display()
193                    ),
194                }
195            }
196        },
197        None => Outcome {
198            ok: false,
199            line: format!("{BOLD}config.toml{RST}  {RED}could not resolve path{RST}"),
200        },
201    };
202    print_check(&config_outcome);
203
204    // 6) Proxy upstreams
205    let proxy_outcome = proxy_upstream_outcome();
206    if proxy_outcome.ok {
207        passed += 1;
208    }
209    print_check(&proxy_outcome);
210
211    // 7) Shell aliases
212    let aliases = shell_aliases_outcome();
213    if aliases.ok {
214        passed += 1;
215    }
216    print_check(&aliases);
217
218    // 7) MCP
219    let mcp = mcp_config_outcome();
220    if mcp.ok {
221        passed += 1;
222    }
223    print_check(&mcp);
224
225    // 8) Workspace-scope MCP (optional; only when a project-local config exists)
226    let workspace_scope = workspace_scope::workspace_scope_outcome(mcp.ok);
227    if let Some(ref ws) = workspace_scope {
228        if ws.ok {
229            passed += 1;
230        }
231        print_check(ws);
232    }
233
234    // 9) SKILL.md
235    let skill = skill_files_outcome();
236    if skill.ok {
237        passed += 1;
238    }
239    print_check(&skill);
240
241    // 10) Port
242    let port = port_3333_outcome();
243    if port.ok {
244        passed += 1;
245    }
246    print_check(&port);
247
248    // Daemon status
249    #[cfg(unix)]
250    let daemon_outcome = {
251        let autostart = crate::daemon_autostart::is_installed();
252        let autostart_tag = if autostart {
253            format!("  {DIM}[autostart: on]{RST}")
254        } else {
255            String::new()
256        };
257        if crate::daemon::is_daemon_running() {
258            let pid_path = crate::daemon::daemon_pid_path();
259            let pid_str = std::fs::read_to_string(&pid_path).unwrap_or_default();
260            Outcome {
261                ok: true,
262                line: format!(
263                    "{BOLD}Daemon{RST}  {GREEN}running (PID {}){RST}{autostart_tag}",
264                    pid_str.trim()
265                ),
266            }
267        } else {
268            let hint = if autostart {
269                format!("{DIM}(autostart enabled, will restart){RST}")
270            } else {
271                format!("{DIM}(run: lean-ctx daemon start  or: lean-ctx daemon enable){RST}")
272            };
273            Outcome {
274                ok: true,
275                line: format!("{BOLD}Daemon{RST}  {YELLOW}not running{RST}  {hint}"),
276            }
277        }
278    };
279    #[cfg(not(unix))]
280    let daemon_outcome = Outcome {
281        ok: true,
282        line: format!("{BOLD}Daemon{RST}  {DIM}not supported on this platform{RST}"),
283    };
284    if daemon_outcome.ok {
285        passed += 1;
286    }
287    print_check(&daemon_outcome);
288
289    // Daemon diagnostics: systemctl is-active, linger, crash-loop log
290    #[cfg(target_os = "linux")]
291    {
292        if let Ok(o) = std::process::Command::new("systemctl")
293            .args(["--user", "is-active", "lean-ctx-daemon.service"])
294            .output()
295        {
296            let state = String::from_utf8_lossy(&o.stdout).trim().to_string();
297            if state != "active" {
298                println!(
299                    "  {DIM}  systemd unit state: {YELLOW}{state}{RST}{DIM} (expected: active){RST}"
300                );
301            }
302        }
303        let username = std::env::var("USER")
304            .or_else(|_| std::env::var("LOGNAME"))
305            .unwrap_or_else(|_| "$(whoami)".to_string());
306        if let Ok(o) = std::process::Command::new("loginctl")
307            .args(["show-user", &username, "-p", "Linger", "--value"])
308            .output()
309        {
310            let val = String::from_utf8_lossy(&o.stdout).trim().to_string();
311            if val != "yes" {
312                println!(
313                    "  {YELLOW}⚠{RST}  Linger not enabled — daemon won't start at boot without login"
314                );
315                println!("     {DIM}Fix: loginctl enable-linger {username}{RST}");
316            }
317        }
318    }
319    if let Some(log_path) = crate::core::startup_guard::crash_loop_log_path(
320        crate::core::startup_guard::MCP_PROCESS_NAME,
321    ) {
322        if log_path.exists() {
323            if let Ok(contents) = std::fs::read_to_string(&log_path) {
324                let lines: Vec<&str> = contents.lines().collect();
325                if lines.len() >= 5 {
326                    println!(
327                        "  {YELLOW}⚠{RST}  Crash-loop log: {} recent restarts  {DIM}({}){RST}",
328                        lines.len(),
329                        log_path.display()
330                    );
331                }
332            }
333        }
334    }
335
336    // Providers
337    let provider_outcome = provider_outcome();
338    print_check(&provider_outcome);
339
340    // MCP Bridges
341    let bridge_outcomes = mcp_bridge_outcomes();
342    for bridge_check in &bridge_outcomes {
343        print_check(bridge_check);
344    }
345
346    // Plan mode
347    let plan_outcomes = plan_mode_outcomes();
348    for plan_check in &plan_outcomes {
349        print_check(plan_check);
350    }
351
352    // 9) Session state (project_root + shell_cwd)
353    let session_outcome = session_state_outcome();
354    if session_outcome.ok {
355        passed += 1;
356    }
357    print_check(&session_outcome);
358
359    // 10) Docker env vars (optional, only in containers)
360    let docker_outcomes = docker_env_outcomes();
361    for docker_check in &docker_outcomes {
362        if docker_check.ok {
363            passed += 1;
364        }
365        print_check(docker_check);
366    }
367
368    // 11) Pi Coding Agent (optional)
369    let pi = pi_outcome();
370    if let Some(ref pi_check) = pi {
371        if pi_check.ok {
372            passed += 1;
373        }
374        print_check(pi_check);
375    }
376
377    // 12) Build integrity (canary / origin check)
378    let integrity = crate::core::integrity::check();
379    let integrity_ok = integrity.seed_ok && integrity.origin_ok;
380    if integrity_ok {
381        passed += 1;
382    }
383    let integrity_line = if integrity_ok {
384        format!(
385            "{BOLD}Build origin{RST}  {GREEN}official{RST}  {DIM}{}{RST}",
386            integrity.repo
387        )
388    } else {
389        format!(
390            "{BOLD}Build origin{RST}  {RED}MODIFIED REDISTRIBUTION{RST}  {YELLOW}pkg={}, repo={}{RST}",
391            integrity.pkg_name, integrity.repo
392        )
393    };
394    print_check(&Outcome {
395        ok: integrity_ok,
396        line: integrity_line,
397    });
398
399    // 13) Cache safety
400    let cache_safety = cache_safety_outcome();
401    if cache_safety.ok {
402        passed += 1;
403    }
404    print_check(&cache_safety);
405
406    // 14) Claude Code instruction truncation guard
407    let claude_truncation = claude_truncation_outcome();
408    if let Some(ref ct) = claude_truncation {
409        if ct.ok {
410            passed += 1;
411        }
412        print_check(ct);
413    }
414
415    // 15) BM25 cache health
416    let bm25_health = bm25_cache_health_outcome();
417    if bm25_health.ok {
418        passed += 1;
419    }
420    print_check(&bm25_health);
421
422    // 15a) Semantic index runtime status (state/timing/persistence) for the
423    // active project — surfaces a stuck "warming" index (issue #249).
424    let semantic_index = semantic_index_outcome();
425    if let Some(ref check) = semantic_index {
426        if check.ok {
427            passed += 1;
428        }
429        print_check(check);
430    }
431
432    // 15b) Archive FTS footprint
433    let archive_footprint = archive_footprint_outcome();
434    if archive_footprint.ok {
435        passed += 1;
436    }
437    print_check(&archive_footprint);
438
439    // 16) Memory profile
440    let mem_profile = memory_profile_outcome();
441    passed += 1;
442    print_check(&mem_profile);
443
444    // 17) Memory cleanup
445    let mem_cleanup = memory_cleanup_outcome();
446    passed += 1;
447    print_check(&mem_cleanup);
448
449    // 18) RAM Guardian
450    let ram_outcome = ram_guardian_outcome();
451    if ram_outcome.ok {
452        passed += 1;
453    }
454    print_check(&ram_outcome);
455
456    // 19) Capacity warnings (memory stores near limits)
457    let cap_warnings = capacity_warnings();
458    for cw in &cap_warnings {
459        if cw.ok {
460            passed += 1;
461        }
462        print_check(cw);
463    }
464
465    // 20) Proxy health
466    let proxy_health = proxy_health_outcome();
467    if proxy_health.ok {
468        passed += 1;
469    }
470    print_check(&proxy_health);
471
472    // 20) Stale proxy env (ANTHROPIC_BASE_URL pointing to local proxy while proxy is not enabled)
473    let stale_env = stale_proxy_env_outcome();
474    if let Some(ref check) = stale_env {
475        if check.ok {
476            passed += 1;
477        }
478        print_check(check);
479    }
480
481    // LSP servers (optional, informational)
482    println!("\n  {BOLD}{WHITE}LSP (optional — for ctx_refactor):{RST}");
483    let lsp_outcomes = lsp_server_outcomes();
484    for lsp_check in &lsp_outcomes {
485        print_check(lsp_check);
486    }
487
488    let mut effective_total = total + 10; // session_state + integrity + cache_safety + bm25_health + archive_footprint + daemon + mem_profile + mem_cleanup + ram_guardian + proxy_health
489    effective_total += cap_warnings.len() as u32;
490    effective_total += docker_outcomes.len() as u32;
491    if pi.is_some() {
492        effective_total += 1;
493    }
494    if claude_truncation.is_some() {
495        effective_total += 1;
496    }
497    if stale_env.is_some() {
498        effective_total += 1;
499    }
500    if workspace_scope.is_some() {
501        effective_total += 1;
502    }
503    if semantic_index.is_some() {
504        effective_total += 1;
505    }
506    // Shadow mode status
507    let cfg = crate::core::config::Config::load();
508    let shadow_line = if cfg.shadow_mode {
509        format!("{BOLD}Shadow mode{RST}  {GREEN}active{RST}  {DIM}(native tools intercepted → ctx_*){RST}")
510    } else {
511        format!("{BOLD}Shadow mode{RST}  {DIM}disabled{RST}  {DIM}(enable: lean-ctx config set shadow_mode true){RST}")
512    };
513    println!("  {shadow_line}");
514
515    let needs_attention = effective_total.saturating_sub(passed);
516    println!();
517    println!("  {BOLD}{WHITE}Summary:{RST}  {GREEN}{passed}{RST}{DIM}/{effective_total}{RST} checks passed");
518    if needs_attention > 0 {
519        println!(
520            "  {YELLOW}{needs_attention} check(s) need attention.{RST}  Auto-repair what's fixable:  {BOLD}lean-ctx doctor --fix{RST}"
521        );
522    } else {
523        println!("  {GREEN}Everything looks good.{RST}");
524    }
525    println!("  {DIM}LSP servers are optional enhancements (not counted in score){RST}");
526    println!("  {DIM}{}{RST}", crate::core::integrity::origin_line());
527}
528
529pub fn run_compact() {
530    let (passed, total) = compact_score();
531    print_compact_status(passed, total);
532}
533
534pub fn run_cli(args: &[String]) -> i32 {
535    let (sub, rest) = match args.first().map(String::as_str) {
536        Some("integrations") => ("integrations", &args[1..]),
537        _ => ("", args),
538    };
539
540    let fix = rest.iter().any(|a| a == "--fix");
541    let json = rest.iter().any(|a| a == "--json");
542    let help = rest.iter().any(|a| a == "--help" || a == "-h");
543
544    if help {
545        println!("Usage:");
546        println!("  lean-ctx doctor");
547        println!("  lean-ctx doctor integrations [--json]");
548        println!("  lean-ctx doctor --fix [--json]");
549        return 0;
550    }
551
552    if sub == "integrations" {
553        if fix {
554            let _ = fix::run_fix(&fix::DoctorFixOptions { json: false });
555        }
556        return integrations::run_integrations(&integrations::IntegrationsOptions { json });
557    }
558
559    if !fix {
560        run();
561        return 0;
562    }
563
564    match fix::run_fix(&fix::DoctorFixOptions { json }) {
565        Ok(code) => code,
566        Err(e) => {
567            tracing::error!("doctor --fix failed: {e}");
568            2
569        }
570    }
571}
572
573pub fn compact_score() -> (u32, u32) {
574    let mut passed = 0u32;
575    let total = 6u32;
576
577    if resolve_lean_ctx_binary().is_some() || path_in_path_env() {
578        passed += 1;
579    }
580    let lean_dir = crate::core::data_dir::lean_ctx_data_dir().ok();
581    if lean_dir.as_ref().is_some_and(|p| p.is_dir()) {
582        passed += 1;
583    }
584    if lean_dir
585        .as_ref()
586        .map(|d| d.join("stats.json"))
587        .and_then(|p| std::fs::metadata(p).ok())
588        .is_some_and(|m| m.is_file())
589    {
590        passed += 1;
591    }
592    if shell_aliases_outcome().ok {
593        passed += 1;
594    }
595    if mcp_config_outcome().ok {
596        passed += 1;
597    }
598    if skill_files_outcome().ok {
599        passed += 1;
600    }
601
602    (passed, total)
603}
604
605pub(super) fn print_compact_status(passed: u32, total: u32) {
606    let status = if passed == total {
607        format!("{GREEN}✓ All {total} checks passed{RST}")
608    } else {
609        format!("{YELLOW}{passed}/{total} passed{RST} — run {BOLD}lean-ctx doctor{RST} for details")
610    };
611    println!("  {status}");
612}
613
614#[cfg(test)]
615mod tests {
616    use super::is_active_shell_impl;
617
618    fn make_capacity_check(name: &str, current: usize, limit: usize) -> Option<(bool, String)> {
619        if limit == 0 {
620            return None;
621        }
622        let pct = (current as f64 / limit as f64 * 100.0) as u32;
623        if pct >= 95 {
624            Some((true, format!("{name}: {current}/{limit} ({pct}%)")))
625        } else if pct >= 80 {
626            Some((false, format!("{name}: {current}/{limit} ({pct}%)")))
627        } else {
628            None
629        }
630    }
631
632    #[test]
633    fn capacity_below_80_no_warning() {
634        assert!(make_capacity_check("facts", 100, 200).is_none());
635        assert!(make_capacity_check("facts", 159, 200).is_none());
636    }
637
638    #[test]
639    fn capacity_at_80_yellow_warning() {
640        let result = make_capacity_check("facts", 160, 200);
641        assert!(result.is_some());
642        let (critical, msg) = result.unwrap();
643        assert!(!critical);
644        assert!(msg.contains("160/200"));
645        assert!(msg.contains("80%"));
646    }
647
648    #[test]
649    fn capacity_at_92_yellow_warning() {
650        let result = make_capacity_check("facts", 185, 200);
651        assert!(result.is_some());
652        let (critical, msg) = result.unwrap();
653        assert!(!critical);
654        assert!(msg.contains("185/200"));
655        assert!(msg.contains("92%"));
656    }
657
658    #[test]
659    fn capacity_at_95_critical() {
660        let result = make_capacity_check("facts", 190, 200);
661        assert!(result.is_some());
662        let (critical, msg) = result.unwrap();
663        assert!(critical);
664        assert!(msg.contains("190/200"));
665        assert!(msg.contains("95%"));
666    }
667
668    #[test]
669    fn capacity_at_100_critical() {
670        let result = make_capacity_check("facts", 200, 200);
671        assert!(result.is_some());
672        let (critical, _) = result.unwrap();
673        assert!(critical);
674    }
675
676    #[test]
677    fn capacity_zero_limit_skipped() {
678        assert!(make_capacity_check("facts", 50, 0).is_none());
679    }
680
681    #[test]
682    fn bashrc_active_on_non_windows_when_shell_empty() {
683        assert!(is_active_shell_impl("~/.bashrc", "", false, false));
684    }
685
686    #[test]
687    fn bashrc_not_active_on_windows_when_shell_empty() {
688        assert!(!is_active_shell_impl("~/.bashrc", "", true, false));
689    }
690
691    #[test]
692    fn bashrc_active_when_shell_contains_bash_on_linux() {
693        assert!(is_active_shell_impl(
694            "~/.bashrc",
695            "/usr/bin/bash",
696            false,
697            false
698        ));
699    }
700
701    #[test]
702    fn bashrc_not_active_on_windows_even_with_bash_in_shell_env() {
703        // Issue #214: On Windows, Git Bash sets $SHELL globally to bash.exe.
704        // .bashrc should NOT be flagged on Windows unless actually inside bash.
705        std::env::remove_var("BASH_VERSION");
706        assert!(!is_active_shell_impl(
707            "~/.bashrc",
708            "C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe",
709            true,
710            false,
711        ));
712    }
713
714    #[test]
715    fn bashrc_not_active_on_windows_powershell_even_with_bash_in_shell() {
716        assert!(!is_active_shell_impl(
717            "~/.bashrc",
718            "C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe",
719            true,
720            true,
721        ));
722    }
723
724    #[test]
725    fn bashrc_not_active_on_windows_powershell_with_empty_shell() {
726        assert!(!is_active_shell_impl("~/.bashrc", "", true, true));
727    }
728
729    #[test]
730    fn zshrc_unaffected_by_powershell_flag() {
731        assert!(is_active_shell_impl("~/.zshrc", "/bin/zsh", false, false));
732        assert!(is_active_shell_impl("~/.zshrc", "/bin/zsh", true, true));
733    }
734
735    #[test]
736    fn bashrc_not_active_on_windows_without_powershell_detection() {
737        // Windows + $SHELL=bash but NOT in actual bash session (no BASH_VERSION).
738        // This is the exact scenario from issue #214: Git Bash sets $SHELL globally.
739        std::env::remove_var("BASH_VERSION");
740        assert!(!is_active_shell_impl(
741            "~/.bashrc",
742            "/usr/bin/bash",
743            true,
744            false,
745        ));
746    }
747
748    #[test]
749    fn bashrc_active_on_linux() {
750        assert!(is_active_shell_impl("~/.bashrc", "/bin/bash", false, false));
751        assert!(is_active_shell_impl("~/.bashrc", "", false, false));
752    }
753}