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