Skip to main content

lean_ctx/doctor/
mod.rs

1//! Environment diagnostics for lean-ctx installation and integration.
2
3mod checks;
4mod common;
5mod deprecations;
6mod fix;
7mod integrations;
8mod lint_context;
9mod migrate;
10mod overhead;
11mod report;
12mod workspace_scope;
13
14#[allow(clippy::wildcard_imports)]
15use checks::*;
16#[allow(clippy::wildcard_imports)]
17use common::*;
18
19pub use report::{HealthCheck, HealthLevel, HealthReport, health_report};
20
21/// Run `doctor --fix` and return the structured `SetupReport` without printing
22/// anything — the in-process entry point for the dashboard fix route (#466).
23///
24/// # Errors
25/// Propagates any repair-step failure (e.g. an unwritable data directory).
26pub fn run_fix_report() -> Result<crate::core::setup_report::SetupReport, String> {
27    fix::fix_report()
28}
29
30pub(super) const GREEN: &str = "\x1b[32m";
31
32pub(super) const RED: &str = "\x1b[31m";
33
34pub(super) const BOLD: &str = "\x1b[1m";
35
36pub(super) const RST: &str = "\x1b[0m";
37
38pub(super) const DIM: &str = "\x1b[2m";
39
40pub(super) const WHITE: &str = "\x1b[97m";
41
42pub(super) const YELLOW: &str = "\x1b[33m";
43
44pub(super) struct Outcome {
45    pub ok: bool,
46    pub line: String,
47}
48
49/// Accumulates doctor checks so the rendered ✓/✗ list and the summary tally can
50/// never diverge (#433): every scored check is counted exactly once via
51/// [`Scoreboard::check`]; only explicitly-optional advisories (LSP, "not
52/// configured" notes) use [`Scoreboard::info`], which renders without counting.
53/// The old hand-maintained `passed`/`effective_total` pair drifted whenever a
54/// check was added without bumping the total — routing every render through the
55/// board makes that class of bug structurally impossible.
56#[derive(Default)]
57struct Scoreboard {
58    passed: u32,
59    total: u32,
60}
61
62impl Scoreboard {
63    /// A scored health check: render it and count it (pass iff `ok`).
64    fn check(&mut self, outcome: &Outcome) {
65        self.total += 1;
66        if outcome.ok {
67            self.passed += 1;
68        }
69        print_check(outcome);
70    }
71
72    /// An optional/advisory line: render it but never count it toward the score
73    /// (LSP servers, "no providers configured", MCP bridges, plan-mode presence).
74    ///
75    /// Deliberately a method (not a free function) so every rendered line flows
76    /// through the board and each call site has to choose `check` vs `info` — the
77    /// `&self` is unused by design, which is the whole point.
78    #[allow(clippy::unused_self)]
79    fn info(&self, outcome: &Outcome) {
80        print_check(outcome);
81    }
82}
83
84/// Run diagnostic checks and print colored results to stdout.
85/// Renders the full diagnostics board and returns how many checks need
86/// attention, so `lean-ctx doctor` can exit non-zero when something is wrong
87/// (a health gate must fail loudly, not silently exit 0).
88pub fn run() -> u32 {
89    let mut board = Scoreboard::default();
90
91    println!("{BOLD}{WHITE}lean-ctx doctor{RST}  {DIM}diagnostics{RST}\n");
92
93    // 1) Binary on PATH
94    let path_bin = resolve_lean_ctx_binary();
95    let also_in_path_dirs = path_in_path_env();
96    let bin_ok = path_bin.is_some() || also_in_path_dirs;
97    let bin_line = if let Some(p) = path_bin {
98        format!("{BOLD}lean-ctx in PATH{RST}  {WHITE}{}{RST}", p.display())
99    } else if also_in_path_dirs {
100        format!(
101            "{BOLD}lean-ctx in PATH{RST}  {YELLOW}found via PATH walk (not resolved by `command -v`){RST}"
102        )
103    } else {
104        format!("{BOLD}lean-ctx in PATH{RST}  {RED}not found{RST}")
105    };
106    board.check(&Outcome {
107        ok: bin_ok,
108        line: bin_line,
109    });
110
111    // 2) Version from PATH binary
112    let ver = if bin_ok {
113        lean_ctx_version_from_path()
114    } else {
115        Outcome {
116            ok: false,
117            line: format!("{BOLD}lean-ctx version{RST}  {RED}skipped (binary not in PATH){RST}"),
118        }
119    };
120    board.check(&ver);
121
122    // 3) data directory (respects LEAN_CTX_DATA_DIR)
123    let lean_dir = crate::core::data_dir::lean_ctx_data_dir().ok();
124    let dir_outcome = match &lean_dir {
125        Some(p) if p.is_dir() => Outcome {
126            ok: true,
127            line: format!(
128                "{BOLD}data dir{RST}  {GREEN}exists{RST}  {DIM}{}{RST}",
129                p.display()
130            ),
131        },
132        Some(p) => Outcome {
133            ok: false,
134            line: format!(
135                "{BOLD}data dir{RST}  {RED}missing or not a directory{RST}  {DIM}{}{RST}",
136                p.display()
137            ),
138        },
139        None => Outcome {
140            ok: false,
141            line: format!("{BOLD}data dir{RST}  {RED}could not resolve data directory{RST}"),
142        },
143    };
144    board.check(&dir_outcome);
145
146    // 4) stats.json + size
147    let stats_path = lean_dir.as_ref().map(|d| d.join("stats.json"));
148    let stats_outcome = match stats_path.as_ref().and_then(|p| std::fs::metadata(p).ok()) {
149        Some(m) if m.is_file() => {
150            let size = m.len();
151            let path_display = if let Some(p) = stats_path.as_ref() {
152                p.display().to_string()
153            } else {
154                String::new()
155            };
156            Outcome {
157                ok: true,
158                line: format!(
159                    "{BOLD}stats.json{RST}  {GREEN}exists{RST}  {WHITE}{size} bytes{RST}  {DIM}{path_display}{RST}",
160                ),
161            }
162        }
163        Some(_m) => {
164            let path_display = if let Some(p) = stats_path.as_ref() {
165                p.display().to_string()
166            } else {
167                String::new()
168            };
169            Outcome {
170                ok: false,
171                line: format!(
172                    "{BOLD}stats.json{RST}  {RED}not a file{RST}  {DIM}{path_display}{RST}",
173                ),
174            }
175        }
176        None => Outcome {
177            ok: true,
178            line: match &stats_path {
179                Some(p) => format!(
180                    "{BOLD}stats.json{RST}  {YELLOW}not yet created{RST}  {DIM}(will appear after first use) {}{RST}",
181                    p.display()
182                ),
183                None => format!("{BOLD}stats.json{RST}  {RED}could not resolve path{RST}"),
184            },
185        },
186    };
187    board.check(&stats_outcome);
188
189    let split_dirs = crate::core::data_dir::all_data_dirs_with_stats();
190    if split_dirs.len() >= 2 {
191        let dirs_str = split_dirs
192            .iter()
193            .map(|d| d.display().to_string())
194            .collect::<Vec<_>>()
195            .join(", ");
196        board.check(&Outcome {
197            ok: false,
198            line: format!(
199                "{BOLD}data dir split{RST}  {RED}stats.json found in {count} locations{RST}: {dirs_str}  {DIM}(run: lean-ctx doctor --fix to merge){RST}",
200                count = split_dirs.len(),
201            ),
202        });
203    }
204
205    // XDG layout (GH #408): a legacy/mixed single-dir install mixes config with
206    // data/state/cache, which blocks a read-only config sandbox. Scored as a
207    // failure while present (#433) — `doctor --fix` splits it into the four typed
208    // XDG dirs, after which this check disappears.
209    if let Some((src, n)) = crate::core::xdg_migrate::pending() {
210        board.check(&Outcome {
211            ok: false,
212            line: format!(
213                "{BOLD}XDG layout{RST}  {YELLOW}{n} item(s) in single dir{RST}  {DIM}{}{RST}  {DIM}(run: lean-ctx doctor --fix to split into config/data/state/cache){RST}",
214                src.display()
215            ),
216        });
217    }
218
219    // #594: a `config.toml` stranded in the data dir means the MCP server (an
220    // older `LEAN_CTX_DATA_DIR` env collapsed its layout) and the CLI were
221    // reading *different* config. Flag it; `lean-ctx setup`/`update` and
222    // `doctor --fix` relocate it to the config dir so both agree again.
223    if let Some(stray) = crate::core::config_heal::pending() {
224        board.check(&Outcome {
225            ok: false,
226            line: format!(
227                "{BOLD}config location{RST}  {YELLOW}stray config.toml in the data dir{RST}  {DIM}{}{RST}  {DIM}(run: lean-ctx doctor --fix to unify CLI + MCP){RST}",
228                stray.display()
229            ),
230        });
231    }
232
233    // Layout commitment (GL #623): a pinned XDG install can no longer be
234    // hijacked by a stray ~/.lean-ctx. Surface the mode and flag a residual dir
235    // (heal reclaims it on the next start / `doctor --fix`).
236    {
237        let pinned = crate::core::layout_pin::is_xdg_pinned();
238        let residual = crate::core::xdg_migrate::residual_legacy_present();
239        let line = if pinned && residual {
240            format!(
241                "{BOLD}layout{RST}  {GREEN}xdg-pinned{RST}  {YELLOW}residual ~/.lean-ctx present{RST}  {DIM}(auto-reclaimed on next start){RST}"
242            )
243        } else if pinned {
244            format!(
245                "{BOLD}layout{RST}  {GREEN}xdg-pinned{RST}  {DIM}(~/.lean-ctx can no longer hijack this install){RST}"
246            )
247        } else {
248            format!(
249                "{BOLD}layout{RST}  {WHITE}single-dir / legacy{RST}  {DIM}(run: lean-ctx doctor --fix to commit to XDG){RST}"
250            )
251        };
252        board.check(&Outcome { ok: true, line });
253    }
254
255    // 5) config.toml (missing is OK). It lives in the CONFIG dir
256    // ($XDG_CONFIG_HOME/lean-ctx after a split), not the data dir — resolve it
257    // through the same path as the loader so the report matches reality
258    // post-migration instead of pointing at the old location (#435).
259    let config_path = crate::core::config::Config::path();
260    let config_outcome = match &config_path {
261        Some(p) => match std::fs::metadata(p) {
262            Ok(m) if m.is_file() => Outcome {
263                ok: true,
264                line: format!(
265                    "{BOLD}config.toml{RST}  {GREEN}exists{RST}  {DIM}{}{RST}",
266                    p.display()
267                ),
268            },
269            Ok(_) => Outcome {
270                ok: false,
271                line: format!(
272                    "{BOLD}config.toml{RST}  {RED}exists but is not a regular file{RST}  {DIM}{}{RST}",
273                    p.display()
274                ),
275            },
276            Err(_) => Outcome {
277                ok: true,
278                line: format!(
279                    "{BOLD}config.toml{RST}  {YELLOW}not found, using defaults{RST}  {DIM}(expected at {}){RST}",
280                    p.display()
281                ),
282            },
283        },
284        None => Outcome {
285            ok: false,
286            line: format!("{BOLD}config.toml{RST}  {RED}could not resolve path{RST}"),
287        },
288    };
289    board.check(&config_outcome);
290
291    // 5a2) #594: CLI<->MCP config parity — warn if any editor MCP entry still
292    // pins a stale LEAN_CTX_DATA_DIR (which would make that editor's MCP server
293    // read a different config.toml than this CLI), and print the resolved path.
294    board.check(&config_parity_outcome());
295
296    // 5b) Shell allowlist (effective runtime view + silent-parse-error trap, #341)
297    let allowlist_outcome = shell_allowlist_outcome();
298    board.check(&allowlist_outcome);
299
300    // 5b2) Path jail (effective state + dead allow_paths entries, GH #392)
301    let path_jail = path_jail_outcome();
302    board.check(&path_jail);
303
304    // 5b3) Workspace trust for project-local .lean-ctx.toml (security audit #4)
305    let workspace_trust = workspace_trust_outcome();
306    board.check(&workspace_trust);
307
308    // 5b3b) Secret/.env redaction — the exfiltration-defense plane, independent
309    // of the jail + shell gating above (#507).
310    let secret_detection = secret_detection_outcome();
311    board.check(&secret_detection);
312
313    // 5b4) Cognition v2 activation (science subsystems wired + active)
314    let cognition = cognition_activity_outcome();
315    board.check(&cognition);
316
317    // 5c) Compact-format passthrough (preserve already-compact TOON output, #342)
318    let passthrough_outcome = compact_format_passthrough_outcome();
319    board.check(&passthrough_outcome);
320
321    // 5d) IDE permission inheritance (mirror host IDE bash/rm rules onto ctx_*)
322    let perm_inherit_outcome = permission_inheritance_outcome();
323    board.check(&perm_inherit_outcome);
324
325    // 6) Proxy upstreams
326    let proxy_outcome = proxy_upstream_outcome();
327    board.check(&proxy_outcome);
328
329    // 7) Shell aliases
330    let aliases = shell_aliases_outcome();
331    board.check(&aliases);
332
333    // 7) MCP
334    let mcp = mcp_config_outcome();
335    board.check(&mcp);
336
337    // 8) Workspace-scope MCP (optional; only when a project-local config exists)
338    let workspace_scope = workspace_scope::workspace_scope_outcome(mcp.ok);
339    if let Some(ref ws) = workspace_scope {
340        board.check(ws);
341    }
342
343    // 9) SKILL.md
344    let skill = skill_files_outcome();
345    board.check(&skill);
346
347    // 10) Port
348    let port = port_3333_outcome();
349    board.check(&port);
350
351    // Daemon status
352    #[cfg(unix)]
353    let daemon_outcome = {
354        let autostart = crate::daemon_autostart::is_installed();
355        // GH #394: surface the exact service file so users can audit/edit it
356        // and know the unit name for systemctl/launchctl without searching.
357        let autostart_tag = if autostart {
358            match crate::daemon_autostart::service_file_path() {
359                Some(p) => format!("  {DIM}[autostart: on — {}]{RST}", p.display()),
360                None => format!("  {DIM}[autostart: on]{RST}"),
361            }
362        } else {
363            String::new()
364        };
365        if crate::daemon::is_daemon_running() {
366            let pid_path = crate::daemon::daemon_pid_path();
367            let pid_str = std::fs::read_to_string(&pid_path).unwrap_or_default();
368            Outcome {
369                ok: true,
370                line: format!(
371                    "{BOLD}Daemon{RST}  {GREEN}running (PID {}){RST}{autostart_tag}",
372                    pid_str.trim()
373                ),
374            }
375        } else {
376            let hint = if autostart {
377                format!("{DIM}(autostart enabled, will restart){RST}")
378            } else {
379                format!("{DIM}(run: lean-ctx daemon start  or: lean-ctx daemon enable){RST}")
380            };
381            Outcome {
382                ok: true,
383                line: format!("{BOLD}Daemon{RST}  {YELLOW}not running{RST}  {hint}"),
384            }
385        }
386    };
387    #[cfg(not(unix))]
388    let daemon_outcome = Outcome {
389        ok: true,
390        line: format!("{BOLD}Daemon{RST}  {DIM}not supported on this platform{RST}"),
391    };
392    board.check(&daemon_outcome);
393
394    // Daemon diagnostics: systemctl is-active, linger, crash-loop log
395    #[cfg(target_os = "linux")]
396    {
397        if let Ok(o) = std::process::Command::new("systemctl")
398            .args(["--user", "is-active", "lean-ctx-daemon.service"])
399            .output()
400        {
401            let state = String::from_utf8_lossy(&o.stdout).trim().to_string();
402            if state != "active" {
403                println!(
404                    "  {DIM}  systemd unit state: {YELLOW}{state}{RST}{DIM} (expected: active){RST}"
405                );
406            }
407        }
408        let username = std::env::var("USER")
409            .or_else(|_| std::env::var("LOGNAME"))
410            .unwrap_or_else(|_| "$(whoami)".to_string());
411        if let Ok(o) = std::process::Command::new("loginctl")
412            .args(["show-user", &username, "-p", "Linger", "--value"])
413            .output()
414        {
415            let val = String::from_utf8_lossy(&o.stdout).trim().to_string();
416            if val != "yes" {
417                println!(
418                    "  {YELLOW}⚠{RST}  Linger not enabled — daemon won't start at boot without login"
419                );
420                println!("     {DIM}Fix: loginctl enable-linger {username}{RST}");
421            }
422        }
423    }
424    if let Some(log_path) = crate::core::startup_guard::crash_loop_log_path(
425        crate::core::startup_guard::MCP_PROCESS_NAME,
426    ) && log_path.exists()
427        && let Ok(contents) = std::fs::read_to_string(&log_path)
428    {
429        let lines: Vec<&str> = contents.lines().collect();
430        if lines.len() >= 5 {
431            println!(
432                "  {YELLOW}⚠{RST}  Crash-loop log: {} recent restarts  {DIM}({}){RST}",
433                lines.len(),
434                display_user_path(&log_path)
435            );
436        }
437    }
438
439    // Providers (advisory — presence/health varies per environment, not scored)
440    let provider_outcome = provider_outcome();
441    board.info(&provider_outcome);
442
443    // MCP Bridges (advisory)
444    let bridge_outcomes = mcp_bridge_outcomes();
445    for bridge_check in &bridge_outcomes {
446        board.info(bridge_check);
447    }
448
449    // Plan mode (advisory)
450    let plan_outcomes = plan_mode_outcomes();
451    for plan_check in &plan_outcomes {
452        board.info(plan_check);
453    }
454
455    // 9) Session state (project_root + shell_cwd)
456    let session_outcome = session_state_outcome();
457    board.check(&session_outcome);
458
459    // 10) Docker env vars (optional, only in containers)
460    let docker_outcomes = docker_env_outcomes();
461    for docker_check in &docker_outcomes {
462        board.check(docker_check);
463    }
464
465    // 11) Pi Coding Agent (optional)
466    let pi = pi_outcome();
467    if let Some(ref pi_check) = pi {
468        board.check(pi_check);
469    }
470
471    // 12) Build integrity (canary / origin check)
472    let integrity = crate::core::integrity::check();
473    let integrity_ok = integrity.seed_ok && integrity.origin_ok;
474    let integrity_line = if integrity_ok {
475        format!(
476            "{BOLD}Build origin{RST}  {GREEN}official{RST}  {DIM}{}{RST}",
477            integrity.repo
478        )
479    } else {
480        format!(
481            "{BOLD}Build origin{RST}  {RED}MODIFIED REDISTRIBUTION{RST}  {YELLOW}pkg={}, repo={}{RST}",
482            integrity.pkg_name, integrity.repo
483        )
484    };
485    board.check(&Outcome {
486        ok: integrity_ok,
487        line: integrity_line,
488    });
489
490    // 13) Cache safety
491    let cache_safety = cache_safety_outcome();
492    board.check(&cache_safety);
493
494    // 14) Claude Code instruction truncation guard
495    let claude_truncation = claude_truncation_outcome();
496    if let Some(ref ct) = claude_truncation {
497        board.check(ct);
498    }
499
500    // 14a) CodeBuddy instruction truncation guard
501    let codebuddy_truncation = codebuddy_truncation_outcome();
502    if let Some(ref cbt) = codebuddy_truncation {
503        board.check(cbt);
504    }
505
506    // 15) BM25 cache health
507    let bm25_health = bm25_cache_health_outcome();
508    board.check(&bm25_health);
509
510    // 15a) Semantic index runtime status (state/timing/persistence) for the
511    // active project — surfaces a stuck "warming" index (issue #249).
512    let semantic_index = semantic_index_outcome();
513    if let Some(ref check) = semantic_index {
514        board.check(check);
515    }
516
517    // 15b) Archive FTS footprint
518    let archive_footprint = archive_footprint_outcome();
519    board.check(&archive_footprint);
520
521    // 16) Memory profile
522    let mem_profile = memory_profile_outcome();
523    board.check(&mem_profile);
524
525    // 17) Memory cleanup
526    let mem_cleanup = memory_cleanup_outcome();
527    board.check(&mem_cleanup);
528
529    // 18) RAM Guardian
530    let ram_outcome = ram_guardian_outcome();
531    board.check(&ram_outcome);
532
533    // 19) Capacity warnings (memory stores near limits)
534    let cap_warnings = capacity_warnings();
535    for cw in &cap_warnings {
536        board.check(cw);
537    }
538
539    // 19b) Orphaned knowledge stores (deleted projects — reclaimable bloat, #615)
540    let orphan_outcome = orphaned_knowledge_outcome();
541    board.check(&orphan_outcome);
542
543    // 20) Proxy health
544    let proxy_health = proxy_health_outcome();
545    board.check(&proxy_health);
546
547    // 20a) Proxy upstream drift (#449): running proxy serves a different upstream
548    // than config.toml resolves to (env override masking config). Only surfaces
549    // when the proxy is up and actually drifting.
550    let upstream_drift = proxy_upstream_drift_outcome();
551    if let Some(ref check) = upstream_drift {
552        board.check(check);
553    }
554
555    // 20) Stale proxy env (ANTHROPIC_BASE_URL pointing to local proxy while proxy is not enabled)
556    let stale_env = stale_proxy_env_outcome();
557    if let Some(ref check) = stale_env {
558        board.check(check);
559    }
560
561    // 21) Claude Pro/Max subscription routed through the proxy without an API key
562    let subscription_conflict = proxy_subscription_conflict_outcome();
563    if let Some(ref check) = subscription_conflict {
564        board.check(check);
565    }
566
567    // 22) Deprecation register (CONTRACTS.md policy, GL #394): warn about
568    // every surface this build deprecates, with replacement and removal floor.
569    let deprecation_check = deprecations::deprecations_outcome();
570    board.check(&deprecation_check);
571
572    // MCP server CWD warning (informational, only fires when running as MCP)
573    let mcp_cwd = mcp_server_cwd_outcome();
574    board.check(&mcp_cwd);
575
576    // LSP servers (optional, informational)
577    println!("\n  {BOLD}{WHITE}LSP (optional — for ctx_refactor):{RST}");
578    let lsp_outcomes = lsp_server_outcomes();
579    for lsp_check in &lsp_outcomes {
580        board.info(lsp_check);
581    }
582
583    // Shadow mode status
584    let cfg = crate::core::config::Config::load();
585    let shadow_line = if cfg.shadow_mode {
586        format!(
587            "{BOLD}Shadow mode{RST}  {GREEN}active{RST}  {DIM}(native tools denied → ctx_* mandatory){RST}"
588        )
589    } else {
590        format!(
591            "{BOLD}Shadow mode{RST}  {DIM}disabled{RST}  {DIM}(enable: lean-ctx config set shadow_mode true){RST}"
592        )
593    };
594    println!("  {shadow_line}");
595
596    // Tool-schema footprint (informational, not scored). With no profile pinned
597    // the server runs in lean mode — only the lazy core is advertised and every
598    // tool stays reachable via ctx_call — so report that, not the internal
599    // `power` call-gate fallback that `from_config` returns for an empty config
600    // (otherwise `doctor` claimed "power" right after the wizard chose lean, #415).
601    let tool_profile_line = if crate::server::tool_visibility::explicit_profile(&cfg) {
602        let profile = crate::core::tool_profiles::ToolProfile::from_config(&cfg);
603        format!(
604            "{BOLD}Tool profile{RST}  {WHITE}{profile}{RST}  {DIM}{} + ctx_call gateway{RST}",
605            profile.description()
606        )
607    } else {
608        let lazy_count = crate::tool_defs::core_tool_names().len();
609        format!(
610            "{BOLD}Tool profile{RST}  {WHITE}lean (default){RST}  {DIM}{lazy_count} lazy-core tools advertised + ctx_call gateway{RST}"
611        )
612    };
613    println!("  {tool_profile_line}");
614
615    // Session cache health (#361): answer "is the cache actually engaging?"
616    // without external instrumentation. CEP sessions + the cross-call hit ratio
617    // come from the persistent stats store; `verify-cache` proves it live.
618    let cep = &crate::core::stats::load().cep;
619    let hit_ratio = if cep.total_cache_reads > 0 {
620        (cep.total_cache_hits as f64 / cep.total_cache_reads as f64) * 100.0
621    } else {
622        0.0
623    };
624    println!(
625        "  {BOLD}Session cache{RST}  {WHITE}{} sessions{RST}  {DIM}{}/{} reads cached ({hit_ratio:.0}% hit) · prove: lean-ctx verify-cache{RST}",
626        cep.sessions, cep.total_cache_hits, cep.total_cache_reads
627    );
628
629    // The board counted exactly what it rendered — the displayed ✓/✗ list and
630    // this tally can no longer drift apart (#433).
631    let passed = board.passed;
632    let total = board.total;
633    let needs_attention = total.saturating_sub(passed);
634    println!();
635    println!("  {BOLD}{WHITE}Summary:{RST}  {GREEN}{passed}{RST}{DIM}/{total}{RST} checks passed");
636    if needs_attention > 0 {
637        println!(
638            "  {YELLOW}{needs_attention} check(s) need attention.{RST}  Auto-repair what's fixable:  {BOLD}lean-ctx doctor --fix{RST}"
639        );
640    } else {
641        println!("  {GREEN}Everything looks good.{RST}");
642    }
643    println!("  {DIM}LSP servers are optional enhancements (not counted in score){RST}");
644    println!("  {DIM}{}{RST}", crate::core::integrity::origin_line());
645
646    // Refresh the cached latest-version in the background and, if the running
647    // binary is behind, nudge toward the fast self-updater right where a
648    // confused user looks when something seems off (the "stuck updating"
649    // report). Notify-only — never auto-installs.
650    crate::core::version_check::check_background();
651    if let Some(banner) = crate::core::version_check::get_update_banner() {
652        println!();
653        println!("{banner}");
654    }
655
656    needs_attention
657}
658
659pub fn run_compact() {
660    let (passed, total) = compact_score();
661    print_compact_status(passed, total);
662}
663
664pub fn run_cli(args: &[String]) -> i32 {
665    let (sub, rest) = match args.first().map(String::as_str) {
666        Some("integrations") => ("integrations", &args[1..]),
667        Some("overhead") => ("overhead", &args[1..]),
668        Some("lint-context") => ("lint-context", &args[1..]),
669        _ => ("", args),
670    };
671
672    let fix = rest.iter().any(|a| a == "--fix");
673    let json = rest.iter().any(|a| a == "--json");
674    let gate = rest.iter().any(|a| a == "--gate");
675    let migrate_check = rest.iter().any(|a| a == "--migrate-check");
676    let help = rest.iter().any(|a| a == "--help" || a == "-h");
677
678    if help {
679        println!("Usage:");
680        println!("  lean-ctx doctor");
681        println!(
682            "  lean-ctx doctor overhead [--json] [--gate]   Fixed context cost per session (--gate: non-zero exit when over [context] budget_tokens)"
683        );
684        println!(
685            "  lean-ctx doctor lint-context [--json]   Lint injected context for low-signal/dup lines"
686        );
687        println!("  lean-ctx doctor integrations [--json]");
688        println!("  lean-ctx doctor --fix [--json]");
689        println!("  lean-ctx doctor --migrate-check [--json]");
690        return 0;
691    }
692
693    if sub == "overhead" {
694        return overhead::run_overhead(json, gate);
695    }
696
697    if sub == "lint-context" {
698        return lint_context::run_lint_context(json);
699    }
700
701    if migrate_check {
702        return migrate::run_migrate_check(json);
703    }
704
705    if sub == "integrations" {
706        if fix {
707            let _ = fix::run_fix(&fix::DoctorFixOptions { json: false });
708        }
709        return integrations::run_integrations(&integrations::IntegrationsOptions { json });
710    }
711
712    if !fix {
713        // Non-zero exit when checks need attention so `lean-ctx doctor` works
714        // as a CI/health gate, not just a pretty printer.
715        return i32::from(run() > 0);
716    }
717
718    match fix::run_fix(&fix::DoctorFixOptions { json }) {
719        Ok(code) => code,
720        Err(e) => {
721            tracing::error!("doctor --fix failed: {e}");
722            2
723        }
724    }
725}
726
727pub fn compact_score() -> (u32, u32) {
728    let mut passed = 0u32;
729    let total = 6u32;
730
731    if resolve_lean_ctx_binary().is_some() || path_in_path_env() {
732        passed += 1;
733    }
734    let lean_dir = crate::core::data_dir::lean_ctx_data_dir().ok();
735    if lean_dir.as_ref().is_some_and(|p| p.is_dir()) {
736        passed += 1;
737    }
738    if lean_dir
739        .as_ref()
740        .map(|d| d.join("stats.json"))
741        .and_then(|p| std::fs::metadata(p).ok())
742        .is_some_and(|m| m.is_file())
743    {
744        passed += 1;
745    }
746    if shell_aliases_outcome().ok {
747        passed += 1;
748    }
749    if mcp_config_outcome().ok {
750        passed += 1;
751    }
752    if skill_files_outcome().ok {
753        passed += 1;
754    }
755
756    (passed, total)
757}
758
759pub(super) fn print_compact_status(passed: u32, total: u32) {
760    let status = if passed == total {
761        format!("{GREEN}✓ All {total} checks passed{RST}")
762    } else {
763        format!("{YELLOW}{passed}/{total} passed{RST} — run {BOLD}lean-ctx doctor{RST} for details")
764    };
765    println!("  {status}");
766}
767
768#[cfg(test)]
769mod tests {
770    use super::is_active_shell_impl;
771
772    // Mirrors the inline classification in `checks::capacity_warnings`: a store at
773    // or below its cap is at most a WARN (healthy, eviction keeps it there); only
774    // a store *over* cap is CRIT (eviction is not keeping up).
775    fn make_capacity_check(name: &str, current: usize, limit: usize) -> Option<(bool, String)> {
776        if limit == 0 {
777            return None;
778        }
779        let pct = (current as f64 / limit as f64 * 100.0) as u32;
780        if pct > 100 {
781            Some((true, format!("{name}: {current}/{limit} ({pct}%)")))
782        } else if pct >= 80 {
783            Some((false, format!("{name}: {current}/{limit} ({pct}%)")))
784        } else {
785            None
786        }
787    }
788
789    #[test]
790    fn capacity_below_80_no_warning() {
791        assert!(make_capacity_check("facts", 100, 200).is_none());
792        assert!(make_capacity_check("facts", 159, 200).is_none());
793    }
794
795    #[test]
796    fn capacity_at_80_yellow_warning() {
797        let result = make_capacity_check("facts", 160, 200);
798        assert!(result.is_some());
799        let (critical, msg) = result.unwrap();
800        assert!(!critical);
801        assert!(msg.contains("160/200"));
802        assert!(msg.contains("80%"));
803    }
804
805    #[test]
806    fn capacity_at_92_yellow_warning() {
807        let result = make_capacity_check("facts", 185, 200);
808        assert!(result.is_some());
809        let (critical, msg) = result.unwrap();
810        assert!(!critical);
811        assert!(msg.contains("185/200"));
812        assert!(msg.contains("92%"));
813    }
814
815    #[test]
816    fn capacity_at_95_is_warning_not_critical() {
817        let result = make_capacity_check("facts", 190, 200);
818        assert!(result.is_some());
819        let (critical, msg) = result.unwrap();
820        assert!(!critical, "95% is full-but-healthy, not over cap");
821        assert!(msg.contains("190/200"));
822        assert!(msg.contains("95%"));
823    }
824
825    #[test]
826    fn capacity_at_100_is_warning_not_critical() {
827        // A store exactly at its cap is healthy — eviction keeps it there.
828        let result = make_capacity_check("facts", 200, 200);
829        assert!(result.is_some());
830        let (critical, _) = result.unwrap();
831        assert!(!critical);
832    }
833
834    #[test]
835    fn capacity_over_100_is_critical() {
836        // Genuinely over cap => eviction is not keeping up (regression guard for
837        // the 206/200 "CRIT" that fired before lifecycle eviction was fixed).
838        let result = make_capacity_check("facts", 206, 200);
839        assert!(result.is_some());
840        let (critical, msg) = result.unwrap();
841        assert!(critical);
842        assert!(msg.contains("206/200"));
843        assert!(msg.contains("103%"));
844    }
845
846    #[test]
847    fn capacity_zero_limit_skipped() {
848        assert!(make_capacity_check("facts", 50, 0).is_none());
849    }
850
851    #[test]
852    fn bashrc_active_on_non_windows_when_shell_empty() {
853        assert!(is_active_shell_impl("~/.bashrc", "", false, false));
854    }
855
856    #[test]
857    fn bashrc_not_active_on_windows_when_shell_empty() {
858        assert!(!is_active_shell_impl("~/.bashrc", "", true, false));
859    }
860
861    #[test]
862    fn bashrc_active_when_shell_contains_bash_on_linux() {
863        assert!(is_active_shell_impl(
864            "~/.bashrc",
865            "/usr/bin/bash",
866            false,
867            false
868        ));
869    }
870
871    #[test]
872    fn bashrc_not_active_on_windows_even_with_bash_in_shell_env() {
873        // Issue #214: On Windows, Git Bash sets $SHELL globally to bash.exe.
874        // .bashrc should NOT be flagged on Windows unless actually inside bash.
875        crate::test_env::remove_var("BASH_VERSION");
876        assert!(!is_active_shell_impl(
877            "~/.bashrc",
878            "C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe",
879            true,
880            false,
881        ));
882    }
883
884    #[test]
885    fn bashrc_not_active_on_windows_powershell_even_with_bash_in_shell() {
886        assert!(!is_active_shell_impl(
887            "~/.bashrc",
888            "C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe",
889            true,
890            true,
891        ));
892    }
893
894    #[test]
895    fn bashrc_not_active_on_windows_powershell_with_empty_shell() {
896        assert!(!is_active_shell_impl("~/.bashrc", "", true, true));
897    }
898
899    #[test]
900    fn zshrc_unaffected_by_powershell_flag() {
901        assert!(is_active_shell_impl("~/.zshrc", "/bin/zsh", false, false));
902        assert!(is_active_shell_impl("~/.zshrc", "/bin/zsh", true, true));
903    }
904
905    #[test]
906    fn bashrc_not_active_on_windows_without_powershell_detection() {
907        // Windows + $SHELL=bash but NOT in actual bash session (no BASH_VERSION).
908        // This is the exact scenario from issue #214: Git Bash sets $SHELL globally.
909        crate::test_env::remove_var("BASH_VERSION");
910        assert!(!is_active_shell_impl(
911            "~/.bashrc",
912            "/usr/bin/bash",
913            true,
914            false,
915        ));
916    }
917
918    #[test]
919    fn bashrc_active_on_linux() {
920        assert!(is_active_shell_impl("~/.bashrc", "/bin/bash", false, false));
921        assert!(is_active_shell_impl("~/.bashrc", "", false, false));
922    }
923}