Skip to main content

lean_ctx/doctor/
mod.rs

1//! Environment diagnostics for lean-ctx installation and integration.
2
3mod fix;
4mod integrations;
5
6use std::net::TcpListener;
7use std::path::PathBuf;
8
9pub(super) const GREEN: &str = "\x1b[32m";
10const RED: &str = "\x1b[31m";
11pub(super) const BOLD: &str = "\x1b[1m";
12pub(super) const RST: &str = "\x1b[0m";
13pub(super) const DIM: &str = "\x1b[2m";
14pub(super) const WHITE: &str = "\x1b[97m";
15pub(super) const YELLOW: &str = "\x1b[33m";
16
17pub(super) struct Outcome {
18    pub ok: bool,
19    pub line: String,
20}
21
22fn print_check(outcome: &Outcome) {
23    let mark = if outcome.ok {
24        format!("{GREEN}✓{RST}")
25    } else {
26        format!("{RED}✗{RST}")
27    };
28    println!("  {mark}  {}", outcome.line);
29}
30
31fn path_in_path_env() -> bool {
32    if let Ok(path) = std::env::var("PATH") {
33        for dir in std::env::split_paths(&path) {
34            if dir.join("lean-ctx").is_file() {
35                return true;
36            }
37            if cfg!(windows)
38                && (dir.join("lean-ctx.exe").is_file() || dir.join("lean-ctx.cmd").is_file())
39            {
40                return true;
41            }
42        }
43    }
44    false
45}
46
47pub(super) fn resolve_lean_ctx_binary() -> Option<PathBuf> {
48    if let Ok(path) = std::env::var("PATH") {
49        for dir in std::env::split_paths(&path) {
50            if cfg!(windows) {
51                let exe = dir.join("lean-ctx.exe");
52                if exe.is_file() {
53                    return Some(exe);
54                }
55                let cmd = dir.join("lean-ctx.cmd");
56                if cmd.is_file() {
57                    return Some(cmd);
58                }
59            } else {
60                let bin = dir.join("lean-ctx");
61                if bin.is_file() {
62                    return Some(bin);
63                }
64            }
65        }
66    }
67    None
68}
69
70fn lean_ctx_version_from_path() -> Outcome {
71    let resolved = resolve_lean_ctx_binary();
72    let bin = resolved
73        .clone()
74        .unwrap_or_else(|| std::env::current_exe().unwrap_or_else(|_| "lean-ctx".into()));
75
76    let v = env!("CARGO_PKG_VERSION");
77    let note = match std::env::current_exe() {
78        Ok(exe) if exe == bin => format!("{DIM}(this binary){RST}"),
79        Ok(_) | Err(_) => format!("{DIM}(resolved: {}){RST}", bin.display()),
80    };
81    Outcome {
82        ok: true,
83        line: format!("{BOLD}lean-ctx version{RST}  {WHITE}lean-ctx {v}{RST}  {note}"),
84    }
85}
86
87fn rc_contains_lean_ctx(path: &PathBuf) -> bool {
88    match std::fs::read_to_string(path) {
89        Ok(s) => s.contains("lean-ctx"),
90        Err(_) => false,
91    }
92}
93
94fn has_pipe_guard_in_content(content: &str) -> bool {
95    content.contains("! -t 1")
96        || content.contains("isatty stdout")
97        || content.contains("IsOutputRedirected")
98}
99
100fn rc_references_shell_hook(content: &str) -> bool {
101    content.contains("lean-ctx/shell-hook.") || content.contains("lean-ctx\\shell-hook.")
102}
103
104fn rc_has_pipe_guard(path: &PathBuf) -> bool {
105    match std::fs::read_to_string(path) {
106        Ok(s) => {
107            if has_pipe_guard_in_content(&s) {
108                return true;
109            }
110            if rc_references_shell_hook(&s) {
111                let dirs_to_check = hook_dirs();
112                for dir in &dirs_to_check {
113                    for ext in &["zsh", "bash", "fish", "ps1"] {
114                        let hook = dir.join(format!("shell-hook.{ext}"));
115                        if let Ok(h) = std::fs::read_to_string(&hook) {
116                            if has_pipe_guard_in_content(&h) {
117                                return true;
118                            }
119                        }
120                    }
121                }
122            }
123            false
124        }
125        Err(_) => false,
126    }
127}
128
129fn hook_dirs() -> Vec<std::path::PathBuf> {
130    let mut dirs = Vec::new();
131    if let Ok(d) = crate::core::data_dir::lean_ctx_data_dir() {
132        dirs.push(d);
133    }
134    if let Some(home) = dirs::home_dir() {
135        let legacy = home.join(".lean-ctx");
136        if !dirs.iter().any(|d| d == &legacy) {
137            dirs.push(legacy);
138        }
139        let xdg = home.join(".config").join("lean-ctx");
140        if !dirs.iter().any(|d| d == &xdg) {
141            dirs.push(xdg);
142        }
143    }
144    dirs
145}
146
147fn is_active_shell_impl(rc_name: &str, shell: &str, is_windows: bool, is_powershell: bool) -> bool {
148    match rc_name {
149        "~/.zshrc" => shell.contains("zsh"),
150        "~/.bashrc" => {
151            // On Windows, .bashrc is only relevant when explicitly running
152            // inside Git Bash (not PowerShell, cmd, or other Windows shells).
153            // Git Bash sets $SHELL to bash.exe system-wide, which makes $SHELL
154            // unreliable on Windows. We also check that the user is NOT in
155            // PowerShell (PSModulePath) and NOT in plain cmd (PROMPT).
156            if is_windows {
157                if is_powershell {
158                    return false;
159                }
160                // Even without PSModulePath, $SHELL containing "bash" on Windows
161                // is unreliable (Git Bash sets it globally). Only flag if running
162                // from an actual bash interactive session (BASH_VERSION is set).
163                return std::env::var("BASH_VERSION").is_ok();
164            }
165            shell.contains("bash") || shell.is_empty()
166        }
167        "~/.config/fish/config.fish" => shell.contains("fish"),
168        _ => true,
169    }
170}
171
172/// Detect whether we are running inside a PowerShell session on Windows.
173/// Git Bash may set `$SHELL` to bash.exe system-wide, so `$SHELL` alone
174/// is not sufficient — we also need to rule out PowerShell as the actual
175/// running host process.
176fn is_powershell_session() -> bool {
177    std::env::var("PSModulePath").is_ok()
178}
179
180fn is_active_shell(rc_name: &str) -> bool {
181    let shell = std::env::var("SHELL").unwrap_or_default();
182    is_active_shell_impl(rc_name, &shell, cfg!(windows), is_powershell_session())
183}
184
185pub(super) fn shell_aliases_outcome() -> Outcome {
186    let Some(home) = dirs::home_dir() else {
187        return Outcome {
188            ok: false,
189            line: format!("{BOLD}Shell aliases{RST}  {RED}could not resolve home directory{RST}"),
190        };
191    };
192
193    let mut parts = Vec::new();
194    let mut needs_update = Vec::new();
195
196    let zsh = home.join(".zshrc");
197    if rc_contains_lean_ctx(&zsh) {
198        parts.push(format!("{DIM}~/.zshrc{RST}"));
199        if !rc_has_pipe_guard(&zsh) && is_active_shell("~/.zshrc") {
200            needs_update.push("~/.zshrc");
201        }
202    }
203    let bash = home.join(".bashrc");
204    if rc_contains_lean_ctx(&bash) {
205        parts.push(format!("{DIM}~/.bashrc{RST}"));
206        if !rc_has_pipe_guard(&bash) && is_active_shell("~/.bashrc") {
207            needs_update.push("~/.bashrc");
208        }
209    }
210
211    let fish = home.join(".config").join("fish").join("config.fish");
212    if rc_contains_lean_ctx(&fish) {
213        parts.push(format!("{DIM}~/.config/fish/config.fish{RST}"));
214        if !rc_has_pipe_guard(&fish) && is_active_shell("~/.config/fish/config.fish") {
215            needs_update.push("~/.config/fish/config.fish");
216        }
217    }
218
219    #[cfg(windows)]
220    {
221        let ps_profile = home
222            .join("Documents")
223            .join("PowerShell")
224            .join("Microsoft.PowerShell_profile.ps1");
225        let ps_profile_legacy = home
226            .join("Documents")
227            .join("WindowsPowerShell")
228            .join("Microsoft.PowerShell_profile.ps1");
229        if rc_contains_lean_ctx(&ps_profile) {
230            parts.push(format!("{DIM}PowerShell profile{RST}"));
231            if !rc_has_pipe_guard(&ps_profile) {
232                needs_update.push("PowerShell profile");
233            }
234        } else if rc_contains_lean_ctx(&ps_profile_legacy) {
235            parts.push(format!("{DIM}WindowsPowerShell profile{RST}"));
236            if !rc_has_pipe_guard(&ps_profile_legacy) {
237                needs_update.push("WindowsPowerShell profile");
238            }
239        }
240    }
241
242    if parts.is_empty() {
243        let hint = if cfg!(windows) {
244            "no \"lean-ctx\" in PowerShell profile, ~/.zshrc or ~/.bashrc"
245        } else {
246            "no \"lean-ctx\" in ~/.zshrc, ~/.bashrc, or ~/.config/fish/config.fish"
247        };
248        Outcome {
249            ok: false,
250            line: format!("{BOLD}Shell aliases{RST}  {RED}{hint}{RST}"),
251        }
252    } else if !needs_update.is_empty() {
253        Outcome {
254            ok: false,
255            line: format!(
256                "{BOLD}Shell aliases{RST}  {YELLOW}outdated hook in {} — run {BOLD}lean-ctx init --global{RST}{YELLOW} to fix (pipe guard missing){RST}",
257                needs_update.join(", ")
258            ),
259        }
260    } else {
261        Outcome {
262            ok: true,
263            line: format!(
264                "{BOLD}Shell aliases{RST}  {GREEN}lean-ctx referenced in {}{RST}",
265                parts.join(", ")
266            ),
267        }
268    }
269}
270
271struct McpLocation {
272    name: &'static str,
273    display: String,
274    path: PathBuf,
275}
276
277fn mcp_config_locations(home: &std::path::Path) -> Vec<McpLocation> {
278    let mut locations = vec![
279        McpLocation {
280            name: "Cursor",
281            display: "~/.cursor/mcp.json".into(),
282            path: home.join(".cursor").join("mcp.json"),
283        },
284        McpLocation {
285            name: "Claude Code",
286            display: format!(
287                "{}",
288                crate::core::editor_registry::claude_mcp_json_path(home).display()
289            ),
290            path: crate::core::editor_registry::claude_mcp_json_path(home),
291        },
292        McpLocation {
293            name: "Windsurf",
294            display: "~/.codeium/windsurf/mcp_config.json".into(),
295            path: home
296                .join(".codeium")
297                .join("windsurf")
298                .join("mcp_config.json"),
299        },
300        McpLocation {
301            name: "Codex",
302            display: {
303                let codex_dir =
304                    crate::core::home::resolve_codex_dir().unwrap_or_else(|| home.join(".codex"));
305                format!("{}/config.toml", codex_dir.display())
306            },
307            path: crate::core::home::resolve_codex_dir()
308                .unwrap_or_else(|| home.join(".codex"))
309                .join("config.toml"),
310        },
311        McpLocation {
312            name: "Gemini CLI",
313            display: "~/.gemini/settings.json".into(),
314            path: home.join(".gemini").join("settings.json"),
315        },
316        McpLocation {
317            name: "Antigravity",
318            display: "~/.gemini/antigravity/mcp_config.json".into(),
319            path: home
320                .join(".gemini")
321                .join("antigravity")
322                .join("mcp_config.json"),
323        },
324    ];
325
326    #[cfg(unix)]
327    {
328        let zed_cfg = home.join(".config").join("zed").join("settings.json");
329        locations.push(McpLocation {
330            name: "Zed",
331            display: "~/.config/zed/settings.json".into(),
332            path: zed_cfg,
333        });
334    }
335
336    locations.push(McpLocation {
337        name: "Qwen Code",
338        display: "~/.qwen/settings.json".into(),
339        path: home.join(".qwen").join("settings.json"),
340    });
341    locations.push(McpLocation {
342        name: "Trae",
343        display: "~/.trae/mcp.json".into(),
344        path: home.join(".trae").join("mcp.json"),
345    });
346    locations.push(McpLocation {
347        name: "Amazon Q",
348        display: "~/.aws/amazonq/default.json".into(),
349        path: home.join(".aws").join("amazonq").join("default.json"),
350    });
351    locations.push(McpLocation {
352        name: "JetBrains",
353        display: "~/.jb-mcp.json".into(),
354        path: home.join(".jb-mcp.json"),
355    });
356    locations.push(McpLocation {
357        name: "AWS Kiro",
358        display: "~/.kiro/settings/mcp.json".into(),
359        path: home.join(".kiro").join("settings").join("mcp.json"),
360    });
361    locations.push(McpLocation {
362        name: "Verdent",
363        display: "~/.verdent/mcp.json".into(),
364        path: home.join(".verdent").join("mcp.json"),
365    });
366    locations.push(McpLocation {
367        name: "Crush",
368        display: "~/.config/crush/crush.json".into(),
369        path: home.join(".config").join("crush").join("crush.json"),
370    });
371    locations.push(McpLocation {
372        name: "Pi",
373        display: "~/.pi/agent/mcp.json".into(),
374        path: home.join(".pi").join("agent").join("mcp.json"),
375    });
376    locations.push(McpLocation {
377        name: "Amp",
378        display: "~/.config/amp/settings.json".into(),
379        path: home.join(".config").join("amp").join("settings.json"),
380    });
381
382    {
383        #[cfg(unix)]
384        let opencode_cfg = home.join(".config").join("opencode").join("opencode.json");
385        #[cfg(unix)]
386        let opencode_display = "~/.config/opencode/opencode.json";
387
388        #[cfg(windows)]
389        let opencode_cfg = if let Ok(appdata) = std::env::var("APPDATA") {
390            std::path::PathBuf::from(appdata)
391                .join("opencode")
392                .join("opencode.json")
393        } else {
394            home.join(".config").join("opencode").join("opencode.json")
395        };
396        #[cfg(windows)]
397        let opencode_display = "%APPDATA%/opencode/opencode.json";
398
399        locations.push(McpLocation {
400            name: "OpenCode",
401            display: opencode_display.into(),
402            path: opencode_cfg,
403        });
404    }
405
406    #[cfg(target_os = "macos")]
407    {
408        let vscode_mcp = home.join("Library/Application Support/Code/User/mcp.json");
409        locations.push(McpLocation {
410            name: "VS Code",
411            display: "~/Library/Application Support/Code/User/mcp.json".into(),
412            path: vscode_mcp,
413        });
414    }
415    #[cfg(target_os = "linux")]
416    {
417        let vscode_mcp = home.join(".config/Code/User/mcp.json");
418        locations.push(McpLocation {
419            name: "VS Code",
420            display: "~/.config/Code/User/mcp.json".into(),
421            path: vscode_mcp,
422        });
423    }
424    #[cfg(target_os = "windows")]
425    {
426        if let Ok(appdata) = std::env::var("APPDATA") {
427            let vscode_mcp = std::path::PathBuf::from(appdata).join("Code/User/mcp.json");
428            locations.push(McpLocation {
429                name: "VS Code",
430                display: "%APPDATA%/Code/User/mcp.json".into(),
431                path: vscode_mcp,
432            });
433        }
434    }
435
436    locations.push(McpLocation {
437        name: "Copilot CLI",
438        display: "~/.copilot/mcp-config.json".into(),
439        path: home.join(".copilot/mcp-config.json"),
440    });
441
442    locations.push(McpLocation {
443        name: "Hermes Agent",
444        display: "~/.hermes/config.yaml".into(),
445        path: home.join(".hermes").join("config.yaml"),
446    });
447
448    {
449        let cline_path = crate::core::editor_registry::cline_mcp_path();
450        if cline_path.to_str().is_some_and(|s| s != "/nonexistent") {
451            locations.push(McpLocation {
452                name: "Cline",
453                display: cline_path.display().to_string(),
454                path: cline_path,
455            });
456        }
457    }
458    {
459        let roo_path = crate::core::editor_registry::roo_mcp_path();
460        if roo_path.to_str().is_some_and(|s| s != "/nonexistent") {
461            locations.push(McpLocation {
462                name: "Roo Code",
463                display: roo_path.display().to_string(),
464                path: roo_path,
465            });
466        }
467    }
468
469    locations
470}
471
472fn mcp_config_outcome() -> Outcome {
473    let Some(home) = dirs::home_dir() else {
474        return Outcome {
475            ok: false,
476            line: format!("{BOLD}MCP config{RST}  {RED}could not resolve home directory{RST}"),
477        };
478    };
479
480    let locations = mcp_config_locations(&home);
481    let mut found: Vec<String> = Vec::new();
482    let mut exists_no_ref: Vec<String> = Vec::new();
483
484    for loc in &locations {
485        if let Ok(content) = std::fs::read_to_string(&loc.path) {
486            if has_lean_ctx_mcp_entry(&content) {
487                found.push(format!("{} {DIM}({}){RST}", loc.name, loc.display));
488            } else {
489                exists_no_ref.push(loc.name.to_string());
490            }
491        }
492    }
493
494    found.sort();
495    found.dedup();
496    exists_no_ref.sort();
497    exists_no_ref.dedup();
498
499    if !found.is_empty() {
500        Outcome {
501            ok: true,
502            line: format!(
503                "{BOLD}MCP config{RST}  {GREEN}lean-ctx found in: {}{RST}",
504                found.join(", ")
505            ),
506        }
507    } else if !exists_no_ref.is_empty() {
508        let has_claude = exists_no_ref.iter().any(|n| n.starts_with("Claude Code"));
509        let cause = if has_claude {
510            format!("{DIM}(Claude Code may overwrite ~/.claude.json on startup — lean-ctx entry missing from mcpServers){RST}")
511        } else {
512            String::new()
513        };
514        let hint = if has_claude {
515            format!("{DIM}(run: lean-ctx doctor --fix OR lean-ctx init --agent claude){RST}")
516        } else {
517            format!("{DIM}(run: lean-ctx doctor --fix OR lean-ctx setup){RST}")
518        };
519        Outcome {
520            ok: false,
521            line: format!(
522                "{BOLD}MCP config{RST}  {YELLOW}config exists for {} but mcpServers does not contain lean-ctx{RST}  {cause} {hint}",
523                exists_no_ref.join(", "),
524            ),
525        }
526    } else {
527        Outcome {
528            ok: false,
529            line: format!(
530                "{BOLD}MCP config{RST}  {YELLOW}no MCP config found{RST}  {DIM}(run: lean-ctx setup){RST}"
531            ),
532        }
533    }
534}
535
536fn has_lean_ctx_mcp_entry(content: &str) -> bool {
537    if let Ok(json) = serde_json::from_str::<serde_json::Value>(content) {
538        if let Some(servers) = json.get("mcpServers").and_then(|v| v.as_object()) {
539            return servers.contains_key("lean-ctx");
540        }
541        if let Some(servers) = json
542            .get("mcp")
543            .and_then(|v| v.get("servers"))
544            .and_then(|v| v.as_object())
545        {
546            return servers.contains_key("lean-ctx");
547        }
548    }
549    content.contains("lean-ctx")
550}
551
552fn port_3333_outcome() -> Outcome {
553    match TcpListener::bind("127.0.0.1:3333") {
554        Ok(_listener) => Outcome {
555            ok: true,
556            line: format!("{BOLD}Dashboard port 3333{RST}  {GREEN}available on 127.0.0.1{RST}"),
557        },
558        Err(e) => Outcome {
559            ok: false,
560            line: format!("{BOLD}Dashboard port 3333{RST}  {RED}not available: {e}{RST}"),
561        },
562    }
563}
564
565fn pi_outcome() -> Option<Outcome> {
566    let pi_result = std::process::Command::new("pi").arg("--version").output();
567
568    match pi_result {
569        Ok(output) if output.status.success() => {
570            let version = String::from_utf8_lossy(&output.stdout).trim().to_string();
571            let has_plugin = std::process::Command::new("pi")
572                .args(["list"])
573                .output()
574                .is_ok_and(|o| {
575                    o.status.success() && String::from_utf8_lossy(&o.stdout).contains("pi-lean-ctx")
576                });
577
578            let has_mcp = dirs::home_dir()
579                .map(|h| h.join(".pi/agent/mcp.json"))
580                .and_then(|p| std::fs::read_to_string(p).ok())
581                .is_some_and(|c| c.contains("lean-ctx"));
582
583            if has_plugin && has_mcp {
584                Some(Outcome {
585                    ok: true,
586                    line: format!(
587                        "{BOLD}Pi Coding Agent{RST}  {GREEN}{version}, pi-lean-ctx + MCP configured{RST}"
588                    ),
589                })
590            } else if has_plugin {
591                Some(Outcome {
592                    ok: true,
593                    line: format!(
594                        "{BOLD}Pi Coding Agent{RST}  {GREEN}{version}, pi-lean-ctx installed{RST}  {DIM}(MCP not configured — embedded bridge active){RST}"
595                    ),
596                })
597            } else {
598                Some(Outcome {
599                    ok: false,
600                    line: format!(
601                        "{BOLD}Pi Coding Agent{RST}  {YELLOW}{version}, but pi-lean-ctx not installed{RST}  {DIM}(run: pi install npm:pi-lean-ctx){RST}"
602                    ),
603                })
604            }
605        }
606        _ => None,
607    }
608}
609
610fn session_state_outcome() -> Outcome {
611    use crate::core::session::SessionState;
612
613    match SessionState::load_latest() {
614        Some(session) => {
615            let root = session
616                .project_root
617                .as_deref()
618                .unwrap_or("(not set)");
619            let cwd = session
620                .shell_cwd
621                .as_deref()
622                .unwrap_or("(not tracked)");
623            Outcome {
624                ok: true,
625                line: format!(
626                    "{BOLD}Session state{RST}  {GREEN}active{RST}  {DIM}root: {root}, cwd: {cwd}, v{}{RST}",
627                    session.version
628                ),
629            }
630        }
631        None => Outcome {
632            ok: true,
633            line: format!(
634                "{BOLD}Session state{RST}  {YELLOW}no active session{RST}  {DIM}(will be created on first tool call){RST}"
635            ),
636        },
637    }
638}
639
640fn docker_env_outcomes() -> Vec<Outcome> {
641    if !crate::shell::is_container() {
642        return vec![];
643    }
644    let env_sh = crate::core::data_dir::lean_ctx_data_dir().map_or_else(
645        |_| "/root/.lean-ctx/env.sh".to_string(),
646        |d| d.join("env.sh").to_string_lossy().to_string(),
647    );
648
649    let mut outcomes = vec![];
650
651    let shell_name = std::env::var("SHELL").unwrap_or_default();
652    let is_bash = shell_name.contains("bash") || shell_name.is_empty();
653
654    if is_bash {
655        let has_bash_env = std::env::var("BASH_ENV").is_ok();
656        outcomes.push(if has_bash_env {
657            Outcome {
658                ok: true,
659                line: format!(
660                    "{BOLD}BASH_ENV{RST}  {GREEN}set{RST}  {DIM}({}){RST}",
661                    std::env::var("BASH_ENV").unwrap_or_default()
662                ),
663            }
664        } else {
665            Outcome {
666                ok: false,
667                line: format!(
668                    "{BOLD}BASH_ENV{RST}  {RED}not set{RST}  {YELLOW}(add to Dockerfile: ENV BASH_ENV=\"{env_sh}\"){RST}"
669                ),
670            }
671        });
672    }
673
674    let has_claude_env = std::env::var("CLAUDE_ENV_FILE").is_ok();
675    outcomes.push(if has_claude_env {
676        Outcome {
677            ok: true,
678            line: format!(
679                "{BOLD}CLAUDE_ENV_FILE{RST}  {GREEN}set{RST}  {DIM}({}){RST}",
680                std::env::var("CLAUDE_ENV_FILE").unwrap_or_default()
681            ),
682        }
683    } else {
684        Outcome {
685            ok: false,
686            line: format!(
687                "{BOLD}CLAUDE_ENV_FILE{RST}  {RED}not set{RST}  {YELLOW}(for Claude Code: ENV CLAUDE_ENV_FILE=\"{env_sh}\"){RST}"
688            ),
689        }
690    });
691
692    outcomes
693}
694
695/// Run diagnostic checks and print colored results to stdout.
696pub fn run() {
697    let mut passed = 0u32;
698    let total = 10u32;
699
700    println!("{BOLD}{WHITE}lean-ctx doctor{RST}  {DIM}diagnostics{RST}\n");
701
702    // 1) Binary on PATH
703    let path_bin = resolve_lean_ctx_binary();
704    let also_in_path_dirs = path_in_path_env();
705    let bin_ok = path_bin.is_some() || also_in_path_dirs;
706    if bin_ok {
707        passed += 1;
708    }
709    let bin_line = if let Some(p) = path_bin {
710        format!("{BOLD}lean-ctx in PATH{RST}  {WHITE}{}{RST}", p.display())
711    } else if also_in_path_dirs {
712        format!(
713            "{BOLD}lean-ctx in PATH{RST}  {YELLOW}found via PATH walk (not resolved by `command -v`){RST}"
714        )
715    } else {
716        format!("{BOLD}lean-ctx in PATH{RST}  {RED}not found{RST}")
717    };
718    print_check(&Outcome {
719        ok: bin_ok,
720        line: bin_line,
721    });
722
723    // 2) Version from PATH binary
724    let ver = if bin_ok {
725        lean_ctx_version_from_path()
726    } else {
727        Outcome {
728            ok: false,
729            line: format!("{BOLD}lean-ctx version{RST}  {RED}skipped (binary not in PATH){RST}"),
730        }
731    };
732    if ver.ok {
733        passed += 1;
734    }
735    print_check(&ver);
736
737    // 3) data directory (respects LEAN_CTX_DATA_DIR)
738    let lean_dir = crate::core::data_dir::lean_ctx_data_dir().ok();
739    let dir_outcome = match &lean_dir {
740        Some(p) if p.is_dir() => {
741            passed += 1;
742            Outcome {
743                ok: true,
744                line: format!(
745                    "{BOLD}data dir{RST}  {GREEN}exists{RST}  {DIM}{}{RST}",
746                    p.display()
747                ),
748            }
749        }
750        Some(p) => Outcome {
751            ok: false,
752            line: format!(
753                "{BOLD}data dir{RST}  {RED}missing or not a directory{RST}  {DIM}{}{RST}",
754                p.display()
755            ),
756        },
757        None => Outcome {
758            ok: false,
759            line: format!("{BOLD}data dir{RST}  {RED}could not resolve data directory{RST}"),
760        },
761    };
762    print_check(&dir_outcome);
763
764    // 4) stats.json + size
765    let stats_path = lean_dir.as_ref().map(|d| d.join("stats.json"));
766    let stats_outcome = match stats_path.as_ref().and_then(|p| std::fs::metadata(p).ok()) {
767        Some(m) if m.is_file() => {
768            passed += 1;
769            let size = m.len();
770            let path_display = if let Some(p) = stats_path.as_ref() {
771                p.display().to_string()
772            } else {
773                String::new()
774            };
775            Outcome {
776                ok: true,
777                line: format!(
778                    "{BOLD}stats.json{RST}  {GREEN}exists{RST}  {WHITE}{size} bytes{RST}  {DIM}{path_display}{RST}",
779                ),
780            }
781        }
782        Some(_m) => {
783            let path_display = if let Some(p) = stats_path.as_ref() {
784                p.display().to_string()
785            } else {
786                String::new()
787            };
788            Outcome {
789                ok: false,
790                line: format!(
791                    "{BOLD}stats.json{RST}  {RED}not a file{RST}  {DIM}{path_display}{RST}",
792                ),
793            }
794        }
795        None => {
796            passed += 1;
797            Outcome {
798                ok: true,
799                line: match &stats_path {
800                    Some(p) => format!(
801                        "{BOLD}stats.json{RST}  {YELLOW}not yet created{RST}  {DIM}(will appear after first use) {}{RST}",
802                        p.display()
803                    ),
804                    None => format!("{BOLD}stats.json{RST}  {RED}could not resolve path{RST}"),
805                },
806            }
807        }
808    };
809    print_check(&stats_outcome);
810
811    let split_dirs = crate::core::data_dir::all_data_dirs_with_stats();
812    if split_dirs.len() >= 2 {
813        let dirs_str = split_dirs
814            .iter()
815            .map(|d| d.display().to_string())
816            .collect::<Vec<_>>()
817            .join(", ");
818        print_check(&Outcome {
819            ok: false,
820            line: format!(
821                "{BOLD}data dir split{RST}  {RED}stats.json found in {count} locations{RST}: {dirs_str}  {DIM}(run: lean-ctx setup to auto-merge){RST}",
822                count = split_dirs.len(),
823            ),
824        });
825    }
826
827    // 5) config.toml (missing is OK)
828    let config_path = lean_dir.as_ref().map(|d| d.join("config.toml"));
829    let config_outcome = match &config_path {
830        Some(p) => match std::fs::metadata(p) {
831            Ok(m) if m.is_file() => {
832                passed += 1;
833                Outcome {
834                    ok: true,
835                    line: format!(
836                        "{BOLD}config.toml{RST}  {GREEN}exists{RST}  {DIM}{}{RST}",
837                        p.display()
838                    ),
839                }
840            }
841            Ok(_) => Outcome {
842                ok: false,
843                line: format!(
844                    "{BOLD}config.toml{RST}  {RED}exists but is not a regular file{RST}  {DIM}{}{RST}",
845                    p.display()
846                ),
847            },
848            Err(_) => {
849                passed += 1;
850                Outcome {
851                    ok: true,
852                    line: format!(
853                        "{BOLD}config.toml{RST}  {YELLOW}not found, using defaults{RST}  {DIM}(expected at {}){RST}",
854                        p.display()
855                    ),
856                }
857            }
858        },
859        None => Outcome {
860            ok: false,
861            line: format!("{BOLD}config.toml{RST}  {RED}could not resolve path{RST}"),
862        },
863    };
864    print_check(&config_outcome);
865
866    // 6) Proxy upstreams
867    let proxy_outcome = proxy_upstream_outcome();
868    if proxy_outcome.ok {
869        passed += 1;
870    }
871    print_check(&proxy_outcome);
872
873    // 7) Shell aliases
874    let aliases = shell_aliases_outcome();
875    if aliases.ok {
876        passed += 1;
877    }
878    print_check(&aliases);
879
880    // 7) MCP
881    let mcp = mcp_config_outcome();
882    if mcp.ok {
883        passed += 1;
884    }
885    print_check(&mcp);
886
887    // 9) SKILL.md
888    let skill = skill_files_outcome();
889    if skill.ok {
890        passed += 1;
891    }
892    print_check(&skill);
893
894    // 10) Port
895    let port = port_3333_outcome();
896    if port.ok {
897        passed += 1;
898    }
899    print_check(&port);
900
901    // Daemon status
902    #[cfg(unix)]
903    let daemon_outcome = if crate::daemon::is_daemon_running() {
904        let pid_path = crate::daemon::daemon_pid_path();
905        let pid_str = std::fs::read_to_string(&pid_path).unwrap_or_default();
906        Outcome {
907            ok: true,
908            line: format!(
909                "{BOLD}Daemon{RST}  {GREEN}running (PID {}){RST}",
910                pid_str.trim()
911            ),
912        }
913    } else {
914        Outcome {
915            ok: true,
916            line: format!(
917                "{BOLD}Daemon{RST}  {YELLOW}not running{RST}  {DIM}(run: lean-ctx serve -d){RST}"
918            ),
919        }
920    };
921    #[cfg(not(unix))]
922    let daemon_outcome = Outcome {
923        ok: true,
924        line: format!("{BOLD}Daemon{RST}  {DIM}not supported on this platform{RST}"),
925    };
926    if daemon_outcome.ok {
927        passed += 1;
928    }
929    print_check(&daemon_outcome);
930
931    // 9) Session state (project_root + shell_cwd)
932    let session_outcome = session_state_outcome();
933    if session_outcome.ok {
934        passed += 1;
935    }
936    print_check(&session_outcome);
937
938    // 10) Docker env vars (optional, only in containers)
939    let docker_outcomes = docker_env_outcomes();
940    for docker_check in &docker_outcomes {
941        if docker_check.ok {
942            passed += 1;
943        }
944        print_check(docker_check);
945    }
946
947    // 11) Pi Coding Agent (optional)
948    let pi = pi_outcome();
949    if let Some(ref pi_check) = pi {
950        if pi_check.ok {
951            passed += 1;
952        }
953        print_check(pi_check);
954    }
955
956    // 12) Build integrity (canary / origin check)
957    let integrity = crate::core::integrity::check();
958    let integrity_ok = integrity.seed_ok && integrity.origin_ok;
959    if integrity_ok {
960        passed += 1;
961    }
962    let integrity_line = if integrity_ok {
963        format!(
964            "{BOLD}Build origin{RST}  {GREEN}official{RST}  {DIM}{}{RST}",
965            integrity.repo
966        )
967    } else {
968        format!(
969            "{BOLD}Build origin{RST}  {RED}MODIFIED REDISTRIBUTION{RST}  {YELLOW}pkg={}, repo={}{RST}",
970            integrity.pkg_name, integrity.repo
971        )
972    };
973    print_check(&Outcome {
974        ok: integrity_ok,
975        line: integrity_line,
976    });
977
978    // 13) Cache safety
979    let cache_safety = cache_safety_outcome();
980    if cache_safety.ok {
981        passed += 1;
982    }
983    print_check(&cache_safety);
984
985    // 14) Claude Code instruction truncation guard
986    let claude_truncation = claude_truncation_outcome();
987    if let Some(ref ct) = claude_truncation {
988        if ct.ok {
989            passed += 1;
990        }
991        print_check(ct);
992    }
993
994    // 15) BM25 cache health
995    let bm25_health = bm25_cache_health_outcome();
996    if bm25_health.ok {
997        passed += 1;
998    }
999    print_check(&bm25_health);
1000
1001    // 16) Memory profile
1002    let mem_profile = memory_profile_outcome();
1003    passed += 1;
1004    print_check(&mem_profile);
1005
1006    // 17) Memory cleanup
1007    let mem_cleanup = memory_cleanup_outcome();
1008    passed += 1;
1009    print_check(&mem_cleanup);
1010
1011    // 18) RAM Guardian
1012    let ram_outcome = ram_guardian_outcome();
1013    if ram_outcome.ok {
1014        passed += 1;
1015    }
1016    print_check(&ram_outcome);
1017
1018    // 19) Proxy health
1019    let proxy_health = proxy_health_outcome();
1020    if proxy_health.ok {
1021        passed += 1;
1022    }
1023    print_check(&proxy_health);
1024
1025    // LSP servers (optional, informational)
1026    println!("\n  {BOLD}{WHITE}LSP (optional — for ctx_refactor):{RST}");
1027    let lsp_outcomes = lsp_server_outcomes();
1028    for lsp_check in &lsp_outcomes {
1029        print_check(lsp_check);
1030    }
1031
1032    let mut effective_total = total + 9; // session_state + integrity + cache_safety + bm25_health + daemon + mem_profile + mem_cleanup + ram_guardian + proxy_health
1033    effective_total += docker_outcomes.len() as u32;
1034    if pi.is_some() {
1035        effective_total += 1;
1036    }
1037    if claude_truncation.is_some() {
1038        effective_total += 1;
1039    }
1040    println!();
1041    println!("  {BOLD}{WHITE}Summary:{RST}  {GREEN}{passed}{RST}{DIM}/{effective_total}{RST} checks passed");
1042    println!("  {DIM}LSP servers are optional enhancements (not counted in score){RST}");
1043    println!("  {DIM}{}{RST}", crate::core::integrity::origin_line());
1044}
1045
1046fn skill_files_outcome() -> Outcome {
1047    let Some(home) = dirs::home_dir() else {
1048        return Outcome {
1049            ok: false,
1050            line: format!("{BOLD}SKILL.md{RST}  {RED}could not resolve home directory{RST}"),
1051        };
1052    };
1053
1054    let candidates = [
1055        ("Claude Code", home.join(".claude/skills/lean-ctx/SKILL.md")),
1056        ("Cursor", home.join(".cursor/skills/lean-ctx/SKILL.md")),
1057        (
1058            "Codex CLI",
1059            crate::core::home::resolve_codex_dir()
1060                .unwrap_or_else(|| home.join(".codex"))
1061                .join("skills/lean-ctx/SKILL.md"),
1062        ),
1063        (
1064            "GitHub Copilot",
1065            home.join(".vscode/skills/lean-ctx/SKILL.md"),
1066        ),
1067    ];
1068
1069    let mut found: Vec<&str> = Vec::new();
1070    for (name, path) in &candidates {
1071        if path.exists() {
1072            found.push(name);
1073        }
1074    }
1075
1076    if found.is_empty() {
1077        Outcome {
1078            ok: false,
1079            line: format!(
1080                "{BOLD}SKILL.md{RST}  {YELLOW}not installed{RST}  {DIM}(run: lean-ctx setup){RST}"
1081            ),
1082        }
1083    } else {
1084        Outcome {
1085            ok: true,
1086            line: format!(
1087                "{BOLD}SKILL.md{RST}  {GREEN}installed for {}{RST}",
1088                found.join(", ")
1089            ),
1090        }
1091    }
1092}
1093
1094fn proxy_health_outcome() -> Outcome {
1095    use crate::core::config::Config;
1096
1097    let cfg = Config::load();
1098    let port = crate::proxy_setup::default_port();
1099
1100    match cfg.proxy_enabled {
1101        Some(true) => {
1102            let installed = crate::proxy_autostart::is_installed();
1103            let reachable = std::net::TcpStream::connect_timeout(
1104                &format!("127.0.0.1:{port}")
1105                    .parse()
1106                    .expect("BUG: invalid hardcoded address"),
1107                std::time::Duration::from_millis(200),
1108            )
1109            .is_ok();
1110
1111            if installed && reachable {
1112                Outcome {
1113                    ok: true,
1114                    line: format!(
1115                        "{BOLD}Proxy{RST}  {GREEN}enabled, running on port {port}{RST}"
1116                    ),
1117                }
1118            } else if installed && !reachable {
1119                Outcome {
1120                    ok: false,
1121                    line: format!(
1122                        "{BOLD}Proxy{RST}  {RED}enabled but not reachable on port {port}{RST}  {YELLOW}fix: lean-ctx proxy start{RST}"
1123                    ),
1124                }
1125            } else {
1126                Outcome {
1127                    ok: false,
1128                    line: format!(
1129                        "{BOLD}Proxy{RST}  {RED}enabled but autostart not installed{RST}  {YELLOW}fix: lean-ctx proxy enable{RST}"
1130                    ),
1131                }
1132            }
1133        }
1134        Some(false) => Outcome {
1135            ok: true,
1136            line: format!(
1137                "{BOLD}Proxy{RST}  {DIM}disabled (optional feature){RST}  {DIM}enable: lean-ctx proxy enable{RST}"
1138            ),
1139        },
1140        None => Outcome {
1141            ok: true,
1142            line: format!(
1143                "{BOLD}Proxy{RST}  {DIM}not configured{RST}  {DIM}enable: lean-ctx proxy enable{RST}"
1144            ),
1145        },
1146    }
1147}
1148
1149fn proxy_upstream_outcome() -> Outcome {
1150    use crate::core::config::{is_local_proxy_url, Config, ProxyProvider};
1151
1152    let cfg = Config::load();
1153    let checks = [
1154        (
1155            "Anthropic",
1156            "proxy.anthropic_upstream",
1157            cfg.proxy.resolve_upstream(ProxyProvider::Anthropic),
1158        ),
1159        (
1160            "OpenAI",
1161            "proxy.openai_upstream",
1162            cfg.proxy.resolve_upstream(ProxyProvider::OpenAi),
1163        ),
1164        (
1165            "Gemini",
1166            "proxy.gemini_upstream",
1167            cfg.proxy.resolve_upstream(ProxyProvider::Gemini),
1168        ),
1169    ];
1170
1171    let mut custom = Vec::new();
1172    for (label, key, resolved) in &checks {
1173        if is_local_proxy_url(resolved) {
1174            return Outcome {
1175                ok: false,
1176                line: format!(
1177                    "{BOLD}Proxy upstream{RST}  {RED}{label} upstream points back to local proxy{RST}  {YELLOW}run: lean-ctx config set {key} <url>{RST}"
1178                ),
1179            };
1180        }
1181        if !resolved.starts_with("http://") && !resolved.starts_with("https://") {
1182            return Outcome {
1183                ok: false,
1184                line: format!(
1185                    "{BOLD}Proxy upstream{RST}  {RED}invalid {label} upstream{RST}  {YELLOW}set {key} to an http(s) URL{RST}"
1186                ),
1187            };
1188        }
1189        let is_default = matches!(
1190            *label,
1191            "Anthropic" if resolved == "https://api.anthropic.com"
1192        ) || matches!(
1193            *label,
1194            "OpenAI" if resolved == "https://api.openai.com"
1195        ) || matches!(
1196            *label,
1197            "Gemini" if resolved == "https://generativelanguage.googleapis.com"
1198        );
1199        if !is_default {
1200            custom.push(format!("{label}={resolved}"));
1201        }
1202    }
1203
1204    if custom.is_empty() {
1205        Outcome {
1206            ok: true,
1207            line: format!("{BOLD}Proxy upstream{RST}  {GREEN}provider defaults{RST}"),
1208        }
1209    } else {
1210        Outcome {
1211            ok: true,
1212            line: format!(
1213                "{BOLD}Proxy upstream{RST}  {GREEN}custom: {}{RST}",
1214                custom.join(", ")
1215            ),
1216        }
1217    }
1218}
1219
1220fn cache_safety_outcome() -> Outcome {
1221    use crate::core::neural::cache_alignment::CacheAlignedOutput;
1222    use crate::core::provider_cache::ProviderCacheState;
1223
1224    let mut issues = Vec::new();
1225
1226    let mut aligned = CacheAlignedOutput::new();
1227    aligned.add_stable_block("test", "stable content".into(), 1);
1228    aligned.add_variable_block("test_var", "variable content".into(), 1);
1229    let rendered = aligned.render();
1230    if rendered.find("stable content").unwrap_or(usize::MAX)
1231        > rendered.find("variable content").unwrap_or(0)
1232    {
1233        issues.push("cache_alignment: stable blocks not ordered first");
1234    }
1235
1236    let mut state = ProviderCacheState::new();
1237    let section = crate::core::provider_cache::CacheableSection::new(
1238        "doctor_test",
1239        "test content".into(),
1240        crate::core::provider_cache::SectionPriority::System,
1241        true,
1242    );
1243    state.mark_sent(&section);
1244    if state.needs_update(&section) {
1245        issues.push("provider_cache: hash tracking broken");
1246    }
1247
1248    if issues.is_empty() {
1249        Outcome {
1250            ok: true,
1251            line: format!(
1252                "{BOLD}Cache safety{RST}  {GREEN}cache_alignment + provider_cache operational{RST}"
1253            ),
1254        }
1255    } else {
1256        Outcome {
1257            ok: false,
1258            line: format!("{BOLD}Cache safety{RST}  {RED}{}{RST}", issues.join("; ")),
1259        }
1260    }
1261}
1262
1263pub(super) fn claude_binary_exists() -> bool {
1264    #[cfg(unix)]
1265    {
1266        std::process::Command::new("which")
1267            .arg("claude")
1268            .output()
1269            .is_ok_and(|o| o.status.success())
1270    }
1271    #[cfg(windows)]
1272    {
1273        std::process::Command::new("where")
1274            .arg("claude")
1275            .output()
1276            .is_ok_and(|o| o.status.success())
1277    }
1278}
1279
1280fn claude_truncation_outcome() -> Option<Outcome> {
1281    let home = dirs::home_dir()?;
1282    let claude_detected = crate::core::editor_registry::claude_mcp_json_path(&home).exists()
1283        || crate::core::editor_registry::claude_state_dir(&home).exists()
1284        || claude_binary_exists();
1285
1286    if !claude_detected {
1287        return None;
1288    }
1289
1290    let rules_path = crate::core::editor_registry::claude_rules_dir(&home).join("lean-ctx.md");
1291    let skill_path = home.join(".claude/skills/lean-ctx/SKILL.md");
1292
1293    let has_rules = rules_path.exists();
1294    let has_skill = skill_path.exists();
1295
1296    if has_rules && has_skill {
1297        Some(Outcome {
1298            ok: true,
1299            line: format!(
1300                "{BOLD}Claude Code instructions{RST}  {GREEN}rules + skill installed{RST}  {DIM}(MCP instructions capped at 2048 chars — full content via rules file){RST}"
1301            ),
1302        })
1303    } else if has_rules {
1304        Some(Outcome {
1305            ok: true,
1306            line: format!(
1307                "{BOLD}Claude Code instructions{RST}  {GREEN}rules file installed{RST}  {DIM}(MCP instructions capped at 2048 chars — full content via rules file){RST}"
1308            ),
1309        })
1310    } else {
1311        Some(Outcome {
1312            ok: false,
1313            line: format!(
1314                "{BOLD}Claude Code instructions{RST}  {YELLOW}MCP instructions truncated at 2048 chars, no rules file found{RST}  {DIM}(run: lean-ctx init --agent claude){RST}"
1315            ),
1316        })
1317    }
1318}
1319
1320fn bm25_cache_health_outcome() -> Outcome {
1321    let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
1322        return Outcome {
1323            ok: true,
1324            line: format!("{BOLD}BM25 cache{RST}  {DIM}skipped (no data dir){RST}"),
1325        };
1326    };
1327
1328    let vectors_dir = data_dir.join("vectors");
1329    let Ok(entries) = std::fs::read_dir(&vectors_dir) else {
1330        return Outcome {
1331            ok: true,
1332            line: format!("{BOLD}BM25 cache{RST}  {GREEN}no vector dirs{RST}"),
1333        };
1334    };
1335
1336    let max_bytes = crate::core::config::Config::load().bm25_max_cache_mb * 1024 * 1024;
1337    let warn_bytes = 100 * 1024 * 1024; // 100 MB
1338    let mut total_dirs = 0u32;
1339    let mut total_bytes = 0u64;
1340    let mut oversized: Vec<(String, u64)> = Vec::new();
1341    let mut warnings: Vec<(String, u64)> = Vec::new();
1342    let mut quarantined_count = 0u32;
1343
1344    for entry in entries.flatten() {
1345        let dir = entry.path();
1346        if !dir.is_dir() {
1347            continue;
1348        }
1349        total_dirs += 1;
1350
1351        if dir.join("bm25_index.json.quarantined").exists()
1352            || dir.join("bm25_index.bin.quarantined").exists()
1353            || dir.join("bm25_index.bin.zst.quarantined").exists()
1354        {
1355            quarantined_count += 1;
1356        }
1357
1358        let index_path = if dir.join("bm25_index.bin.zst").exists() {
1359            dir.join("bm25_index.bin.zst")
1360        } else if dir.join("bm25_index.bin").exists() {
1361            dir.join("bm25_index.bin")
1362        } else {
1363            dir.join("bm25_index.json")
1364        };
1365        if let Ok(meta) = std::fs::metadata(&index_path) {
1366            let size = meta.len();
1367            total_bytes += size;
1368            let display = index_path.display().to_string();
1369            if size > max_bytes {
1370                oversized.push((display, size));
1371            } else if size > warn_bytes {
1372                warnings.push((display, size));
1373            }
1374        }
1375    }
1376
1377    if !oversized.is_empty() {
1378        let details: Vec<String> = oversized
1379            .iter()
1380            .map(|(p, s)| format!("{p} ({:.1} GB)", *s as f64 / 1_073_741_824.0))
1381            .collect();
1382        return Outcome {
1383            ok: false,
1384            line: format!(
1385                "{BOLD}BM25 cache{RST}  {RED}{} index(es) exceed limit ({:.0} MB){RST}: {}  {DIM}(run: lean-ctx cache prune){RST}",
1386                oversized.len(),
1387                max_bytes / (1024 * 1024),
1388                details.join(", ")
1389            ),
1390        };
1391    }
1392
1393    if !warnings.is_empty() {
1394        let details: Vec<String> = warnings
1395            .iter()
1396            .map(|(p, s)| format!("{p} ({:.0} MB)", *s as f64 / 1_048_576.0))
1397            .collect();
1398        return Outcome {
1399            ok: true,
1400            line: format!(
1401                "{BOLD}BM25 cache{RST}  {YELLOW}{} large index(es) (>100 MB){RST}: {}  {DIM}(consider extra_ignore_patterns){RST}",
1402                warnings.len(),
1403                details.join(", ")
1404            ),
1405        };
1406    }
1407
1408    let quarantine_note = if quarantined_count > 0 {
1409        format!("  {YELLOW}{quarantined_count} quarantined (run: lean-ctx cache prune){RST}")
1410    } else {
1411        String::new()
1412    };
1413
1414    Outcome {
1415        ok: true,
1416        line: format!(
1417            "{BOLD}BM25 cache{RST}  {GREEN}{total_dirs} index(es), {:.1} MB total{RST}{quarantine_note}",
1418            total_bytes as f64 / 1_048_576.0
1419        ),
1420    }
1421}
1422
1423pub fn run_compact() {
1424    let (passed, total) = compact_score();
1425    print_compact_status(passed, total);
1426}
1427
1428pub fn run_cli(args: &[String]) -> i32 {
1429    let (sub, rest) = match args.first().map(String::as_str) {
1430        Some("integrations") => ("integrations", &args[1..]),
1431        _ => ("", args),
1432    };
1433
1434    let fix = rest.iter().any(|a| a == "--fix");
1435    let json = rest.iter().any(|a| a == "--json");
1436    let help = rest.iter().any(|a| a == "--help" || a == "-h");
1437
1438    if help {
1439        println!("Usage:");
1440        println!("  lean-ctx doctor");
1441        println!("  lean-ctx doctor integrations [--json]");
1442        println!("  lean-ctx doctor --fix [--json]");
1443        return 0;
1444    }
1445
1446    if sub == "integrations" {
1447        if fix {
1448            let _ = fix::run_fix(&fix::DoctorFixOptions { json: false });
1449        }
1450        return integrations::run_integrations(&integrations::IntegrationsOptions { json });
1451    }
1452
1453    if !fix {
1454        run();
1455        return 0;
1456    }
1457
1458    match fix::run_fix(&fix::DoctorFixOptions { json }) {
1459        Ok(code) => code,
1460        Err(e) => {
1461            tracing::error!("doctor --fix failed: {e}");
1462            2
1463        }
1464    }
1465}
1466
1467pub fn compact_score() -> (u32, u32) {
1468    let mut passed = 0u32;
1469    let total = 6u32;
1470
1471    if resolve_lean_ctx_binary().is_some() || path_in_path_env() {
1472        passed += 1;
1473    }
1474    let lean_dir = crate::core::data_dir::lean_ctx_data_dir().ok();
1475    if lean_dir.as_ref().is_some_and(|p| p.is_dir()) {
1476        passed += 1;
1477    }
1478    if lean_dir
1479        .as_ref()
1480        .map(|d| d.join("stats.json"))
1481        .and_then(|p| std::fs::metadata(p).ok())
1482        .is_some_and(|m| m.is_file())
1483    {
1484        passed += 1;
1485    }
1486    if shell_aliases_outcome().ok {
1487        passed += 1;
1488    }
1489    if mcp_config_outcome().ok {
1490        passed += 1;
1491    }
1492    if skill_files_outcome().ok {
1493        passed += 1;
1494    }
1495
1496    (passed, total)
1497}
1498
1499pub(super) fn print_compact_status(passed: u32, total: u32) {
1500    let status = if passed == total {
1501        format!("{GREEN}✓ All {total} checks passed{RST}")
1502    } else {
1503        format!("{YELLOW}{passed}/{total} passed{RST} — run {BOLD}lean-ctx doctor{RST} for details")
1504    };
1505    println!("  {status}");
1506}
1507
1508fn memory_profile_outcome() -> Outcome {
1509    let cfg = crate::core::config::Config::load();
1510    let profile = crate::core::config::MemoryProfile::effective(&cfg);
1511    let (label, detail) = match profile {
1512        crate::core::config::MemoryProfile::Low => {
1513            ("low", "embeddings+semantic cache disabled, BM25 64 MB")
1514        }
1515        crate::core::config::MemoryProfile::Balanced => {
1516            ("balanced", "default — BM25 128 MB, single embedding engine")
1517        }
1518        crate::core::config::MemoryProfile::Performance => {
1519            ("performance", "full caches, BM25 512 MB")
1520        }
1521    };
1522    let source = if crate::core::config::MemoryProfile::from_env().is_some() {
1523        "env"
1524    } else if cfg.memory_profile != crate::core::config::MemoryProfile::default() {
1525        "config"
1526    } else {
1527        "default"
1528    };
1529    Outcome {
1530        ok: true,
1531        line: format!(
1532            "{BOLD}Memory profile{RST}  {GREEN}{label}{RST}  {DIM}({source}: {detail}){RST}"
1533        ),
1534    }
1535}
1536
1537fn memory_cleanup_outcome() -> Outcome {
1538    let cfg = crate::core::config::Config::load();
1539    let cleanup = crate::core::config::MemoryCleanup::effective(&cfg);
1540    let (label, detail) = match cleanup {
1541        crate::core::config::MemoryCleanup::Aggressive => (
1542            "aggressive",
1543            "cache cleared after 5 min idle, single-IDE optimized",
1544        ),
1545        crate::core::config::MemoryCleanup::Shared => (
1546            "shared",
1547            "cache retained 30 min, multi-IDE/multi-model optimized",
1548        ),
1549    };
1550    let source = if crate::core::config::MemoryCleanup::from_env().is_some() {
1551        "env"
1552    } else if cfg.memory_cleanup != crate::core::config::MemoryCleanup::default() {
1553        "config"
1554    } else {
1555        "default"
1556    };
1557    Outcome {
1558        ok: true,
1559        line: format!(
1560            "{BOLD}Memory cleanup{RST}  {GREEN}{label}{RST}  {DIM}({source}: {detail}){RST}"
1561        ),
1562    }
1563}
1564
1565fn ram_guardian_outcome() -> Outcome {
1566    let Some(snap) = crate::core::memory_guard::MemorySnapshot::capture() else {
1567        return Outcome {
1568            ok: true,
1569            line: format!(
1570                "{BOLD}RAM Guardian{RST}  {YELLOW}not available{RST}  {DIM}(platform unsupported){RST}"
1571            ),
1572        };
1573    };
1574    let allocator = if cfg!(all(feature = "jemalloc", not(windows))) {
1575        "jemalloc"
1576    } else {
1577        "system"
1578    };
1579    let ok = snap.pressure_level == crate::core::memory_guard::PressureLevel::Normal;
1580    let color = if ok { GREEN } else { RED };
1581    Outcome {
1582        ok,
1583        line: format!(
1584            "{BOLD}RAM Guardian{RST}  {color}{:.0} MB{RST} / {:.1} GB system ({:.1}%)  {DIM}limit: {:.0} MB ({allocator}){RST}",
1585            snap.rss_bytes as f64 / 1_048_576.0,
1586            snap.system_ram_bytes as f64 / 1_073_741_824.0,
1587            snap.rss_percent,
1588            snap.rss_limit_bytes as f64 / 1_048_576.0,
1589        ),
1590    }
1591}
1592
1593fn lsp_server_outcomes() -> Vec<Outcome> {
1594    use crate::lsp::config::{find_binary_in_path, KNOWN_SERVERS};
1595
1596    KNOWN_SERVERS
1597        .iter()
1598        .map(|info| {
1599            let found = find_binary_in_path(info.binary);
1600            match found {
1601                Some(path) => Outcome {
1602                    ok: true,
1603                    line: format!(
1604                        "{BOLD}{}{RST}  {GREEN}✓ {}{RST}  {DIM}{}{RST}",
1605                        info.language,
1606                        info.binary,
1607                        path.display()
1608                    ),
1609                },
1610                None => Outcome {
1611                    ok: false,
1612                    line: format!(
1613                        "{BOLD}{}{RST}  {DIM}not installed{RST}  {YELLOW}{}{RST}",
1614                        info.language, info.install_hint
1615                    ),
1616                },
1617            }
1618        })
1619        .collect()
1620}
1621
1622#[cfg(test)]
1623mod tests {
1624    use super::is_active_shell_impl;
1625
1626    #[test]
1627    fn bashrc_active_on_non_windows_when_shell_empty() {
1628        assert!(is_active_shell_impl("~/.bashrc", "", false, false));
1629    }
1630
1631    #[test]
1632    fn bashrc_not_active_on_windows_when_shell_empty() {
1633        assert!(!is_active_shell_impl("~/.bashrc", "", true, false));
1634    }
1635
1636    #[test]
1637    fn bashrc_active_when_shell_contains_bash_on_linux() {
1638        assert!(is_active_shell_impl(
1639            "~/.bashrc",
1640            "/usr/bin/bash",
1641            false,
1642            false
1643        ));
1644    }
1645
1646    #[test]
1647    fn bashrc_not_active_on_windows_even_with_bash_in_shell_env() {
1648        // Issue #214: On Windows, Git Bash sets $SHELL globally to bash.exe.
1649        // .bashrc should NOT be flagged on Windows unless actually inside bash.
1650        std::env::remove_var("BASH_VERSION");
1651        assert!(!is_active_shell_impl(
1652            "~/.bashrc",
1653            "C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe",
1654            true,
1655            false,
1656        ));
1657    }
1658
1659    #[test]
1660    fn bashrc_not_active_on_windows_powershell_even_with_bash_in_shell() {
1661        assert!(!is_active_shell_impl(
1662            "~/.bashrc",
1663            "C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe",
1664            true,
1665            true,
1666        ));
1667    }
1668
1669    #[test]
1670    fn bashrc_not_active_on_windows_powershell_with_empty_shell() {
1671        assert!(!is_active_shell_impl("~/.bashrc", "", true, true));
1672    }
1673
1674    #[test]
1675    fn zshrc_unaffected_by_powershell_flag() {
1676        assert!(is_active_shell_impl("~/.zshrc", "/bin/zsh", false, false));
1677        assert!(is_active_shell_impl("~/.zshrc", "/bin/zsh", true, true));
1678    }
1679
1680    #[test]
1681    fn bashrc_not_active_on_windows_without_powershell_detection() {
1682        // Windows + $SHELL=bash but NOT in actual bash session (no BASH_VERSION).
1683        // This is the exact scenario from issue #214: Git Bash sets $SHELL globally.
1684        std::env::remove_var("BASH_VERSION");
1685        assert!(!is_active_shell_impl(
1686            "~/.bashrc",
1687            "/usr/bin/bash",
1688            true,
1689            false,
1690        ));
1691    }
1692
1693    #[test]
1694    fn bashrc_active_on_linux() {
1695        assert!(is_active_shell_impl("~/.bashrc", "/bin/bash", false, false));
1696        assert!(is_active_shell_impl("~/.bashrc", "", false, false));
1697    }
1698}