Skip to main content

lean_ctx_cli/doctor/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Environment diagnostics for lean-ctx installation and integration.
3
4/// Every doctor line goes through [`emit_line`], which drops the ANSI styling
5/// under `NO_COLOR`, `TERM=dumb` or a non-TTY stdout. Shadowing `println!` for
6/// this module tree keeps the many styled format strings unchanged while making
7/// it impossible for a new check to leak escape codes into a pipe or log.
8macro_rules! println {
9    () => {
10        ::std::println!()
11    };
12    ($($arg:tt)*) => {
13        $crate::doctor::emit_line(&::std::format!($($arg)*))
14    };
15}
16
17mod checks;
18mod common;
19mod deprecations;
20mod fix;
21mod integrations;
22mod lint_context;
23mod migrate;
24mod overhead;
25mod report;
26mod workspace_scope;
27
28#[allow(clippy::wildcard_imports)]
29use checks::*;
30pub(crate) use checks::{configured_host_coverage, shadow_hosts, shadow_status};
31#[allow(clippy::wildcard_imports)]
32use common::*;
33
34pub use report::{HealthCheck, HealthLevel, HealthReport, health_report};
35
36/// Run `doctor --fix` and return the structured `SetupReport` without printing
37/// anything — the in-process entry point for the dashboard fix route (#466).
38///
39/// # Errors
40/// Propagates any repair-step failure (e.g. an unwritable data directory).
41pub fn run_fix_report() -> Result<lean_ctx::core::setup_report::SetupReport, String> {
42    fix::fix_report()
43}
44
45pub(super) const GREEN: &str = "\x1b[32m";
46
47pub(super) const RED: &str = "\x1b[31m";
48
49pub(super) const BOLD: &str = "\x1b[1m";
50
51pub(super) const RST: &str = "\x1b[0m";
52
53pub(super) const DIM: &str = "\x1b[2m";
54
55pub(super) const WHITE: &str = "\x1b[97m";
56
57pub(super) const YELLOW: &str = "\x1b[33m";
58
59pub(super) struct Outcome {
60    pub ok: bool,
61    pub line: String,
62}
63
64/// The daemon autostart service as doctor sees it.
65enum DaemonAutostart {
66    /// No autostart service exists on this platform (Windows, BSD): the
67    /// daemon is started by `daemon start` or on demand by editors.
68    Unsupported,
69    Off,
70    /// Installed, with its service file when known (GH #394).
71    On(Option<std::path::PathBuf>),
72}
73
74/// Doctor's line for lean-ctx services of this user that this instance has
75/// no record of (owner decision 02.11.): `stop`/`restart` leave them alone,
76/// so doctor names each with its PID and the exact way to stop it. `None`
77/// when there are none. Pure; advisory (never fails doctor).
78fn unrecorded_services_outcome(lines: Option<(String, String)>) -> Option<Outcome> {
79    let (what, how) = lines?;
80    Some(Outcome {
81        ok: true,
82        line: format!("{BOLD}Unrecorded services{RST}  {YELLOW}{what}{RST}  {DIM}{how}{RST}"),
83    })
84}
85
86/// Doctor's daemon line from the observed state. Pure, so the line every
87/// platform prints is covered by tests on any host (#2176: Windows printed
88/// "not supported on this platform" while its daemon was running).
89fn daemon_outcome(running_pid: Option<u32>, autostart: &DaemonAutostart) -> Outcome {
90    let autostart_tag = match autostart {
91        DaemonAutostart::On(Some(p)) => format!("  {DIM}[autostart: on — {}]{RST}", p.display()),
92        DaemonAutostart::On(None) => format!("  {DIM}[autostart: on]{RST}"),
93        DaemonAutostart::Off | DaemonAutostart::Unsupported => String::new(),
94    };
95    let line = if let Some(pid) = running_pid {
96        format!("{BOLD}Daemon{RST}  {GREEN}running (PID {pid}){RST}{autostart_tag}")
97    } else {
98        let hint = match autostart {
99            DaemonAutostart::On(_) => format!("{DIM}(autostart enabled, will restart){RST}"),
100            DaemonAutostart::Off => {
101                format!("{DIM}(run: lean-ctx daemon start  or: lean-ctx daemon enable){RST}")
102            }
103            DaemonAutostart::Unsupported => {
104                format!("{DIM}(run: lean-ctx daemon start — editors also start it on demand){RST}")
105            }
106        };
107        format!("{BOLD}Daemon{RST}  {YELLOW}not running{RST}  {hint}")
108    };
109    Outcome { ok: true, line }
110}
111
112/// Accumulates doctor checks so the rendered ✓/✗ list and the summary tally can
113/// never diverge (#433): every scored check is counted exactly once via
114/// [`Scoreboard::check`]; only explicitly-optional advisories (LSP, "not
115/// configured" notes) use [`Scoreboard::info`], which renders without counting.
116/// The old hand-maintained `passed`/`effective_total` pair drifted whenever a
117/// check was added without bumping the total — routing every render through the
118/// board makes that class of bug structurally impossible.
119#[derive(Default)]
120struct Scoreboard {
121    passed: u32,
122    total: u32,
123    json_mode: bool,
124    entries: Vec<JsonCheck>,
125}
126
127/// A single doctor check entry for JSON serialization (GH #1470).
128#[derive(Default, serde::Serialize)]
129struct JsonCheck {
130    ok: bool,
131    name: String,
132    scored: bool,
133}
134
135fn strip_ansi(s: &str) -> String {
136    // Strip ANSI escape sequences for machine-readable output
137    let mut result = String::with_capacity(s.len());
138    let mut in_escape = false;
139    for c in s.chars() {
140        if c == '\x1b' {
141            in_escape = true;
142        } else if in_escape {
143            if c.is_ascii_alphabetic() {
144                in_escape = false;
145            }
146        } else {
147            result.push(c);
148        }
149    }
150    result
151}
152
153/// Print one doctor line, stripped of ANSI styling when colour is off.
154pub(crate) fn emit_line(line: &str) {
155    if lean_ctx::core::theme::no_color() {
156        ::std::println!("{}", strip_ansi(line));
157    } else {
158        ::std::println!("{line}");
159    }
160}
161
162impl Scoreboard {
163    fn new(json_mode: bool) -> Self {
164        Self {
165            passed: 0,
166            total: 0,
167            json_mode,
168            entries: Vec::new(),
169        }
170    }
171
172    /// A scored health check: render it and count it (pass iff `ok`).
173    fn check(&mut self, outcome: &Outcome) {
174        self.total += 1;
175        if outcome.ok {
176            self.passed += 1;
177        }
178        self.entries.push(JsonCheck {
179            ok: outcome.ok,
180            name: strip_ansi(&outcome.line),
181            scored: true,
182        });
183        if !self.json_mode {
184            print_check(outcome, true);
185        }
186    }
187
188    /// An optional/advisory line: render it but never count it toward the score.
189    fn info(&mut self, outcome: &Outcome) {
190        self.entries.push(JsonCheck {
191            ok: outcome.ok,
192            name: strip_ansi(&outcome.line),
193            scored: false,
194        });
195        if !self.json_mode {
196            print_check(outcome, false);
197        }
198    }
199
200    /// A free-form advisory note (daemon diagnostics): printed as-is in text
201    /// mode, recorded as an unscored JSON entry with `--json`, so nothing but
202    /// the JSON document reaches stdout (#2179).
203    fn note(&mut self, outcome: &Outcome) {
204        self.entries.push(JsonCheck {
205            ok: outcome.ok,
206            name: strip_ansi(outcome.line.trim()),
207            scored: false,
208        });
209        if !self.json_mode {
210            println!("{}", outcome.line);
211        }
212    }
213}
214
215/// Daemon diagnostics that are not checks of their own: the systemd unit
216/// state and linger (Linux) and a crash-looping MCP server. Returned rather
217/// than printed, so the caller decides between text and JSON.
218fn daemon_diagnostic_notes() -> Vec<Outcome> {
219    let mut notes = Vec::new();
220    #[cfg(target_os = "linux")]
221    {
222        if let Ok(o) = std::process::Command::new("systemctl")
223            .args(["--user", "is-active", "lean-ctx-daemon.service"])
224            .output()
225        {
226            let state = String::from_utf8_lossy(&o.stdout).trim().to_string();
227            if state != "active" {
228                notes.push(Outcome {
229                    ok: false,
230                    line: format!(
231                        "  {DIM}  systemd unit state: {YELLOW}{state}{RST}{DIM} (expected: active){RST}"
232                    ),
233                });
234            }
235        }
236        let username = std::env::var("USER")
237            .or_else(|_| std::env::var("LOGNAME"))
238            .unwrap_or_else(|_| "$(whoami)".to_string());
239        if let Ok(o) = std::process::Command::new("loginctl")
240            .args(["show-user", &username, "-p", "Linger", "--value"])
241            .output()
242        {
243            let val = String::from_utf8_lossy(&o.stdout).trim().to_string();
244            if val != "yes" {
245                notes.push(Outcome {
246                    ok: false,
247                    line: format!(
248                        "  {YELLOW}⚠{RST}  Linger not enabled — daemon won't start at boot without login\n     {DIM}Fix: loginctl enable-linger {username}{RST}"
249                    ),
250                });
251            }
252        }
253    }
254    if let Some(log_path) = lean_ctx::core::startup_guard::crash_loop_log_path(
255        lean_ctx::core::startup_guard::MCP_PROCESS_NAME,
256    ) && log_path.exists()
257        && let Ok(contents) = std::fs::read_to_string(&log_path)
258    {
259        let lines: Vec<&str> = contents.lines().collect();
260        if lines.len() >= 5 {
261            notes.push(Outcome {
262                ok: false,
263                line: format!(
264                    "  {YELLOW}⚠{RST}  Crash-loop log: {} recent restarts  {DIM}({}){RST}",
265                    lines.len(),
266                    display_user_path(&log_path)
267                ),
268            });
269        }
270    }
271    notes
272}
273
274/// Run diagnostic checks and print colored results to stdout.
275/// Renders the full diagnostics board and returns how many checks need
276/// attention, so `lean-ctx doctor` can exit non-zero when something is wrong
277/// (a health gate must fail loudly, not silently exit 0).
278pub fn run() -> u32 {
279    run_inner(false)
280}
281
282/// GH #1470: JSON output variant of `run()`.
283pub fn run_json() -> u32 {
284    run_inner(true)
285}
286
287fn run_inner(json: bool) -> u32 {
288    let mut board = Scoreboard::new(json);
289
290    if !json {
291        println!("{BOLD}{WHITE}lean-ctx doctor{RST}  {DIM}diagnostics{RST}\n");
292    }
293
294    // 1) Binary on PATH
295    let path_bin = resolve_lean_ctx_binary();
296    let also_in_path_dirs = path_in_path_env();
297    let bin_ok = path_bin.is_some() || also_in_path_dirs;
298    let bin_line = if let Some(p) = path_bin {
299        format!("{BOLD}lean-ctx in PATH{RST}  {WHITE}{}{RST}", p.display())
300    } else if also_in_path_dirs {
301        format!(
302            "{BOLD}lean-ctx in PATH{RST}  {YELLOW}found via PATH walk (not resolved by `command -v`){RST}"
303        )
304    } else {
305        format!("{BOLD}lean-ctx in PATH{RST}  {RED}not found{RST}")
306    };
307    board.check(&Outcome {
308        ok: bin_ok,
309        line: bin_line,
310    });
311
312    // 2) Version from PATH binary
313    let ver = if bin_ok {
314        lean_ctx_version_from_path()
315    } else {
316        Outcome {
317            ok: false,
318            line: format!("{BOLD}lean-ctx version{RST}  {RED}skipped (binary not in PATH){RST}"),
319        }
320    };
321    board.check(&ver);
322
323    // 3) data directory (respects LEAN_CTX_DATA_DIR)
324    let lean_dir = lean_ctx::core::data_dir::lean_ctx_data_dir().ok();
325    let dir_outcome = match &lean_dir {
326        Some(p) if p.is_dir() => Outcome {
327            ok: true,
328            line: format!(
329                "{BOLD}data dir{RST}  {GREEN}exists{RST}  {DIM}{}{RST}",
330                p.display()
331            ),
332        },
333        // A fresh install creates it on first use, like stats.json below.
334        Some(p) if !p.exists() => Outcome {
335            ok: true,
336            line: format!(
337                "{BOLD}data dir{RST}  {WHITE}not yet created{RST}  {DIM}(will appear after first use) {}{RST}",
338                p.display()
339            ),
340        },
341        Some(p) => Outcome {
342            ok: false,
343            line: format!(
344                "{BOLD}data dir{RST}  {RED}not a directory{RST}  {DIM}{}{RST}",
345                p.display()
346            ),
347        },
348        None => Outcome {
349            ok: false,
350            line: format!("{BOLD}data dir{RST}  {RED}could not resolve data directory{RST}"),
351        },
352    };
353    board.check(&dir_outcome);
354
355    // 4) stats.json + size
356    let stats_path = lean_dir.as_ref().map(|d| d.join("stats.json"));
357    let stats_outcome = match stats_path.as_ref().and_then(|p| std::fs::metadata(p).ok()) {
358        Some(m) if m.is_file() => {
359            let size = m.len();
360            let path_display = if let Some(p) = stats_path.as_ref() {
361                p.display().to_string()
362            } else {
363                String::new()
364            };
365            Outcome {
366                ok: true,
367                line: format!(
368                    "{BOLD}stats.json{RST}  {GREEN}exists{RST}  {WHITE}{size} bytes{RST}  {DIM}{path_display}{RST}",
369                ),
370            }
371        }
372        Some(_m) => {
373            let path_display = if let Some(p) = stats_path.as_ref() {
374                p.display().to_string()
375            } else {
376                String::new()
377            };
378            Outcome {
379                ok: false,
380                line: format!(
381                    "{BOLD}stats.json{RST}  {RED}not a file{RST}  {DIM}{path_display}{RST}",
382                ),
383            }
384        }
385        None => Outcome {
386            ok: true,
387            line: match &stats_path {
388                Some(p) => format!(
389                    "{BOLD}stats.json{RST}  {WHITE}not yet created{RST}  {DIM}(will appear after first use) {}{RST}",
390                    p.display()
391                ),
392                None => format!("{BOLD}stats.json{RST}  {RED}could not resolve path{RST}"),
393            },
394        },
395    };
396    board.check(&stats_outcome);
397
398    let split_dirs = lean_ctx::core::data_dir::all_data_dirs_with_stats();
399    if split_dirs.len() >= 2 {
400        let dirs_str = split_dirs
401            .iter()
402            .map(|d| d.display().to_string())
403            .collect::<Vec<_>>()
404            .join(", ");
405        board.check(&Outcome {
406            ok: false,
407            line: format!(
408                "{BOLD}data dir split{RST}  {RED}stats.json found in {count} locations{RST}: {dirs_str}  {DIM}(run: lean-ctx doctor --fix to merge){RST}",
409                count = split_dirs.len(),
410            ),
411        });
412    }
413
414    // XDG layout (GH #408): a legacy/mixed single-dir install mixes config with
415    // data/state/cache, which blocks a read-only config sandbox. Scored as a
416    // failure while present (#433) — `doctor --fix` splits it into the four typed
417    // XDG dirs, after which this check disappears.
418    if let Some((src, n)) = lean_ctx::core::xdg_migrate::pending() {
419        board.check(&Outcome {
420            ok: false,
421            line: format!(
422                "{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}",
423                src.display()
424            ),
425        });
426    }
427
428    // #594: a `config.toml` stranded in the data dir means the MCP server (an
429    // older `LEAN_CTX_DATA_DIR` env collapsed its layout) and the CLI were
430    // reading *different* config. Flag it; `lean-ctx setup`/`update` and
431    // `doctor --fix` relocate it to the config dir so both agree again.
432    if let Some(stray) = lean_ctx::core::config_heal::pending() {
433        board.check(&Outcome {
434            ok: false,
435            line: format!(
436                "{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}",
437                stray.display()
438            ),
439        });
440    }
441
442    // Layout commitment (GL #623): a pinned XDG install can no longer be
443    // hijacked by a stray ~/.lean-ctx. Surface the mode and flag a residual dir
444    // (heal reclaims it on the next start / `doctor --fix`).
445    {
446        let pinned = lean_ctx::core::layout_pin::is_xdg_pinned();
447        let residual = lean_ctx::core::xdg_migrate::residual_legacy_present();
448        let line = if pinned && residual {
449            format!(
450                "{BOLD}layout{RST}  {GREEN}xdg-pinned{RST}  {YELLOW}residual ~/.lean-ctx present{RST}  {DIM}(auto-reclaimed on next start){RST}"
451            )
452        } else if pinned {
453            format!(
454                "{BOLD}layout{RST}  {GREEN}xdg-pinned{RST}  {DIM}(~/.lean-ctx can no longer hijack this install){RST}"
455            )
456        } else {
457            format!(
458                "{BOLD}layout{RST}  {WHITE}single-dir / legacy{RST}  {DIM}(run: lean-ctx doctor --fix to commit to XDG){RST}"
459            )
460        };
461        board.check(&Outcome { ok: true, line });
462    }
463
464    // 5) config.toml (missing is OK). It lives in the CONFIG dir
465    // ($XDG_CONFIG_HOME/lean-ctx after a split), not the data dir — resolve it
466    // through the same path as the loader so the report matches reality
467    // post-migration instead of pointing at the old location (#435).
468    let config_path = lean_ctx::core::config::Config::path();
469    let config_outcome = match &config_path {
470        Some(p) => match std::fs::metadata(p) {
471            Ok(m) if m.is_file() => Outcome {
472                ok: true,
473                line: format!(
474                    "{BOLD}config.toml{RST}  {GREEN}exists{RST}  {DIM}{}{RST}",
475                    p.display()
476                ),
477            },
478            Ok(_) => Outcome {
479                ok: false,
480                line: format!(
481                    "{BOLD}config.toml{RST}  {RED}exists but is not a regular file{RST}  {DIM}{}{RST}",
482                    p.display()
483                ),
484            },
485            Err(_) => Outcome {
486                ok: true,
487                line: format!(
488                    "{BOLD}config.toml{RST}  {WHITE}not found, using defaults{RST}  {DIM}(expected at {}){RST}",
489                    p.display()
490                ),
491            },
492        },
493        None => Outcome {
494            ok: false,
495            line: format!("{BOLD}config.toml{RST}  {RED}could not resolve path{RST}"),
496        },
497    };
498    board.check(&config_outcome);
499
500    // 5a1) #2175: a paused config migration, on every doctor run (the
501    // warning itself is shown once per state).
502    if let Some(outcome) = config_path
503        .as_deref()
504        .and_then(config_migration_pause_outcome)
505    {
506        board.check(&outcome);
507    }
508
509    // 5a2) #594: CLI<->MCP config parity — warn if any editor MCP entry still
510    // pins a stale LEAN_CTX_DATA_DIR (which would make that editor's MCP server
511    // read a different config.toml than this CLI), and print the resolved path.
512    board.check(&config_parity_outcome());
513    board.check(&project_pin_outcome());
514
515    // 5b) Shell allowlist (effective runtime view + silent-parse-error trap, #341)
516    let allowlist_outcome = shell_allowlist_outcome();
517    board.check(&allowlist_outcome);
518
519    // 5b1) GH #1419 follow-up: upgrade advisory + shadowing advisory, both
520    // read-only and silent when there's nothing to report.
521    if let Some(upgrade) = shell_allowlist_upgrade_advisory_outcome() {
522        board.check(&upgrade);
523    }
524    if let Some(shadowing) = shell_allowlist_shadowing_outcome() {
525        board.check(&shadowing);
526    }
527
528    // 5b2) Path jail (effective state + dead allow_paths entries, GH #392)
529    let path_jail = path_jail_outcome();
530    board.check(&path_jail);
531
532    // 5b3) Workspace trust for project-local .lean-ctx.toml (security audit #4)
533    let workspace_trust = workspace_trust_outcome();
534    board.check(&workspace_trust);
535
536    // 5b3b) Secret/.env redaction — the exfiltration-defense plane, independent
537    // of the jail + shell gating above (#507).
538    let secret_detection = secret_detection_outcome();
539    board.check(&secret_detection);
540    let context_gateway = context_gateway_outcome();
541    board.check(&context_gateway);
542
543    // 5b3c) Managed addon binaries (GH #725): receipt path + sha256 pin +
544    // revocation, so binhash-gate refusals surface here instead of at first
545    // tool call. Silent when nothing is managed.
546    if let Some(managed_bins) = managed_addon_binaries_outcome() {
547        board.check(&managed_bins);
548    }
549
550    // 5b3d) Managed ONNX Runtime (GH #732). The managed runtime was removed;
551    // stays silent (embeddings are opt-in).
552    if let Some(managed_ort) = managed_ort_outcome() {
553        board.check(&managed_ort);
554    }
555
556    // 5b4) Cognition v2 activation (science subsystems wired + active)
557    let cognition = cognition_activity_outcome();
558    board.check(&cognition);
559
560    // 5c) Compact-format passthrough (preserve already-compact TOON output, #342)
561    let passthrough_outcome = compact_format_passthrough_outcome();
562    board.check(&passthrough_outcome);
563
564    // 5d) IDE permission inheritance (mirror host IDE bash/rm rules onto ctx_*)
565    let perm_inherit_outcome = permission_inheritance_outcome();
566    board.check(&perm_inherit_outcome);
567
568    // 6) Proxy upstreams
569    let proxy_outcome = proxy_upstream_outcome();
570    board.check(&proxy_outcome);
571
572    // Exit-code contract: `doctor` exits non-zero only when a scored check
573    // fails. On a fresh install that was never set up (no host carries a
574    // lean-ctx MCP entry, hooks or proxy route), the setup items below are the
575    // next step, not errors: they render as optional (–) with the setup hint
576    // and are not counted. Once any host is configured they are scored again,
577    // so a half-broken setup still fails the gate.
578    let setup_pending = dirs::home_dir().is_some_and(|home| {
579        lean_ctx_mcp_location_names(&home).is_empty()
580            && checks::configured_host_coverage(&home).is_empty()
581    });
582    if setup_pending && !json {
583        println!(
584            "  {DIM}Not set up yet — run {RST}{BOLD}lean-ctx setup{RST}{DIM} to connect your AI tools (items marked – are optional until then).{RST}"
585        );
586    }
587    let setup_item = |board: &mut Scoreboard, outcome: &Outcome| {
588        if setup_pending {
589            board.info(outcome);
590        } else {
591            board.check(outcome);
592        }
593    };
594
595    // 7) Shell aliases
596    let aliases = shell_aliases_outcome();
597    setup_item(&mut board, &aliases);
598
599    // 7b) Agent aliases opt-out
600    let agent_aliases = skip_agent_aliases_outcome();
601    board.check(&agent_aliases);
602
603    // 8) MCP
604    let mcp = mcp_config_outcome();
605    setup_item(&mut board, &mcp);
606    // 8a) Claude Code: denied native tools need the MCP server that replaces them.
607    if let Some(tools) = lean_ctx::core::home::resolve_home_dir()
608        .and_then(|home| checks::claude_tool_access_outcome(&home))
609    {
610        board.check(&tools);
611    }
612    let user_scope_mcp_locations = dirs::home_dir()
613        .map(|home| lean_ctx_mcp_location_names(&home))
614        .unwrap_or_default();
615
616    // 7b) WSL2 + VS Code: surface the upstream first-call invoke race (GH #669)
617    if let Some(wsl_hint) = wsl_vscode_mcp_outcome() {
618        board.check(&wsl_hint);
619    }
620
621    // 8) Workspace-scope MCP (optional; only when a project-local config exists)
622    let workspace_scope = workspace_scope::workspace_scope_outcome(&user_scope_mcp_locations);
623    if let Some(ref ws) = workspace_scope {
624        board.check(ws);
625    }
626
627    // 9) SKILL.md
628    let skill = skill_files_outcome();
629    setup_item(&mut board, &skill);
630
631    // 9a0) One lean-ctx rules channel per host (A3): advisory, names the fix.
632    board.check(&overhead::rules_channels_outcome());
633
634    // 9a) Optional Claude Code mod (informational; never fails doctor).
635    if let Some(claude_mod) = checks::claude_mod_outcome() {
636        board.check(&claude_mod);
637    }
638
639    // 9a') Hive org policy (HIVE-RT-D5): informational, never fails doctor.
640    if let Some(hive_policy) = checks::hive_policy_outcome() {
641        board.info(&hive_policy);
642    }
643
644    // 9b) Output triage (#1534): the 3.9.19 filter ran invisibly while doctor
645    // reported all green — its state stays on the board whether on or off.
646    let output_triage = output_triage_outcome();
647    board.check(&output_triage);
648
649    // 10) Port
650    let port = port_3333_outcome();
651    board.check(&port);
652
653    // Daemon status — on every platform: Windows runs the daemon too (GL
654    // #545); only the autostart service is macOS/Linux-specific (#2176).
655    let daemon_autostart = if lean_ctx::daemon_autostart::is_supported() {
656        if lean_ctx::daemon_autostart::is_installed() {
657            DaemonAutostart::On(lean_ctx::daemon_autostart::service_file_path())
658        } else {
659            DaemonAutostart::Off
660        }
661    } else {
662        DaemonAutostart::Unsupported
663    };
664    // Verified, not just alive: a PID file can outlive its daemon and the
665    // PID can be reused by any process (#2176 review #1).
666    let daemon_pid = lean_ctx::daemon::verified_daemon().map(|daemon| daemon.pid);
667    board.check(&daemon_outcome(daemon_pid, &daemon_autostart));
668    if let Some(unrecorded) =
669        unrecorded_services_outcome(lean_ctx::daemon::unrecorded_services_warning())
670    {
671        board.info(&unrecorded);
672    }
673
674    // Daemon diagnostics: systemctl is-active, linger, crash-loop log. They go
675    // through the board so `--json` keeps stdout one JSON document (#2179).
676    for note in daemon_diagnostic_notes() {
677        board.note(&note);
678    }
679
680    // Providers (advisory — presence/health varies per environment, not scored)
681    let provider_outcome = provider_outcome();
682    board.info(&provider_outcome);
683
684    // MCP Bridges (advisory)
685    let bridge_outcomes = mcp_bridge_outcomes();
686    for bridge_check in &bridge_outcomes {
687        board.info(bridge_check);
688    }
689
690    // GH #1470: Version-skew detection between CLI and agent bridges
691    let skew_outcomes = version_skew_outcomes();
692    for skew_check in &skew_outcomes {
693        board.check(&skew_check);
694    }
695
696    // Plan mode (advisory)
697    let plan_outcomes = plan_mode_outcomes();
698    for plan_check in &plan_outcomes {
699        board.info(plan_check);
700    }
701
702    // 9) Session state (project_root + shell_cwd)
703    let session_outcome = session_state_outcome();
704    board.check(&session_outcome);
705
706    // 10) Docker env vars (optional, only in containers)
707    let docker_outcomes = docker_env_outcomes();
708    for docker_check in &docker_outcomes {
709        board.check(docker_check);
710    }
711
712    // 11) Pi Coding Agent (optional)
713    let pi = pi_outcome();
714    if let Some(ref pi_check) = pi {
715        board.check(pi_check);
716    }
717
718    // 12) Build integrity (canary / origin check)
719    let integrity = lean_ctx::core::integrity::check();
720    let integrity_ok = integrity.seed_ok && integrity.origin_ok;
721    let integrity_line = if integrity_ok {
722        format!(
723            "{BOLD}Build origin{RST}  {GREEN}official{RST}  {DIM}{}{RST}",
724            integrity.repo
725        )
726    } else {
727        format!(
728            "{BOLD}Build origin{RST}  {RED}MODIFIED REDISTRIBUTION{RST}  {YELLOW}pkg={}, repo={}{RST}",
729            integrity.pkg_name, integrity.repo
730        )
731    };
732    board.check(&Outcome {
733        ok: integrity_ok,
734        line: integrity_line,
735    });
736
737    // 13) Cache safety
738    let cache_safety = cache_safety_outcome();
739    board.check(&cache_safety);
740
741    // 14) Claude Code instruction truncation guard
742    let claude_truncation = claude_truncation_outcome();
743    if let Some(ref ct) = claude_truncation {
744        board.check(ct);
745    }
746
747    // 14a) CodeBuddy instruction truncation guard
748    let codebuddy_truncation = codebuddy_truncation_outcome();
749    if let Some(ref cbt) = codebuddy_truncation {
750        board.check(cbt);
751    }
752
753    // 14b) Installed addons: what the registry actually holds, which is not
754    // the same question as what the store contains — `addon list` reads disk,
755    // this reads the running engine.
756    if let Some(ref addons) = addons_loaded_outcome() {
757        board.check(addons);
758    }
759
760    // 15) BM25 cache health
761    let bm25_health = bm25_cache_health_outcome();
762    board.check(&bm25_health);
763
764    // 15-pre) Quarantined corrupt stats.json (#706): the loader preserved a
765    // display cache it could not parse — surface it instead of losing history.
766    let stats_quarantine = stats_quarantine_outcome();
767    board.check(&stats_quarantine);
768
769    // 15a) Search indexes for the active project: the BM25 runtime status
770    // (surfaces a stuck "warming" index, #249) and the dense vector index
771    // on disk — reported separately so neither masquerades as the other (#1887).
772    for check in search_index_outcomes() {
773        board.check(&check);
774    }
775
776    // 15b) Archive FTS footprint
777    let archive_footprint = archive_footprint_outcome();
778    board.check(&archive_footprint);
779
780    // 16) Memory profile
781    let mem_profile = memory_profile_outcome();
782    board.check(&mem_profile);
783
784    // 17) Memory cleanup
785    let mem_cleanup = memory_cleanup_outcome();
786    board.check(&mem_cleanup);
787
788    // 18) RAM Guardian
789    let ram_outcome = ram_guardian_outcome();
790    board.check(&ram_outcome);
791
792    // 19) Capacity warnings (memory stores near limits)
793    let cap_warnings = capacity_warnings();
794    for cw in &cap_warnings {
795        board.check(cw);
796    }
797
798    // 19b) Orphaned knowledge stores (deleted projects — reclaimable bloat, #615)
799    let orphan_outcome = orphaned_knowledge_outcome();
800    board.check(&orphan_outcome);
801
802    // 20) Proxy health
803    let proxy_health = proxy_health_outcome();
804    board.check(&proxy_health);
805
806    // 20a) Proxy upstream drift (#449): running proxy serves a different upstream
807    // than config.toml resolves to (env override masking config). Only surfaces
808    // when the proxy is up and actually drifting.
809    let upstream_drift = proxy_upstream_drift_outcome();
810    if let Some(ref check) = upstream_drift {
811        board.check(check);
812    }
813
814    // 20) Stale proxy env (ANTHROPIC_BASE_URL pointing to local proxy while proxy is not enabled)
815    let stale_env = stale_proxy_env_outcome();
816    if let Some(ref check) = stale_env {
817        board.check(check);
818    }
819
820    // 21) Claude Pro/Max subscription routed through the proxy without an API key
821    let subscription_conflict = proxy_subscription_conflict_outcome();
822    if let Some(ref check) = subscription_conflict {
823        board.check(check);
824    }
825
826    // 21a) Removed automatic model routing: a leftover tier table routes nothing.
827    if let Some(ref check) = removed_routing_tiers_outcome() {
828        board.check(check);
829    }
830
831    // 21b) Context gateway coverage per configured host (G7): enforced only
832    // where model traffic is proxy-routed; never claims more than it sees.
833    let coverage_check = gateway_coverage_outcome();
834    board.check(&coverage_check);
835
836    // 22) Deprecation register (CONTRACTS.md policy, GL #394): warn about
837    // every surface this build deprecates, with replacement and removal floor.
838    let deprecation_check = deprecations::deprecations_outcome();
839    board.check(&deprecation_check);
840
841    // MCP server CWD warning (informational, only fires when running as MCP)
842    let mcp_cwd = mcp_server_cwd_outcome();
843    board.check(&mcp_cwd);
844
845    // LSP servers (optional, informational)
846    if !json {
847        println!(
848            "\n  {BOLD}{WHITE}Semantic intelligence (optional — LSP references + verified graph edges):{RST}"
849        );
850    }
851    board.info(&semantic_mode_outcome());
852    let lsp_outcomes = lsp_server_outcomes();
853    for lsp_check in &lsp_outcomes {
854        board.info(lsp_check);
855    }
856    for coverage in semantic_coverage_outcomes() {
857        board.info(&coverage);
858    }
859
860    // Shadow mode status. #1280: the old single line claimed "native tools
861    // denied" wholesale, but that guarantee only covers Read/Grep/Glob — shell
862    // coverage depends on shell_hook_mode (rewrite hooks pass unknown commands
863    // through raw). Report the two surfaces separately so users audit against
864    // reality.
865    let cfg = lean_ctx::core::config::Config::load();
866    let shell_mode = std::env::var("LEAN_CTX_SHELL_HOOK_MODE")
867        .ok()
868        .filter(|v| !v.trim().is_empty())
869        .or_else(|| cfg.shell_hook_mode.clone())
870        .unwrap_or_default();
871    let shell_desc = if shell_mode.trim().eq_ignore_ascii_case("deny") {
872        format!("{GREEN}deny{RST} {DIM}(all shell via ctx_shell){RST}")
873    } else {
874        format!(
875            "{YELLOW}rewrite{RST} {DIM}(unknown commands pass through raw — shell_hook_mode=deny closes this){RST}"
876        )
877    };
878    // Only claim "active" when a host really has lean-ctx hooks installed —
879    // `shadow_mode = true` is the default even before anything is configured.
880    let shadow_hosts = dirs::home_dir()
881        .map(|home| checks::shadow_hosts(&home))
882        .unwrap_or_default();
883    let (shadow_state, shadow_detail) = checks::shadow_status(cfg.shadow_mode, &shadow_hosts);
884    let state_color = if shadow_state == "active" { GREEN } else { DIM };
885    let shadow_line = if shadow_state == "not active" || shadow_state == "disabled" {
886        format!(
887            "{BOLD}Shadow mode{RST}  {state_color}{shadow_state}{RST}  {DIM}{shadow_detail}{RST}"
888        )
889    } else {
890        format!(
891            "{BOLD}Shadow mode{RST}  {state_color}{shadow_state}{RST}  {DIM}{shadow_detail}{RST}  shell: {shell_desc}"
892        )
893    };
894    if !json {
895        println!("  {shadow_line}");
896    }
897
898    // Tool-schema footprint (informational, not scored). With no profile pinned
899    // the server runs in lean mode — only the lazy core is advertised and every
900    // tool stays reachable via ctx_call — so report that, not the internal
901    // `power` call-gate fallback that `from_config` returns for an empty config
902    // (otherwise `doctor` claimed "power" right after the wizard chose lean, #415).
903    let tool_profile_line = if lean_ctx_server::server::tool_visibility::explicit_profile(&cfg) {
904        let profile = lean_ctx::core::tool_profiles::ToolProfile::from_config(&cfg);
905        format!(
906            "{BOLD}Tool profile{RST}  {WHITE}{profile}{RST}  {DIM}{} + ctx_call gateway{RST}",
907            profile.description()
908        )
909    } else {
910        let lazy_count = lean_ctx::tool_defs::core_tool_names().len();
911        format!(
912            "{BOLD}Tool profile{RST}  {WHITE}lean (default){RST}  {DIM}{lazy_count} lazy-core tools advertised + ctx_call gateway{RST}"
913        )
914    };
915    if !json {
916        println!("  {tool_profile_line}");
917    }
918
919    // Session cache health (#361): answer "is the cache actually engaging?"
920    // without external instrumentation. CEP sessions + the cross-call hit ratio
921    // come from the persistent stats store; `verify-cache` proves it live.
922    let cep = &lean_ctx::core::stats::load().cep;
923    let hit_ratio = if cep.total_cache_reads > 0 {
924        (cep.total_cache_hits as f64 / cep.total_cache_reads as f64) * 100.0
925    } else {
926        0.0
927    };
928    if !json {
929        println!(
930            "  {BOLD}Session cache{RST}  {WHITE}{} sessions{RST}  {DIM}{}/{} reads cached ({hit_ratio:.0}% hit) · prove: lean-ctx verify-cache{RST}",
931            cep.sessions, cep.total_cache_hits, cep.total_cache_reads
932        );
933    }
934
935    // The board counted exactly what it rendered — the displayed ✓/✗ list and
936    // this tally can no longer drift apart (#433).
937    let passed = board.passed;
938    let total = board.total;
939    let needs_attention = total.saturating_sub(passed);
940
941    if json {
942        let output = serde_json::json!({
943            "version": env!("CARGO_PKG_VERSION"),
944            "passed": passed,
945            "total": total,
946            "needs_attention": needs_attention,
947            "checks": board.entries,
948        });
949        println!(
950            "{}",
951            serde_json::to_string_pretty(&output).unwrap_or_default()
952        );
953    } else {
954        println!();
955        println!(
956            "  {BOLD}{WHITE}Summary:{RST}  {GREEN}{passed}{RST}{DIM}/{total}{RST} checks passed"
957        );
958        if needs_attention > 0 {
959            println!(
960                "  {YELLOW}{needs_attention} check(s) need attention.{RST}  Auto-repair what's fixable:  {BOLD}lean-ctx doctor --fix{RST}"
961            );
962        } else {
963            println!("  {GREEN}Everything looks good.{RST}");
964        }
965        println!("  {DIM}LSP servers are optional enhancements (not counted in score){RST}");
966        println!("  {DIM}{}{RST}", lean_ctx::core::integrity::origin_line());
967
968        lean_ctx::core::version_check::check_background();
969        if let Some(banner) = lean_ctx::core::version_check::get_update_banner() {
970            println!();
971            println!("{banner}");
972        }
973    }
974
975    needs_attention
976}
977
978pub fn run_compact() {
979    let (passed, total) = compact_score();
980    print_compact_status(passed, total);
981}
982
983pub fn run_cli(args: &[String]) -> i32 {
984    let (sub, rest) = match args.first().map(String::as_str) {
985        Some("integrations") => ("integrations", &args[1..]),
986        Some("overhead") => ("overhead", &args[1..]),
987        Some("lint-context") => ("lint-context", &args[1..]),
988        _ => ("", args),
989    };
990
991    let fix = rest.iter().any(|a| a == "--fix");
992    let json = rest.iter().any(|a| a == "--json");
993    let gate = rest.iter().any(|a| a == "--gate");
994    let migrate_check = rest.iter().any(|a| a == "--migrate-check");
995    let help = rest.iter().any(|a| a == "--help" || a == "-h");
996
997    if help {
998        println!("Usage:");
999        println!("  lean-ctx doctor");
1000        println!(
1001            "  lean-ctx doctor overhead [--json] [--gate]   Fixed context cost per session (--gate: non-zero exit when over [context] budget_tokens)"
1002        );
1003        println!(
1004            "  lean-ctx doctor lint-context [--json]   Lint injected context for low-signal/dup lines"
1005        );
1006        println!("  lean-ctx doctor integrations [--json]");
1007        println!("  lean-ctx doctor --fix [--json]");
1008        println!("  lean-ctx doctor --migrate-check [--json]");
1009        println!();
1010        println!(
1011            "Exit status: 0 when every scored check passes (optional items and a not-yet-set-up install never fail), 1 when a check needs attention."
1012        );
1013        return 0;
1014    }
1015
1016    if sub == "overhead" {
1017        return overhead::run_overhead(json, gate);
1018    }
1019
1020    if sub == "lint-context" {
1021        return lint_context::run_lint_context(json);
1022    }
1023
1024    if migrate_check {
1025        return migrate::run_migrate_check(json);
1026    }
1027
1028    if sub == "integrations" {
1029        if fix {
1030            let _ = fix::run_fix(&fix::DoctorFixOptions { json: false });
1031        }
1032        return integrations::run_integrations(&integrations::IntegrationsOptions { json });
1033    }
1034
1035    if !fix {
1036        // Non-zero exit when checks need attention so `lean-ctx doctor` works
1037        // as a CI/health gate, not just a pretty printer.
1038        let needs = if json { run_json() } else { run() };
1039        return i32::from(needs > 0);
1040    }
1041
1042    match fix::run_fix(&fix::DoctorFixOptions { json }) {
1043        Ok(code) => code,
1044        Err(e) => {
1045            tracing::error!("doctor --fix failed: {e}");
1046            2
1047        }
1048    }
1049}
1050
1051pub fn compact_score() -> (u32, u32) {
1052    let mut passed = 0u32;
1053    let total = 6u32;
1054
1055    if resolve_lean_ctx_binary().is_some() || path_in_path_env() {
1056        passed += 1;
1057    }
1058    let lean_dir = lean_ctx::core::data_dir::lean_ctx_data_dir().ok();
1059    if lean_dir.as_ref().is_some_and(|p| p.is_dir()) {
1060        passed += 1;
1061    }
1062    if lean_dir
1063        .as_ref()
1064        .map(|d| d.join("stats.json"))
1065        .and_then(|p| std::fs::metadata(p).ok())
1066        .is_some_and(|m| m.is_file())
1067    {
1068        passed += 1;
1069    }
1070    if shell_aliases_outcome().ok {
1071        passed += 1;
1072    }
1073    if mcp_config_outcome().ok {
1074        passed += 1;
1075    }
1076    if skill_files_outcome().ok {
1077        passed += 1;
1078    }
1079
1080    (passed, total)
1081}
1082
1083pub(super) fn print_compact_status(passed: u32, total: u32) {
1084    let status = if passed == total {
1085        format!("{GREEN}✓ All {total} checks passed{RST}")
1086    } else {
1087        format!("{YELLOW}{passed}/{total} passed{RST} — run {BOLD}lean-ctx doctor{RST} for details")
1088    };
1089    println!("  {status}");
1090}
1091
1092/// One line for a paused config migration (#2175): the stable state, both
1093/// journal files and the action that works in that state.
1094fn config_migration_pause_outcome(config: &std::path::Path) -> Option<Outcome> {
1095    let pause = lean_ctx::core::config::config_migration_pause_status(config)?;
1096    Some(Outcome {
1097        ok: false,
1098        line: format!(
1099            "{BOLD}config migration{RST}  {YELLOW}paused ({}){RST}  {DIM}{} · {}{RST}  {DIM}({}){RST}",
1100            pause.label,
1101            pause.backup.display(),
1102            pause.receipt.display(),
1103            pause.action
1104        ),
1105    })
1106}
1107
1108#[cfg(test)]
1109mod tests {
1110    use super::is_active_shell_impl;
1111    use super::{DaemonAutostart, daemon_outcome, unrecorded_services_outcome};
1112
1113    /// Owner decision 02.11.: services this instance did not record are
1114    /// listed with PID and the exact stop command; nothing when none run.
1115    #[test]
1116    fn daemon_unrecorded_services_line_lists_pids_and_the_stop_command() {
1117        assert!(unrecorded_services_outcome(None).is_none());
1118        let outcome = unrecorded_services_outcome(Some((
1119            "Still running, not started by this instance (left alone): proxy (PID 913).".into(),
1120            "Stop them with: kill 913".into(),
1121        )))
1122        .expect("listed");
1123        assert!(outcome.ok);
1124        assert!(outcome.line.contains("proxy (PID 913)"), "{}", outcome.line);
1125        assert!(outcome.line.contains("kill 913"), "{}", outcome.line);
1126    }
1127
1128    /// #2176: Windows doctor said "not supported on this platform" although
1129    /// the daemon runs there. Every platform reports the real state now.
1130    #[test]
1131    fn daemon_line_reports_real_state_without_autostart_service() {
1132        let running = daemon_outcome(Some(36492), &DaemonAutostart::Unsupported);
1133        assert!(running.ok);
1134        assert!(
1135            running.line.contains("running (PID 36492)"),
1136            "{}",
1137            running.line
1138        );
1139        assert!(!running.line.contains("not supported"));
1140        assert!(!running.line.contains("autostart"));
1141
1142        let stopped = daemon_outcome(None, &DaemonAutostart::Unsupported);
1143        assert!(stopped.line.contains("not running"), "{}", stopped.line);
1144        assert!(stopped.line.contains("lean-ctx daemon start"));
1145        assert!(!stopped.line.contains("daemon enable"), "{}", stopped.line);
1146        assert!(!stopped.line.contains("not supported"));
1147    }
1148
1149    #[test]
1150    fn daemon_line_keeps_autostart_details_where_supported() {
1151        let path = std::path::PathBuf::from("/x/com.leanctx.daemon.plist");
1152        let on = daemon_outcome(Some(7), &DaemonAutostart::On(Some(path)));
1153        assert!(on.line.contains("running (PID 7)"));
1154        assert!(
1155            on.line
1156                .contains("autostart: on — /x/com.leanctx.daemon.plist")
1157        );
1158        let restarting = daemon_outcome(None, &DaemonAutostart::On(None));
1159        assert!(restarting.line.contains("autostart enabled, will restart"));
1160        let off = daemon_outcome(None, &DaemonAutostart::Off);
1161        assert!(off.line.contains("lean-ctx daemon enable"));
1162    }
1163
1164    #[test]
1165    fn doctor_reports_a_paused_config_migration_with_files_and_action() {
1166        let _isolated = lean_ctx::core::data_dir::isolated_data_dir();
1167        let path = lean_ctx::core::config::Config::path().expect("isolated config path");
1168        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1169        // Unique bytes: `Config::load` caches by content hash.
1170        std::fs::write(
1171            &path,
1172            "# doctor paused-migration test\nterse_agent = \"full\"\n",
1173        )
1174        .unwrap();
1175        assert!(super::config_migration_pause_outcome(&path).is_none());
1176
1177        // A journal that cannot be verified pauses the migration on load.
1178        let backup = path.with_file_name("config.toml.v4-migration.bak");
1179        let receipt = path.with_file_name("config.toml.v4-migration.json");
1180        std::fs::write(&backup, "tampered = true\n").unwrap();
1181        std::fs::write(&receipt, "{ not json").unwrap();
1182        let _ = lean_ctx::core::config::Config::load();
1183
1184        let outcome =
1185            super::config_migration_pause_outcome(&path).expect("doctor reports the pause");
1186        assert!(!outcome.ok);
1187        assert!(
1188            outcome.line.contains("receipt-unverifiable"),
1189            "{}",
1190            outcome.line
1191        );
1192        assert!(
1193            outcome.line.contains("config.toml.v4-migration.bak"),
1194            "{}",
1195            outcome.line
1196        );
1197        assert!(
1198            outcome.line.contains("config.toml.v4-migration.json"),
1199            "{}",
1200            outcome.line
1201        );
1202        assert!(
1203            outcome.line.contains("move both out of"),
1204            "{}",
1205            outcome.line
1206        );
1207    }
1208
1209    // Mirrors the inline classification in `checks::capacity_warnings`: a store at
1210    // or below its cap is at most a WARN (healthy, eviction keeps it there); only
1211    // a store *over* cap is CRIT (eviction is not keeping up).
1212    fn make_capacity_check(name: &str, current: usize, limit: usize) -> Option<(bool, String)> {
1213        if limit == 0 {
1214            return None;
1215        }
1216        let pct = (current as f64 / limit as f64 * 100.0) as u32;
1217        if pct > 100 {
1218            Some((true, format!("{name}: {current}/{limit} ({pct}%)")))
1219        } else if pct >= 80 {
1220            Some((false, format!("{name}: {current}/{limit} ({pct}%)")))
1221        } else {
1222            None
1223        }
1224    }
1225
1226    #[test]
1227    fn capacity_below_80_no_warning() {
1228        assert!(make_capacity_check("facts", 100, 200).is_none());
1229        assert!(make_capacity_check("facts", 159, 200).is_none());
1230    }
1231
1232    #[test]
1233    fn capacity_at_80_yellow_warning() {
1234        let result = make_capacity_check("facts", 160, 200);
1235        assert!(result.is_some());
1236        let (critical, msg) = result.unwrap();
1237        assert!(!critical);
1238        assert!(msg.contains("160/200"));
1239        assert!(msg.contains("80%"));
1240    }
1241
1242    #[test]
1243    fn capacity_at_92_yellow_warning() {
1244        let result = make_capacity_check("facts", 185, 200);
1245        assert!(result.is_some());
1246        let (critical, msg) = result.unwrap();
1247        assert!(!critical);
1248        assert!(msg.contains("185/200"));
1249        assert!(msg.contains("92%"));
1250    }
1251
1252    #[test]
1253    fn capacity_at_95_is_warning_not_critical() {
1254        let result = make_capacity_check("facts", 190, 200);
1255        assert!(result.is_some());
1256        let (critical, msg) = result.unwrap();
1257        assert!(!critical, "95% is full-but-healthy, not over cap");
1258        assert!(msg.contains("190/200"));
1259        assert!(msg.contains("95%"));
1260    }
1261
1262    #[test]
1263    fn capacity_at_100_is_warning_not_critical() {
1264        // A store exactly at its cap is healthy — eviction keeps it there.
1265        let result = make_capacity_check("facts", 200, 200);
1266        assert!(result.is_some());
1267        let (critical, _) = result.unwrap();
1268        assert!(!critical);
1269    }
1270
1271    #[test]
1272    fn capacity_over_100_is_critical() {
1273        // Genuinely over cap => eviction is not keeping up (regression guard for
1274        // the 206/200 "CRIT" that fired before lifecycle eviction was fixed).
1275        let result = make_capacity_check("facts", 206, 200);
1276        assert!(result.is_some());
1277        let (critical, msg) = result.unwrap();
1278        assert!(critical);
1279        assert!(msg.contains("206/200"));
1280        assert!(msg.contains("103%"));
1281    }
1282
1283    #[test]
1284    fn capacity_zero_limit_skipped() {
1285        assert!(make_capacity_check("facts", 50, 0).is_none());
1286    }
1287
1288    #[test]
1289    fn bashrc_active_on_non_windows_when_shell_empty() {
1290        assert!(is_active_shell_impl("~/.bashrc", "", false, false));
1291    }
1292
1293    #[test]
1294    fn bashrc_not_active_on_windows_when_shell_empty() {
1295        assert!(!is_active_shell_impl("~/.bashrc", "", true, false));
1296    }
1297
1298    #[test]
1299    fn bashrc_active_when_shell_contains_bash_on_linux() {
1300        assert!(is_active_shell_impl(
1301            "~/.bashrc",
1302            "/usr/bin/bash",
1303            false,
1304            false
1305        ));
1306    }
1307
1308    #[test]
1309    fn bashrc_not_active_on_windows_even_with_bash_in_shell_env() {
1310        let _env_lock = lean_ctx::core::data_dir::test_env_lock();
1311        // Issue #214: On Windows, Git Bash sets $SHELL globally to bash.exe.
1312        // .bashrc should NOT be flagged on Windows unless actually inside bash.
1313        lean_ctx::test_env::remove_var("BASH_VERSION");
1314        assert!(!is_active_shell_impl(
1315            "~/.bashrc",
1316            "C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe",
1317            true,
1318            false,
1319        ));
1320    }
1321
1322    #[test]
1323    fn bashrc_not_active_on_windows_powershell_even_with_bash_in_shell() {
1324        assert!(!is_active_shell_impl(
1325            "~/.bashrc",
1326            "C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe",
1327            true,
1328            true,
1329        ));
1330    }
1331
1332    #[test]
1333    fn bashrc_not_active_on_windows_powershell_with_empty_shell() {
1334        assert!(!is_active_shell_impl("~/.bashrc", "", true, true));
1335    }
1336
1337    #[test]
1338    fn zshrc_unaffected_by_powershell_flag() {
1339        assert!(is_active_shell_impl("~/.zshrc", "/bin/zsh", false, false));
1340        assert!(is_active_shell_impl("~/.zshrc", "/bin/zsh", true, true));
1341    }
1342
1343    #[test]
1344    fn bashrc_not_active_on_windows_without_powershell_detection() {
1345        let _env_lock = lean_ctx::core::data_dir::test_env_lock();
1346        // Windows + $SHELL=bash but NOT in actual bash session (no BASH_VERSION).
1347        // This is the exact scenario from issue #214: Git Bash sets $SHELL globally.
1348        lean_ctx::test_env::remove_var("BASH_VERSION");
1349        assert!(!is_active_shell_impl(
1350            "~/.bashrc",
1351            "/usr/bin/bash",
1352            true,
1353            false,
1354        ));
1355    }
1356
1357    #[test]
1358    fn bashrc_active_on_linux() {
1359        assert!(is_active_shell_impl("~/.bashrc", "/bin/bash", false, false));
1360        assert!(is_active_shell_impl("~/.bashrc", "", false, false));
1361    }
1362}