1macro_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
36pub 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
64enum DaemonAutostart {
66 Unsupported,
69 Off,
70 On(Option<std::path::PathBuf>),
72}
73
74fn 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
86fn 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#[derive(Default)]
120struct Scoreboard {
121 passed: u32,
122 total: u32,
123 json_mode: bool,
124 entries: Vec<JsonCheck>,
125}
126
127#[derive(Default, serde::Serialize)]
129struct JsonCheck {
130 ok: bool,
131 name: String,
132 scored: bool,
133}
134
135fn strip_ansi(s: &str) -> String {
136 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
153pub(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 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 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 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
215fn 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
274pub fn run() -> u32 {
279 run_inner(false)
280}
281
282pub 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 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 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 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 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 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 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 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 {
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 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 if let Some(outcome) = config_path
503 .as_deref()
504 .and_then(config_migration_pause_outcome)
505 {
506 board.check(&outcome);
507 }
508
509 board.check(&config_parity_outcome());
513 board.check(&project_pin_outcome());
514
515 let allowlist_outcome = shell_allowlist_outcome();
517 board.check(&allowlist_outcome);
518
519 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 let path_jail = path_jail_outcome();
530 board.check(&path_jail);
531
532 let workspace_trust = workspace_trust_outcome();
534 board.check(&workspace_trust);
535
536 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 if let Some(managed_bins) = managed_addon_binaries_outcome() {
547 board.check(&managed_bins);
548 }
549
550 if let Some(managed_ort) = managed_ort_outcome() {
553 board.check(&managed_ort);
554 }
555
556 let cognition = cognition_activity_outcome();
558 board.check(&cognition);
559
560 let passthrough_outcome = compact_format_passthrough_outcome();
562 board.check(&passthrough_outcome);
563
564 let perm_inherit_outcome = permission_inheritance_outcome();
566 board.check(&perm_inherit_outcome);
567
568 let proxy_outcome = proxy_upstream_outcome();
570 board.check(&proxy_outcome);
571
572 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 let aliases = shell_aliases_outcome();
597 setup_item(&mut board, &aliases);
598
599 let agent_aliases = skip_agent_aliases_outcome();
601 board.check(&agent_aliases);
602
603 let mcp = mcp_config_outcome();
605 setup_item(&mut board, &mcp);
606 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 if let Some(wsl_hint) = wsl_vscode_mcp_outcome() {
618 board.check(&wsl_hint);
619 }
620
621 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 let skill = skill_files_outcome();
629 setup_item(&mut board, &skill);
630
631 board.check(&overhead::rules_channels_outcome());
633
634 if let Some(claude_mod) = checks::claude_mod_outcome() {
636 board.check(&claude_mod);
637 }
638
639 if let Some(hive_policy) = checks::hive_policy_outcome() {
641 board.info(&hive_policy);
642 }
643
644 let output_triage = output_triage_outcome();
647 board.check(&output_triage);
648
649 let port = port_3333_outcome();
651 board.check(&port);
652
653 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 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 for note in daemon_diagnostic_notes() {
677 board.note(¬e);
678 }
679
680 let provider_outcome = provider_outcome();
682 board.info(&provider_outcome);
683
684 let bridge_outcomes = mcp_bridge_outcomes();
686 for bridge_check in &bridge_outcomes {
687 board.info(bridge_check);
688 }
689
690 let skew_outcomes = version_skew_outcomes();
692 for skew_check in &skew_outcomes {
693 board.check(&skew_check);
694 }
695
696 let plan_outcomes = plan_mode_outcomes();
698 for plan_check in &plan_outcomes {
699 board.info(plan_check);
700 }
701
702 let session_outcome = session_state_outcome();
704 board.check(&session_outcome);
705
706 let docker_outcomes = docker_env_outcomes();
708 for docker_check in &docker_outcomes {
709 board.check(docker_check);
710 }
711
712 let pi = pi_outcome();
714 if let Some(ref pi_check) = pi {
715 board.check(pi_check);
716 }
717
718 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 let cache_safety = cache_safety_outcome();
739 board.check(&cache_safety);
740
741 let claude_truncation = claude_truncation_outcome();
743 if let Some(ref ct) = claude_truncation {
744 board.check(ct);
745 }
746
747 let codebuddy_truncation = codebuddy_truncation_outcome();
749 if let Some(ref cbt) = codebuddy_truncation {
750 board.check(cbt);
751 }
752
753 if let Some(ref addons) = addons_loaded_outcome() {
757 board.check(addons);
758 }
759
760 let bm25_health = bm25_cache_health_outcome();
762 board.check(&bm25_health);
763
764 let stats_quarantine = stats_quarantine_outcome();
767 board.check(&stats_quarantine);
768
769 for check in search_index_outcomes() {
773 board.check(&check);
774 }
775
776 let archive_footprint = archive_footprint_outcome();
778 board.check(&archive_footprint);
779
780 let mem_profile = memory_profile_outcome();
782 board.check(&mem_profile);
783
784 let mem_cleanup = memory_cleanup_outcome();
786 board.check(&mem_cleanup);
787
788 let ram_outcome = ram_guardian_outcome();
790 board.check(&ram_outcome);
791
792 let cap_warnings = capacity_warnings();
794 for cw in &cap_warnings {
795 board.check(cw);
796 }
797
798 let orphan_outcome = orphaned_knowledge_outcome();
800 board.check(&orphan_outcome);
801
802 let proxy_health = proxy_health_outcome();
804 board.check(&proxy_health);
805
806 let upstream_drift = proxy_upstream_drift_outcome();
810 if let Some(ref check) = upstream_drift {
811 board.check(check);
812 }
813
814 let stale_env = stale_proxy_env_outcome();
816 if let Some(ref check) = stale_env {
817 board.check(check);
818 }
819
820 let subscription_conflict = proxy_subscription_conflict_outcome();
822 if let Some(ref check) = subscription_conflict {
823 board.check(check);
824 }
825
826 if let Some(ref check) = removed_routing_tiers_outcome() {
828 board.check(check);
829 }
830
831 let coverage_check = gateway_coverage_outcome();
834 board.check(&coverage_check);
835
836 let deprecation_check = deprecations::deprecations_outcome();
839 board.check(&deprecation_check);
840
841 let mcp_cwd = mcp_server_cwd_outcome();
843 board.check(&mcp_cwd);
844
845 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 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 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 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 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 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 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
1092fn 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 #[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 #[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 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 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 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 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 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 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 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}