1mod checks;
4mod common;
5mod fix;
6mod integrations;
7mod workspace_scope;
8
9#[allow(clippy::wildcard_imports)]
10use checks::*;
11#[allow(clippy::wildcard_imports)]
12use common::*;
13
14pub(super) const GREEN: &str = "\x1b[32m";
15
16pub(super) const RED: &str = "\x1b[31m";
17
18pub(super) const BOLD: &str = "\x1b[1m";
19
20pub(super) const RST: &str = "\x1b[0m";
21
22pub(super) const DIM: &str = "\x1b[2m";
23
24pub(super) const WHITE: &str = "\x1b[97m";
25
26pub(super) const YELLOW: &str = "\x1b[33m";
27
28pub(super) struct Outcome {
29 pub ok: bool,
30 pub line: String,
31}
32
33pub fn run() {
35 let mut passed = 0u32;
36 let total = 10u32;
37
38 println!("{BOLD}{WHITE}lean-ctx doctor{RST} {DIM}diagnostics{RST}\n");
39
40 let path_bin = resolve_lean_ctx_binary();
42 let also_in_path_dirs = path_in_path_env();
43 let bin_ok = path_bin.is_some() || also_in_path_dirs;
44 if bin_ok {
45 passed += 1;
46 }
47 let bin_line = if let Some(p) = path_bin {
48 format!("{BOLD}lean-ctx in PATH{RST} {WHITE}{}{RST}", p.display())
49 } else if also_in_path_dirs {
50 format!(
51 "{BOLD}lean-ctx in PATH{RST} {YELLOW}found via PATH walk (not resolved by `command -v`){RST}"
52 )
53 } else {
54 format!("{BOLD}lean-ctx in PATH{RST} {RED}not found{RST}")
55 };
56 print_check(&Outcome {
57 ok: bin_ok,
58 line: bin_line,
59 });
60
61 let ver = if bin_ok {
63 lean_ctx_version_from_path()
64 } else {
65 Outcome {
66 ok: false,
67 line: format!("{BOLD}lean-ctx version{RST} {RED}skipped (binary not in PATH){RST}"),
68 }
69 };
70 if ver.ok {
71 passed += 1;
72 }
73 print_check(&ver);
74
75 let lean_dir = crate::core::data_dir::lean_ctx_data_dir().ok();
77 let dir_outcome = match &lean_dir {
78 Some(p) if p.is_dir() => {
79 passed += 1;
80 Outcome {
81 ok: true,
82 line: format!(
83 "{BOLD}data dir{RST} {GREEN}exists{RST} {DIM}{}{RST}",
84 p.display()
85 ),
86 }
87 }
88 Some(p) => Outcome {
89 ok: false,
90 line: format!(
91 "{BOLD}data dir{RST} {RED}missing or not a directory{RST} {DIM}{}{RST}",
92 p.display()
93 ),
94 },
95 None => Outcome {
96 ok: false,
97 line: format!("{BOLD}data dir{RST} {RED}could not resolve data directory{RST}"),
98 },
99 };
100 print_check(&dir_outcome);
101
102 let stats_path = lean_dir.as_ref().map(|d| d.join("stats.json"));
104 let stats_outcome = match stats_path.as_ref().and_then(|p| std::fs::metadata(p).ok()) {
105 Some(m) if m.is_file() => {
106 passed += 1;
107 let size = m.len();
108 let path_display = if let Some(p) = stats_path.as_ref() {
109 p.display().to_string()
110 } else {
111 String::new()
112 };
113 Outcome {
114 ok: true,
115 line: format!(
116 "{BOLD}stats.json{RST} {GREEN}exists{RST} {WHITE}{size} bytes{RST} {DIM}{path_display}{RST}",
117 ),
118 }
119 }
120 Some(_m) => {
121 let path_display = if let Some(p) = stats_path.as_ref() {
122 p.display().to_string()
123 } else {
124 String::new()
125 };
126 Outcome {
127 ok: false,
128 line: format!(
129 "{BOLD}stats.json{RST} {RED}not a file{RST} {DIM}{path_display}{RST}",
130 ),
131 }
132 }
133 None => {
134 passed += 1;
135 Outcome {
136 ok: true,
137 line: match &stats_path {
138 Some(p) => format!(
139 "{BOLD}stats.json{RST} {YELLOW}not yet created{RST} {DIM}(will appear after first use) {}{RST}",
140 p.display()
141 ),
142 None => format!("{BOLD}stats.json{RST} {RED}could not resolve path{RST}"),
143 },
144 }
145 }
146 };
147 print_check(&stats_outcome);
148
149 let split_dirs = crate::core::data_dir::all_data_dirs_with_stats();
150 if split_dirs.len() >= 2 {
151 let dirs_str = split_dirs
152 .iter()
153 .map(|d| d.display().to_string())
154 .collect::<Vec<_>>()
155 .join(", ");
156 print_check(&Outcome {
157 ok: false,
158 line: format!(
159 "{BOLD}data dir split{RST} {RED}stats.json found in {count} locations{RST}: {dirs_str} {DIM}(run: lean-ctx setup to auto-merge){RST}",
160 count = split_dirs.len(),
161 ),
162 });
163 }
164
165 let config_path = lean_dir.as_ref().map(|d| d.join("config.toml"));
167 let config_outcome = match &config_path {
168 Some(p) => match std::fs::metadata(p) {
169 Ok(m) if m.is_file() => {
170 passed += 1;
171 Outcome {
172 ok: true,
173 line: format!(
174 "{BOLD}config.toml{RST} {GREEN}exists{RST} {DIM}{}{RST}",
175 p.display()
176 ),
177 }
178 }
179 Ok(_) => Outcome {
180 ok: false,
181 line: format!(
182 "{BOLD}config.toml{RST} {RED}exists but is not a regular file{RST} {DIM}{}{RST}",
183 p.display()
184 ),
185 },
186 Err(_) => {
187 passed += 1;
188 Outcome {
189 ok: true,
190 line: format!(
191 "{BOLD}config.toml{RST} {YELLOW}not found, using defaults{RST} {DIM}(expected at {}){RST}",
192 p.display()
193 ),
194 }
195 }
196 },
197 None => Outcome {
198 ok: false,
199 line: format!("{BOLD}config.toml{RST} {RED}could not resolve path{RST}"),
200 },
201 };
202 print_check(&config_outcome);
203
204 let allowlist_outcome = shell_allowlist_outcome();
206 if allowlist_outcome.ok {
207 passed += 1;
208 }
209 print_check(&allowlist_outcome);
210
211 let passthrough_outcome = compact_format_passthrough_outcome();
213 if passthrough_outcome.ok {
214 passed += 1;
215 }
216 print_check(&passthrough_outcome);
217
218 let proxy_outcome = proxy_upstream_outcome();
220 if proxy_outcome.ok {
221 passed += 1;
222 }
223 print_check(&proxy_outcome);
224
225 let aliases = shell_aliases_outcome();
227 if aliases.ok {
228 passed += 1;
229 }
230 print_check(&aliases);
231
232 let mcp = mcp_config_outcome();
234 if mcp.ok {
235 passed += 1;
236 }
237 print_check(&mcp);
238
239 let workspace_scope = workspace_scope::workspace_scope_outcome(mcp.ok);
241 if let Some(ref ws) = workspace_scope {
242 if ws.ok {
243 passed += 1;
244 }
245 print_check(ws);
246 }
247
248 let skill = skill_files_outcome();
250 if skill.ok {
251 passed += 1;
252 }
253 print_check(&skill);
254
255 let port = port_3333_outcome();
257 if port.ok {
258 passed += 1;
259 }
260 print_check(&port);
261
262 #[cfg(unix)]
264 let daemon_outcome = {
265 let autostart = crate::daemon_autostart::is_installed();
266 let autostart_tag = if autostart {
267 format!(" {DIM}[autostart: on]{RST}")
268 } else {
269 String::new()
270 };
271 if crate::daemon::is_daemon_running() {
272 let pid_path = crate::daemon::daemon_pid_path();
273 let pid_str = std::fs::read_to_string(&pid_path).unwrap_or_default();
274 Outcome {
275 ok: true,
276 line: format!(
277 "{BOLD}Daemon{RST} {GREEN}running (PID {}){RST}{autostart_tag}",
278 pid_str.trim()
279 ),
280 }
281 } else {
282 let hint = if autostart {
283 format!("{DIM}(autostart enabled, will restart){RST}")
284 } else {
285 format!("{DIM}(run: lean-ctx daemon start or: lean-ctx daemon enable){RST}")
286 };
287 Outcome {
288 ok: true,
289 line: format!("{BOLD}Daemon{RST} {YELLOW}not running{RST} {hint}"),
290 }
291 }
292 };
293 #[cfg(not(unix))]
294 let daemon_outcome = Outcome {
295 ok: true,
296 line: format!("{BOLD}Daemon{RST} {DIM}not supported on this platform{RST}"),
297 };
298 if daemon_outcome.ok {
299 passed += 1;
300 }
301 print_check(&daemon_outcome);
302
303 #[cfg(target_os = "linux")]
305 {
306 if let Ok(o) = std::process::Command::new("systemctl")
307 .args(["--user", "is-active", "lean-ctx-daemon.service"])
308 .output()
309 {
310 let state = String::from_utf8_lossy(&o.stdout).trim().to_string();
311 if state != "active" {
312 println!(
313 " {DIM} systemd unit state: {YELLOW}{state}{RST}{DIM} (expected: active){RST}"
314 );
315 }
316 }
317 let username = std::env::var("USER")
318 .or_else(|_| std::env::var("LOGNAME"))
319 .unwrap_or_else(|_| "$(whoami)".to_string());
320 if let Ok(o) = std::process::Command::new("loginctl")
321 .args(["show-user", &username, "-p", "Linger", "--value"])
322 .output()
323 {
324 let val = String::from_utf8_lossy(&o.stdout).trim().to_string();
325 if val != "yes" {
326 println!(
327 " {YELLOW}⚠{RST} Linger not enabled — daemon won't start at boot without login"
328 );
329 println!(" {DIM}Fix: loginctl enable-linger {username}{RST}");
330 }
331 }
332 }
333 if let Some(log_path) = crate::core::startup_guard::crash_loop_log_path(
334 crate::core::startup_guard::MCP_PROCESS_NAME,
335 ) {
336 if log_path.exists() {
337 if let Ok(contents) = std::fs::read_to_string(&log_path) {
338 let lines: Vec<&str> = contents.lines().collect();
339 if lines.len() >= 5 {
340 println!(
341 " {YELLOW}⚠{RST} Crash-loop log: {} recent restarts {DIM}({}){RST}",
342 lines.len(),
343 log_path.display()
344 );
345 }
346 }
347 }
348 }
349
350 let provider_outcome = provider_outcome();
352 print_check(&provider_outcome);
353
354 let bridge_outcomes = mcp_bridge_outcomes();
356 for bridge_check in &bridge_outcomes {
357 print_check(bridge_check);
358 }
359
360 let plan_outcomes = plan_mode_outcomes();
362 for plan_check in &plan_outcomes {
363 print_check(plan_check);
364 }
365
366 let session_outcome = session_state_outcome();
368 if session_outcome.ok {
369 passed += 1;
370 }
371 print_check(&session_outcome);
372
373 let docker_outcomes = docker_env_outcomes();
375 for docker_check in &docker_outcomes {
376 if docker_check.ok {
377 passed += 1;
378 }
379 print_check(docker_check);
380 }
381
382 let pi = pi_outcome();
384 if let Some(ref pi_check) = pi {
385 if pi_check.ok {
386 passed += 1;
387 }
388 print_check(pi_check);
389 }
390
391 let integrity = crate::core::integrity::check();
393 let integrity_ok = integrity.seed_ok && integrity.origin_ok;
394 if integrity_ok {
395 passed += 1;
396 }
397 let integrity_line = if integrity_ok {
398 format!(
399 "{BOLD}Build origin{RST} {GREEN}official{RST} {DIM}{}{RST}",
400 integrity.repo
401 )
402 } else {
403 format!(
404 "{BOLD}Build origin{RST} {RED}MODIFIED REDISTRIBUTION{RST} {YELLOW}pkg={}, repo={}{RST}",
405 integrity.pkg_name, integrity.repo
406 )
407 };
408 print_check(&Outcome {
409 ok: integrity_ok,
410 line: integrity_line,
411 });
412
413 let cache_safety = cache_safety_outcome();
415 if cache_safety.ok {
416 passed += 1;
417 }
418 print_check(&cache_safety);
419
420 let claude_truncation = claude_truncation_outcome();
422 if let Some(ref ct) = claude_truncation {
423 if ct.ok {
424 passed += 1;
425 }
426 print_check(ct);
427 }
428
429 let bm25_health = bm25_cache_health_outcome();
431 if bm25_health.ok {
432 passed += 1;
433 }
434 print_check(&bm25_health);
435
436 let semantic_index = semantic_index_outcome();
439 if let Some(ref check) = semantic_index {
440 if check.ok {
441 passed += 1;
442 }
443 print_check(check);
444 }
445
446 let archive_footprint = archive_footprint_outcome();
448 if archive_footprint.ok {
449 passed += 1;
450 }
451 print_check(&archive_footprint);
452
453 let mem_profile = memory_profile_outcome();
455 passed += 1;
456 print_check(&mem_profile);
457
458 let mem_cleanup = memory_cleanup_outcome();
460 passed += 1;
461 print_check(&mem_cleanup);
462
463 let ram_outcome = ram_guardian_outcome();
465 if ram_outcome.ok {
466 passed += 1;
467 }
468 print_check(&ram_outcome);
469
470 let cap_warnings = capacity_warnings();
472 for cw in &cap_warnings {
473 if cw.ok {
474 passed += 1;
475 }
476 print_check(cw);
477 }
478
479 let proxy_health = proxy_health_outcome();
481 if proxy_health.ok {
482 passed += 1;
483 }
484 print_check(&proxy_health);
485
486 let stale_env = stale_proxy_env_outcome();
488 if let Some(ref check) = stale_env {
489 if check.ok {
490 passed += 1;
491 }
492 print_check(check);
493 }
494
495 println!("\n {BOLD}{WHITE}LSP (optional — for ctx_refactor):{RST}");
497 let lsp_outcomes = lsp_server_outcomes();
498 for lsp_check in &lsp_outcomes {
499 print_check(lsp_check);
500 }
501
502 let mut effective_total = total + 10; effective_total += 1; effective_total += 1; effective_total += cap_warnings.len() as u32;
506 effective_total += docker_outcomes.len() as u32;
507 if pi.is_some() {
508 effective_total += 1;
509 }
510 if claude_truncation.is_some() {
511 effective_total += 1;
512 }
513 if stale_env.is_some() {
514 effective_total += 1;
515 }
516 if workspace_scope.is_some() {
517 effective_total += 1;
518 }
519 if semantic_index.is_some() {
520 effective_total += 1;
521 }
522 let cfg = crate::core::config::Config::load();
524 let shadow_line = if cfg.shadow_mode {
525 format!("{BOLD}Shadow mode{RST} {GREEN}active{RST} {DIM}(native tools intercepted → ctx_*){RST}")
526 } else {
527 format!("{BOLD}Shadow mode{RST} {DIM}disabled{RST} {DIM}(enable: lean-ctx config set shadow_mode true){RST}")
528 };
529 println!(" {shadow_line}");
530
531 let needs_attention = effective_total.saturating_sub(passed);
532 println!();
533 println!(" {BOLD}{WHITE}Summary:{RST} {GREEN}{passed}{RST}{DIM}/{effective_total}{RST} checks passed");
534 if needs_attention > 0 {
535 println!(
536 " {YELLOW}{needs_attention} check(s) need attention.{RST} Auto-repair what's fixable: {BOLD}lean-ctx doctor --fix{RST}"
537 );
538 } else {
539 println!(" {GREEN}Everything looks good.{RST}");
540 }
541 println!(" {DIM}LSP servers are optional enhancements (not counted in score){RST}");
542 println!(" {DIM}{}{RST}", crate::core::integrity::origin_line());
543}
544
545pub fn run_compact() {
546 let (passed, total) = compact_score();
547 print_compact_status(passed, total);
548}
549
550pub fn run_cli(args: &[String]) -> i32 {
551 let (sub, rest) = match args.first().map(String::as_str) {
552 Some("integrations") => ("integrations", &args[1..]),
553 _ => ("", args),
554 };
555
556 let fix = rest.iter().any(|a| a == "--fix");
557 let json = rest.iter().any(|a| a == "--json");
558 let help = rest.iter().any(|a| a == "--help" || a == "-h");
559
560 if help {
561 println!("Usage:");
562 println!(" lean-ctx doctor");
563 println!(" lean-ctx doctor integrations [--json]");
564 println!(" lean-ctx doctor --fix [--json]");
565 return 0;
566 }
567
568 if sub == "integrations" {
569 if fix {
570 let _ = fix::run_fix(&fix::DoctorFixOptions { json: false });
571 }
572 return integrations::run_integrations(&integrations::IntegrationsOptions { json });
573 }
574
575 if !fix {
576 run();
577 return 0;
578 }
579
580 match fix::run_fix(&fix::DoctorFixOptions { json }) {
581 Ok(code) => code,
582 Err(e) => {
583 tracing::error!("doctor --fix failed: {e}");
584 2
585 }
586 }
587}
588
589pub fn compact_score() -> (u32, u32) {
590 let mut passed = 0u32;
591 let total = 6u32;
592
593 if resolve_lean_ctx_binary().is_some() || path_in_path_env() {
594 passed += 1;
595 }
596 let lean_dir = crate::core::data_dir::lean_ctx_data_dir().ok();
597 if lean_dir.as_ref().is_some_and(|p| p.is_dir()) {
598 passed += 1;
599 }
600 if lean_dir
601 .as_ref()
602 .map(|d| d.join("stats.json"))
603 .and_then(|p| std::fs::metadata(p).ok())
604 .is_some_and(|m| m.is_file())
605 {
606 passed += 1;
607 }
608 if shell_aliases_outcome().ok {
609 passed += 1;
610 }
611 if mcp_config_outcome().ok {
612 passed += 1;
613 }
614 if skill_files_outcome().ok {
615 passed += 1;
616 }
617
618 (passed, total)
619}
620
621pub(super) fn print_compact_status(passed: u32, total: u32) {
622 let status = if passed == total {
623 format!("{GREEN}✓ All {total} checks passed{RST}")
624 } else {
625 format!("{YELLOW}{passed}/{total} passed{RST} — run {BOLD}lean-ctx doctor{RST} for details")
626 };
627 println!(" {status}");
628}
629
630#[cfg(test)]
631mod tests {
632 use super::is_active_shell_impl;
633
634 fn make_capacity_check(name: &str, current: usize, limit: usize) -> Option<(bool, String)> {
635 if limit == 0 {
636 return None;
637 }
638 let pct = (current as f64 / limit as f64 * 100.0) as u32;
639 if pct >= 95 {
640 Some((true, format!("{name}: {current}/{limit} ({pct}%)")))
641 } else if pct >= 80 {
642 Some((false, format!("{name}: {current}/{limit} ({pct}%)")))
643 } else {
644 None
645 }
646 }
647
648 #[test]
649 fn capacity_below_80_no_warning() {
650 assert!(make_capacity_check("facts", 100, 200).is_none());
651 assert!(make_capacity_check("facts", 159, 200).is_none());
652 }
653
654 #[test]
655 fn capacity_at_80_yellow_warning() {
656 let result = make_capacity_check("facts", 160, 200);
657 assert!(result.is_some());
658 let (critical, msg) = result.unwrap();
659 assert!(!critical);
660 assert!(msg.contains("160/200"));
661 assert!(msg.contains("80%"));
662 }
663
664 #[test]
665 fn capacity_at_92_yellow_warning() {
666 let result = make_capacity_check("facts", 185, 200);
667 assert!(result.is_some());
668 let (critical, msg) = result.unwrap();
669 assert!(!critical);
670 assert!(msg.contains("185/200"));
671 assert!(msg.contains("92%"));
672 }
673
674 #[test]
675 fn capacity_at_95_critical() {
676 let result = make_capacity_check("facts", 190, 200);
677 assert!(result.is_some());
678 let (critical, msg) = result.unwrap();
679 assert!(critical);
680 assert!(msg.contains("190/200"));
681 assert!(msg.contains("95%"));
682 }
683
684 #[test]
685 fn capacity_at_100_critical() {
686 let result = make_capacity_check("facts", 200, 200);
687 assert!(result.is_some());
688 let (critical, _) = result.unwrap();
689 assert!(critical);
690 }
691
692 #[test]
693 fn capacity_zero_limit_skipped() {
694 assert!(make_capacity_check("facts", 50, 0).is_none());
695 }
696
697 #[test]
698 fn bashrc_active_on_non_windows_when_shell_empty() {
699 assert!(is_active_shell_impl("~/.bashrc", "", false, false));
700 }
701
702 #[test]
703 fn bashrc_not_active_on_windows_when_shell_empty() {
704 assert!(!is_active_shell_impl("~/.bashrc", "", true, false));
705 }
706
707 #[test]
708 fn bashrc_active_when_shell_contains_bash_on_linux() {
709 assert!(is_active_shell_impl(
710 "~/.bashrc",
711 "/usr/bin/bash",
712 false,
713 false
714 ));
715 }
716
717 #[test]
718 fn bashrc_not_active_on_windows_even_with_bash_in_shell_env() {
719 std::env::remove_var("BASH_VERSION");
722 assert!(!is_active_shell_impl(
723 "~/.bashrc",
724 "C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe",
725 true,
726 false,
727 ));
728 }
729
730 #[test]
731 fn bashrc_not_active_on_windows_powershell_even_with_bash_in_shell() {
732 assert!(!is_active_shell_impl(
733 "~/.bashrc",
734 "C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe",
735 true,
736 true,
737 ));
738 }
739
740 #[test]
741 fn bashrc_not_active_on_windows_powershell_with_empty_shell() {
742 assert!(!is_active_shell_impl("~/.bashrc", "", true, true));
743 }
744
745 #[test]
746 fn zshrc_unaffected_by_powershell_flag() {
747 assert!(is_active_shell_impl("~/.zshrc", "/bin/zsh", false, false));
748 assert!(is_active_shell_impl("~/.zshrc", "/bin/zsh", true, true));
749 }
750
751 #[test]
752 fn bashrc_not_active_on_windows_without_powershell_detection() {
753 std::env::remove_var("BASH_VERSION");
756 assert!(!is_active_shell_impl(
757 "~/.bashrc",
758 "/usr/bin/bash",
759 true,
760 false,
761 ));
762 }
763
764 #[test]
765 fn bashrc_active_on_linux() {
766 assert!(is_active_shell_impl("~/.bashrc", "/bin/bash", false, false));
767 assert!(is_active_shell_impl("~/.bashrc", "", false, false));
768 }
769}