Skip to main content

lean_ctx/
doctor.rs

1//! Environment diagnostics for lean-ctx installation and integration.
2
3use std::net::TcpListener;
4use std::path::PathBuf;
5
6use chrono::Utc;
7
8const GREEN: &str = "\x1b[32m";
9const RED: &str = "\x1b[31m";
10const BOLD: &str = "\x1b[1m";
11const RST: &str = "\x1b[0m";
12const DIM: &str = "\x1b[2m";
13const WHITE: &str = "\x1b[97m";
14const YELLOW: &str = "\x1b[33m";
15
16struct Outcome {
17    ok: bool,
18    line: String,
19}
20
21fn print_check(outcome: &Outcome) {
22    let mark = if outcome.ok {
23        format!("{GREEN}✓{RST}")
24    } else {
25        format!("{RED}✗{RST}")
26    };
27    println!("  {mark}  {}", outcome.line);
28}
29
30fn path_in_path_env() -> bool {
31    if let Ok(path) = std::env::var("PATH") {
32        for dir in std::env::split_paths(&path) {
33            if dir.join("lean-ctx").is_file() {
34                return true;
35            }
36            if cfg!(windows)
37                && (dir.join("lean-ctx.exe").is_file() || dir.join("lean-ctx.cmd").is_file())
38            {
39                return true;
40            }
41        }
42    }
43    false
44}
45
46fn resolve_lean_ctx_binary() -> Option<PathBuf> {
47    if let Ok(path) = std::env::var("PATH") {
48        for dir in std::env::split_paths(&path) {
49            if cfg!(windows) {
50                let exe = dir.join("lean-ctx.exe");
51                if exe.is_file() {
52                    return Some(exe);
53                }
54                let cmd = dir.join("lean-ctx.cmd");
55                if cmd.is_file() {
56                    return Some(cmd);
57                }
58            } else {
59                let bin = dir.join("lean-ctx");
60                if bin.is_file() {
61                    return Some(bin);
62                }
63            }
64        }
65    }
66    None
67}
68
69fn lean_ctx_version_from_path() -> Outcome {
70    let resolved = resolve_lean_ctx_binary();
71    let bin = resolved
72        .clone()
73        .unwrap_or_else(|| std::env::current_exe().unwrap_or_else(|_| "lean-ctx".into()));
74
75    let v = env!("CARGO_PKG_VERSION");
76    let note = match std::env::current_exe() {
77        Ok(exe) if exe == bin => format!("{DIM}(this binary){RST}"),
78        Ok(_) => format!("{DIM}(resolved: {}){RST}", bin.display()),
79        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_has_pipe_guard(path: &PathBuf) -> bool {
101    match std::fs::read_to_string(path) {
102        Ok(s) => {
103            if has_pipe_guard_in_content(&s) {
104                return true;
105            }
106            if s.contains(".lean-ctx/shell-hook.") {
107                if let Some(home) = dirs::home_dir() {
108                    for ext in &["zsh", "bash", "fish", "ps1"] {
109                        let hook = home.join(format!(".lean-ctx/shell-hook.{ext}"));
110                        if let Ok(h) = std::fs::read_to_string(&hook) {
111                            if has_pipe_guard_in_content(&h) {
112                                return true;
113                            }
114                        }
115                    }
116                }
117            }
118            false
119        }
120        Err(_) => false,
121    }
122}
123
124fn is_active_shell(rc_name: &str) -> bool {
125    let shell = std::env::var("SHELL").unwrap_or_default();
126    match rc_name {
127        "~/.zshrc" => shell.contains("zsh"),
128        "~/.bashrc" => shell.contains("bash") || shell.is_empty(),
129        "~/.config/fish/config.fish" => shell.contains("fish"),
130        _ => true,
131    }
132}
133
134fn shell_aliases_outcome() -> Outcome {
135    let home = match dirs::home_dir() {
136        Some(h) => h,
137        None => {
138            return Outcome {
139                ok: false,
140                line: format!(
141                    "{BOLD}Shell aliases{RST}  {RED}could not resolve home directory{RST}"
142                ),
143            };
144        }
145    };
146
147    let mut parts = Vec::new();
148    let mut needs_update = Vec::new();
149
150    let zsh = home.join(".zshrc");
151    if rc_contains_lean_ctx(&zsh) {
152        parts.push(format!("{DIM}~/.zshrc{RST}"));
153        if !rc_has_pipe_guard(&zsh) && is_active_shell("~/.zshrc") {
154            needs_update.push("~/.zshrc");
155        }
156    }
157    let bash = home.join(".bashrc");
158    if rc_contains_lean_ctx(&bash) {
159        parts.push(format!("{DIM}~/.bashrc{RST}"));
160        if !rc_has_pipe_guard(&bash) && is_active_shell("~/.bashrc") {
161            needs_update.push("~/.bashrc");
162        }
163    }
164
165    let fish = home.join(".config").join("fish").join("config.fish");
166    if rc_contains_lean_ctx(&fish) {
167        parts.push(format!("{DIM}~/.config/fish/config.fish{RST}"));
168        if !rc_has_pipe_guard(&fish) && is_active_shell("~/.config/fish/config.fish") {
169            needs_update.push("~/.config/fish/config.fish");
170        }
171    }
172
173    #[cfg(windows)]
174    {
175        let ps_profile = home
176            .join("Documents")
177            .join("PowerShell")
178            .join("Microsoft.PowerShell_profile.ps1");
179        let ps_profile_legacy = home
180            .join("Documents")
181            .join("WindowsPowerShell")
182            .join("Microsoft.PowerShell_profile.ps1");
183        if rc_contains_lean_ctx(&ps_profile) {
184            parts.push(format!("{DIM}PowerShell profile{RST}"));
185            if !rc_has_pipe_guard(&ps_profile) {
186                needs_update.push("PowerShell profile");
187            }
188        } else if rc_contains_lean_ctx(&ps_profile_legacy) {
189            parts.push(format!("{DIM}WindowsPowerShell profile{RST}"));
190            if !rc_has_pipe_guard(&ps_profile_legacy) {
191                needs_update.push("WindowsPowerShell profile");
192            }
193        }
194    }
195
196    if parts.is_empty() {
197        let hint = if cfg!(windows) {
198            "no \"lean-ctx\" in PowerShell profile, ~/.zshrc or ~/.bashrc"
199        } else {
200            "no \"lean-ctx\" in ~/.zshrc, ~/.bashrc, or ~/.config/fish/config.fish"
201        };
202        Outcome {
203            ok: false,
204            line: format!("{BOLD}Shell aliases{RST}  {RED}{hint}{RST}"),
205        }
206    } else if !needs_update.is_empty() {
207        Outcome {
208            ok: false,
209            line: format!(
210                "{BOLD}Shell aliases{RST}  {YELLOW}outdated hook in {} — run {BOLD}lean-ctx init --global{RST}{YELLOW} to fix (pipe guard missing){RST}",
211                needs_update.join(", ")
212            ),
213        }
214    } else {
215        Outcome {
216            ok: true,
217            line: format!(
218                "{BOLD}Shell aliases{RST}  {GREEN}lean-ctx referenced in {}{RST}",
219                parts.join(", ")
220            ),
221        }
222    }
223}
224
225struct McpLocation {
226    name: &'static str,
227    display: String,
228    path: PathBuf,
229}
230
231fn mcp_config_locations(home: &std::path::Path) -> Vec<McpLocation> {
232    let mut locations = vec![
233        McpLocation {
234            name: "Cursor",
235            display: "~/.cursor/mcp.json".into(),
236            path: home.join(".cursor").join("mcp.json"),
237        },
238        McpLocation {
239            name: "Claude Code",
240            display: format!(
241                "{}",
242                crate::core::editor_registry::claude_mcp_json_path(home).display()
243            ),
244            path: crate::core::editor_registry::claude_mcp_json_path(home),
245        },
246        McpLocation {
247            name: "Windsurf",
248            display: "~/.codeium/windsurf/mcp_config.json".into(),
249            path: home
250                .join(".codeium")
251                .join("windsurf")
252                .join("mcp_config.json"),
253        },
254        McpLocation {
255            name: "Codex",
256            display: "~/.codex/config.toml".into(),
257            path: home.join(".codex").join("config.toml"),
258        },
259        McpLocation {
260            name: "Gemini CLI",
261            display: "~/.gemini/settings/mcp.json".into(),
262            path: home.join(".gemini").join("settings").join("mcp.json"),
263        },
264        McpLocation {
265            name: "Antigravity",
266            display: "~/.gemini/antigravity/mcp_config.json".into(),
267            path: home
268                .join(".gemini")
269                .join("antigravity")
270                .join("mcp_config.json"),
271        },
272    ];
273
274    #[cfg(unix)]
275    {
276        let zed_cfg = home.join(".config").join("zed").join("settings.json");
277        locations.push(McpLocation {
278            name: "Zed",
279            display: "~/.config/zed/settings.json".into(),
280            path: zed_cfg,
281        });
282    }
283
284    locations.push(McpLocation {
285        name: "Qwen Code",
286        display: "~/.qwen/mcp.json".into(),
287        path: home.join(".qwen").join("mcp.json"),
288    });
289    locations.push(McpLocation {
290        name: "Trae",
291        display: "~/.trae/mcp.json".into(),
292        path: home.join(".trae").join("mcp.json"),
293    });
294    locations.push(McpLocation {
295        name: "Amazon Q",
296        display: "~/.aws/amazonq/mcp.json".into(),
297        path: home.join(".aws").join("amazonq").join("mcp.json"),
298    });
299    locations.push(McpLocation {
300        name: "JetBrains",
301        display: "~/.jb-mcp.json".into(),
302        path: home.join(".jb-mcp.json"),
303    });
304    locations.push(McpLocation {
305        name: "AWS Kiro",
306        display: "~/.kiro/settings/mcp.json".into(),
307        path: home.join(".kiro").join("settings").join("mcp.json"),
308    });
309    locations.push(McpLocation {
310        name: "Verdent",
311        display: "~/.verdent/mcp.json".into(),
312        path: home.join(".verdent").join("mcp.json"),
313    });
314    locations.push(McpLocation {
315        name: "Crush",
316        display: "~/.config/crush/crush.json".into(),
317        path: home.join(".config").join("crush").join("crush.json"),
318    });
319    locations.push(McpLocation {
320        name: "Pi",
321        display: "~/.pi/agent/mcp.json".into(),
322        path: home.join(".pi").join("agent").join("mcp.json"),
323    });
324    locations.push(McpLocation {
325        name: "Aider",
326        display: "~/.aider/mcp.json".into(),
327        path: home.join(".aider").join("mcp.json"),
328    });
329    locations.push(McpLocation {
330        name: "Amp",
331        display: "~/.config/amp/settings.json".into(),
332        path: home.join(".config").join("amp").join("settings.json"),
333    });
334
335    {
336        #[cfg(unix)]
337        let opencode_cfg = home.join(".config").join("opencode").join("opencode.json");
338        #[cfg(unix)]
339        let opencode_display = "~/.config/opencode/opencode.json";
340
341        #[cfg(windows)]
342        let opencode_cfg = if let Ok(appdata) = std::env::var("APPDATA") {
343            std::path::PathBuf::from(appdata)
344                .join("opencode")
345                .join("opencode.json")
346        } else {
347            home.join(".config").join("opencode").join("opencode.json")
348        };
349        #[cfg(windows)]
350        let opencode_display = "%APPDATA%/opencode/opencode.json";
351
352        locations.push(McpLocation {
353            name: "OpenCode",
354            display: opencode_display.into(),
355            path: opencode_cfg,
356        });
357    }
358
359    #[cfg(target_os = "macos")]
360    {
361        let vscode_mcp = home.join("Library/Application Support/Code/User/mcp.json");
362        locations.push(McpLocation {
363            name: "VS Code / Copilot",
364            display: "~/Library/Application Support/Code/User/mcp.json".into(),
365            path: vscode_mcp,
366        });
367    }
368    #[cfg(target_os = "linux")]
369    {
370        let vscode_mcp = home.join(".config/Code/User/mcp.json");
371        locations.push(McpLocation {
372            name: "VS Code / Copilot",
373            display: "~/.config/Code/User/mcp.json".into(),
374            path: vscode_mcp,
375        });
376    }
377    #[cfg(target_os = "windows")]
378    {
379        if let Ok(appdata) = std::env::var("APPDATA") {
380            let vscode_mcp = std::path::PathBuf::from(appdata).join("Code/User/mcp.json");
381            locations.push(McpLocation {
382                name: "VS Code / Copilot",
383                display: "%APPDATA%/Code/User/mcp.json".into(),
384                path: vscode_mcp,
385            });
386        }
387    }
388
389    locations.push(McpLocation {
390        name: "Hermes Agent",
391        display: "~/.hermes/config.yaml".into(),
392        path: home.join(".hermes").join("config.yaml"),
393    });
394
395    {
396        let cline_path = crate::core::editor_registry::cline_mcp_path();
397        if cline_path.to_str().is_some_and(|s| s != "/nonexistent") {
398            locations.push(McpLocation {
399                name: "Cline",
400                display: cline_path.display().to_string(),
401                path: cline_path,
402            });
403        }
404    }
405    {
406        let roo_path = crate::core::editor_registry::roo_mcp_path();
407        if roo_path.to_str().is_some_and(|s| s != "/nonexistent") {
408            locations.push(McpLocation {
409                name: "Roo Code",
410                display: roo_path.display().to_string(),
411                path: roo_path,
412            });
413        }
414    }
415
416    locations
417}
418
419fn mcp_config_outcome() -> Outcome {
420    let home = match dirs::home_dir() {
421        Some(h) => h,
422        None => {
423            return Outcome {
424                ok: false,
425                line: format!("{BOLD}MCP config{RST}  {RED}could not resolve home directory{RST}"),
426            };
427        }
428    };
429
430    let locations = mcp_config_locations(&home);
431    let mut found: Vec<String> = Vec::new();
432    let mut exists_no_ref: Vec<String> = Vec::new();
433
434    for loc in &locations {
435        if let Ok(content) = std::fs::read_to_string(&loc.path) {
436            if has_lean_ctx_mcp_entry(&content) {
437                found.push(format!("{} {DIM}({}){RST}", loc.name, loc.display));
438            } else {
439                exists_no_ref.push(loc.name.to_string());
440            }
441        }
442    }
443
444    found.sort();
445    found.dedup();
446    exists_no_ref.sort();
447    exists_no_ref.dedup();
448
449    if !found.is_empty() {
450        Outcome {
451            ok: true,
452            line: format!(
453                "{BOLD}MCP config{RST}  {GREEN}lean-ctx found in: {}{RST}",
454                found.join(", ")
455            ),
456        }
457    } else if !exists_no_ref.is_empty() {
458        let has_claude = exists_no_ref.iter().any(|n| n.starts_with("Claude Code"));
459        let cause = if has_claude {
460            format!("{DIM}(Claude Code may overwrite ~/.claude.json on startup — lean-ctx entry missing from mcpServers){RST}")
461        } else {
462            String::new()
463        };
464        let hint = if has_claude {
465            format!("{DIM}(run: lean-ctx doctor --fix OR lean-ctx init --agent claude){RST}")
466        } else {
467            format!("{DIM}(run: lean-ctx doctor --fix OR lean-ctx setup){RST}")
468        };
469        Outcome {
470            ok: false,
471            line: format!(
472                "{BOLD}MCP config{RST}  {YELLOW}config exists for {} but mcpServers does not contain lean-ctx{RST}  {cause} {hint}",
473                exists_no_ref.join(", "),
474            ),
475        }
476    } else {
477        Outcome {
478            ok: false,
479            line: format!(
480                "{BOLD}MCP config{RST}  {YELLOW}no MCP config found{RST}  {DIM}(run: lean-ctx setup){RST}"
481            ),
482        }
483    }
484}
485
486fn has_lean_ctx_mcp_entry(content: &str) -> bool {
487    if let Ok(json) = serde_json::from_str::<serde_json::Value>(content) {
488        if let Some(servers) = json.get("mcpServers").and_then(|v| v.as_object()) {
489            return servers.contains_key("lean-ctx");
490        }
491        if let Some(servers) = json
492            .get("mcp")
493            .and_then(|v| v.get("servers"))
494            .and_then(|v| v.as_object())
495        {
496            return servers.contains_key("lean-ctx");
497        }
498    }
499    content.contains("lean-ctx")
500}
501
502fn port_3333_outcome() -> Outcome {
503    match TcpListener::bind("127.0.0.1:3333") {
504        Ok(_listener) => Outcome {
505            ok: true,
506            line: format!("{BOLD}Dashboard port 3333{RST}  {GREEN}available on 127.0.0.1{RST}"),
507        },
508        Err(e) => Outcome {
509            ok: false,
510            line: format!("{BOLD}Dashboard port 3333{RST}  {RED}not available: {e}{RST}"),
511        },
512    }
513}
514
515fn pi_outcome() -> Option<Outcome> {
516    let pi_result = std::process::Command::new("pi").arg("--version").output();
517
518    match pi_result {
519        Ok(output) if output.status.success() => {
520            let version = String::from_utf8_lossy(&output.stdout).trim().to_string();
521            let has_plugin = std::process::Command::new("pi")
522                .args(["list"])
523                .output()
524                .map(|o| String::from_utf8_lossy(&o.stdout).contains("pi-lean-ctx"))
525                .unwrap_or(false);
526
527            let has_mcp = dirs::home_dir()
528                .map(|h| h.join(".pi/agent/mcp.json"))
529                .and_then(|p| std::fs::read_to_string(p).ok())
530                .map(|c| c.contains("lean-ctx"))
531                .unwrap_or(false);
532
533            if has_plugin && has_mcp {
534                Some(Outcome {
535                    ok: true,
536                    line: format!(
537                        "{BOLD}Pi Coding Agent{RST}  {GREEN}{version}, pi-lean-ctx + MCP configured{RST}"
538                    ),
539                })
540            } else if has_plugin {
541                Some(Outcome {
542                    ok: true,
543                    line: format!(
544                        "{BOLD}Pi Coding Agent{RST}  {GREEN}{version}, pi-lean-ctx installed{RST}  {DIM}(MCP not configured — embedded bridge active){RST}"
545                    ),
546                })
547            } else {
548                Some(Outcome {
549                    ok: false,
550                    line: format!(
551                        "{BOLD}Pi Coding Agent{RST}  {YELLOW}{version}, but pi-lean-ctx not installed{RST}  {DIM}(run: pi install npm:pi-lean-ctx){RST}"
552                    ),
553                })
554            }
555        }
556        _ => None,
557    }
558}
559
560fn session_state_outcome() -> Outcome {
561    use crate::core::session::SessionState;
562
563    match SessionState::load_latest() {
564        Some(session) => {
565            let root = session
566                .project_root
567                .as_deref()
568                .unwrap_or("(not set)");
569            let cwd = session
570                .shell_cwd
571                .as_deref()
572                .unwrap_or("(not tracked)");
573            Outcome {
574                ok: true,
575                line: format!(
576                    "{BOLD}Session state{RST}  {GREEN}active{RST}  {DIM}root: {root}, cwd: {cwd}, v{}{RST}",
577                    session.version
578                ),
579            }
580        }
581        None => Outcome {
582            ok: true,
583            line: format!(
584                "{BOLD}Session state{RST}  {YELLOW}no active session{RST}  {DIM}(will be created on first tool call){RST}"
585            ),
586        },
587    }
588}
589
590fn docker_env_outcomes() -> Vec<Outcome> {
591    if !crate::shell::is_container() {
592        return vec![];
593    }
594    let env_sh = dirs::home_dir()
595        .map(|h| {
596            h.join(".lean-ctx")
597                .join("env.sh")
598                .to_string_lossy()
599                .to_string()
600        })
601        .unwrap_or_else(|| "/root/.lean-ctx/env.sh".to_string());
602
603    let mut outcomes = vec![];
604
605    let shell_name = std::env::var("SHELL").unwrap_or_default();
606    let is_bash = shell_name.contains("bash") || shell_name.is_empty();
607
608    if is_bash {
609        let has_bash_env = std::env::var("BASH_ENV").is_ok();
610        outcomes.push(if has_bash_env {
611            Outcome {
612                ok: true,
613                line: format!(
614                    "{BOLD}BASH_ENV{RST}  {GREEN}set{RST}  {DIM}({}){RST}",
615                    std::env::var("BASH_ENV").unwrap_or_default()
616                ),
617            }
618        } else {
619            Outcome {
620                ok: false,
621                line: format!(
622                    "{BOLD}BASH_ENV{RST}  {RED}not set{RST}  {YELLOW}(add to Dockerfile: ENV BASH_ENV=\"{env_sh}\"){RST}"
623                ),
624            }
625        });
626    }
627
628    let has_claude_env = std::env::var("CLAUDE_ENV_FILE").is_ok();
629    outcomes.push(if has_claude_env {
630        Outcome {
631            ok: true,
632            line: format!(
633                "{BOLD}CLAUDE_ENV_FILE{RST}  {GREEN}set{RST}  {DIM}({}){RST}",
634                std::env::var("CLAUDE_ENV_FILE").unwrap_or_default()
635            ),
636        }
637    } else {
638        Outcome {
639            ok: false,
640            line: format!(
641                "{BOLD}CLAUDE_ENV_FILE{RST}  {RED}not set{RST}  {YELLOW}(for Claude Code: ENV CLAUDE_ENV_FILE=\"{env_sh}\"){RST}"
642            ),
643        }
644    });
645
646    outcomes
647}
648
649/// Run diagnostic checks and print colored results to stdout.
650pub fn run() {
651    let mut passed = 0u32;
652    let total = 8u32;
653
654    println!("{BOLD}{WHITE}lean-ctx doctor{RST}  {DIM}diagnostics{RST}\n");
655
656    // 1) Binary on PATH
657    let path_bin = resolve_lean_ctx_binary();
658    let also_in_path_dirs = path_in_path_env();
659    let bin_ok = path_bin.is_some() || also_in_path_dirs;
660    if bin_ok {
661        passed += 1;
662    }
663    let bin_line = if let Some(p) = path_bin {
664        format!("{BOLD}lean-ctx in PATH{RST}  {WHITE}{}{RST}", p.display())
665    } else if also_in_path_dirs {
666        format!(
667            "{BOLD}lean-ctx in PATH{RST}  {YELLOW}found via PATH walk (not resolved by `command -v`){RST}"
668        )
669    } else {
670        format!("{BOLD}lean-ctx in PATH{RST}  {RED}not found{RST}")
671    };
672    print_check(&Outcome {
673        ok: bin_ok,
674        line: bin_line,
675    });
676
677    // 2) Version from PATH binary
678    let ver = if bin_ok {
679        lean_ctx_version_from_path()
680    } else {
681        Outcome {
682            ok: false,
683            line: format!("{BOLD}lean-ctx version{RST}  {RED}skipped (binary not in PATH){RST}"),
684        }
685    };
686    if ver.ok {
687        passed += 1;
688    }
689    print_check(&ver);
690
691    // 3) ~/.lean-ctx directory
692    let lean_dir = dirs::home_dir().map(|h| h.join(".lean-ctx"));
693    let dir_outcome = match &lean_dir {
694        Some(p) if p.is_dir() => {
695            passed += 1;
696            Outcome {
697                ok: true,
698                line: format!(
699                    "{BOLD}~/.lean-ctx/{RST}  {GREEN}exists{RST}  {DIM}{}{RST}",
700                    p.display()
701                ),
702            }
703        }
704        Some(p) => Outcome {
705            ok: false,
706            line: format!(
707                "{BOLD}~/.lean-ctx/{RST}  {RED}missing or not a directory{RST}  {DIM}{}{RST}",
708                p.display()
709            ),
710        },
711        None => Outcome {
712            ok: false,
713            line: format!("{BOLD}~/.lean-ctx/{RST}  {RED}could not resolve home directory{RST}"),
714        },
715    };
716    print_check(&dir_outcome);
717
718    // 4) stats.json + size
719    let stats_path = lean_dir.as_ref().map(|d| d.join("stats.json"));
720    let stats_outcome = match stats_path.as_ref().and_then(|p| std::fs::metadata(p).ok()) {
721        Some(m) if m.is_file() => {
722            passed += 1;
723            let size = m.len();
724            Outcome {
725                ok: true,
726                line: format!(
727                    "{BOLD}stats.json{RST}  {GREEN}exists{RST}  {WHITE}{size} bytes{RST}  {DIM}{}{RST}",
728                    stats_path.as_ref().unwrap().display()
729                ),
730            }
731        }
732        Some(_m) => Outcome {
733            ok: false,
734            line: format!(
735                "{BOLD}stats.json{RST}  {RED}not a file{RST}  {DIM}{}{RST}",
736                stats_path.as_ref().unwrap().display()
737            ),
738        },
739        None => {
740            passed += 1;
741            Outcome {
742                ok: true,
743                line: match &stats_path {
744                    Some(p) => format!(
745                        "{BOLD}stats.json{RST}  {YELLOW}not yet created{RST}  {DIM}(will appear after first use) {}{RST}",
746                        p.display()
747                    ),
748                    None => format!("{BOLD}stats.json{RST}  {RED}could not resolve path{RST}"),
749                },
750            }
751        }
752    };
753    print_check(&stats_outcome);
754
755    // 5) config.toml (missing is OK)
756    let config_path = lean_dir.as_ref().map(|d| d.join("config.toml"));
757    let config_outcome = match &config_path {
758        Some(p) => match std::fs::metadata(p) {
759            Ok(m) if m.is_file() => {
760                passed += 1;
761                Outcome {
762                    ok: true,
763                    line: format!(
764                        "{BOLD}config.toml{RST}  {GREEN}exists{RST}  {DIM}{}{RST}",
765                        p.display()
766                    ),
767                }
768            }
769            Ok(_) => Outcome {
770                ok: false,
771                line: format!(
772                    "{BOLD}config.toml{RST}  {RED}exists but is not a regular file{RST}  {DIM}{}{RST}",
773                    p.display()
774                ),
775            },
776            Err(_) => {
777                passed += 1;
778                Outcome {
779                    ok: true,
780                    line: format!(
781                        "{BOLD}config.toml{RST}  {YELLOW}not found, using defaults{RST}  {DIM}(expected at {}){RST}",
782                        p.display()
783                    ),
784                }
785            }
786        },
787        None => Outcome {
788            ok: false,
789            line: format!("{BOLD}config.toml{RST}  {RED}could not resolve path{RST}"),
790        },
791    };
792    print_check(&config_outcome);
793
794    // 6) Shell aliases
795    let aliases = shell_aliases_outcome();
796    if aliases.ok {
797        passed += 1;
798    }
799    print_check(&aliases);
800
801    // 7) MCP
802    let mcp = mcp_config_outcome();
803    if mcp.ok {
804        passed += 1;
805    }
806    print_check(&mcp);
807
808    // 9) Port
809    let port = port_3333_outcome();
810    if port.ok {
811        passed += 1;
812    }
813    print_check(&port);
814
815    // 9) Session state (project_root + shell_cwd)
816    let session_outcome = session_state_outcome();
817    if session_outcome.ok {
818        passed += 1;
819    }
820    print_check(&session_outcome);
821
822    // 10) Docker env vars (optional, only in containers)
823    let docker_outcomes = docker_env_outcomes();
824    for docker_check in &docker_outcomes {
825        if docker_check.ok {
826            passed += 1;
827        }
828        print_check(docker_check);
829    }
830
831    // 11) Pi Coding Agent (optional)
832    let pi = pi_outcome();
833    if let Some(ref pi_check) = pi {
834        if pi_check.ok {
835            passed += 1;
836        }
837        print_check(pi_check);
838    }
839
840    // 12) Build integrity (canary / origin check)
841    let integrity = crate::core::integrity::check();
842    let integrity_ok = integrity.seed_ok && integrity.origin_ok;
843    if integrity_ok {
844        passed += 1;
845    }
846    let integrity_line = if integrity_ok {
847        format!(
848            "{BOLD}Build origin{RST}  {GREEN}official{RST}  {DIM}{}{RST}",
849            integrity.repo
850        )
851    } else {
852        format!(
853            "{BOLD}Build origin{RST}  {RED}MODIFIED REDISTRIBUTION{RST}  {YELLOW}pkg={}, repo={}{RST}",
854            integrity.pkg_name, integrity.repo
855        )
856    };
857    print_check(&Outcome {
858        ok: integrity_ok,
859        line: integrity_line,
860    });
861
862    // 13) Claude Code instruction truncation guard
863    let claude_truncation = claude_truncation_outcome();
864    if let Some(ref ct) = claude_truncation {
865        if ct.ok {
866            passed += 1;
867        }
868        print_check(ct);
869    }
870
871    let mut effective_total = total + 2; // session_state + integrity always shown
872    effective_total += docker_outcomes.len() as u32;
873    if pi.is_some() {
874        effective_total += 1;
875    }
876    if claude_truncation.is_some() {
877        effective_total += 1;
878    }
879    println!();
880    println!("  {BOLD}{WHITE}Summary:{RST}  {GREEN}{passed}{RST}{DIM}/{effective_total}{RST} checks passed");
881    println!("  {DIM}{}{RST}", crate::core::integrity::origin_line());
882}
883
884fn claude_binary_exists() -> bool {
885    #[cfg(unix)]
886    {
887        std::process::Command::new("which")
888            .arg("claude")
889            .output()
890            .map(|o| o.status.success())
891            .unwrap_or(false)
892    }
893    #[cfg(windows)]
894    {
895        std::process::Command::new("where")
896            .arg("claude")
897            .output()
898            .map(|o| o.status.success())
899            .unwrap_or(false)
900    }
901}
902
903fn claude_truncation_outcome() -> Option<Outcome> {
904    let home = dirs::home_dir()?;
905    let claude_detected = crate::core::editor_registry::claude_mcp_json_path(&home).exists()
906        || crate::core::editor_registry::claude_state_dir(&home).exists()
907        || claude_binary_exists();
908
909    if !claude_detected {
910        return None;
911    }
912
913    let rules_path = crate::core::editor_registry::claude_rules_dir(&home).join("lean-ctx.md");
914    let skill_path = home.join(".claude/skills/lean-ctx/SKILL.md");
915
916    let has_rules = rules_path.exists();
917    let has_skill = skill_path.exists();
918
919    if has_rules && has_skill {
920        Some(Outcome {
921            ok: true,
922            line: format!(
923                "{BOLD}Claude Code instructions{RST}  {GREEN}rules + skill installed{RST}  {DIM}(MCP instructions capped at 2048 chars — full content via rules file){RST}"
924            ),
925        })
926    } else if has_rules {
927        Some(Outcome {
928            ok: true,
929            line: format!(
930                "{BOLD}Claude Code instructions{RST}  {GREEN}rules file installed{RST}  {DIM}(MCP instructions capped at 2048 chars — full content via rules file){RST}"
931            ),
932        })
933    } else {
934        Some(Outcome {
935            ok: false,
936            line: format!(
937                "{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}"
938            ),
939        })
940    }
941}
942
943pub fn run_compact() {
944    let (passed, total) = compact_score();
945    print_compact_status(passed, total);
946}
947
948pub fn run_cli(args: &[String]) -> i32 {
949    let fix = args.iter().any(|a| a == "--fix");
950    let json = args.iter().any(|a| a == "--json");
951    let help = args.iter().any(|a| a == "--help" || a == "-h");
952
953    if help {
954        println!("Usage:");
955        println!("  lean-ctx doctor");
956        println!("  lean-ctx doctor --fix [--json]");
957        return 0;
958    }
959
960    if !fix {
961        run();
962        return 0;
963    }
964
965    match run_fix(DoctorFixOptions { json }) {
966        Ok(code) => code,
967        Err(e) => {
968            eprintln!("{RED}doctor --fix failed:{RST} {e}");
969            2
970        }
971    }
972}
973
974struct DoctorFixOptions {
975    json: bool,
976}
977
978fn run_fix(opts: DoctorFixOptions) -> Result<i32, String> {
979    use crate::core::setup_report::{
980        doctor_report_path, PlatformInfo, SetupItem, SetupReport, SetupStepReport,
981    };
982
983    let _quiet_guard = opts
984        .json
985        .then(|| crate::setup::EnvVarGuard::set("LEAN_CTX_QUIET", "1"));
986    let started_at = Utc::now();
987    let home = dirs::home_dir().ok_or_else(|| "Cannot determine home directory".to_string())?;
988
989    let mut steps: Vec<SetupStepReport> = Vec::new();
990
991    // Step: shell hook repair
992    let mut shell_step = SetupStepReport {
993        name: "shell_hook".to_string(),
994        ok: true,
995        items: Vec::new(),
996        warnings: Vec::new(),
997        errors: Vec::new(),
998    };
999    let before = shell_aliases_outcome();
1000    if before.ok {
1001        shell_step.items.push(SetupItem {
1002            name: "init --global".to_string(),
1003            status: "already".to_string(),
1004            path: None,
1005            note: None,
1006        });
1007    } else {
1008        if opts.json {
1009            crate::cli::cmd_init_quiet(&["--global".to_string()]);
1010        } else {
1011            crate::cli::cmd_init(&["--global".to_string()]);
1012        }
1013        let after = shell_aliases_outcome();
1014        shell_step.ok = after.ok;
1015        shell_step.items.push(SetupItem {
1016            name: "init --global".to_string(),
1017            status: if after.ok {
1018                "fixed".to_string()
1019            } else {
1020                "failed".to_string()
1021            },
1022            path: None,
1023            note: if after.ok {
1024                None
1025            } else {
1026                Some("shell hook still not detected by doctor checks".to_string())
1027            },
1028        });
1029        if !after.ok {
1030            shell_step
1031                .warnings
1032                .push("shell hook not detected after init --global".to_string());
1033        }
1034    }
1035    steps.push(shell_step);
1036
1037    // Step: MCP config repair (detected tools)
1038    let mut mcp_step = SetupStepReport {
1039        name: "mcp_config".to_string(),
1040        ok: true,
1041        items: Vec::new(),
1042        warnings: Vec::new(),
1043        errors: Vec::new(),
1044    };
1045    let binary = crate::core::portable_binary::resolve_portable_binary();
1046    let targets = crate::core::editor_registry::build_targets(&home);
1047    for t in &targets {
1048        if !t.detect_path.exists() {
1049            continue;
1050        }
1051        let short = t.config_path.to_string_lossy().to_string();
1052        let res = crate::core::editor_registry::write_config_with_options(
1053            t,
1054            &binary,
1055            crate::core::editor_registry::WriteOptions {
1056                overwrite_invalid: true,
1057            },
1058        );
1059        match res {
1060            Ok(r) => {
1061                let status = match r.action {
1062                    crate::core::editor_registry::WriteAction::Created => "created",
1063                    crate::core::editor_registry::WriteAction::Updated => "updated",
1064                    crate::core::editor_registry::WriteAction::Already => "already",
1065                };
1066                mcp_step.items.push(SetupItem {
1067                    name: t.name.to_string(),
1068                    status: status.to_string(),
1069                    path: Some(short),
1070                    note: r.note,
1071                });
1072            }
1073            Err(e) => {
1074                mcp_step.ok = false;
1075                mcp_step.items.push(SetupItem {
1076                    name: t.name.to_string(),
1077                    status: "error".to_string(),
1078                    path: Some(short),
1079                    note: Some(e.clone()),
1080                });
1081                mcp_step.errors.push(format!("{}: {e}", t.name));
1082            }
1083        }
1084    }
1085    if mcp_step.items.is_empty() {
1086        mcp_step
1087            .warnings
1088            .push("no supported AI tools detected; skipped MCP config repair".to_string());
1089    }
1090    steps.push(mcp_step);
1091
1092    // Step: agent rules injection
1093    let mut rules_step = SetupStepReport {
1094        name: "agent_rules".to_string(),
1095        ok: true,
1096        items: Vec::new(),
1097        warnings: Vec::new(),
1098        errors: Vec::new(),
1099    };
1100    let inj = crate::rules_inject::inject_all_rules(&home);
1101    if !inj.injected.is_empty() {
1102        rules_step.items.push(SetupItem {
1103            name: "injected".to_string(),
1104            status: inj.injected.len().to_string(),
1105            path: None,
1106            note: Some(inj.injected.join(", ")),
1107        });
1108    }
1109    if !inj.updated.is_empty() {
1110        rules_step.items.push(SetupItem {
1111            name: "updated".to_string(),
1112            status: inj.updated.len().to_string(),
1113            path: None,
1114            note: Some(inj.updated.join(", ")),
1115        });
1116    }
1117    if !inj.already.is_empty() {
1118        rules_step.items.push(SetupItem {
1119            name: "already".to_string(),
1120            status: inj.already.len().to_string(),
1121            path: None,
1122            note: Some(inj.already.join(", ")),
1123        });
1124    }
1125    if !inj.errors.is_empty() {
1126        rules_step.ok = false;
1127        rules_step.errors.extend(inj.errors.clone());
1128    }
1129    steps.push(rules_step);
1130
1131    // Step: verify (compact)
1132    let mut verify_step = SetupStepReport {
1133        name: "verify".to_string(),
1134        ok: true,
1135        items: Vec::new(),
1136        warnings: Vec::new(),
1137        errors: Vec::new(),
1138    };
1139    let (passed, total) = compact_score();
1140    verify_step.items.push(SetupItem {
1141        name: "doctor_compact".to_string(),
1142        status: format!("{passed}/{total}"),
1143        path: None,
1144        note: None,
1145    });
1146    if passed != total {
1147        verify_step.warnings.push(format!(
1148            "doctor compact not fully passing: {passed}/{total}"
1149        ));
1150    }
1151    steps.push(verify_step);
1152
1153    let finished_at = Utc::now();
1154    let success = steps.iter().all(|s| s.ok);
1155
1156    let report = SetupReport {
1157        schema_version: 1,
1158        started_at,
1159        finished_at,
1160        success,
1161        platform: PlatformInfo {
1162            os: std::env::consts::OS.to_string(),
1163            arch: std::env::consts::ARCH.to_string(),
1164        },
1165        steps,
1166        warnings: Vec::new(),
1167        errors: Vec::new(),
1168    };
1169
1170    let path = doctor_report_path()?;
1171    let json_text = serde_json::to_string_pretty(&report).map_err(|e| e.to_string())?;
1172    crate::config_io::write_atomic_with_backup(&path, &json_text)?;
1173
1174    if opts.json {
1175        println!("{json_text}");
1176    } else {
1177        let (passed, total) = compact_score();
1178        print_compact_status(passed, total);
1179        println!("  {DIM}report saved:{RST} {}", path.display());
1180    }
1181
1182    Ok(if report.success { 0 } else { 1 })
1183}
1184
1185pub fn compact_score() -> (u32, u32) {
1186    let mut passed = 0u32;
1187    let total = 5u32;
1188
1189    if resolve_lean_ctx_binary().is_some() || path_in_path_env() {
1190        passed += 1;
1191    }
1192    let lean_dir = dirs::home_dir().map(|h| h.join(".lean-ctx"));
1193    if lean_dir.as_ref().is_some_and(|p| p.is_dir()) {
1194        passed += 1;
1195    }
1196    if lean_dir
1197        .as_ref()
1198        .map(|d| d.join("stats.json"))
1199        .and_then(|p| std::fs::metadata(p).ok())
1200        .is_some_and(|m| m.is_file())
1201    {
1202        passed += 1;
1203    }
1204    if shell_aliases_outcome().ok {
1205        passed += 1;
1206    }
1207    if mcp_config_outcome().ok {
1208        passed += 1;
1209    }
1210
1211    (passed, total)
1212}
1213
1214fn print_compact_status(passed: u32, total: u32) {
1215    let status = if passed == total {
1216        format!("{GREEN}✓ All {total} checks passed{RST}")
1217    } else {
1218        format!("{YELLOW}{passed}/{total} passed{RST} — run {BOLD}lean-ctx doctor{RST} for details")
1219    };
1220    println!("  {status}");
1221}