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 proxy_outcome = proxy_upstream_outcome();
206 if proxy_outcome.ok {
207 passed += 1;
208 }
209 print_check(&proxy_outcome);
210
211 let aliases = shell_aliases_outcome();
213 if aliases.ok {
214 passed += 1;
215 }
216 print_check(&aliases);
217
218 let mcp = mcp_config_outcome();
220 if mcp.ok {
221 passed += 1;
222 }
223 print_check(&mcp);
224
225 let workspace_scope = workspace_scope::workspace_scope_outcome(mcp.ok);
227 if let Some(ref ws) = workspace_scope {
228 if ws.ok {
229 passed += 1;
230 }
231 print_check(ws);
232 }
233
234 let skill = skill_files_outcome();
236 if skill.ok {
237 passed += 1;
238 }
239 print_check(&skill);
240
241 let port = port_3333_outcome();
243 if port.ok {
244 passed += 1;
245 }
246 print_check(&port);
247
248 #[cfg(unix)]
250 let daemon_outcome = {
251 let autostart = crate::daemon_autostart::is_installed();
252 let autostart_tag = if autostart {
253 format!(" {DIM}[autostart: on]{RST}")
254 } else {
255 String::new()
256 };
257 if crate::daemon::is_daemon_running() {
258 let pid_path = crate::daemon::daemon_pid_path();
259 let pid_str = std::fs::read_to_string(&pid_path).unwrap_or_default();
260 Outcome {
261 ok: true,
262 line: format!(
263 "{BOLD}Daemon{RST} {GREEN}running (PID {}){RST}{autostart_tag}",
264 pid_str.trim()
265 ),
266 }
267 } else {
268 let hint = if autostart {
269 format!("{DIM}(autostart enabled, will restart){RST}")
270 } else {
271 format!("{DIM}(run: lean-ctx daemon start or: lean-ctx daemon enable){RST}")
272 };
273 Outcome {
274 ok: true,
275 line: format!("{BOLD}Daemon{RST} {YELLOW}not running{RST} {hint}"),
276 }
277 }
278 };
279 #[cfg(not(unix))]
280 let daemon_outcome = Outcome {
281 ok: true,
282 line: format!("{BOLD}Daemon{RST} {DIM}not supported on this platform{RST}"),
283 };
284 if daemon_outcome.ok {
285 passed += 1;
286 }
287 print_check(&daemon_outcome);
288
289 #[cfg(target_os = "linux")]
291 {
292 if let Ok(o) = std::process::Command::new("systemctl")
293 .args(["--user", "is-active", "lean-ctx-daemon.service"])
294 .output()
295 {
296 let state = String::from_utf8_lossy(&o.stdout).trim().to_string();
297 if state != "active" {
298 println!(
299 " {DIM} systemd unit state: {YELLOW}{state}{RST}{DIM} (expected: active){RST}"
300 );
301 }
302 }
303 let username = std::env::var("USER")
304 .or_else(|_| std::env::var("LOGNAME"))
305 .unwrap_or_else(|_| "$(whoami)".to_string());
306 if let Ok(o) = std::process::Command::new("loginctl")
307 .args(["show-user", &username, "-p", "Linger", "--value"])
308 .output()
309 {
310 let val = String::from_utf8_lossy(&o.stdout).trim().to_string();
311 if val != "yes" {
312 println!(
313 " {YELLOW}⚠{RST} Linger not enabled — daemon won't start at boot without login"
314 );
315 println!(" {DIM}Fix: loginctl enable-linger {username}{RST}");
316 }
317 }
318 }
319 if let Some(log_path) = crate::core::startup_guard::crash_loop_log_path(
320 crate::core::startup_guard::MCP_PROCESS_NAME,
321 ) {
322 if log_path.exists() {
323 if let Ok(contents) = std::fs::read_to_string(&log_path) {
324 let lines: Vec<&str> = contents.lines().collect();
325 if lines.len() >= 5 {
326 println!(
327 " {YELLOW}⚠{RST} Crash-loop log: {} recent restarts {DIM}({}){RST}",
328 lines.len(),
329 log_path.display()
330 );
331 }
332 }
333 }
334 }
335
336 let provider_outcome = provider_outcome();
338 print_check(&provider_outcome);
339
340 let bridge_outcomes = mcp_bridge_outcomes();
342 for bridge_check in &bridge_outcomes {
343 print_check(bridge_check);
344 }
345
346 let plan_outcomes = plan_mode_outcomes();
348 for plan_check in &plan_outcomes {
349 print_check(plan_check);
350 }
351
352 let session_outcome = session_state_outcome();
354 if session_outcome.ok {
355 passed += 1;
356 }
357 print_check(&session_outcome);
358
359 let docker_outcomes = docker_env_outcomes();
361 for docker_check in &docker_outcomes {
362 if docker_check.ok {
363 passed += 1;
364 }
365 print_check(docker_check);
366 }
367
368 let pi = pi_outcome();
370 if let Some(ref pi_check) = pi {
371 if pi_check.ok {
372 passed += 1;
373 }
374 print_check(pi_check);
375 }
376
377 let integrity = crate::core::integrity::check();
379 let integrity_ok = integrity.seed_ok && integrity.origin_ok;
380 if integrity_ok {
381 passed += 1;
382 }
383 let integrity_line = if integrity_ok {
384 format!(
385 "{BOLD}Build origin{RST} {GREEN}official{RST} {DIM}{}{RST}",
386 integrity.repo
387 )
388 } else {
389 format!(
390 "{BOLD}Build origin{RST} {RED}MODIFIED REDISTRIBUTION{RST} {YELLOW}pkg={}, repo={}{RST}",
391 integrity.pkg_name, integrity.repo
392 )
393 };
394 print_check(&Outcome {
395 ok: integrity_ok,
396 line: integrity_line,
397 });
398
399 let cache_safety = cache_safety_outcome();
401 if cache_safety.ok {
402 passed += 1;
403 }
404 print_check(&cache_safety);
405
406 let claude_truncation = claude_truncation_outcome();
408 if let Some(ref ct) = claude_truncation {
409 if ct.ok {
410 passed += 1;
411 }
412 print_check(ct);
413 }
414
415 let bm25_health = bm25_cache_health_outcome();
417 if bm25_health.ok {
418 passed += 1;
419 }
420 print_check(&bm25_health);
421
422 let mem_profile = memory_profile_outcome();
424 passed += 1;
425 print_check(&mem_profile);
426
427 let mem_cleanup = memory_cleanup_outcome();
429 passed += 1;
430 print_check(&mem_cleanup);
431
432 let ram_outcome = ram_guardian_outcome();
434 if ram_outcome.ok {
435 passed += 1;
436 }
437 print_check(&ram_outcome);
438
439 let cap_warnings = capacity_warnings();
441 for cw in &cap_warnings {
442 if cw.ok {
443 passed += 1;
444 }
445 print_check(cw);
446 }
447
448 let proxy_health = proxy_health_outcome();
450 if proxy_health.ok {
451 passed += 1;
452 }
453 print_check(&proxy_health);
454
455 let stale_env = stale_proxy_env_outcome();
457 if let Some(ref check) = stale_env {
458 if check.ok {
459 passed += 1;
460 }
461 print_check(check);
462 }
463
464 println!("\n {BOLD}{WHITE}LSP (optional — for ctx_refactor):{RST}");
466 let lsp_outcomes = lsp_server_outcomes();
467 for lsp_check in &lsp_outcomes {
468 print_check(lsp_check);
469 }
470
471 let mut effective_total = total + 9; effective_total += cap_warnings.len() as u32;
473 effective_total += docker_outcomes.len() as u32;
474 if pi.is_some() {
475 effective_total += 1;
476 }
477 if claude_truncation.is_some() {
478 effective_total += 1;
479 }
480 if stale_env.is_some() {
481 effective_total += 1;
482 }
483 if workspace_scope.is_some() {
484 effective_total += 1;
485 }
486 println!();
487 println!(" {BOLD}{WHITE}Summary:{RST} {GREEN}{passed}{RST}{DIM}/{effective_total}{RST} checks passed");
488 println!(" {DIM}LSP servers are optional enhancements (not counted in score){RST}");
489 println!(" {DIM}{}{RST}", crate::core::integrity::origin_line());
490}
491
492pub fn run_compact() {
493 let (passed, total) = compact_score();
494 print_compact_status(passed, total);
495}
496
497pub fn run_cli(args: &[String]) -> i32 {
498 let (sub, rest) = match args.first().map(String::as_str) {
499 Some("integrations") => ("integrations", &args[1..]),
500 _ => ("", args),
501 };
502
503 let fix = rest.iter().any(|a| a == "--fix");
504 let json = rest.iter().any(|a| a == "--json");
505 let help = rest.iter().any(|a| a == "--help" || a == "-h");
506
507 if help {
508 println!("Usage:");
509 println!(" lean-ctx doctor");
510 println!(" lean-ctx doctor integrations [--json]");
511 println!(" lean-ctx doctor --fix [--json]");
512 return 0;
513 }
514
515 if sub == "integrations" {
516 if fix {
517 let _ = fix::run_fix(&fix::DoctorFixOptions { json: false });
518 }
519 return integrations::run_integrations(&integrations::IntegrationsOptions { json });
520 }
521
522 if !fix {
523 run();
524 return 0;
525 }
526
527 match fix::run_fix(&fix::DoctorFixOptions { json }) {
528 Ok(code) => code,
529 Err(e) => {
530 tracing::error!("doctor --fix failed: {e}");
531 2
532 }
533 }
534}
535
536pub fn compact_score() -> (u32, u32) {
537 let mut passed = 0u32;
538 let total = 6u32;
539
540 if resolve_lean_ctx_binary().is_some() || path_in_path_env() {
541 passed += 1;
542 }
543 let lean_dir = crate::core::data_dir::lean_ctx_data_dir().ok();
544 if lean_dir.as_ref().is_some_and(|p| p.is_dir()) {
545 passed += 1;
546 }
547 if lean_dir
548 .as_ref()
549 .map(|d| d.join("stats.json"))
550 .and_then(|p| std::fs::metadata(p).ok())
551 .is_some_and(|m| m.is_file())
552 {
553 passed += 1;
554 }
555 if shell_aliases_outcome().ok {
556 passed += 1;
557 }
558 if mcp_config_outcome().ok {
559 passed += 1;
560 }
561 if skill_files_outcome().ok {
562 passed += 1;
563 }
564
565 (passed, total)
566}
567
568pub(super) fn print_compact_status(passed: u32, total: u32) {
569 let status = if passed == total {
570 format!("{GREEN}✓ All {total} checks passed{RST}")
571 } else {
572 format!("{YELLOW}{passed}/{total} passed{RST} — run {BOLD}lean-ctx doctor{RST} for details")
573 };
574 println!(" {status}");
575}
576
577#[cfg(test)]
578mod tests {
579 use super::is_active_shell_impl;
580
581 fn make_capacity_check(name: &str, current: usize, limit: usize) -> Option<(bool, String)> {
582 if limit == 0 {
583 return None;
584 }
585 let pct = (current as f64 / limit as f64 * 100.0) as u32;
586 if pct >= 95 {
587 Some((true, format!("{name}: {current}/{limit} ({pct}%)")))
588 } else if pct >= 80 {
589 Some((false, format!("{name}: {current}/{limit} ({pct}%)")))
590 } else {
591 None
592 }
593 }
594
595 #[test]
596 fn capacity_below_80_no_warning() {
597 assert!(make_capacity_check("facts", 100, 200).is_none());
598 assert!(make_capacity_check("facts", 159, 200).is_none());
599 }
600
601 #[test]
602 fn capacity_at_80_yellow_warning() {
603 let result = make_capacity_check("facts", 160, 200);
604 assert!(result.is_some());
605 let (critical, msg) = result.unwrap();
606 assert!(!critical);
607 assert!(msg.contains("160/200"));
608 assert!(msg.contains("80%"));
609 }
610
611 #[test]
612 fn capacity_at_92_yellow_warning() {
613 let result = make_capacity_check("facts", 185, 200);
614 assert!(result.is_some());
615 let (critical, msg) = result.unwrap();
616 assert!(!critical);
617 assert!(msg.contains("185/200"));
618 assert!(msg.contains("92%"));
619 }
620
621 #[test]
622 fn capacity_at_95_critical() {
623 let result = make_capacity_check("facts", 190, 200);
624 assert!(result.is_some());
625 let (critical, msg) = result.unwrap();
626 assert!(critical);
627 assert!(msg.contains("190/200"));
628 assert!(msg.contains("95%"));
629 }
630
631 #[test]
632 fn capacity_at_100_critical() {
633 let result = make_capacity_check("facts", 200, 200);
634 assert!(result.is_some());
635 let (critical, _) = result.unwrap();
636 assert!(critical);
637 }
638
639 #[test]
640 fn capacity_zero_limit_skipped() {
641 assert!(make_capacity_check("facts", 50, 0).is_none());
642 }
643
644 #[test]
645 fn bashrc_active_on_non_windows_when_shell_empty() {
646 assert!(is_active_shell_impl("~/.bashrc", "", false, false));
647 }
648
649 #[test]
650 fn bashrc_not_active_on_windows_when_shell_empty() {
651 assert!(!is_active_shell_impl("~/.bashrc", "", true, false));
652 }
653
654 #[test]
655 fn bashrc_active_when_shell_contains_bash_on_linux() {
656 assert!(is_active_shell_impl(
657 "~/.bashrc",
658 "/usr/bin/bash",
659 false,
660 false
661 ));
662 }
663
664 #[test]
665 fn bashrc_not_active_on_windows_even_with_bash_in_shell_env() {
666 std::env::remove_var("BASH_VERSION");
669 assert!(!is_active_shell_impl(
670 "~/.bashrc",
671 "C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe",
672 true,
673 false,
674 ));
675 }
676
677 #[test]
678 fn bashrc_not_active_on_windows_powershell_even_with_bash_in_shell() {
679 assert!(!is_active_shell_impl(
680 "~/.bashrc",
681 "C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe",
682 true,
683 true,
684 ));
685 }
686
687 #[test]
688 fn bashrc_not_active_on_windows_powershell_with_empty_shell() {
689 assert!(!is_active_shell_impl("~/.bashrc", "", true, true));
690 }
691
692 #[test]
693 fn zshrc_unaffected_by_powershell_flag() {
694 assert!(is_active_shell_impl("~/.zshrc", "/bin/zsh", false, false));
695 assert!(is_active_shell_impl("~/.zshrc", "/bin/zsh", true, true));
696 }
697
698 #[test]
699 fn bashrc_not_active_on_windows_without_powershell_detection() {
700 std::env::remove_var("BASH_VERSION");
703 assert!(!is_active_shell_impl(
704 "~/.bashrc",
705 "/usr/bin/bash",
706 true,
707 false,
708 ));
709 }
710
711 #[test]
712 fn bashrc_active_on_linux() {
713 assert!(is_active_shell_impl("~/.bashrc", "/bin/bash", false, false));
714 assert!(is_active_shell_impl("~/.bashrc", "", false, false));
715 }
716}