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::{
31 configured_host_coverage, empty_session_lines, shadow_hosts, shadow_status,
32};
33#[allow(clippy::wildcard_imports)]
34use common::*;
35
36pub use report::{HealthCheck, HealthLevel, HealthReport, health_report};
37
38pub fn run_fix_report() -> Result<lean_ctx_ext::core::setup_report::SetupReport, String> {
44 fix::fix_report()
45}
46
47pub(super) const GREEN: &str = "\x1b[32m";
48
49pub(super) const RED: &str = "\x1b[31m";
50
51pub(super) const BOLD: &str = "\x1b[1m";
52
53pub(super) const RST: &str = "\x1b[0m";
54
55pub(super) const DIM: &str = "\x1b[2m";
56
57pub(super) const WHITE: &str = "\x1b[97m";
58
59pub(super) const YELLOW: &str = "\x1b[33m";
60
61pub(super) struct Outcome {
62 pub ok: bool,
63 pub line: String,
64}
65
66enum DaemonAutostart {
68 Unsupported,
71 Off,
72 On(Option<std::path::PathBuf>),
74}
75
76fn unrecorded_services_outcome(lines: Option<(String, String)>) -> Option<Outcome> {
81 let (what, how) = lines?;
82 Some(Outcome {
83 ok: true,
84 line: format!("{BOLD}Unrecorded services{RST} {YELLOW}{what}{RST} {DIM}{how}{RST}"),
85 })
86}
87
88fn daemon_outcome(running_pid: Option<u32>, autostart: &DaemonAutostart) -> Outcome {
92 let autostart_tag = match autostart {
93 DaemonAutostart::On(Some(p)) => format!(" {DIM}[autostart: on — {}]{RST}", p.display()),
94 DaemonAutostart::On(None) => format!(" {DIM}[autostart: on]{RST}"),
95 DaemonAutostart::Off | DaemonAutostart::Unsupported => String::new(),
96 };
97 let line = if let Some(pid) = running_pid {
98 format!("{BOLD}Daemon{RST} {GREEN}running (PID {pid}){RST}{autostart_tag}")
99 } else {
100 let hint = match autostart {
101 DaemonAutostart::On(_) => format!("{DIM}(autostart enabled, will restart){RST}"),
102 DaemonAutostart::Off => {
103 format!("{DIM}(run: lean-ctx daemon start or: lean-ctx daemon enable){RST}")
104 }
105 DaemonAutostart::Unsupported => {
106 format!("{DIM}(run: lean-ctx daemon start — editors also start it on demand){RST}")
107 }
108 };
109 format!("{BOLD}Daemon{RST} {YELLOW}not running{RST} {hint}")
110 };
111 Outcome { ok: true, line }
112}
113
114fn cloud_sync_outcome(cloud_connected: bool, autostart: &DaemonAutostart) -> Option<Outcome> {
119 if !cloud_connected {
120 return None;
121 }
122 match autostart {
123 DaemonAutostart::On(_) => Some(Outcome {
124 ok: true,
125 line: format!(
126 "{BOLD}Cloud sync{RST} {GREEN}in the background (supervised daemon){RST}"
127 ),
128 }),
129 DaemonAutostart::Off => Some(Outcome {
130 ok: false,
131 line: format!(
132 "{BOLD}Cloud sync{RST} {YELLOW}needs a supervised daemon{RST} {DIM}(run: lean-ctx daemon enable){RST}"
133 ),
134 }),
135 DaemonAutostart::Unsupported => None,
136 }
137}
138
139#[derive(Default)]
151struct Scoreboard {
152 json_mode: bool,
153 entries: Vec<JsonCheck>,
154}
155
156#[derive(Default, serde::Serialize)]
158struct JsonCheck {
159 ok: bool,
160 name: String,
161 scored: bool,
162 needs_attention: bool,
165 #[serde(skip_serializing_if = "Option::is_none")]
168 advice: Option<Advice>,
169}
170
171impl JsonCheck {
172 fn new(ok: bool, name: String, scored: bool) -> Self {
173 Self {
174 ok,
175 name,
176 scored,
177 needs_attention: scored && !ok,
178 advice: None,
179 }
180 }
181}
182
183#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
187pub(crate) struct Advice {
188 pub id: &'static str,
190 pub title: String,
191 pub severity: Severity,
192 pub detail: String,
194 pub actions: Vec<FixAction>,
196}
197
198#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
199#[serde(rename_all = "lowercase")]
200pub(crate) enum Severity {
201 Error,
203 Warning,
205}
206
207#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
209pub(crate) struct FixAction {
210 pub label: String,
212 pub changes: String,
214 pub commands: Vec<String>,
216}
217
218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
220struct Summary {
221 passed: u32,
223 total: u32,
225 needs_attention: u32,
227 optional: u32,
229}
230
231fn summarize(entries: &[JsonCheck]) -> Summary {
232 let count = |keep: fn(&JsonCheck) -> bool| {
233 u32::try_from(entries.iter().filter(|entry| keep(entry)).count()).unwrap_or(u32::MAX)
234 };
235 Summary {
236 passed: count(|entry| entry.scored && entry.ok),
237 total: count(|entry| entry.scored),
238 needs_attention: count(|entry| entry.needs_attention),
239 optional: count(|entry| !entry.scored && !entry.ok),
240 }
241}
242
243fn strip_ansi(s: &str) -> String {
244 let mut result = String::with_capacity(s.len());
246 let mut in_escape = false;
247 for c in s.chars() {
248 if c == '\x1b' {
249 in_escape = true;
250 } else if in_escape {
251 if c.is_ascii_alphabetic() {
252 in_escape = false;
253 }
254 } else {
255 result.push(c);
256 }
257 }
258 result
259}
260
261pub(crate) fn emit_line(line: &str) {
263 if lean_ctx::core::theme::no_color() {
264 ::std::println!("{}", strip_ansi(line));
265 } else {
266 ::std::println!("{line}");
267 }
268}
269
270impl Scoreboard {
271 fn new(json_mode: bool) -> Self {
272 Self {
273 json_mode,
274 entries: Vec::new(),
275 }
276 }
277
278 fn check(&mut self, outcome: &Outcome) {
280 self.entries
281 .push(JsonCheck::new(outcome.ok, strip_ansi(&outcome.line), true));
282 if !self.json_mode {
283 print_check(outcome, true);
284 }
285 }
286
287 fn check_advised(&mut self, outcome: &Outcome, advice: Option<Advice>) {
291 if !self.json_mode {
292 print_check(outcome, true);
293 if let Some(advice) = &advice {
294 print_advice(advice);
295 }
296 }
297 let mut entry = JsonCheck::new(outcome.ok, strip_ansi(&outcome.line), true);
298 entry.advice = advice;
299 self.entries.push(entry);
300 }
301
302 fn info(&mut self, outcome: &Outcome) {
304 self.entries
305 .push(JsonCheck::new(outcome.ok, strip_ansi(&outcome.line), false));
306 if !self.json_mode {
307 print_check(outcome, false);
308 }
309 }
310
311 fn note(&mut self, outcome: &Outcome) {
315 self.entries.push(JsonCheck::new(
316 outcome.ok,
317 strip_ansi(outcome.line.trim()),
318 false,
319 ));
320 if !self.json_mode {
321 println!("{}", outcome.line);
322 }
323 }
324
325 fn summary(&self) -> Summary {
327 summarize(&self.entries)
328 }
329
330 fn report_json(&self) -> serde_json::Value {
332 let summary = self.summary();
333 serde_json::json!({
334 "version": env!("CARGO_PKG_VERSION"),
335 "build": lean_ctx::core::integrity::build().to_json(),
336 "passed": summary.passed,
337 "total": summary.total,
338 "needs_attention": summary.needs_attention,
339 "optional": summary.optional,
340 "checks": self.entries,
341 })
342 }
343
344 fn summary_lines(&self) -> Vec<String> {
346 let Summary {
347 passed,
348 total,
349 needs_attention,
350 optional,
351 } = self.summary();
352 let mut lines = vec![format!(
353 " {BOLD}{WHITE}Summary:{RST} {GREEN}{passed}{RST}{DIM}/{total}{RST} checks passed"
354 )];
355 if needs_attention > 0 {
356 lines.push(format!(
357 " {YELLOW}{needs_attention} check(s) need attention.{RST} Auto-repair what's fixable: {BOLD}lean-ctx doctor --fix{RST}"
358 ));
359 } else {
360 lines.push(format!(" {GREEN}Everything looks good.{RST}"));
361 }
362 if optional > 0 {
363 lines.push(format!(
364 " {DIM}{optional} optional item(s) marked – are not set up (not counted in score){RST}"
365 ));
366 }
367 lines
368 }
369}
370
371const STUCK_REQUEST_AFTER: std::time::Duration = std::time::Duration::from_secs(30);
373
374fn request_ledger_outcomes(
378 snapshots: &[lean_ctx::core::request_ledger::RequestLedgerSnapshot],
379 now_ms: u64,
380) -> Vec<Outcome> {
381 snapshots
382 .iter()
383 .map(|snapshot| {
384 let stuck = snapshot
387 .oldest_pending_age(now_ms)
388 .is_some_and(|age| age >= STUCK_REQUEST_AFTER)
389 || snapshot.orphaned_handlers > 0;
390 let colour = if stuck { YELLOW } else { DIM };
391 Outcome {
392 ok: !stuck,
393 line: format!(
394 "{BOLD}Requests{RST} {colour}{}{RST}",
395 snapshot.render(now_ms)
396 ),
397 }
398 })
399 .collect()
400}
401
402fn daemon_diagnostic_notes() -> Vec<Outcome> {
406 let mut notes = Vec::new();
407 #[cfg(target_os = "linux")]
410 if lean_ctx::daemon_autostart::controls_user_services() {
411 if let Ok(o) = std::process::Command::new("systemctl")
412 .args(["--user", "is-active", "lean-ctx-daemon.service"])
413 .output()
414 {
415 let state = String::from_utf8_lossy(&o.stdout).trim().to_string();
416 if state != "active" {
417 notes.push(Outcome {
418 ok: false,
419 line: format!(
420 " {DIM} systemd unit state: {YELLOW}{state}{RST}{DIM} (expected: active){RST}"
421 ),
422 });
423 }
424 }
425 let username = std::env::var("USER")
426 .or_else(|_| std::env::var("LOGNAME"))
427 .unwrap_or_else(|_| "$(whoami)".to_string());
428 if let Ok(o) = std::process::Command::new("loginctl")
429 .args(["show-user", &username, "-p", "Linger", "--value"])
430 .output()
431 {
432 let val = String::from_utf8_lossy(&o.stdout).trim().to_string();
433 if val != "yes" {
434 notes.push(Outcome {
435 ok: false,
436 line: format!(
437 " {YELLOW}⚠{RST} Linger not enabled — daemon won't start at boot without login\n {DIM}Fix: loginctl enable-linger {username}{RST}"
438 ),
439 });
440 }
441 }
442 }
443 if let Some(log_path) = lean_ctx::core::startup_guard::crash_loop_log_path(
444 lean_ctx::core::startup_guard::MCP_PROCESS_NAME,
445 ) && log_path.exists()
446 && let Ok(contents) = std::fs::read_to_string(&log_path)
447 {
448 let lines: Vec<&str> = contents.lines().collect();
449 if lines.len() >= 5 {
450 notes.push(Outcome {
451 ok: false,
452 line: format!(
453 " {YELLOW}⚠{RST} Crash-loop log: {} recent restarts {DIM}({}){RST}",
454 lines.len(),
455 display_user_path(&log_path)
456 ),
457 });
458 }
459 }
460 notes
461}
462
463pub fn run() -> u32 {
468 run_inner(false)
469}
470
471pub fn run_json() -> u32 {
473 run_inner(true)
474}
475
476fn run_inner(json: bool) -> u32 {
477 let mut board = Scoreboard::new(json);
478
479 if !json {
480 println!("{BOLD}{WHITE}lean-ctx doctor{RST} {DIM}diagnostics{RST}\n");
481 }
482
483 let path_bin = resolve_lean_ctx_binary();
485 let also_in_path_dirs = path_in_path_env();
486 let bin_ok = path_bin.is_some() || also_in_path_dirs;
487 let bin_line = if let Some(p) = path_bin {
488 format!("{BOLD}lean-ctx in PATH{RST} {WHITE}{}{RST}", p.display())
489 } else if also_in_path_dirs {
490 format!(
491 "{BOLD}lean-ctx in PATH{RST} {YELLOW}found via PATH walk (not resolved by `command -v`){RST}"
492 )
493 } else {
494 format!("{BOLD}lean-ctx in PATH{RST} {RED}not found{RST}")
495 };
496 board.check(&Outcome {
497 ok: bin_ok,
498 line: bin_line,
499 });
500
501 let ver = if bin_ok {
503 lean_ctx_version_from_path()
504 } else {
505 Outcome {
506 ok: false,
507 line: format!("{BOLD}lean-ctx version{RST} {RED}skipped (binary not in PATH){RST}"),
508 }
509 };
510 board.check(&ver);
511
512 let lean_dir = lean_ctx::core::data_dir::lean_ctx_data_dir().ok();
514 let dir_outcome = match &lean_dir {
515 Some(p) if p.is_dir() => Outcome {
516 ok: true,
517 line: format!(
518 "{BOLD}data dir{RST} {GREEN}exists{RST} {DIM}{}{RST}",
519 p.display()
520 ),
521 },
522 Some(p) if !p.exists() => Outcome {
524 ok: true,
525 line: format!(
526 "{BOLD}data dir{RST} {WHITE}not yet created{RST} {DIM}(will appear after first use) {}{RST}",
527 p.display()
528 ),
529 },
530 Some(p) => Outcome {
531 ok: false,
532 line: format!(
533 "{BOLD}data dir{RST} {RED}not a directory{RST} {DIM}{}{RST}",
534 p.display()
535 ),
536 },
537 None => Outcome {
538 ok: false,
539 line: format!("{BOLD}data dir{RST} {RED}could not resolve data directory{RST}"),
540 },
541 };
542 board.check(&dir_outcome);
543
544 let stats_path = lean_dir.as_ref().map(|d| d.join("stats.json"));
546 let stats_outcome = match stats_path.as_ref().and_then(|p| std::fs::metadata(p).ok()) {
547 Some(m) if m.is_file() => {
548 let size = m.len();
549 let path_display = if let Some(p) = stats_path.as_ref() {
550 p.display().to_string()
551 } else {
552 String::new()
553 };
554 Outcome {
555 ok: true,
556 line: format!(
557 "{BOLD}stats.json{RST} {GREEN}exists{RST} {WHITE}{size} bytes{RST} {DIM}{path_display}{RST}",
558 ),
559 }
560 }
561 Some(_m) => {
562 let path_display = if let Some(p) = stats_path.as_ref() {
563 p.display().to_string()
564 } else {
565 String::new()
566 };
567 Outcome {
568 ok: false,
569 line: format!(
570 "{BOLD}stats.json{RST} {RED}not a file{RST} {DIM}{path_display}{RST}",
571 ),
572 }
573 }
574 None => Outcome {
575 ok: true,
576 line: match &stats_path {
577 Some(p) => format!(
578 "{BOLD}stats.json{RST} {WHITE}not yet created{RST} {DIM}(will appear after first use) {}{RST}",
579 p.display()
580 ),
581 None => format!("{BOLD}stats.json{RST} {RED}could not resolve path{RST}"),
582 },
583 },
584 };
585 board.check(&stats_outcome);
586
587 let split_dirs = lean_ctx::core::data_dir::all_data_dirs_with_stats();
588 if split_dirs.len() >= 2 {
589 let dirs_str = split_dirs
590 .iter()
591 .map(|d| d.display().to_string())
592 .collect::<Vec<_>>()
593 .join(", ");
594 board.check(&Outcome {
595 ok: false,
596 line: format!(
597 "{BOLD}data dir split{RST} {RED}stats.json found in {count} locations{RST}: {dirs_str} {DIM}(run: lean-ctx doctor --fix to merge){RST}",
598 count = split_dirs.len(),
599 ),
600 });
601 }
602
603 if let Some((src, n)) = lean_ctx::core::xdg_migrate::pending() {
608 board.check(&Outcome {
609 ok: false,
610 line: format!(
611 "{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}",
612 src.display()
613 ),
614 });
615 }
616
617 if let Some(stray) = lean_ctx::core::config_heal::pending() {
622 board.check(&Outcome {
623 ok: false,
624 line: format!(
625 "{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}",
626 stray.display()
627 ),
628 });
629 }
630
631 {
635 let pinned = lean_ctx::core::layout_pin::is_xdg_pinned();
636 let residual = lean_ctx::core::xdg_migrate::residual_legacy_present();
637 let line = if pinned && residual {
638 format!(
639 "{BOLD}layout{RST} {GREEN}xdg-pinned{RST} {YELLOW}residual ~/.lean-ctx present{RST} {DIM}(auto-reclaimed on next start){RST}"
640 )
641 } else if pinned {
642 format!(
643 "{BOLD}layout{RST} {GREEN}xdg-pinned{RST} {DIM}(~/.lean-ctx can no longer hijack this install){RST}"
644 )
645 } else {
646 format!(
647 "{BOLD}layout{RST} {WHITE}single-dir / legacy{RST} {DIM}(run: lean-ctx doctor --fix to commit to XDG){RST}"
648 )
649 };
650 board.check(&Outcome { ok: true, line });
651 }
652
653 let config_path = lean_ctx::core::config::Config::path();
658 let config_outcome = match &config_path {
659 Some(p) => match std::fs::metadata(p) {
660 Ok(m) if m.is_file() => Outcome {
661 ok: true,
662 line: format!(
663 "{BOLD}config.toml{RST} {GREEN}exists{RST} {DIM}{}{RST}",
664 p.display()
665 ),
666 },
667 Ok(_) => Outcome {
668 ok: false,
669 line: format!(
670 "{BOLD}config.toml{RST} {RED}exists but is not a regular file{RST} {DIM}{}{RST}",
671 p.display()
672 ),
673 },
674 Err(_) => Outcome {
675 ok: true,
676 line: format!(
677 "{BOLD}config.toml{RST} {WHITE}not found, using defaults{RST} {DIM}(expected at {}){RST}",
678 p.display()
679 ),
680 },
681 },
682 None => Outcome {
683 ok: false,
684 line: format!("{BOLD}config.toml{RST} {RED}could not resolve path{RST}"),
685 },
686 };
687 board.check(&config_outcome);
688
689 if let Some(outcome) = config_path
692 .as_deref()
693 .and_then(config_migration_pause_outcome)
694 {
695 board.check(&outcome);
696 }
697
698 board.check(&config_parity_outcome());
702 board.check(&project_pin_outcome());
703
704 let allowlist_outcome = shell_allowlist_outcome();
706 board.check(&allowlist_outcome);
707
708 if let Some(upgrade) = shell_allowlist_upgrade_advisory_outcome() {
711 board.check(&upgrade);
712 }
713 if let Some(shadowing) = shell_allowlist_shadowing_outcome() {
714 board.check(&shadowing);
715 }
716
717 let path_jail = path_jail_outcome();
719 board.check(&path_jail);
720
721 let workspace_trust = workspace_trust_outcome();
723 board.check(&workspace_trust);
724
725 let secret_detection = secret_detection_outcome();
728 board.check(&secret_detection);
729 let context_gateway = context_gateway_outcome();
730 board.check(&context_gateway);
731
732 if let Some(managed_bins) = managed_addon_binaries_outcome() {
736 board.check(&managed_bins);
737 }
738
739 if let Some(managed_ort) = managed_ort_outcome() {
742 board.check(&managed_ort);
743 }
744
745 let cognition = cognition_activity_outcome();
747 board.check(&cognition);
748
749 let passthrough_outcome = compact_format_passthrough_outcome();
751 board.check(&passthrough_outcome);
752
753 let perm_inherit_outcome = permission_inheritance_outcome();
755 board.check(&perm_inherit_outcome);
756
757 let proxy_outcome = proxy_upstream_outcome();
759 board.check(&proxy_outcome);
760
761 let setup_pending = dirs::home_dir().is_some_and(|home| {
768 lean_ctx_mcp_location_names(&home).is_empty()
769 && checks::configured_host_coverage(&home).is_empty()
770 });
771 if setup_pending && !json {
772 println!(
773 " {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}"
774 );
775 }
776 let setup_item = |board: &mut Scoreboard, outcome: &Outcome| {
777 if setup_pending {
778 board.info(outcome);
779 } else {
780 board.check(outcome);
781 }
782 };
783
784 let aliases = shell_aliases_outcome();
786 setup_item(&mut board, &aliases);
787
788 let agent_aliases = skip_agent_aliases_outcome();
790 board.check(&agent_aliases);
791
792 let mcp = mcp_config_outcome();
794 setup_item(&mut board, &mcp);
795 if let Some(tools) = lean_ctx::core::home::resolve_home_dir()
797 .and_then(|home| checks::claude_tool_access_outcome(&home))
798 {
799 board.check(&tools);
800 }
801 let user_scope_mcp_locations = dirs::home_dir()
802 .map(|home| lean_ctx_mcp_location_names(&home))
803 .unwrap_or_default();
804
805 if let Some(wsl_hint) = wsl_vscode_mcp_outcome() {
807 board.check(&wsl_hint);
808 }
809
810 let workspace_scope = workspace_scope::workspace_scope_outcome(&user_scope_mcp_locations);
812 if let Some(ref ws) = workspace_scope {
813 board.check(ws);
814 }
815
816 let skill = skill_files_outcome();
818 setup_item(&mut board, &skill);
819
820 board.check(&overhead::rules_channels_outcome());
822
823 if let Some(claude_mod) = checks::claude_mod_outcome() {
825 board.check(&claude_mod);
826 }
827 if let Some(code_mode) = checks::claude_code_mode_outcome() {
828 board.info(&code_mode);
829 }
830
831 if let Some(cloud_policy) = checks::cloud_policy_outcome() {
833 board.info(&cloud_policy);
834 }
835
836 let output_triage = output_triage_outcome();
839 board.check(&output_triage);
840
841 let port = port_3333_outcome();
843 board.check(&port);
844
845 let daemon_autostart = if lean_ctx::daemon_autostart::is_supported()
851 && lean_ctx::daemon_autostart::controls_user_services()
852 {
853 if lean_ctx::daemon_autostart::is_installed() {
854 DaemonAutostart::On(lean_ctx::daemon_autostart::service_file_path())
855 } else {
856 DaemonAutostart::Off
857 }
858 } else {
859 DaemonAutostart::Unsupported
860 };
861 let daemon_pid = lean_ctx::daemon::verified_daemon().map(|daemon| daemon.pid);
864 board.check(&daemon_outcome(daemon_pid, &daemon_autostart));
865 let cloud_connected = lean_ctx_cloud::CloudStore::open()
866 .is_ok_and(|store| matches!(store.instance(), Ok(Some(_))));
867 if let Some(sync) = cloud_sync_outcome(cloud_connected, &daemon_autostart) {
868 board.check(&sync);
869 }
870 if let Some(unrecorded) =
871 unrecorded_services_outcome(lean_ctx::daemon::unrecorded_services_warning())
872 {
873 board.info(&unrecorded);
874 }
875
876 for note in daemon_diagnostic_notes() {
879 board.note(¬e);
880 }
881
882 for outcome in request_ledger_outcomes(
885 &lean_ctx::core::request_ledger::published_snapshots(),
886 lean_ctx::core::request_ledger::epoch_ms(),
887 ) {
888 board.info(&outcome);
889 }
890
891 let provider_outcome = provider_outcome();
893 board.info(&provider_outcome);
894
895 let bridge_outcomes = mcp_bridge_outcomes();
897 for bridge_check in &bridge_outcomes {
898 board.info(bridge_check);
899 }
900
901 let skew_outcomes = version_skew_outcomes();
903 for (skew_check, advice) in skew_outcomes {
904 board.check_advised(&skew_check, advice);
905 }
906
907 let plan_outcomes = plan_mode_outcomes();
909 for plan_check in &plan_outcomes {
910 board.info(plan_check);
911 }
912
913 let session_outcome = session_state_outcome();
915 board.check(&session_outcome);
916
917 let docker_outcomes = docker_env_outcomes();
919 for docker_check in &docker_outcomes {
920 board.check(docker_check);
921 }
922
923 let pi = pi_outcome();
925 if let Some(ref pi_check) = pi {
926 board.check(pi_check);
927 }
928
929 let integrity = lean_ctx::core::integrity::check();
931 let integrity_ok = integrity.seed_ok && integrity.origin_ok;
932 let integrity_line = if integrity_ok && integrity.build.is_official() {
933 format!(
934 "{BOLD}Build origin{RST} {GREEN}official{RST} {DIM}{}{RST}",
935 integrity.repo
936 )
937 } else if integrity_ok {
938 format!(
939 "{BOLD}Build origin{RST} {YELLOW}{}{RST} {DIM}not a release build, {}{RST}",
940 integrity.build.label(),
941 integrity.repo
942 )
943 } else {
944 format!(
945 "{BOLD}Build origin{RST} {RED}MODIFIED REDISTRIBUTION{RST} {YELLOW}pkg={}, repo={}{RST}",
946 integrity.pkg_name, integrity.repo
947 )
948 };
949 board.check(&Outcome {
950 ok: integrity_ok,
951 line: integrity_line,
952 });
953
954 let cache_safety = cache_safety_outcome();
956 board.check(&cache_safety);
957
958 let claude_truncation = claude_truncation_outcome();
962 if let Some(ref ct) = claude_truncation {
963 record_client_item(&mut board, ct, "Claude Code", &user_scope_mcp_locations);
964 }
965
966 let codebuddy_truncation = codebuddy_truncation_outcome();
968 if let Some(ref cbt) = codebuddy_truncation {
969 record_client_item(&mut board, cbt, "CodeBuddy", &user_scope_mcp_locations);
970 }
971
972 for check in empty_session_outcomes() {
975 board.info(&check);
976 }
977
978 if let Some(ref addons) = addons_loaded_outcome() {
982 board.check(addons);
983 }
984
985 let bm25_health = bm25_cache_health_outcome();
987 board.check(&bm25_health);
988
989 let stats_quarantine = stats_quarantine_outcome();
992 board.check(&stats_quarantine);
993
994 for check in search_index_outcomes() {
998 board.check(&check);
999 }
1000
1001 let archive_footprint = archive_footprint_outcome();
1003 board.check(&archive_footprint);
1004
1005 let mem_profile = memory_profile_outcome();
1007 board.check(&mem_profile);
1008
1009 let mem_cleanup = memory_cleanup_outcome();
1011 board.check(&mem_cleanup);
1012
1013 let ram_outcome = ram_guardian_outcome();
1015 board.check(&ram_outcome);
1016
1017 let cap_warnings = capacity_warnings();
1019 for cw in &cap_warnings {
1020 board.check(cw);
1021 }
1022
1023 let orphan_outcome = orphaned_knowledge_outcome();
1025 board.check(&orphan_outcome);
1026
1027 let proxy_health = proxy_health_outcome();
1029 board.check(&proxy_health);
1030
1031 let upstream_drift = proxy_upstream_drift_outcome();
1035 if let Some(ref check) = upstream_drift {
1036 board.check(check);
1037 }
1038
1039 let stale_env = stale_proxy_env_outcome();
1041 if let Some(ref check) = stale_env {
1042 board.check(check);
1043 }
1044
1045 if let Some((check, advice)) = proxy_subscription_conflict_outcome() {
1047 board.check_advised(&check, Some(advice));
1048 }
1049
1050 if let Some(ref check) = removed_routing_tiers_outcome() {
1052 board.check(check);
1053 }
1054
1055 let coverage_check = gateway_coverage_outcome();
1058 board.check(&coverage_check);
1059
1060 let deprecation_check = deprecations::deprecations_outcome();
1063 board.check(&deprecation_check);
1064
1065 let mcp_cwd = mcp_server_cwd_outcome();
1067 board.check(&mcp_cwd);
1068
1069 if !json {
1071 println!(
1072 "\n {BOLD}{WHITE}Semantic intelligence (optional — LSP references + verified graph edges):{RST}"
1073 );
1074 }
1075 board.info(&semantic_mode_outcome());
1076 let lsp_outcomes = lsp_server_outcomes();
1077 for lsp_check in &lsp_outcomes {
1078 board.info(lsp_check);
1079 }
1080 for coverage in semantic_coverage_outcomes() {
1081 board.info(&coverage);
1082 }
1083
1084 let cfg = lean_ctx::core::config::Config::load();
1090 let shell_mode = std::env::var("LEAN_CTX_SHELL_HOOK_MODE")
1091 .ok()
1092 .filter(|v| !v.trim().is_empty())
1093 .or_else(|| cfg.shell_hook_mode.clone())
1094 .unwrap_or_default();
1095 let shell_desc = if shell_mode.trim().eq_ignore_ascii_case("deny") {
1096 format!("{GREEN}deny{RST} {DIM}(all shell via ctx_shell){RST}")
1097 } else {
1098 format!(
1099 "{YELLOW}rewrite{RST} {DIM}(unknown commands pass through raw — shell_hook_mode=deny closes this){RST}"
1100 )
1101 };
1102 let shadow_hosts = dirs::home_dir()
1105 .map(|home| checks::shadow_hosts(&home))
1106 .unwrap_or_default();
1107 let (shadow_state, shadow_detail) = checks::shadow_status(cfg.shadow_mode, &shadow_hosts);
1108 let state_color = if shadow_state == "active" { GREEN } else { DIM };
1109 let shadow_line = if shadow_state == "not active" || shadow_state == "disabled" {
1110 format!(
1111 "{BOLD}Shadow mode{RST} {state_color}{shadow_state}{RST} {DIM}{shadow_detail}{RST}"
1112 )
1113 } else {
1114 format!(
1115 "{BOLD}Shadow mode{RST} {state_color}{shadow_state}{RST} {DIM}{shadow_detail}{RST} shell: {shell_desc}"
1116 )
1117 };
1118 if !json {
1119 println!(" {shadow_line}");
1120 }
1121
1122 let tool_profile_line = if lean_ctx_server::server::tool_visibility::explicit_profile(&cfg) {
1128 let profile = lean_ctx::core::tool_profiles::ToolProfile::from_config(&cfg);
1129 format!(
1130 "{BOLD}Tool profile{RST} {WHITE}{profile}{RST} {DIM}{} + ctx_call gateway{RST}",
1131 profile.description()
1132 )
1133 } else {
1134 let lazy_count = lean_ctx::tool_defs::core_tool_names().len();
1135 format!(
1136 "{BOLD}Tool profile{RST} {WHITE}lean (default){RST} {DIM}{lazy_count} lazy-core tools advertised + ctx_call gateway{RST}"
1137 )
1138 };
1139 if !json {
1140 println!(" {tool_profile_line}");
1141 }
1142
1143 let cep = &lean_ctx::core::stats::load().cep;
1147 let hit_ratio = if cep.total_cache_reads > 0 {
1148 (cep.total_cache_hits as f64 / cep.total_cache_reads as f64) * 100.0
1149 } else {
1150 0.0
1151 };
1152 if !json {
1153 println!(
1154 " {BOLD}Session cache{RST} {WHITE}{} sessions{RST} {DIM}{}/{} reads cached ({hit_ratio:.0}% hit) · prove: lean-ctx verify-cache{RST}",
1155 cep.sessions, cep.total_cache_hits, cep.total_cache_reads
1156 );
1157 println!(
1158 " {BOLD}Usage{RST} {WHITE}{}{RST}",
1159 lean_ctx::core::stats::display_calls_saved_line()
1160 );
1161 }
1162
1163 let needs_attention = board.summary().needs_attention;
1167
1168 if json {
1169 println!(
1170 "{}",
1171 serde_json::to_string_pretty(&board.report_json()).unwrap_or_default()
1172 );
1173 } else {
1174 println!();
1175 for line in board.summary_lines() {
1176 println!("{line}");
1177 }
1178 println!(" {DIM}LSP servers are optional enhancements (not counted in score){RST}");
1179 println!(" {DIM}{}{RST}", lean_ctx::core::integrity::origin_line());
1180
1181 lean_ctx::core::version_check::check_background();
1182 if let Some(banner) = lean_ctx::core::version_check::get_update_banner() {
1183 println!();
1184 println!("{banner}");
1185 }
1186 }
1187
1188 needs_attention
1189}
1190
1191pub fn run_compact() {
1192 let (passed, total) = compact_score();
1193 print_compact_status(passed, total);
1194}
1195
1196pub fn run_cli(args: &[String]) -> i32 {
1197 let (sub, rest) = match args.first().map(String::as_str) {
1198 Some("integrations") => ("integrations", &args[1..]),
1199 Some("overhead") => ("overhead", &args[1..]),
1200 Some("lint-context") => ("lint-context", &args[1..]),
1201 _ => ("", args),
1202 };
1203
1204 let fix = rest.iter().any(|a| a == "--fix");
1205 let json = rest.iter().any(|a| a == "--json");
1206 let gate = rest.iter().any(|a| a == "--gate");
1207 let migrate_check = rest.iter().any(|a| a == "--migrate-check");
1208 let help = rest.iter().any(|a| a == "--help" || a == "-h");
1209
1210 if help {
1211 println!("Usage:");
1212 println!(" lean-ctx doctor");
1213 println!(
1214 " lean-ctx doctor overhead [--json] [--gate] Fixed context cost per session (--gate: non-zero exit when over [context] budget_tokens)"
1215 );
1216 println!(
1217 " lean-ctx doctor lint-context [--json] Lint injected context for low-signal/dup lines"
1218 );
1219 println!(" lean-ctx doctor integrations [--json]");
1220 println!(" lean-ctx doctor --fix [--json]");
1221 println!(" lean-ctx doctor --migrate-check [--json]");
1222 println!();
1223 println!(
1224 "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."
1225 );
1226 return 0;
1227 }
1228
1229 if sub == "overhead" {
1230 return overhead::run_overhead(json, gate);
1231 }
1232
1233 if sub == "lint-context" {
1234 return lint_context::run_lint_context(json);
1235 }
1236
1237 if migrate_check {
1238 return migrate::run_migrate_check(json);
1239 }
1240
1241 if sub == "integrations" {
1242 if fix {
1243 let _ = fix::run_fix(&fix::DoctorFixOptions { json: false });
1244 }
1245 return integrations::run_integrations(&integrations::IntegrationsOptions { json });
1246 }
1247
1248 if !fix {
1249 let needs = if json { run_json() } else { run() };
1252 return i32::from(needs > 0);
1253 }
1254
1255 match fix::run_fix(&fix::DoctorFixOptions { json }) {
1256 Ok(code) => code,
1257 Err(e) => {
1258 tracing::error!("doctor --fix failed: {e}");
1259 2
1260 }
1261 }
1262}
1263
1264pub fn compact_score() -> (u32, u32) {
1265 let mut passed = 0u32;
1266 let total = 6u32;
1267
1268 if resolve_lean_ctx_binary().is_some() || path_in_path_env() {
1269 passed += 1;
1270 }
1271 let lean_dir = lean_ctx::core::data_dir::lean_ctx_data_dir().ok();
1272 if lean_dir.as_ref().is_some_and(|p| p.is_dir()) {
1273 passed += 1;
1274 }
1275 if lean_dir
1276 .as_ref()
1277 .map(|d| d.join("stats.json"))
1278 .and_then(|p| std::fs::metadata(p).ok())
1279 .is_some_and(|m| m.is_file())
1280 {
1281 passed += 1;
1282 }
1283 if shell_aliases_outcome().ok {
1284 passed += 1;
1285 }
1286 if mcp_config_outcome().ok {
1287 passed += 1;
1288 }
1289 if skill_files_outcome().ok {
1290 passed += 1;
1291 }
1292
1293 (passed, total)
1294}
1295
1296pub(super) fn print_compact_status(passed: u32, total: u32) {
1297 let status = if passed == total {
1298 format!("{GREEN}✓ All {total} checks passed{RST}")
1299 } else {
1300 format!("{YELLOW}{passed}/{total} passed{RST} — run {BOLD}lean-ctx doctor{RST} for details")
1301 };
1302 println!(" {status}");
1303}
1304
1305fn config_migration_pause_outcome(config: &std::path::Path) -> Option<Outcome> {
1308 let pause = lean_ctx::core::config::config_migration_pause_status(config)?;
1309 Some(Outcome {
1310 ok: false,
1311 line: format!(
1312 "{BOLD}config migration{RST} {YELLOW}paused ({}){RST} {DIM}{} · {}{RST} {DIM}({}){RST}",
1313 pause.label,
1314 pause.backup.display(),
1315 pause.receipt.display(),
1316 pause.action
1317 ),
1318 })
1319}
1320
1321fn record_client_item(
1324 board: &mut Scoreboard,
1325 outcome: &Outcome,
1326 client: &str,
1327 configured: &std::collections::BTreeSet<&'static str>,
1328) {
1329 if configured.contains(client) {
1330 board.check(outcome);
1331 } else {
1332 board.info(outcome);
1333 }
1334}
1335
1336#[cfg(test)]
1337mod tests {
1338 use super::is_active_shell_impl;
1339 use super::{DaemonAutostart, cloud_sync_outcome, daemon_outcome, unrecorded_services_outcome};
1340 use super::{request_ledger_outcomes, strip_ansi};
1341
1342 #[test]
1348 fn doctor_summary_counts_are_counts_of_the_emitted_checks() {
1349 use super::{Outcome, Scoreboard};
1350 let outcome = |ok: bool, line: &str| Outcome {
1351 ok,
1352 line: line.to_owned(),
1353 };
1354 let mut board = Scoreboard::new(true);
1355 board.check(&outcome(true, "Version ok"));
1356 board.check(&outcome(false, "Capacity [gateway receipts] CRIT"));
1357 board.check(&outcome(false, "Claude auth"));
1358 board.info(&outcome(false, "Plan mode VS Code not configured"));
1359 board.info(&outcome(true, "LSP rust-analyzer"));
1360 board.note(&outcome(true, " daemon note "));
1361
1362 let document = board.report_json();
1363 let checks = document["checks"].as_array().expect("checks array");
1364 let count = |keep: &dyn Fn(&serde_json::Value) -> bool| {
1365 checks.iter().filter(|entry| keep(entry)).count() as u64
1366 };
1367 let flag = |entry: &serde_json::Value, key: &str| entry[key].as_bool().expect(key);
1368 let scored = count(&|e| flag(e, "scored"));
1369 let passed = count(&|e| flag(e, "scored") && flag(e, "ok"));
1370 let attention = count(&|e| flag(e, "needs_attention"));
1371 let optional = count(&|e| !flag(e, "scored") && !flag(e, "ok"));
1372
1373 assert_eq!(document["total"], scored, "{document}");
1374 assert_eq!(document["passed"], passed, "{document}");
1375 assert_eq!(document["needs_attention"], attention, "{document}");
1376 assert_eq!(document["optional"], optional, "{document}");
1377 assert_eq!((scored, passed, attention, optional), (3, 1, 2, 1));
1378 assert_eq!(count(&|e| !flag(e, "ok")), attention + optional);
1380 for entry in checks {
1381 assert_eq!(
1382 flag(entry, "needs_attention"),
1383 flag(entry, "scored") && !flag(entry, "ok"),
1384 "{entry}"
1385 );
1386 }
1387
1388 let text = board.summary_lines().join("\n");
1389 let plain = strip_ansi(&text);
1390 assert!(plain.contains("1/3 checks passed"), "{plain}");
1391 assert!(plain.contains("2 check(s) need attention"), "{plain}");
1392 assert!(plain.contains("1 optional item(s)"), "{plain}");
1393 }
1394
1395 #[test]
1400 fn doctor_json_carries_advice_for_the_claude_auth_and_bridge_findings() {
1401 use super::checks::{Bridge, bridge_version_outcome, subscription_conflict};
1402 use super::{Outcome, Scoreboard};
1403 let mut board = Scoreboard::new(true);
1404 board.check(&Outcome {
1405 ok: true,
1406 line: "Version ok".to_owned(),
1407 });
1408 let (auth, auth_advice) = subscription_conflict();
1409 board.check_advised(&auth, Some(auth_advice));
1410 let (pi, pi_advice) = bridge_version_outcome(Bridge::Pi, "3.11.2", "3.12.7");
1411 board.check_advised(&pi, pi_advice);
1412 let (cursor, cursor_advice) = bridge_version_outcome(Bridge::Cursor, "0.4.0", "3.12.7");
1414 assert!(cursor.ok && cursor_advice.is_none());
1415 board.check_advised(&cursor, cursor_advice);
1416 let (pi_now, pi_now_advice) = bridge_version_outcome(Bridge::Pi, "3.12.7", "3.12.7");
1417 assert!(pi_now.ok && pi_now_advice.is_none());
1418
1419 let document = board.report_json();
1420 let checks = document["checks"].as_array().expect("checks array");
1421 assert_eq!(document["needs_attention"], 2, "{document}");
1422 for plain in [&checks[0], &checks[3]] {
1423 let keys: Vec<&str> = plain
1424 .as_object()
1425 .unwrap()
1426 .keys()
1427 .map(String::as_str)
1428 .collect();
1429 assert_eq!(keys.len(), 4, "{plain}");
1430 assert!(plain.get("advice").is_none(), "{plain}");
1431 }
1432
1433 let auth = &checks[1]["advice"];
1434 assert_eq!(auth["id"], "claude_subscription_via_proxy");
1435 assert_eq!(auth["title"], "Claude subscription goes through the proxy");
1436 assert_eq!(auth["severity"], "error");
1437 assert!(auth["detail"].as_str().unwrap().ends_with('.'), "{auth}");
1438 let actions = auth["actions"].as_array().unwrap();
1439 assert_eq!(actions.len(), 2, "{auth}");
1440 assert_eq!(actions[0]["label"], "Turn off the proxy");
1441 assert_eq!(actions[0]["commands"][0], "lean-ctx proxy disable");
1442 assert!(
1443 actions[0]["changes"].as_str().unwrap().contains("Codex"),
1444 "proxy disable turns it off for every client: {auth}"
1445 );
1446 assert_eq!(
1448 actions[1]["commands"].as_array().unwrap().len(),
1449 1,
1450 "{auth}"
1451 );
1452 assert_eq!(actions[1]["commands"][0], "lean-ctx proxy enable");
1453 assert!(
1454 actions[1]["changes"]
1455 .as_str()
1456 .unwrap()
1457 .contains("ANTHROPIC_API_KEY"),
1458 "{auth}"
1459 );
1460 let name = checks[1]["name"].as_str().unwrap();
1462 assert_eq!(
1463 name,
1464 "Claude auth Claude subscription goes through the proxy"
1465 );
1466
1467 let pi = &checks[2]["advice"];
1468 assert_eq!(pi["id"], "bridge_version_pi");
1469 assert_eq!(pi["severity"], "warning");
1470 let detail = pi["detail"].as_str().unwrap();
1471 assert!(
1472 detail.contains("3.11.2") && detail.contains("3.12.7"),
1473 "{pi}"
1474 );
1475 assert_eq!(pi["actions"][0]["label"], "Update pi-lean-ctx");
1476 assert_eq!(
1477 pi["actions"][0]["commands"][0],
1478 "pi install npm:pi-lean-ctx@latest"
1479 );
1480 for entry in checks {
1481 if let Some(advice) = entry.get("advice") {
1482 for action in advice["actions"].as_array().unwrap() {
1483 assert!(
1484 action["changes"].as_str().unwrap().ends_with('.'),
1485 "{action}"
1486 );
1487 }
1488 }
1489 }
1490 }
1491
1492 #[test]
1495 fn doctor_text_prints_advice_as_sentence_fixes_and_commands() {
1496 use super::checks::subscription_conflict;
1497 use super::common::advice_lines;
1498 let (_, advice) = subscription_conflict();
1499 let plain: Vec<String> = advice_lines(&advice)
1500 .iter()
1501 .map(|l| strip_ansi(l))
1502 .collect();
1503 assert!(
1504 plain[0]
1505 .trim()
1506 .starts_with("Claude Code sends its requests"),
1507 "{plain:?}"
1508 );
1509 assert_eq!(plain[1].trim(), "Fix it one of these ways:");
1510 assert!(
1511 plain[2]
1512 .trim()
1513 .starts_with("Turn off the proxy The proxy goes off for every client"),
1514 "{plain:?}"
1515 );
1516 assert_eq!(plain[3].trim(), "$ lean-ctx proxy disable");
1517 assert!(
1518 plain.iter().any(|l| l.trim() == "$ lean-ctx proxy enable"),
1519 "{plain:?}"
1520 );
1521 }
1522
1523 #[test]
1526 fn doctor_text_prints_a_single_fix_and_a_fix_without_commands() {
1527 use super::checks::{Bridge, bridge_version_outcome};
1528 use super::common::advice_lines;
1529 use super::{Advice, FixAction, Severity};
1530 let (_, advice) = bridge_version_outcome(Bridge::Pi, "3.11.2", "3.12.7");
1531 let plain: Vec<String> = advice_lines(&advice.expect("pi is out of step"))
1532 .iter()
1533 .map(|l| strip_ansi(l))
1534 .collect();
1535 assert_eq!(plain.len(), 3, "{plain:?}");
1536 assert!(
1537 plain.iter().all(|l| !l.contains("one of these ways")),
1538 "{plain:?}"
1539 );
1540 assert!(
1541 plain[1].trim().starts_with("Update pi-lean-ctx "),
1542 "{plain:?}"
1543 );
1544 assert_eq!(plain[2].trim(), "$ pi install npm:pi-lean-ctx@latest");
1545
1546 let words_only = Advice {
1547 id: "words_only",
1548 title: "A step without commands".to_string(),
1549 severity: Severity::Warning,
1550 detail: "Only words.".to_string(),
1551 actions: vec![FixAction {
1552 label: "Do it by hand".to_string(),
1553 changes: "Nothing to type.".to_string(),
1554 commands: Vec::new(),
1555 }],
1556 };
1557 let plain: Vec<String> = advice_lines(&words_only)
1558 .iter()
1559 .map(|l| strip_ansi(l))
1560 .collect();
1561 assert_eq!(plain.len(), 2, "{plain:?}");
1562 assert!(
1563 plain.iter().all(|l| !l.trim().starts_with('$')),
1564 "{plain:?}"
1565 );
1566 }
1567
1568 #[test]
1571 fn client_instructions_count_only_for_a_client_configured_with_lean_ctx() {
1572 use super::{Outcome, Scoreboard, record_client_item};
1573 let missing = Outcome {
1574 ok: false,
1575 line: "Claude Code instructions no CLAUDE.md block".to_owned(),
1576 };
1577 let scored = |configured: &[&'static str]| {
1578 let mut board = Scoreboard::new(true);
1579 record_client_item(
1580 &mut board,
1581 &missing,
1582 "Claude Code",
1583 &configured.iter().copied().collect(),
1584 );
1585 board.report_json()["checks"][0]["scored"].clone()
1586 };
1587 assert_eq!(scored(&[]), serde_json::json!(false));
1588 assert_eq!(scored(&["Cursor"]), serde_json::json!(false));
1589 assert_eq!(scored(&["Claude Code"]), serde_json::json!(true));
1590 }
1591 #[test]
1592 fn cloud_sync_needs_a_supervised_daemon_when_connected() {
1593 assert!(cloud_sync_outcome(false, &DaemonAutostart::Off).is_none());
1594 assert!(cloud_sync_outcome(true, &DaemonAutostart::Unsupported).is_none());
1595 let off = cloud_sync_outcome(true, &DaemonAutostart::Off).unwrap();
1596 assert!(!off.ok);
1597 assert!(off.line.contains("lean-ctx daemon enable"), "{}", off.line);
1598 assert!(
1599 cloud_sync_outcome(true, &DaemonAutostart::On(None))
1600 .unwrap()
1601 .ok
1602 );
1603 }
1604
1605 #[test]
1609 fn request_ledger_lines_show_counters_oldest_pending_and_last_completion() {
1610 use lean_ctx::core::request_ledger::{
1611 CompletionRecord, Outcome as RequestOutcome, PendingRequest, RequestLedgerSnapshot,
1612 Stage,
1613 };
1614 let now = 1_000_000_000;
1615 let snapshot = RequestLedgerSnapshot {
1616 pid: 4242,
1617 kind: "http".into(),
1618 generation: "gen".into(),
1619 started_at_ms: now - 600_000,
1620 snapshot_at_ms: now - 1_000,
1621 admitted: 40,
1622 completed: 36,
1623 errored: 1,
1624 refused: 2,
1625 abandoned: 1,
1626 pending: 2,
1627 untracked_pending: 0,
1628 oldest_pending: Some(PendingRequest {
1629 method: "tools/call:ctx_read".into(),
1630 stage: Stage::Handler,
1631 admitted_at_ms: now - 74_000,
1632 age_ms: None,
1633 }),
1634 last_tool_completion: Some(CompletionRecord {
1635 method: "tools/call:ctx_search".into(),
1636 outcome: RequestOutcome::Completed,
1637 finished_at_ms: now - 3_000,
1638 duration_ms: 12,
1639 age_ms: None,
1640 }),
1641 last_initialize: None,
1642 current_phase: None,
1643 observations: lean_ctx::core::events::DetachedObservationStats::default(),
1644 orphaned_handlers: 0,
1645 oldest_orphaned_handler: None,
1646 };
1647 let lines = request_ledger_outcomes(std::slice::from_ref(&snapshot), now);
1648 assert_eq!(lines.len(), 1);
1649 let line = strip_ansi(&lines[0].line);
1650 assert!(!lines[0].ok, "a 74 s pending request is flagged: {line}");
1651 assert!(line.contains("pid 4242 (http), up 10m"), "{line}");
1652 assert!(
1653 line.contains(
1654 "admitted 40 · completed 36 · errored 1 · refused 2 · abandoned 1 · pending 2"
1655 ),
1656 "{line}"
1657 );
1658 assert!(
1659 line.contains("oldest pending tools/call:ctx_read 74s in handler"),
1660 "{line}"
1661 );
1662 assert!(
1663 line.contains("last tool completion 3s ago (completed, 12ms)"),
1664 "{line}"
1665 );
1666 assert!(line.contains("last initialize none yet"), "{line}");
1667
1668 let idle = RequestLedgerSnapshot {
1669 pending: 0,
1670 oldest_pending: None,
1671 ..snapshot
1672 };
1673 let lines = request_ledger_outcomes(std::slice::from_ref(&idle), now);
1674 assert!(lines[0].ok);
1675 let line = strip_ansi(&lines[0].line);
1676 assert!(line.contains("oldest pending none"), "{line}");
1677 assert!(
1678 !line.contains("orphaned"),
1679 "no orphan suffix when none: {line}"
1680 );
1681
1682 let orphaned = RequestLedgerSnapshot {
1685 orphaned_handlers: 2,
1686 oldest_orphaned_handler: Some(lean_ctx::core::request_ledger::OrphanedHandler {
1687 method: "tools/call:ctx_search".into(),
1688 started_at_ms: now - 300_000,
1689 orphaned_at_ms: now - 180_000,
1690 }),
1691 ..idle
1692 };
1693 let lines = request_ledger_outcomes(&[orphaned], now);
1694 let line = strip_ansi(&lines[0].line);
1695 assert!(!lines[0].ok, "an orphaned handler is flagged: {line}");
1696 assert!(
1697 line.contains("orphaned handlers 2 (oldest tools/call:ctx_search 3m since abandoned)"),
1698 "{line}"
1699 );
1700 }
1701
1702 #[test]
1705 fn daemon_unrecorded_services_line_lists_pids_and_the_stop_command() {
1706 assert!(unrecorded_services_outcome(None).is_none());
1707 let outcome = unrecorded_services_outcome(Some((
1708 "Still running, not started by this instance (left alone): proxy (PID 913).".into(),
1709 "Stop them with: kill 913".into(),
1710 )))
1711 .expect("listed");
1712 assert!(outcome.ok);
1713 assert!(outcome.line.contains("proxy (PID 913)"), "{}", outcome.line);
1714 assert!(outcome.line.contains("kill 913"), "{}", outcome.line);
1715 }
1716
1717 #[test]
1720 fn daemon_line_reports_real_state_without_autostart_service() {
1721 let running = daemon_outcome(Some(36492), &DaemonAutostart::Unsupported);
1722 assert!(running.ok);
1723 assert!(
1724 running.line.contains("running (PID 36492)"),
1725 "{}",
1726 running.line
1727 );
1728 assert!(!running.line.contains("not supported"));
1729 assert!(!running.line.contains("autostart"));
1730
1731 let stopped = daemon_outcome(None, &DaemonAutostart::Unsupported);
1732 assert!(stopped.line.contains("not running"), "{}", stopped.line);
1733 assert!(stopped.line.contains("lean-ctx daemon start"));
1734 assert!(!stopped.line.contains("daemon enable"), "{}", stopped.line);
1735 assert!(!stopped.line.contains("not supported"));
1736 }
1737
1738 #[test]
1739 fn daemon_line_keeps_autostart_details_where_supported() {
1740 let path = std::path::PathBuf::from("/x/com.leanctx.daemon.plist");
1741 let on = daemon_outcome(Some(7), &DaemonAutostart::On(Some(path)));
1742 assert!(on.line.contains("running (PID 7)"));
1743 assert!(
1744 on.line
1745 .contains("autostart: on — /x/com.leanctx.daemon.plist")
1746 );
1747 let restarting = daemon_outcome(None, &DaemonAutostart::On(None));
1748 assert!(restarting.line.contains("autostart enabled, will restart"));
1749 let off = daemon_outcome(None, &DaemonAutostart::Off);
1750 assert!(off.line.contains("lean-ctx daemon enable"));
1751 }
1752
1753 #[test]
1754 fn doctor_reports_a_paused_config_migration_with_files_and_action() {
1755 let _isolated = lean_ctx::core::data_dir::isolated_data_dir();
1756 let path = lean_ctx::core::config::Config::path().expect("isolated config path");
1757 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1758 std::fs::write(
1760 &path,
1761 "# doctor paused-migration test\nterse_agent = \"full\"\n",
1762 )
1763 .unwrap();
1764 assert!(super::config_migration_pause_outcome(&path).is_none());
1765
1766 let backup = path.with_file_name("config.toml.v4-migration.bak");
1768 let receipt = path.with_file_name("config.toml.v4-migration.json");
1769 std::fs::write(&backup, "tampered = true\n").unwrap();
1770 std::fs::write(&receipt, "{ not json").unwrap();
1771 let _ = lean_ctx::core::config::Config::load();
1772
1773 let outcome =
1774 super::config_migration_pause_outcome(&path).expect("doctor reports the pause");
1775 assert!(!outcome.ok);
1776 assert!(
1777 outcome.line.contains("receipt-unverifiable"),
1778 "{}",
1779 outcome.line
1780 );
1781 assert!(
1782 outcome.line.contains("config.toml.v4-migration.bak"),
1783 "{}",
1784 outcome.line
1785 );
1786 assert!(
1787 outcome.line.contains("config.toml.v4-migration.json"),
1788 "{}",
1789 outcome.line
1790 );
1791 assert!(
1792 outcome.line.contains("move both out of"),
1793 "{}",
1794 outcome.line
1795 );
1796 }
1797
1798 fn make_capacity_check(name: &str, current: usize, limit: usize) -> Option<(bool, String)> {
1802 if limit == 0 {
1803 return None;
1804 }
1805 let pct = (current as f64 / limit as f64 * 100.0) as u32;
1806 if pct > 100 {
1807 Some((true, format!("{name}: {current}/{limit} ({pct}%)")))
1808 } else if pct >= 80 {
1809 Some((false, format!("{name}: {current}/{limit} ({pct}%)")))
1810 } else {
1811 None
1812 }
1813 }
1814
1815 #[test]
1816 fn capacity_below_80_no_warning() {
1817 assert!(make_capacity_check("facts", 100, 200).is_none());
1818 assert!(make_capacity_check("facts", 159, 200).is_none());
1819 }
1820
1821 #[test]
1822 fn capacity_at_80_yellow_warning() {
1823 let result = make_capacity_check("facts", 160, 200);
1824 assert!(result.is_some());
1825 let (critical, msg) = result.unwrap();
1826 assert!(!critical);
1827 assert!(msg.contains("160/200"));
1828 assert!(msg.contains("80%"));
1829 }
1830
1831 #[test]
1832 fn capacity_at_92_yellow_warning() {
1833 let result = make_capacity_check("facts", 185, 200);
1834 assert!(result.is_some());
1835 let (critical, msg) = result.unwrap();
1836 assert!(!critical);
1837 assert!(msg.contains("185/200"));
1838 assert!(msg.contains("92%"));
1839 }
1840
1841 #[test]
1842 fn capacity_at_95_is_warning_not_critical() {
1843 let result = make_capacity_check("facts", 190, 200);
1844 assert!(result.is_some());
1845 let (critical, msg) = result.unwrap();
1846 assert!(!critical, "95% is full-but-healthy, not over cap");
1847 assert!(msg.contains("190/200"));
1848 assert!(msg.contains("95%"));
1849 }
1850
1851 #[test]
1852 fn capacity_at_100_is_warning_not_critical() {
1853 let result = make_capacity_check("facts", 200, 200);
1855 assert!(result.is_some());
1856 let (critical, _) = result.unwrap();
1857 assert!(!critical);
1858 }
1859
1860 #[test]
1861 fn capacity_over_100_is_critical() {
1862 let result = make_capacity_check("facts", 206, 200);
1865 assert!(result.is_some());
1866 let (critical, msg) = result.unwrap();
1867 assert!(critical);
1868 assert!(msg.contains("206/200"));
1869 assert!(msg.contains("103%"));
1870 }
1871
1872 #[test]
1873 fn capacity_zero_limit_skipped() {
1874 assert!(make_capacity_check("facts", 50, 0).is_none());
1875 }
1876
1877 #[test]
1878 fn bashrc_active_on_non_windows_when_shell_empty() {
1879 assert!(is_active_shell_impl("~/.bashrc", "", false, false));
1880 }
1881
1882 #[test]
1883 fn bashrc_not_active_on_windows_when_shell_empty() {
1884 assert!(!is_active_shell_impl("~/.bashrc", "", true, false));
1885 }
1886
1887 #[test]
1888 fn bashrc_active_when_shell_contains_bash_on_linux() {
1889 assert!(is_active_shell_impl(
1890 "~/.bashrc",
1891 "/usr/bin/bash",
1892 false,
1893 false
1894 ));
1895 }
1896
1897 #[test]
1898 fn bashrc_not_active_on_windows_even_with_bash_in_shell_env() {
1899 let _env_lock = lean_ctx::core::data_dir::test_env_lock();
1900 lean_ctx::test_env::remove_var("BASH_VERSION");
1903 assert!(!is_active_shell_impl(
1904 "~/.bashrc",
1905 "C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe",
1906 true,
1907 false,
1908 ));
1909 }
1910
1911 #[test]
1912 fn bashrc_not_active_on_windows_powershell_even_with_bash_in_shell() {
1913 assert!(!is_active_shell_impl(
1914 "~/.bashrc",
1915 "C:\\\\Program Files\\\\Git\\\\bin\\\\bash.exe",
1916 true,
1917 true,
1918 ));
1919 }
1920
1921 #[test]
1922 fn bashrc_not_active_on_windows_powershell_with_empty_shell() {
1923 assert!(!is_active_shell_impl("~/.bashrc", "", true, true));
1924 }
1925
1926 #[test]
1927 fn zshrc_unaffected_by_powershell_flag() {
1928 assert!(is_active_shell_impl("~/.zshrc", "/bin/zsh", false, false));
1929 assert!(is_active_shell_impl("~/.zshrc", "/bin/zsh", true, true));
1930 }
1931
1932 #[test]
1933 fn bashrc_not_active_on_windows_without_powershell_detection() {
1934 let _env_lock = lean_ctx::core::data_dir::test_env_lock();
1935 lean_ctx::test_env::remove_var("BASH_VERSION");
1938 assert!(!is_active_shell_impl(
1939 "~/.bashrc",
1940 "/usr/bin/bash",
1941 true,
1942 false,
1943 ));
1944 }
1945
1946 #[test]
1947 fn bashrc_active_on_linux() {
1948 assert!(is_active_shell_impl("~/.bashrc", "/bin/bash", false, false));
1949 assert!(is_active_shell_impl("~/.bashrc", "", false, false));
1950 }
1951}