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    // 15b) Archive FTS footprint
423    let archive_footprint = archive_footprint_outcome();
424    if archive_footprint.ok {
425        passed += 1;
426    }
427    print_check(&archive_footprint);
428
429    // 16) Memory profile
430    let mem_profile = memory_profile_outcome();
431    passed += 1;
432    print_check(&mem_profile);
433
434    // 17) Memory cleanup
435    let mem_cleanup = memory_cleanup_outcome();
436    passed += 1;
437    print_check(&mem_cleanup);
438
439    // 18) RAM Guardian
440    let ram_outcome = ram_guardian_outcome();
441    if ram_outcome.ok {
442        passed += 1;
443    }
444    print_check(&ram_outcome);
445
446    // 19) Capacity warnings (memory stores near limits)
447    let cap_warnings = capacity_warnings();
448    for cw in &cap_warnings {
449        if cw.ok {
450            passed += 1;
451        }
452        print_check(cw);
453    }
454
455    // 20) Proxy health
456    let proxy_health = proxy_health_outcome();
457    if proxy_health.ok {
458        passed += 1;
459    }
460    print_check(&proxy_health);
461
462    // 20) Stale proxy env (ANTHROPIC_BASE_URL pointing to local proxy while proxy is not enabled)
463    let stale_env = stale_proxy_env_outcome();
464    if let Some(ref check) = stale_env {
465        if check.ok {
466            passed += 1;
467        }
468        print_check(check);
469    }
470
471    // LSP servers (optional, informational)
472    println!("\n  {BOLD}{WHITE}LSP (optional — for ctx_refactor):{RST}");
473    let lsp_outcomes = lsp_server_outcomes();
474    for lsp_check in &lsp_outcomes {
475        print_check(lsp_check);
476    }
477
478    let mut effective_total = total + 10; // session_state + integrity + cache_safety + bm25_health + archive_footprint + daemon + mem_profile + mem_cleanup + ram_guardian + proxy_health
479    effective_total += cap_warnings.len() as u32;
480    effective_total += docker_outcomes.len() as u32;
481    if pi.is_some() {
482        effective_total += 1;
483    }
484    if claude_truncation.is_some() {
485        effective_total += 1;
486    }
487    if stale_env.is_some() {
488        effective_total += 1;
489    }
490    if workspace_scope.is_some() {
491        effective_total += 1;
492    }
493    println!();
494    println!("  {BOLD}{WHITE}Summary:{RST}  {GREEN}{passed}{RST}{DIM}/{effective_total}{RST} checks passed");
495    println!("  {DIM}LSP servers are optional enhancements (not counted in score){RST}");
496    println!("  {DIM}{}{RST}", crate::core::integrity::origin_line());
497}
498
499pub fn run_compact() {
500    let (passed, total) = compact_score();
501    print_compact_status(passed, total);
502}
503
504pub fn run_cli(args: &[String]) -> i32 {
505    let (sub, rest) = match args.first().map(String::as_str) {
506        Some("integrations") => ("integrations", &args[1..]),
507        _ => ("", args),
508    };
509
510    let fix = rest.iter().any(|a| a == "--fix");
511    let json = rest.iter().any(|a| a == "--json");
512    let help = rest.iter().any(|a| a == "--help" || a == "-h");
513
514    if help {
515        println!("Usage:");
516        println!("  lean-ctx doctor");
517        println!("  lean-ctx doctor integrations [--json]");
518        println!("  lean-ctx doctor --fix [--json]");
519        return 0;
520    }
521
522    if sub == "integrations" {
523        if fix {
524            let _ = fix::run_fix(&fix::DoctorFixOptions { json: false });
525        }
526        return integrations::run_integrations(&integrations::IntegrationsOptions { json });
527    }
528
529    if !fix {
530        run();
531        return 0;
532    }
533
534    match fix::run_fix(&fix::DoctorFixOptions { json }) {
535        Ok(code) => code,
536        Err(e) => {
537            tracing::error!("doctor --fix failed: {e}");
538            2
539        }
540    }
541}
542
543pub fn compact_score() -> (u32, u32) {
544    let mut passed = 0u32;
545    let total = 6u32;
546
547    if resolve_lean_ctx_binary().is_some() || path_in_path_env() {
548        passed += 1;
549    }
550    let lean_dir = crate::core::data_dir::lean_ctx_data_dir().ok();
551    if lean_dir.as_ref().is_some_and(|p| p.is_dir()) {
552        passed += 1;
553    }
554    if lean_dir
555        .as_ref()
556        .map(|d| d.join("stats.json"))
557        .and_then(|p| std::fs::metadata(p).ok())
558        .is_some_and(|m| m.is_file())
559    {
560        passed += 1;
561    }
562    if shell_aliases_outcome().ok {
563        passed += 1;
564    }
565    if mcp_config_outcome().ok {
566        passed += 1;
567    }
568    if skill_files_outcome().ok {
569        passed += 1;
570    }
571
572    (passed, total)
573}
574
575pub(super) fn print_compact_status(passed: u32, total: u32) {
576    let status = if passed == total {
577        format!("{GREEN}✓ All {total} checks passed{RST}")
578    } else {
579        format!("{YELLOW}{passed}/{total} passed{RST} — run {BOLD}lean-ctx doctor{RST} for details")
580    };
581    println!("  {status}");
582}
583
584#[cfg(test)]
585mod tests {
586    use super::is_active_shell_impl;
587
588    fn make_capacity_check(name: &str, current: usize, limit: usize) -> Option<(bool, String)> {
589        if limit == 0 {
590            return None;
591        }
592        let pct = (current as f64 / limit as f64 * 100.0) as u32;
593        if pct >= 95 {
594            Some((true, format!("{name}: {current}/{limit} ({pct}%)")))
595        } else if pct >= 80 {
596            Some((false, format!("{name}: {current}/{limit} ({pct}%)")))
597        } else {
598            None
599        }
600    }
601
602    #[test]
603    fn capacity_below_80_no_warning() {
604        assert!(make_capacity_check("facts", 100, 200).is_none());
605        assert!(make_capacity_check("facts", 159, 200).is_none());
606    }
607
608    #[test]
609    fn capacity_at_80_yellow_warning() {
610        let result = make_capacity_check("facts", 160, 200);
611        assert!(result.is_some());
612        let (critical, msg) = result.unwrap();
613        assert!(!critical);
614        assert!(msg.contains("160/200"));
615        assert!(msg.contains("80%"));
616    }
617
618    #[test]
619    fn capacity_at_92_yellow_warning() {
620        let result = make_capacity_check("facts", 185, 200);
621        assert!(result.is_some());
622        let (critical, msg) = result.unwrap();
623        assert!(!critical);
624        assert!(msg.contains("185/200"));
625        assert!(msg.contains("92%"));
626    }
627
628    #[test]
629    fn capacity_at_95_critical() {
630        let result = make_capacity_check("facts", 190, 200);
631        assert!(result.is_some());
632        let (critical, msg) = result.unwrap();
633        assert!(critical);
634        assert!(msg.contains("190/200"));
635        assert!(msg.contains("95%"));
636    }
637
638    #[test]
639    fn capacity_at_100_critical() {
640        let result = make_capacity_check("facts", 200, 200);
641        assert!(result.is_some());
642        let (critical, _) = result.unwrap();
643        assert!(critical);
644    }
645
646    #[test]
647    fn capacity_zero_limit_skipped() {
648        assert!(make_capacity_check("facts", 50, 0).is_none());
649    }
650
651    #[test]
652    fn bashrc_active_on_non_windows_when_shell_empty() {
653        assert!(is_active_shell_impl("~/.bashrc", "", false, false));
654    }
655
656    #[test]
657    fn bashrc_not_active_on_windows_when_shell_empty() {
658        assert!(!is_active_shell_impl("~/.bashrc", "", true, false));
659    }
660
661    #[test]
662    fn bashrc_active_when_shell_contains_bash_on_linux() {
663        assert!(is_active_shell_impl(
664            "~/.bashrc",
665            "/usr/bin/bash",
666            false,
667            false
668        ));
669    }
670
671    #[test]
672    fn bashrc_not_active_on_windows_even_with_bash_in_shell_env() {
673        // Issue #214: On Windows, Git Bash sets $SHELL globally to bash.exe.
674        // .bashrc should NOT be flagged on Windows unless actually inside bash.
675        std::env::remove_var("BASH_VERSION");
676        assert!(!is_active_shell_impl(
677            "~/.bashrc",
678            "C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe",
679            true,
680            false,
681        ));
682    }
683
684    #[test]
685    fn bashrc_not_active_on_windows_powershell_even_with_bash_in_shell() {
686        assert!(!is_active_shell_impl(
687            "~/.bashrc",
688            "C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe",
689            true,
690            true,
691        ));
692    }
693
694    #[test]
695    fn bashrc_not_active_on_windows_powershell_with_empty_shell() {
696        assert!(!is_active_shell_impl("~/.bashrc", "", true, true));
697    }
698
699    #[test]
700    fn zshrc_unaffected_by_powershell_flag() {
701        assert!(is_active_shell_impl("~/.zshrc", "/bin/zsh", false, false));
702        assert!(is_active_shell_impl("~/.zshrc", "/bin/zsh", true, true));
703    }
704
705    #[test]
706    fn bashrc_not_active_on_windows_without_powershell_detection() {
707        // Windows + $SHELL=bash but NOT in actual bash session (no BASH_VERSION).
708        // This is the exact scenario from issue #214: Git Bash sets $SHELL globally.
709        std::env::remove_var("BASH_VERSION");
710        assert!(!is_active_shell_impl(
711            "~/.bashrc",
712            "/usr/bin/bash",
713            true,
714            false,
715        ));
716    }
717
718    #[test]
719    fn bashrc_active_on_linux() {
720        assert!(is_active_shell_impl("~/.bashrc", "/bin/bash", false, false));
721        assert!(is_active_shell_impl("~/.bashrc", "", false, false));
722    }
723}