1mod 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
21pub 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#[derive(Default)]
57struct Scoreboard {
58 passed: u32,
59 total: u32,
60}
61
62impl Scoreboard {
63 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 #[allow(clippy::unused_self)]
79 fn info(&self, outcome: &Outcome) {
80 print_check(outcome);
81 }
82}
83
84pub fn run() -> u32 {
89 let mut board = Scoreboard::default();
90
91 println!("{BOLD}{WHITE}lean-ctx doctor{RST} {DIM}diagnostics{RST}\n");
92
93 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 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 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 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 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 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 {
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 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 board.check(&config_parity_outcome());
295
296 let allowlist_outcome = shell_allowlist_outcome();
298 board.check(&allowlist_outcome);
299
300 let path_jail = path_jail_outcome();
302 board.check(&path_jail);
303
304 let workspace_trust = workspace_trust_outcome();
306 board.check(&workspace_trust);
307
308 let secret_detection = secret_detection_outcome();
311 board.check(&secret_detection);
312
313 let cognition = cognition_activity_outcome();
315 board.check(&cognition);
316
317 let passthrough_outcome = compact_format_passthrough_outcome();
319 board.check(&passthrough_outcome);
320
321 let perm_inherit_outcome = permission_inheritance_outcome();
323 board.check(&perm_inherit_outcome);
324
325 let proxy_outcome = proxy_upstream_outcome();
327 board.check(&proxy_outcome);
328
329 let aliases = shell_aliases_outcome();
331 board.check(&aliases);
332
333 let mcp = mcp_config_outcome();
335 board.check(&mcp);
336 let user_scope_mcp_locations = dirs::home_dir()
337 .map(|home| lean_ctx_mcp_location_names(&home))
338 .unwrap_or_default();
339
340 if let Some(wsl_hint) = wsl_vscode_mcp_outcome() {
342 board.check(&wsl_hint);
343 }
344
345 let workspace_scope = workspace_scope::workspace_scope_outcome(&user_scope_mcp_locations);
347 if let Some(ref ws) = workspace_scope {
348 board.check(ws);
349 }
350
351 let skill = skill_files_outcome();
353 board.check(&skill);
354
355 let port = port_3333_outcome();
357 board.check(&port);
358
359 #[cfg(unix)]
361 let daemon_outcome = {
362 let autostart = crate::daemon_autostart::is_installed();
363 let autostart_tag = if autostart {
366 match crate::daemon_autostart::service_file_path() {
367 Some(p) => format!(" {DIM}[autostart: on — {}]{RST}", p.display()),
368 None => format!(" {DIM}[autostart: on]{RST}"),
369 }
370 } else {
371 String::new()
372 };
373 if crate::daemon::is_daemon_running() {
374 let pid_path = crate::daemon::daemon_pid_path();
375 let pid_str = std::fs::read_to_string(&pid_path).unwrap_or_default();
376 Outcome {
377 ok: true,
378 line: format!(
379 "{BOLD}Daemon{RST} {GREEN}running (PID {}){RST}{autostart_tag}",
380 pid_str.trim()
381 ),
382 }
383 } else {
384 let hint = if autostart {
385 format!("{DIM}(autostart enabled, will restart){RST}")
386 } else {
387 format!("{DIM}(run: lean-ctx daemon start or: lean-ctx daemon enable){RST}")
388 };
389 Outcome {
390 ok: true,
391 line: format!("{BOLD}Daemon{RST} {YELLOW}not running{RST} {hint}"),
392 }
393 }
394 };
395 #[cfg(not(unix))]
396 let daemon_outcome = Outcome {
397 ok: true,
398 line: format!("{BOLD}Daemon{RST} {DIM}not supported on this platform{RST}"),
399 };
400 board.check(&daemon_outcome);
401
402 #[cfg(target_os = "linux")]
404 {
405 if let Ok(o) = std::process::Command::new("systemctl")
406 .args(["--user", "is-active", "lean-ctx-daemon.service"])
407 .output()
408 {
409 let state = String::from_utf8_lossy(&o.stdout).trim().to_string();
410 if state != "active" {
411 println!(
412 " {DIM} systemd unit state: {YELLOW}{state}{RST}{DIM} (expected: active){RST}"
413 );
414 }
415 }
416 let username = std::env::var("USER")
417 .or_else(|_| std::env::var("LOGNAME"))
418 .unwrap_or_else(|_| "$(whoami)".to_string());
419 if let Ok(o) = std::process::Command::new("loginctl")
420 .args(["show-user", &username, "-p", "Linger", "--value"])
421 .output()
422 {
423 let val = String::from_utf8_lossy(&o.stdout).trim().to_string();
424 if val != "yes" {
425 println!(
426 " {YELLOW}⚠{RST} Linger not enabled — daemon won't start at boot without login"
427 );
428 println!(" {DIM}Fix: loginctl enable-linger {username}{RST}");
429 }
430 }
431 }
432 if let Some(log_path) = crate::core::startup_guard::crash_loop_log_path(
433 crate::core::startup_guard::MCP_PROCESS_NAME,
434 ) && log_path.exists()
435 && let Ok(contents) = std::fs::read_to_string(&log_path)
436 {
437 let lines: Vec<&str> = contents.lines().collect();
438 if lines.len() >= 5 {
439 println!(
440 " {YELLOW}⚠{RST} Crash-loop log: {} recent restarts {DIM}({}){RST}",
441 lines.len(),
442 display_user_path(&log_path)
443 );
444 }
445 }
446
447 let provider_outcome = provider_outcome();
449 board.info(&provider_outcome);
450
451 let bridge_outcomes = mcp_bridge_outcomes();
453 for bridge_check in &bridge_outcomes {
454 board.info(bridge_check);
455 }
456
457 let plan_outcomes = plan_mode_outcomes();
459 for plan_check in &plan_outcomes {
460 board.info(plan_check);
461 }
462
463 let session_outcome = session_state_outcome();
465 board.check(&session_outcome);
466
467 let docker_outcomes = docker_env_outcomes();
469 for docker_check in &docker_outcomes {
470 board.check(docker_check);
471 }
472
473 let pi = pi_outcome();
475 if let Some(ref pi_check) = pi {
476 board.check(pi_check);
477 }
478
479 let integrity = crate::core::integrity::check();
481 let integrity_ok = integrity.seed_ok && integrity.origin_ok;
482 let integrity_line = if integrity_ok {
483 format!(
484 "{BOLD}Build origin{RST} {GREEN}official{RST} {DIM}{}{RST}",
485 integrity.repo
486 )
487 } else {
488 format!(
489 "{BOLD}Build origin{RST} {RED}MODIFIED REDISTRIBUTION{RST} {YELLOW}pkg={}, repo={}{RST}",
490 integrity.pkg_name, integrity.repo
491 )
492 };
493 board.check(&Outcome {
494 ok: integrity_ok,
495 line: integrity_line,
496 });
497
498 let cache_safety = cache_safety_outcome();
500 board.check(&cache_safety);
501
502 let claude_truncation = claude_truncation_outcome();
504 if let Some(ref ct) = claude_truncation {
505 board.check(ct);
506 }
507
508 let codebuddy_truncation = codebuddy_truncation_outcome();
510 if let Some(ref cbt) = codebuddy_truncation {
511 board.check(cbt);
512 }
513
514 let bm25_health = bm25_cache_health_outcome();
516 board.check(&bm25_health);
517
518 let stats_quarantine = stats_quarantine_outcome();
521 board.check(&stats_quarantine);
522
523 let semantic_index = semantic_index_outcome();
526 if let Some(ref check) = semantic_index {
527 board.check(check);
528 }
529
530 let archive_footprint = archive_footprint_outcome();
532 board.check(&archive_footprint);
533
534 let mem_profile = memory_profile_outcome();
536 board.check(&mem_profile);
537
538 let mem_cleanup = memory_cleanup_outcome();
540 board.check(&mem_cleanup);
541
542 let ram_outcome = ram_guardian_outcome();
544 board.check(&ram_outcome);
545
546 let cap_warnings = capacity_warnings();
548 for cw in &cap_warnings {
549 board.check(cw);
550 }
551
552 let orphan_outcome = orphaned_knowledge_outcome();
554 board.check(&orphan_outcome);
555
556 let proxy_health = proxy_health_outcome();
558 board.check(&proxy_health);
559
560 let upstream_drift = proxy_upstream_drift_outcome();
564 if let Some(ref check) = upstream_drift {
565 board.check(check);
566 }
567
568 let stale_env = stale_proxy_env_outcome();
570 if let Some(ref check) = stale_env {
571 board.check(check);
572 }
573
574 let subscription_conflict = proxy_subscription_conflict_outcome();
576 if let Some(ref check) = subscription_conflict {
577 board.check(check);
578 }
579
580 let deprecation_check = deprecations::deprecations_outcome();
583 board.check(&deprecation_check);
584
585 let mcp_cwd = mcp_server_cwd_outcome();
587 board.check(&mcp_cwd);
588
589 println!("\n {BOLD}{WHITE}LSP (optional — for ctx_refactor):{RST}");
591 let lsp_outcomes = lsp_server_outcomes();
592 for lsp_check in &lsp_outcomes {
593 board.info(lsp_check);
594 }
595
596 let cfg = crate::core::config::Config::load();
598 let shadow_line = if cfg.shadow_mode {
599 format!(
600 "{BOLD}Shadow mode{RST} {GREEN}active{RST} {DIM}(native tools denied → ctx_* mandatory){RST}"
601 )
602 } else {
603 format!(
604 "{BOLD}Shadow mode{RST} {DIM}disabled{RST} {DIM}(enable: lean-ctx config set shadow_mode true){RST}"
605 )
606 };
607 println!(" {shadow_line}");
608
609 let tool_profile_line = if crate::server::tool_visibility::explicit_profile(&cfg) {
615 let profile = crate::core::tool_profiles::ToolProfile::from_config(&cfg);
616 format!(
617 "{BOLD}Tool profile{RST} {WHITE}{profile}{RST} {DIM}{} + ctx_call gateway{RST}",
618 profile.description()
619 )
620 } else {
621 let lazy_count = crate::tool_defs::core_tool_names().len();
622 format!(
623 "{BOLD}Tool profile{RST} {WHITE}lean (default){RST} {DIM}{lazy_count} lazy-core tools advertised + ctx_call gateway{RST}"
624 )
625 };
626 println!(" {tool_profile_line}");
627
628 let cep = &crate::core::stats::load().cep;
632 let hit_ratio = if cep.total_cache_reads > 0 {
633 (cep.total_cache_hits as f64 / cep.total_cache_reads as f64) * 100.0
634 } else {
635 0.0
636 };
637 println!(
638 " {BOLD}Session cache{RST} {WHITE}{} sessions{RST} {DIM}{}/{} reads cached ({hit_ratio:.0}% hit) · prove: lean-ctx verify-cache{RST}",
639 cep.sessions, cep.total_cache_hits, cep.total_cache_reads
640 );
641
642 let passed = board.passed;
645 let total = board.total;
646 let needs_attention = total.saturating_sub(passed);
647 println!();
648 println!(" {BOLD}{WHITE}Summary:{RST} {GREEN}{passed}{RST}{DIM}/{total}{RST} checks passed");
649 if needs_attention > 0 {
650 println!(
651 " {YELLOW}{needs_attention} check(s) need attention.{RST} Auto-repair what's fixable: {BOLD}lean-ctx doctor --fix{RST}"
652 );
653 } else {
654 println!(" {GREEN}Everything looks good.{RST}");
655 }
656 println!(" {DIM}LSP servers are optional enhancements (not counted in score){RST}");
657 println!(" {DIM}{}{RST}", crate::core::integrity::origin_line());
658
659 crate::core::version_check::check_background();
664 if let Some(banner) = crate::core::version_check::get_update_banner() {
665 println!();
666 println!("{banner}");
667 }
668
669 needs_attention
670}
671
672pub fn run_compact() {
673 let (passed, total) = compact_score();
674 print_compact_status(passed, total);
675}
676
677pub fn run_cli(args: &[String]) -> i32 {
678 let (sub, rest) = match args.first().map(String::as_str) {
679 Some("integrations") => ("integrations", &args[1..]),
680 Some("overhead") => ("overhead", &args[1..]),
681 Some("lint-context") => ("lint-context", &args[1..]),
682 _ => ("", args),
683 };
684
685 let fix = rest.iter().any(|a| a == "--fix");
686 let json = rest.iter().any(|a| a == "--json");
687 let gate = rest.iter().any(|a| a == "--gate");
688 let migrate_check = rest.iter().any(|a| a == "--migrate-check");
689 let help = rest.iter().any(|a| a == "--help" || a == "-h");
690
691 if help {
692 println!("Usage:");
693 println!(" lean-ctx doctor");
694 println!(
695 " lean-ctx doctor overhead [--json] [--gate] Fixed context cost per session (--gate: non-zero exit when over [context] budget_tokens)"
696 );
697 println!(
698 " lean-ctx doctor lint-context [--json] Lint injected context for low-signal/dup lines"
699 );
700 println!(" lean-ctx doctor integrations [--json]");
701 println!(" lean-ctx doctor --fix [--json]");
702 println!(" lean-ctx doctor --migrate-check [--json]");
703 return 0;
704 }
705
706 if sub == "overhead" {
707 return overhead::run_overhead(json, gate);
708 }
709
710 if sub == "lint-context" {
711 return lint_context::run_lint_context(json);
712 }
713
714 if migrate_check {
715 return migrate::run_migrate_check(json);
716 }
717
718 if sub == "integrations" {
719 if fix {
720 let _ = fix::run_fix(&fix::DoctorFixOptions { json: false });
721 }
722 return integrations::run_integrations(&integrations::IntegrationsOptions { json });
723 }
724
725 if !fix {
726 return i32::from(run() > 0);
729 }
730
731 match fix::run_fix(&fix::DoctorFixOptions { json }) {
732 Ok(code) => code,
733 Err(e) => {
734 tracing::error!("doctor --fix failed: {e}");
735 2
736 }
737 }
738}
739
740pub fn compact_score() -> (u32, u32) {
741 let mut passed = 0u32;
742 let total = 6u32;
743
744 if resolve_lean_ctx_binary().is_some() || path_in_path_env() {
745 passed += 1;
746 }
747 let lean_dir = crate::core::data_dir::lean_ctx_data_dir().ok();
748 if lean_dir.as_ref().is_some_and(|p| p.is_dir()) {
749 passed += 1;
750 }
751 if lean_dir
752 .as_ref()
753 .map(|d| d.join("stats.json"))
754 .and_then(|p| std::fs::metadata(p).ok())
755 .is_some_and(|m| m.is_file())
756 {
757 passed += 1;
758 }
759 if shell_aliases_outcome().ok {
760 passed += 1;
761 }
762 if mcp_config_outcome().ok {
763 passed += 1;
764 }
765 if skill_files_outcome().ok {
766 passed += 1;
767 }
768
769 (passed, total)
770}
771
772pub(super) fn print_compact_status(passed: u32, total: u32) {
773 let status = if passed == total {
774 format!("{GREEN}✓ All {total} checks passed{RST}")
775 } else {
776 format!("{YELLOW}{passed}/{total} passed{RST} — run {BOLD}lean-ctx doctor{RST} for details")
777 };
778 println!(" {status}");
779}
780
781#[cfg(test)]
782mod tests {
783 use super::is_active_shell_impl;
784
785 fn make_capacity_check(name: &str, current: usize, limit: usize) -> Option<(bool, String)> {
789 if limit == 0 {
790 return None;
791 }
792 let pct = (current as f64 / limit as f64 * 100.0) as u32;
793 if pct > 100 {
794 Some((true, format!("{name}: {current}/{limit} ({pct}%)")))
795 } else if pct >= 80 {
796 Some((false, format!("{name}: {current}/{limit} ({pct}%)")))
797 } else {
798 None
799 }
800 }
801
802 #[test]
803 fn capacity_below_80_no_warning() {
804 assert!(make_capacity_check("facts", 100, 200).is_none());
805 assert!(make_capacity_check("facts", 159, 200).is_none());
806 }
807
808 #[test]
809 fn capacity_at_80_yellow_warning() {
810 let result = make_capacity_check("facts", 160, 200);
811 assert!(result.is_some());
812 let (critical, msg) = result.unwrap();
813 assert!(!critical);
814 assert!(msg.contains("160/200"));
815 assert!(msg.contains("80%"));
816 }
817
818 #[test]
819 fn capacity_at_92_yellow_warning() {
820 let result = make_capacity_check("facts", 185, 200);
821 assert!(result.is_some());
822 let (critical, msg) = result.unwrap();
823 assert!(!critical);
824 assert!(msg.contains("185/200"));
825 assert!(msg.contains("92%"));
826 }
827
828 #[test]
829 fn capacity_at_95_is_warning_not_critical() {
830 let result = make_capacity_check("facts", 190, 200);
831 assert!(result.is_some());
832 let (critical, msg) = result.unwrap();
833 assert!(!critical, "95% is full-but-healthy, not over cap");
834 assert!(msg.contains("190/200"));
835 assert!(msg.contains("95%"));
836 }
837
838 #[test]
839 fn capacity_at_100_is_warning_not_critical() {
840 let result = make_capacity_check("facts", 200, 200);
842 assert!(result.is_some());
843 let (critical, _) = result.unwrap();
844 assert!(!critical);
845 }
846
847 #[test]
848 fn capacity_over_100_is_critical() {
849 let result = make_capacity_check("facts", 206, 200);
852 assert!(result.is_some());
853 let (critical, msg) = result.unwrap();
854 assert!(critical);
855 assert!(msg.contains("206/200"));
856 assert!(msg.contains("103%"));
857 }
858
859 #[test]
860 fn capacity_zero_limit_skipped() {
861 assert!(make_capacity_check("facts", 50, 0).is_none());
862 }
863
864 #[test]
865 fn bashrc_active_on_non_windows_when_shell_empty() {
866 assert!(is_active_shell_impl("~/.bashrc", "", false, false));
867 }
868
869 #[test]
870 fn bashrc_not_active_on_windows_when_shell_empty() {
871 assert!(!is_active_shell_impl("~/.bashrc", "", true, false));
872 }
873
874 #[test]
875 fn bashrc_active_when_shell_contains_bash_on_linux() {
876 assert!(is_active_shell_impl(
877 "~/.bashrc",
878 "/usr/bin/bash",
879 false,
880 false
881 ));
882 }
883
884 #[test]
885 fn bashrc_not_active_on_windows_even_with_bash_in_shell_env() {
886 crate::test_env::remove_var("BASH_VERSION");
889 assert!(!is_active_shell_impl(
890 "~/.bashrc",
891 "C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe",
892 true,
893 false,
894 ));
895 }
896
897 #[test]
898 fn bashrc_not_active_on_windows_powershell_even_with_bash_in_shell() {
899 assert!(!is_active_shell_impl(
900 "~/.bashrc",
901 "C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe",
902 true,
903 true,
904 ));
905 }
906
907 #[test]
908 fn bashrc_not_active_on_windows_powershell_with_empty_shell() {
909 assert!(!is_active_shell_impl("~/.bashrc", "", true, true));
910 }
911
912 #[test]
913 fn zshrc_unaffected_by_powershell_flag() {
914 assert!(is_active_shell_impl("~/.zshrc", "/bin/zsh", false, false));
915 assert!(is_active_shell_impl("~/.zshrc", "/bin/zsh", true, true));
916 }
917
918 #[test]
919 fn bashrc_not_active_on_windows_without_powershell_detection() {
920 crate::test_env::remove_var("BASH_VERSION");
923 assert!(!is_active_shell_impl(
924 "~/.bashrc",
925 "/usr/bin/bash",
926 true,
927 false,
928 ));
929 }
930
931 #[test]
932 fn bashrc_active_on_linux() {
933 assert!(is_active_shell_impl("~/.bashrc", "/bin/bash", false, false));
934 assert!(is_active_shell_impl("~/.bashrc", "", false, false));
935 }
936}