1mod 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#[derive(Default)]
44struct Scoreboard {
45 passed: u32,
46 total: u32,
47}
48
49impl Scoreboard {
50 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 #[allow(clippy::unused_self)]
66 fn info(&self, outcome: &Outcome) {
67 print_check(outcome);
68 }
69}
70
71pub fn run() {
73 let mut board = Scoreboard::default();
74
75 println!("{BOLD}{WHITE}lean-ctx doctor{RST} {DIM}diagnostics{RST}\n");
76
77 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 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 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 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 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 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 let allowlist_outcome = shell_allowlist_outcome();
241 board.check(&allowlist_outcome);
242
243 let path_jail = path_jail_outcome();
245 board.check(&path_jail);
246
247 let passthrough_outcome = compact_format_passthrough_outcome();
249 board.check(&passthrough_outcome);
250
251 let perm_inherit_outcome = permission_inheritance_outcome();
253 board.check(&perm_inherit_outcome);
254
255 let proxy_outcome = proxy_upstream_outcome();
257 board.check(&proxy_outcome);
258
259 let aliases = shell_aliases_outcome();
261 board.check(&aliases);
262
263 let mcp = mcp_config_outcome();
265 board.check(&mcp);
266
267 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 let skill = skill_files_outcome();
275 board.check(&skill);
276
277 let port = port_3333_outcome();
279 board.check(&port);
280
281 #[cfg(unix)]
283 let daemon_outcome = {
284 let autostart = crate::daemon_autostart::is_installed();
285 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 #[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 let provider_outcome = provider_outcome();
371 board.info(&provider_outcome);
372
373 let bridge_outcomes = mcp_bridge_outcomes();
375 for bridge_check in &bridge_outcomes {
376 board.info(bridge_check);
377 }
378
379 let plan_outcomes = plan_mode_outcomes();
381 for plan_check in &plan_outcomes {
382 board.info(plan_check);
383 }
384
385 let session_outcome = session_state_outcome();
387 board.check(&session_outcome);
388
389 let docker_outcomes = docker_env_outcomes();
391 for docker_check in &docker_outcomes {
392 board.check(docker_check);
393 }
394
395 let pi = pi_outcome();
397 if let Some(ref pi_check) = pi {
398 board.check(pi_check);
399 }
400
401 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 let cache_safety = cache_safety_outcome();
422 board.check(&cache_safety);
423
424 let claude_truncation = claude_truncation_outcome();
426 if let Some(ref ct) = claude_truncation {
427 board.check(ct);
428 }
429
430 let codebuddy_truncation = codebuddy_truncation_outcome();
432 if let Some(ref cbt) = codebuddy_truncation {
433 board.check(cbt);
434 }
435
436 let bm25_health = bm25_cache_health_outcome();
438 board.check(&bm25_health);
439
440 let semantic_index = semantic_index_outcome();
443 if let Some(ref check) = semantic_index {
444 board.check(check);
445 }
446
447 let archive_footprint = archive_footprint_outcome();
449 board.check(&archive_footprint);
450
451 let mem_profile = memory_profile_outcome();
453 board.check(&mem_profile);
454
455 let mem_cleanup = memory_cleanup_outcome();
457 board.check(&mem_cleanup);
458
459 let ram_outcome = ram_guardian_outcome();
461 board.check(&ram_outcome);
462
463 let cap_warnings = capacity_warnings();
465 for cw in &cap_warnings {
466 board.check(cw);
467 }
468
469 let orphan_outcome = orphaned_knowledge_outcome();
471 board.check(&orphan_outcome);
472
473 let proxy_health = proxy_health_outcome();
475 board.check(&proxy_health);
476
477 let stale_env = stale_proxy_env_outcome();
479 if let Some(ref check) = stale_env {
480 board.check(check);
481 }
482
483 let subscription_conflict = proxy_subscription_conflict_outcome();
485 if let Some(ref check) = subscription_conflict {
486 board.check(check);
487 }
488
489 let deprecation_check = deprecations::deprecations_outcome();
492 board.check(&deprecation_check);
493
494 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 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 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 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 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 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 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 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 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 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}